LLVM 24.0.0git
Verifier.cpp
Go to the documentation of this file.
1//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the function verifier interface, that can be used for some
10// basic correctness checking of input to the system.
11//
12// Note that this does not provide full `Java style' security and verifications,
13// instead it just tries to ensure that code is well-formed.
14//
15// * Both of a binary operator's parameters are of the same type
16// * Verify that the indices of mem access instructions match other operands
17// * Verify that arithmetic and other things are only performed on first-class
18// types. Verify that shifts & logicals only happen on integrals f.e.
19// * All of the constants in a switch statement are of the correct type
20// * The code is in valid SSA form
21// * It should be illegal to put a label into any other type (like a structure)
22// or to return one. [except constant arrays!]
23// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24// * PHI nodes must have an entry for each predecessor, with no extras.
25// * PHI nodes must be the first thing in a basic block, all grouped together
26// * All basic blocks should only end with terminator insts, not contain them
27// * The entry node to a function must not have predecessors
28// * All Instructions must be embedded into a basic block
29// * Functions cannot take a void-typed parameter
30// * Verify that a function's argument list agrees with it's declared type.
31// * It is illegal to specify a name for a void value.
32// * It is illegal to have a internal global value with no initializer
33// * It is illegal to have a ret instruction that returns a value that does not
34// agree with the function return value type.
35// * Function call argument types match the function prototype
36// * A landing pad is defined by a landingpad instruction, and can be jumped to
37// only by the unwind edge of an invoke instruction.
38// * A landingpad instruction must be the first non-PHI instruction in the
39// block.
40// * Landingpad instructions must be in a function with a personality function.
41// * Convergence control intrinsics are introduced in ConvergentOperations.rst.
42// The applied restrictions are too numerous to list here.
43// * The convergence entry intrinsic and the loop heart must be the first
44// non-PHI instruction in their respective block. This does not conflict with
45// the landing pads, since these two kinds cannot occur in the same block.
46// * All other things that are tested by asserts spread about the code...
47//
48//===----------------------------------------------------------------------===//
49
50#include "llvm/IR/Verifier.h"
51#include "IROptions.h"
52#include "VerifierInternal.h"
53#include "llvm/ADT/APFloat.h"
54#include "llvm/ADT/APInt.h"
55#include "llvm/ADT/ArrayRef.h"
56#include "llvm/ADT/DenseMap.h"
57#include "llvm/ADT/MapVector.h"
58#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/StringRef.h"
63#include "llvm/ADT/Twine.h"
65#include "llvm/IR/Argument.h"
67#include "llvm/IR/Attributes.h"
68#include "llvm/IR/AutoUpgrade.h"
69#include "llvm/IR/BasicBlock.h"
71#include "llvm/IR/CFG.h"
72#include "llvm/IR/CallingConv.h"
73#include "llvm/IR/Comdat.h"
74#include "llvm/IR/Constant.h"
77#include "llvm/IR/Constants.h"
79#include "llvm/IR/DataLayout.h"
80#include "llvm/IR/DebugInfo.h"
82#include "llvm/IR/DebugLoc.h"
84#include "llvm/IR/Dominators.h"
86#include "llvm/IR/FPEnv.h"
87#include "llvm/IR/Function.h"
89#include "llvm/IR/GCStrategy.h"
91#include "llvm/IR/GlobalAlias.h"
92#include "llvm/IR/GlobalValue.h"
94#include "llvm/IR/InlineAsm.h"
95#include "llvm/IR/InstVisitor.h"
96#include "llvm/IR/InstrTypes.h"
97#include "llvm/IR/Instruction.h"
100#include "llvm/IR/Intrinsics.h"
101#include "llvm/IR/IntrinsicsAArch64.h"
102#include "llvm/IR/IntrinsicsARM.h"
103#include "llvm/IR/IntrinsicsBPF.h"
104#include "llvm/IR/IntrinsicsNVPTX.h"
105#include "llvm/IR/IntrinsicsRISCV.h"
106#include "llvm/IR/IntrinsicsWebAssembly.h"
107#include "llvm/IR/LLVMContext.h"
109#include "llvm/IR/Metadata.h"
110#include "llvm/IR/Module.h"
112#include "llvm/IR/PassManager.h"
114#include "llvm/IR/Statepoint.h"
115#include "llvm/IR/Type.h"
116#include "llvm/IR/Use.h"
117#include "llvm/IR/User.h"
119#include "llvm/IR/Value.h"
121#include "llvm/Pass.h"
124#include "llvm/Support/Casting.h"
125#include "llvm/Support/CodeGen.h"
129#include "llvm/Support/ModRef.h"
136#include <algorithm>
137#include <cassert>
138#include <cstdint>
139#include <limits>
140#include <memory>
141#include <optional>
142#include <queue>
143#include <string>
144#include <utility>
145
146using namespace llvm;
147
148namespace {
149
150class Verifier : public InstVisitor<Verifier>, VerifierSupport {
151 friend class InstVisitor<Verifier>;
152 DominatorTree DT;
153
154 /// When verifying a basic block, keep track of all of the
155 /// instructions we have seen so far.
156 ///
157 /// This allows us to do efficient dominance checks for the case when an
158 /// instruction has an operand that is an instruction in the same block.
159 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
160
161 /// Keep track of the metadata nodes that have been checked already.
162 SmallPtrSet<const Metadata *, 32> MDNodes;
163
164 /// Keep track which DISubprogram is attached to which function.
165 DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
166
167 /// For each visited DIScope, whether walking its scope chain reaches a
168 /// repeated node.
169 DenseMap<const Metadata *, bool> DIScopeChainReachesCycle;
170
171 /// Track all DICompileUnits visited.
172 SmallPtrSet<const Metadata *, 2> CUVisited;
173
174 /// The result type for a landingpad.
175 Type *LandingPadResultTy;
176
177 /// Whether we've seen a call to @llvm.localescape in this function
178 /// already.
179 bool SawFrameEscape;
180
181 /// Whether the current function has a DISubprogram attached to it.
182 bool HasDebugInfo = false;
183
184 /// Stores the count of how many objects were passed to llvm.localescape for a
185 /// given function and the largest index passed to llvm.localrecover.
186 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
187
188 // Maps catchswitches and cleanuppads that unwind to siblings to the
189 // terminators that indicate the unwind, used to detect cycles therein.
190 MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
191
192 /// Cache which blocks are in which funclet, if an EH funclet personality is
193 /// in use. Otherwise empty.
194 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
195
196 /// Cache of constants visited in search of ConstantExprs.
197 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
198
199 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
200 SmallVector<const Function *, 4> DeoptimizeDeclarations;
201
202 /// Cache of attribute lists verified.
203 SmallPtrSet<const void *, 32> AttributeListsVisited;
204
205 // Verify that this GlobalValue is only used in this module.
206 // This map is used to avoid visiting uses twice. We can arrive at a user
207 // twice, if they have multiple operands. In particular for very large
208 // constant expressions, we can arrive at a particular user many times.
209 SmallPtrSet<const Value *, 32> GlobalValueVisited;
210
211 // Keeps track of duplicate function argument debug info.
213
214 TBAAVerifier TBAAVerifyHelper;
215 ConvergenceVerifier ConvergenceVerifyHelper;
216
217 /// Kind IDs of target metadata checked on every instruction.
218 unsigned MDAMDGPUExpectedActiveLanes;
219 unsigned MDAMDGPUCFS;
220
221 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls;
222
223 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I);
224
225public:
226 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError,
227 const Module &M)
228 : VerifierSupport(OS, M), LandingPadResultTy(nullptr),
229 SawFrameEscape(false), TBAAVerifyHelper(this),
230 MDAMDGPUExpectedActiveLanes(
231 M.getContext().getMDKindID("amdgpu.expected.active.lanes")),
232 MDAMDGPUCFS(M.getContext().getMDKindID("amdgpu.cfs")) {
233 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
234 }
235
236 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; }
237
238 bool verify(const Function &F) {
239 llvm::TimeTraceScope timeScope("Verifier");
240 assert(F.getParent() == &M &&
241 "An instance of this class only works with a specific module!");
242
243 // First ensure the function is well-enough formed to compute dominance
244 // information, and directly compute a dominance tree. We don't rely on the
245 // pass manager to provide this as it isolates us from a potentially
246 // out-of-date dominator tree and makes it significantly more complex to run
247 // this code outside of a pass manager.
248
249 // First check that every basic block has a terminator, otherwise we can't
250 // even inspect the CFG.
251 for (const BasicBlock &BB : F) {
252 if (!BB.empty() && BB.back().isTerminator())
253 continue;
254
255 if (OS) {
256 *OS << "Basic Block in function '" << F.getName()
257 << "' does not have terminator!\n";
258 BB.printAsOperand(*OS, true, MST);
259 *OS << "\n";
260 }
261 return false;
262 }
263
264 // FIXME: It's really gross that we have to cast away constness here.
265 if (!F.empty())
266 DT.recalculate(const_cast<Function &>(F));
267
268 auto FailureCB = [this](const Twine &Message) {
269 this->CheckFailed(Message);
270 };
271 ConvergenceVerifyHelper.initialize(OS, FailureCB, F);
272
273 Broken = false;
274 // FIXME: We strip const here because the inst visitor strips const.
275 visit(const_cast<Function &>(F));
276 verifySiblingFuncletUnwinds();
277
278 if (ConvergenceVerifyHelper.sawTokens())
279 ConvergenceVerifyHelper.verify(DT);
280
281 InstsInThisBlock.clear();
282 DebugFnArgs.clear();
283 DIScopeChainReachesCycle.clear();
284 LandingPadResultTy = nullptr;
285 SawFrameEscape = false;
286 SiblingFuncletInfo.clear();
287 verifyNoAliasScopeDecl();
288 NoAliasScopeDecls.clear();
289
290 return !Broken;
291 }
292
293 /// Verify the module that this instance of \c Verifier was initialized with.
294 bool verify() {
295 Broken = false;
296
297 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
298 for (const Function &F : M)
299 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
300 DeoptimizeDeclarations.push_back(&F);
301
302 // Now that we've visited every function, verify that we never asked to
303 // recover a frame index that wasn't escaped.
304 verifyFrameRecoverIndices();
305 for (const GlobalVariable &GV : M.globals())
306 visitGlobalVariable(GV);
307
308 for (const GlobalAlias &GA : M.aliases())
309 visitGlobalAlias(GA);
310
311 for (const GlobalIFunc &GI : M.ifuncs())
312 visitGlobalIFunc(GI);
313
314 for (const NamedMDNode &NMD : M.named_metadata())
315 visitNamedMDNode(NMD);
316
317 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
318 visitComdat(SMEC.getValue());
319
320 visitModuleFlags();
321 visitModuleIdents();
322 visitModuleCommandLines();
323 visitModuleErrnoTBAA();
324 visitModuleRawSections();
325
326 verifyCompileUnits();
327
328 verifyDeoptimizeCallingConvs();
329 DISubprogramAttachments.clear();
330 DIScopeChainReachesCycle.clear();
331 return !Broken;
332 }
333
334private:
335 /// Whether a metadata node is allowed to be, or contain, a DILocation.
336 enum class AreDebugLocsAllowed { No, Yes };
337
338 /// Metadata that should be treated as a range, with slightly different
339 /// requirements.
340 enum class RangeLikeMetadataKind {
341 Range, // MD_range
342 AbsoluteSymbol, // MD_absolute_symbol
343 NoaliasAddrspace // MD_noalias_addrspace
344 };
345
346 // Verification methods...
347 void visitGlobalValue(const GlobalValue &GV);
348 void visitGlobalVariable(const GlobalVariable &GV);
349 void visitGlobalAlias(const GlobalAlias &GA);
350 void visitGlobalIFunc(const GlobalIFunc &GI);
351 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
352 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
353 const GlobalAlias &A, const Constant &C);
354 void visitNamedMDNode(const NamedMDNode &NMD);
355 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs);
356 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
357 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
358 void visitDIArgList(const DIArgList &AL, Function *F);
359 void visitComdat(const Comdat &C);
360 void visitModuleIdents();
361 void visitModuleCommandLines();
362 void visitModuleErrnoTBAA();
363 void visitModuleRawSections();
364 void visitModuleFlags();
365 void visitModuleFlag(const MDNode *Op,
366 DenseMap<const MDString *, const MDNode *> &SeenIDs,
367 SmallVectorImpl<const MDNode *> &Requirements);
368 void visitModuleFlagCGProfileEntry(const MDOperand &MDO);
369 void visitFunction(const Function &F);
370 void visitBasicBlock(BasicBlock &BB);
371 void verifyRangeLikeMetadata(const Value &V, const MDNode *Range, Type *Ty,
372 RangeLikeMetadataKind Kind);
373 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty);
374 void visitNoFPClassMetadata(Instruction &I, MDNode *Range, Type *Ty);
375 void visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range, Type *Ty);
376 void visitDereferenceableMetadata(Instruction &I, MDNode *MD);
377 void visitNoFreeObjMetadata(Instruction &I, MDNode *MD);
378 void visitProfMetadata(Instruction &I, MDNode *MD);
379 void visitCallStackMetadata(MDNode *MD);
380 void visitMemProfMetadata(Instruction &I, MDNode *MD);
381 void visitCallsiteMetadata(Instruction &I, MDNode *MD);
382 void visitCalleeTypeMetadata(Instruction &I, MDNode *MD);
383 void visitDIAssignIDMetadata(Instruction &I, MDNode *MD);
384 void visitMMRAMetadata(Instruction &I, MDNode *MD);
385 void visitAnnotationMetadata(MDNode *Annotation);
386 void visitAliasScopeMetadata(const MDNode *MD);
387 void visitAliasScopeListMetadata(const MDNode *MD);
388 void visitAccessGroupMetadata(const MDNode *MD);
389 void visitCapturesMetadata(Instruction &I, const MDNode *Captures);
390 void visitAllocTokenMetadata(Instruction &I, MDNode *MD);
391 void visitInlineHistoryMetadata(Instruction &I, MDNode *MD);
392 void visitMemCacheHintMetadata(Instruction &I, MDNode *MD);
393
394#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
395#include "llvm/IR/Metadata.def"
396 void visitDIType(const DIType &N);
397 void visitDIScope(const DIScope &N);
398 void visitDIScopeChain(const DIScope &N);
399 bool hasDIScopeCycle(const Metadata *S);
400 DISubprogram *getSubprogram(Metadata *LocalScope);
401 void visitDIVariable(const DIVariable &N);
402 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
403 void visitDITemplateParameter(const DITemplateParameter &N);
404
405 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
406
407 void visit(DbgLabelRecord &DLR);
408 void visit(DbgVariableRecord &DVR);
409 // InstVisitor overrides...
410 using InstVisitor<Verifier>::visit;
411 void visitDbgRecords(Instruction &I);
412 void visit(Instruction &I);
413
414 void visitTruncInst(TruncInst &I);
415 void visitZExtInst(ZExtInst &I);
416 void visitSExtInst(SExtInst &I);
417 void visitFPTruncInst(FPTruncInst &I);
418 void visitFPExtInst(FPExtInst &I);
419 void visitFPToUIInst(FPToUIInst &I);
420 void visitFPToSIInst(FPToSIInst &I);
421 void visitUIToFPInst(UIToFPInst &I);
422 void visitSIToFPInst(SIToFPInst &I);
423 void visitIntToPtrInst(IntToPtrInst &I);
424 void checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V);
425 void visitPtrToAddrInst(PtrToAddrInst &I);
426 void visitPtrToIntInst(PtrToIntInst &I);
427 void visitBitCastInst(BitCastInst &I);
428 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
429 void visitPHINode(PHINode &PN);
430 void visitCallBase(CallBase &Call);
431 void visitUnaryOperator(UnaryOperator &U);
432 void visitBinaryOperator(BinaryOperator &B);
433 void visitICmpInst(ICmpInst &IC);
434 void visitFCmpInst(FCmpInst &FC);
435 void visitExtractElementInst(ExtractElementInst &EI);
436 void visitInsertElementInst(InsertElementInst &EI);
437 void visitShuffleVectorInst(ShuffleVectorInst &EI);
438 void visitBitInsertInst(BitInsertInst &BII);
439 void visitBitExtractInst(BitExtractInst &BEI);
440 void visitVAArgInst(VAArgInst &VAA);
441 void visitCallInst(CallInst &CI);
442 void visitInvokeInst(InvokeInst &II);
443 void checkGEPOperator(const GEPOperator &GEP);
444 void visitGetElementPtrInst(GetElementPtrInst &GEP);
445 void visitLoadInst(LoadInst &LI);
446 void visitStoreInst(StoreInst &SI);
447 void verifyDominatesUse(Instruction &I, unsigned i);
448 void visitInstruction(Instruction &I);
449 void visitTerminator(Instruction &I);
450 void visitCondBrInst(CondBrInst &BI);
451 void visitReturnInst(ReturnInst &RI);
452 void visitSwitchInst(SwitchInst &SI);
453 void visitIndirectBrInst(IndirectBrInst &BI);
454 void visitCallBrInst(CallBrInst &CBI);
455 void visitSelectInst(SelectInst &SI);
456 void visitUserOp1(Instruction &I);
457 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
458 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call);
459 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
460 void visitVPIntrinsic(VPIntrinsic &VPI);
461 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
462 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
463 void visitFenceInst(FenceInst &FI);
464 void visitAllocaInst(AllocaInst &AI);
465 void visitExtractValueInst(ExtractValueInst &EVI);
466 void visitInsertValueInst(InsertValueInst &IVI);
467 void visitEHPadPredecessors(Instruction &I);
468 void visitLandingPadInst(LandingPadInst &LPI);
469 void visitResumeInst(ResumeInst &RI);
470 void visitCatchPadInst(CatchPadInst &CPI);
471 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
472 void visitCleanupPadInst(CleanupPadInst &CPI);
473 void visitFuncletPadInst(FuncletPadInst &FPI);
474 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
475 void visitCleanupReturnInst(CleanupReturnInst &CRI);
476
477 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal);
478 void verifySwiftErrorValue(const Value *SwiftErrorVal);
479 void verifyTailCCMustTailAttrs(const AttrBuilder &Attrs, StringRef Context);
480 void verifyMustTailCall(CallInst &CI);
481 bool verifyAttributeCount(AttributeList Attrs, unsigned Params);
482 void verifyAttributeTypes(AttributeSet Attrs, const Value *V);
483 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V);
484 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
485 const Value *V);
486 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
487 const Value *V, bool IsIntrinsic, bool IsInlineAsm);
488 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs);
489 void verifyUnknownProfileMetadata(MDNode *MD);
490 void visitConstantExprsRecursively(const Constant *EntryC);
491 void visitConstantExpr(const ConstantExpr *CE);
492 void visitConstantPtrAuth(const ConstantPtrAuth *CPA);
493 void verifyInlineAsmCall(const CallBase &Call);
494 void verifyStatepoint(const CallBase &Call);
495 void verifyFrameRecoverIndices();
496 void verifySiblingFuncletUnwinds();
497
498 void verifyFragmentExpression(const DbgVariableRecord &I);
499 template <typename ValueOrMetadata>
500 void verifyFragmentExpression(const DIVariable &V,
502 ValueOrMetadata *Desc);
503 void verifyFnArgs(const DbgVariableRecord &DVR);
504 void verifyNotEntryValue(const DbgVariableRecord &I);
505
506 /// Module-level debug info verification...
507 void verifyCompileUnits();
508
509 /// Module-level verification that all @llvm.experimental.deoptimize
510 /// declarations share the same calling convention.
511 void verifyDeoptimizeCallingConvs();
512
513 void verifyAttachedCallBundle(const CallBase &Call,
514 const OperandBundleUse &BU);
515
516 /// Verify the llvm.experimental.noalias.scope.decl declarations
517 void verifyNoAliasScopeDecl();
518};
519
520} // end anonymous namespace
521
522/// We know that cond should be true, if not print an error message.
523#define Check(C, ...) \
524 do { \
525 if (!(C)) { \
526 CheckFailed(__VA_ARGS__); \
527 return; \
528 } \
529 } while (false)
530
531/// We know that a debug info condition should be true, if not print
532/// an error message.
533#define CheckDI(C, ...) \
534 do { \
535 if (!(C)) { \
536 DebugInfoCheckFailed(__VA_ARGS__); \
537 return; \
538 } \
539 } while (false)
540
541void Verifier::visitDbgRecords(Instruction &I) {
542 if (!I.getDbgMarker())
543 return;
544 CheckDI(I.getDbgMarker()->MarkedInstr == &I,
545 "Instruction has invalid DebugMarker", &I);
546 CheckDI(!isa<PHINode>(&I) || !I.hasDbgRecords(),
547 "PHI Node must not have any attached DbgRecords", &I);
548 for (DbgRecord &DR : I.getDbgRecordRange()) {
549 CheckDI(DR.getMarker() == I.getDbgMarker(),
550 "DbgRecord had invalid DebugMarker", &I, &DR);
551 if (auto *Loc =
552 dyn_cast_or_null<DILocation>(DR.getDebugLoc().getAsMDNode()))
553 visitMDNode(*Loc, AreDebugLocsAllowed::Yes);
554 if (auto *DVR = dyn_cast<DbgVariableRecord>(&DR)) {
555 visit(*DVR);
556 // These have to appear after `visit` for consistency with existing
557 // intrinsic behaviour.
558 verifyFragmentExpression(*DVR);
559 verifyNotEntryValue(*DVR);
560 } else if (auto *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
561 visit(*DLR);
562 }
563 }
564}
565
566void Verifier::visit(Instruction &I) {
567 visitDbgRecords(I);
568 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
569 Check(I.getOperand(i) != nullptr, "Operand is null", &I);
571}
572
573// Helper to iterate over indirect users. By returning false, the callback can ask to stop traversing further.
574static void forEachUser(const Value *User,
576 llvm::function_ref<bool(const Value *)> Callback) {
577 if (!Visited.insert(User).second)
578 return;
579
581 while (!WorkList.empty()) {
582 const Value *Cur = WorkList.pop_back_val();
583 if (!Visited.insert(Cur).second)
584 continue;
585 if (Callback(Cur))
586 append_range(WorkList, Cur->materialized_users());
587 }
588}
589
590void Verifier::visitGlobalValue(const GlobalValue &GV) {
592 "Global is external, but doesn't have external or weak linkage!", &GV);
593
594 if (const auto *GO = dyn_cast<GlobalObject>(&GV)) {
595 if (const MDNode *Associated =
596 GO->getMetadata(LLVMContext::MD_associated)) {
597 Check(Associated->getNumOperands() == 1,
598 "associated metadata must have one operand", &GV, Associated);
599 const Metadata *Op = Associated->getOperand(0).get();
600 Check(Op, "associated metadata must have a global value", GO, Associated);
601
602 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
603 Check(VM, "associated metadata must be ValueAsMetadata", GO, Associated);
604 if (VM) {
605 Check(isa<PointerType>(VM->getValue()->getType()),
606 "associated value must be pointer typed", GV, Associated);
607
608 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
609 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
610 "associated metadata must point to a GlobalObject", GO, Stripped);
611 Check(Stripped != GO,
612 "global values should not associate to themselves", GO,
613 Associated);
614 }
615 }
616
617 // FIXME: Why is getMetadata on GlobalValue protected?
618 if (const MDNode *AbsoluteSymbol =
619 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
620 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
621 DL.getIntPtrType(GO->getType()),
622 RangeLikeMetadataKind::AbsoluteSymbol);
623 }
624
625 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
626 Check(!GO->isDeclaration(),
627 "ref metadata must not be placed on a declaration", GO);
628
630 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
631 for (const MDNode *MD : MDs) {
632 Check(MD->getNumOperands() == 1, "ref metadata must have one operand",
633 &GV, MD);
634 const Metadata *Op = MD->getOperand(0).get();
635 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(Op);
636 Check(VM, "ref metadata must be ValueAsMetadata", GO, MD);
637 if (VM) {
638 Check(isa<PointerType>(VM->getValue()->getType()),
639 "ref value must be pointer typed", GV, MD);
640
641 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
642 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
643 "ref metadata must point to a GlobalObject", GO, Stripped);
644 Check(Stripped != GO, "values should not reference themselves", GO,
645 MD);
646 }
647 }
648 }
649
650 if (auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
651 Check(Props->getNumOperands() == 2,
652 "elf_section_properties metadata must have two operands", GO,
653 Props);
654 if (Props->getNumOperands() == 2) {
655 auto *Type = dyn_cast<ConstantAsMetadata>(Props->getOperand(0));
656 Check(Type, "type field must be ConstantAsMetadata", GO, Props);
657 auto *TypeInt = dyn_cast<ConstantInt>(Type->getValue());
658 Check(TypeInt, "type field must be ConstantInt", GO, Props);
659
660 auto *Entsize = dyn_cast<ConstantAsMetadata>(Props->getOperand(1));
661 Check(Entsize, "entsize field must be ConstantAsMetadata", GO, Props);
662 auto *EntsizeInt = dyn_cast<ConstantInt>(Entsize->getValue());
663 Check(EntsizeInt, "entsize field must be ConstantInt", GO, Props);
664 }
665 }
666 }
667
669 "Only global variables can have appending linkage!", &GV);
670
671 if (GV.hasAppendingLinkage()) {
672 const auto *GVar = dyn_cast<GlobalVariable>(&GV);
673 Check(GVar && GVar->getValueType()->isArrayTy(),
674 "Only global arrays can have appending linkage!", GVar);
675 }
676
677 if (GV.isDeclarationForLinker())
678 Check(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
679
680 if (GV.hasDLLExportStorageClass()) {
682 "dllexport GlobalValue must have default or protected visibility",
683 &GV);
684 }
685 if (GV.hasDLLImportStorageClass()) {
687 "dllimport GlobalValue must have default visibility", &GV);
688 Check(!GV.isDSOLocal(), "GlobalValue with DLLImport Storage is dso_local!",
689 &GV);
690
691 Check((GV.isDeclaration() &&
694 "Global is marked as dllimport, but not external", &GV);
695 }
696
697 if (GV.isImplicitDSOLocal())
698 Check(GV.isDSOLocal(),
699 "GlobalValue with local linkage or non-default "
700 "visibility must be dso_local!",
701 &GV);
702
703 // Constant::removeDeadConstantUsers skips the use-list walk for globals
704 // that are not marked as possibly having constant users.
705 if (!GV.mayHaveConstantUsers())
706 for (const User *U : GV.materialized_users())
708 "Global is used by a constant but is not marked as possibly having "
709 "constant users",
710 &GV, U);
711
712 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool {
713 if (const auto *I = dyn_cast<Instruction>(V)) {
714 if (!I->getParent() || !I->getParent()->getParent())
715 CheckFailed("Global is referenced by parentless instruction!", &GV, &M,
716 I);
717 else if (I->getParent()->getParent()->getParent() != &M)
718 CheckFailed("Global is referenced in a different module!", &GV, &M, I,
719 I->getParent()->getParent(),
720 I->getParent()->getParent()->getParent());
721 return false;
722 } else if (const auto *F = dyn_cast<Function>(V)) {
723 if (F->getParent() != &M)
724 CheckFailed("Global is used by function in a different module", &GV, &M,
725 F, F->getParent());
726 return false;
727 }
728 return true;
729 });
730}
731
732void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
733 // Target-specific global variable checks. Done first because this function
734 // returns early for a global without an initializer.
736
737 Type *GVType = GV.getValueType();
738
739 if (MaybeAlign A = GV.getAlign()) {
740 Check(A->value() <= Value::MaximumAlignment,
741 "huge alignment values are unsupported", &GV);
742 }
743
744 if (GV.hasInitializer()) {
745 Check(GV.getInitializer()->getType() == GVType,
746 "Global variable initializer type does not match global "
747 "variable type!",
748 &GV);
750 "Global variable initializer must be sized", &GV);
751 visitConstantExprsRecursively(GV.getInitializer());
752 // If the global has common linkage, it must have a zero initializer and
753 // cannot be constant.
754 if (GV.hasCommonLinkage()) {
756 "'common' global must have a zero initializer!", &GV);
757 Check(!GV.isConstant(), "'common' global may not be marked constant!",
758 &GV);
759 Check(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
760 }
761 }
762
763 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
764 GV.getName() == "llvm.global_dtors")) {
766 "invalid linkage for intrinsic global variable", &GV);
768 "invalid uses of intrinsic global variable", &GV);
769
770 // Don't worry about emitting an error for it not being an array,
771 // visitGlobalValue will complain on appending non-array.
772 if (const auto *ATy = dyn_cast<ArrayType>(GVType)) {
773 const auto *STy = dyn_cast<StructType>(ATy->getElementType());
774 PointerType *FuncPtrTy =
775 PointerType::get(Context, DL.getProgramAddressSpace());
776 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
777 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
778 STy->getTypeAtIndex(1) == FuncPtrTy,
779 "wrong type for intrinsic global variable", &GV);
780 Check(STy->getNumElements() == 3,
781 "the third field of the element type is mandatory, "
782 "specify ptr null to migrate from the obsoleted 2-field form");
783 Type *ETy = STy->getTypeAtIndex(2);
784 Check(ETy->isPointerTy(), "wrong type for intrinsic global variable",
785 &GV);
786 }
787
788 auto *Init = GV.hasInitializer()
790 : nullptr;
791 if (Init) {
792 for (const Use &U : Init->operands()) {
793 auto *Structor = dyn_cast<ConstantStruct>(U);
794 if (!Structor || Structor->getNumOperands() != 3)
795 continue;
796 Check(!isa<ConstantPtrAuth>(Structor->getOperand(1)),
797 "signing of ctors/dtors should be requested via module flags");
798 }
799 }
800 }
801
802 if (GV.hasName() && (GV.getName() == "llvm.used" ||
803 GV.getName() == "llvm.compiler.used")) {
805 "invalid linkage for intrinsic global variable", &GV);
807 "invalid uses of intrinsic global variable", &GV);
808
809 if (const auto *ATy = dyn_cast<ArrayType>(GVType)) {
810 const auto *PTy = dyn_cast<PointerType>(ATy->getElementType());
811 Check(PTy, "wrong type for intrinsic global variable", &GV);
812 if (GV.hasInitializer()) {
813 const Constant *Init = GV.getInitializer();
814 const auto *InitArray = dyn_cast<ConstantArray>(Init);
815 Check(InitArray, "wrong initializer for intrinsic global variable",
816 Init);
817 for (Value *Op : InitArray->operands()) {
818 Value *V = Op->stripPointerCasts();
821 Twine("invalid ") + GV.getName() + " member", V);
822 Check(V->hasName(),
823 Twine("members of ") + GV.getName() + " must be named", V);
824 }
825 }
826 }
827 }
828
829 // Visit any debug info attachments.
831 GV.getMetadata(LLVMContext::MD_dbg, MDs);
832 for (MDNode *MD : MDs) {
833 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
834 visitDIGlobalVariableExpression(*GVE);
835 else
836 CheckDI(false, "!dbg attachment of global variable must be a "
837 "DIGlobalVariableExpression");
838 }
839
840 // Scalable vectors cannot be global variables, since we don't know
841 // the runtime size.
842 Check(!GVType->isScalableTy(), "Globals cannot contain scalable types", &GV);
843
844 // Check if it is or contains a target extension type that disallows being
845 // used as a global.
847 "Global @" + GV.getName() + " has illegal target extension type",
848 GVType);
849
850 // Check that the the address space can hold all bits of the type, recognized
851 // by an access in the address space being able to reach all bytes of the
852 // type.
853 Check(!GVType->isSized() ||
854 isUIntN(DL.getAddressSizeInBits(GV.getAddressSpace()),
855 GV.getGlobalSize(DL)),
856 "Global variable is too large to fit into the address space", &GV,
857 GVType);
858
859 if (!GV.hasInitializer()) {
860 visitGlobalValue(GV);
861 return;
862 }
863
864 // Walk any aggregate initializers looking for bitcasts between address spaces
865 visitConstantExprsRecursively(GV.getInitializer());
866
867 visitGlobalValue(GV);
868}
869
870void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
871 SmallPtrSet<const GlobalAlias*, 4> Visited;
872 Visited.insert(&GA);
873 visitAliaseeSubExpr(Visited, GA, C);
874}
875
876void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
877 const GlobalAlias &GA, const Constant &C) {
880 cast<GlobalValue>(C).hasAvailableExternallyLinkage(),
881 "available_externally alias must point to available_externally "
882 "global value",
883 &GA);
884 }
885 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
887 Check(!GV->isDeclarationForLinker(), "Alias must point to a definition",
888 &GA);
889 }
890
891 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
892 Check(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
893
894 Check(!GA2->isInterposable(),
895 "Alias cannot point to an interposable alias", &GA);
896 } else {
897 // Only continue verifying subexpressions of GlobalAliases.
898 // Do not recurse into global initializers.
899 return;
900 }
901 }
902
903 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
904 visitConstantExprsRecursively(CE);
905
906 for (const Use &U : C.operands()) {
907 Value *V = &*U;
908 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
909 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
910 else if (const auto *C2 = dyn_cast<Constant>(V))
911 visitAliaseeSubExpr(Visited, GA, *C2);
912 }
913}
914
915void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
917 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
918 "weak_odr, external, or available_externally linkage!",
919 &GA);
920 const Constant *Aliasee = GA.getAliasee();
921 Check(Aliasee, "Aliasee cannot be NULL!", &GA);
922 Check(GA.getType() == Aliasee->getType(),
923 "Alias and aliasee types should match!", &GA);
924
925 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
926 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
927
928 visitAliaseeSubExpr(GA, *Aliasee);
929
930 visitGlobalValue(GA);
931}
932
933void Verifier::visitGlobalIFunc(const GlobalIFunc &GI) {
934 visitGlobalValue(GI);
935
937 GI.getAllMetadata(MDs);
938 for (const auto &I : MDs) {
939 CheckDI(I.first != LLVMContext::MD_dbg,
940 "an ifunc may not have a !dbg attachment", &GI);
941 Check(I.first != LLVMContext::MD_prof,
942 "an ifunc may not have a !prof attachment", &GI);
943 visitMDNode(*I.second, AreDebugLocsAllowed::No);
944 }
945
947 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
948 "weak_odr, or external linkage!",
949 &GI);
950 // Pierce through ConstantExprs and GlobalAliases and check that the resolver
951 // is a Function definition.
952 const Function *Resolver = GI.getResolverFunction();
953 Check(Resolver, "IFunc must have a Function resolver", &GI);
954 Check(!Resolver->isDeclarationForLinker(),
955 "IFunc resolver must be a definition", &GI);
956
957 // Check that the immediate resolver operand (prior to any bitcasts) has the
958 // correct type.
959 const Type *ResolverTy = GI.getResolver()->getType();
960
962 "IFunc resolver must return a pointer", &GI);
963
964 Check(ResolverTy == PointerType::get(Context, GI.getAddressSpace()),
965 "IFunc resolver has incorrect type", &GI);
966}
967
968void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
969 // There used to be various other llvm.dbg.* nodes, but we don't support
970 // upgrading them and we want to reserve the namespace for future uses.
971 if (NMD.getName().starts_with("llvm.dbg."))
972 CheckDI(NMD.getName() == "llvm.dbg.cu",
973 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
974 for (const MDNode *MD : NMD.operands()) {
975 if (NMD.getName() == "llvm.dbg.cu")
976 CheckDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
977
978 if (!MD)
979 continue;
980
981 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
982 }
983}
984
985/// Parent scope operand of \p S, or null if \p S has no parent (a \c DIFile,
986/// \c DICompileUnit, or non-scope). Mirrors \c DIScope::getScope() without
987/// asserting on unexpected metadata kinds.
988static const Metadata *getRawDIScopeParent(const Metadata *S) {
989 if (!S)
990 return nullptr;
991 if (auto *T = dyn_cast<DIType>(S))
992 return T->getRawScope();
993 if (auto *SP = dyn_cast<DISubprogram>(S))
994 return SP->getRawScope();
995 if (auto *LB = dyn_cast<DILexicalBlockBase>(S))
996 return LB->getRawScope();
997 if (auto *NS = dyn_cast<DINamespace>(S))
998 return NS->getRawScope();
999 if (auto *CB = dyn_cast<DICommonBlock>(S))
1000 return CB->getRawScope();
1001 if (auto *M = dyn_cast<DIModule>(S))
1002 return M->getRawScope();
1003 return nullptr;
1004}
1005
1006/// True if following the scope operand from \p S repeats a node.
1007bool Verifier::hasDIScopeCycle(const Metadata *S) {
1008 SmallPtrSet<const Metadata *, 8> Seen;
1009 auto CacheSeen = [&](bool HasCycle) {
1010 for (const Metadata *M : Seen)
1011 DIScopeChainReachesCycle[M] = HasCycle;
1012 return HasCycle;
1013 };
1014
1015 while (auto *Scope = dyn_cast_or_null<DIScope>(S)) {
1016 auto It = DIScopeChainReachesCycle.find(Scope);
1017 bool IsInCache = It != DIScopeChainReachesCycle.end();
1018 if (IsInCache)
1019 return CacheSeen(It->second);
1020 bool AlreadySeen = !Seen.insert(Scope).second;
1021 if (AlreadySeen) // New cycle detected
1022 return CacheSeen(true);
1023 // No new cycle detected
1024 S = getRawDIScopeParent(Scope);
1025 }
1026
1027 // Finished walking node chain without detecting any cycles
1028 return CacheSeen(false);
1029}
1030
1031void Verifier::visitDIScopeChain(const DIScope &N) {
1032 CheckDI(!hasDIScopeCycle(&N), "DIScope scope chain must not contain a cycle",
1033 &N);
1034}
1035
1036void Verifier::visitMDNode(const MDNode &BaseMD,
1037 AreDebugLocsAllowed AllowLocs) {
1038 // Only visit each node once. Metadata can be mutually recursive, so this
1039 // avoids infinite recursion here, as well as being an optimization.
1040 if (!MDNodes.insert(&BaseMD).second)
1041 return;
1042
1043 std::queue<const MDNode *> Worklist;
1044 Worklist.push(&BaseMD);
1045
1046 while (!Worklist.empty()) {
1047 const MDNode *CurrentMD = Worklist.front();
1048 Worklist.pop();
1049 Check(&CurrentMD->getContext() == &Context,
1050 "MDNode context does not match Module context!", CurrentMD);
1051
1052 switch (CurrentMD->getMetadataID()) {
1053 default:
1054 llvm_unreachable("Invalid MDNode subclass");
1055 case Metadata::MDTupleKind:
1056 break;
1057#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1058 case Metadata::CLASS##Kind: \
1059 visit##CLASS(cast<CLASS>(*CurrentMD)); \
1060 break;
1061#include "llvm/IR/Metadata.def"
1062 }
1063
1064 // A scope chain must terminate.
1065 if (const auto *S = dyn_cast<DIScope>(CurrentMD))
1066 visitDIScopeChain(*S);
1067
1068 for (const Metadata *Op : CurrentMD->operands()) {
1069 if (!Op)
1070 continue;
1071 Check(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
1072 CurrentMD, Op);
1073 CheckDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes,
1074 "DILocation not allowed within this metadata node", CurrentMD,
1075 Op);
1076 if (auto *N = dyn_cast<MDNode>(Op)) {
1077 if (MDNodes.insert(N).second)
1078 Worklist.push(N);
1079 continue;
1080 }
1081 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
1082 visitValueAsMetadata(*V, nullptr);
1083 continue;
1084 }
1085 }
1086
1087 // FIXME: The nested llvm.loop.* property tags (llvm.loop.align,
1088 // llvm.loop.estimated_trip_count, the boolean enable/disable tags below)
1089 // are only meaningful as operands of an llvm.loop node. Neither llvm.loop's
1090 // structure nor the requirement that these tags appear only within it is
1091 // validated here; the checks below fire on any matching tuple regardless of
1092 // where it appears.
1093
1094 // Check llvm.loop.estimated_trip_count.
1095 if (CurrentMD->getNumOperands() > 0 &&
1097 Check(CurrentMD->getNumOperands() == 2, "Expected two operands",
1098 CurrentMD);
1099 auto *Count =
1101 Check(Count && Count->getType()->isIntegerTy() &&
1102 cast<IntegerType>(Count->getType())->getBitWidth() <= 32,
1103 "Expected second operand to be an integer constant of type i32 or "
1104 "smaller",
1105 CurrentMD);
1106 }
1107
1108 // Check llvm.loop.align.
1109 if (CurrentMD->getNumOperands() > 0 &&
1110 CurrentMD->getOperand(0).equalsStr("llvm.loop.align")) {
1111 Check(CurrentMD->getNumOperands() == 2, "Expected two operands",
1112 CurrentMD);
1113 auto *AlignMD =
1115 Check(AlignMD && AlignMD->getType()->isIntegerTy(32),
1116 "Expected the alignment to be an integer constant of type i32",
1117 CurrentMD);
1118 if (AlignMD) {
1119 uint64_t Align = AlignMD->getValue().getZExtValue();
1120 Check(isPowerOf2_64(Align),
1121 "Expected the alignment to be a power of two", CurrentMD);
1122 Check(Align <= Value::MaximumAlignment,
1123 "Alignment is larger than the implementation defined limit",
1124 CurrentMD);
1125 }
1126 }
1127
1128 // Enforce the single-operand form of the loop enable/disable pairs.
1129 if (CurrentMD->getNumOperands() > 0 &&
1130 any_of(OldBooleanLoopTags, [CurrentMD](const BooleanLoopTags &Tags) {
1131 return CurrentMD->getOperand(0).equalsStr(Tags.Enable) ||
1132 CurrentMD->getOperand(0).equalsStr(Tags.Disable);
1133 }))
1134 Check(CurrentMD->getNumOperands() == 1,
1135 "Expecting only the metadata name", CurrentMD);
1136
1137 // Check these last, so we diagnose problems in operands first.
1138 Check(!CurrentMD->isTemporary(), "Expected no forward declarations!",
1139 CurrentMD);
1140 Check(CurrentMD->isResolved(), "All nodes should be resolved!", CurrentMD);
1141 }
1142}
1143
1144void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
1145 Check(MD.getValue(), "Expected valid value", &MD);
1146 Check(!MD.getValue()->getType()->isMetadataTy(),
1147 "Unexpected metadata round-trip through values", &MD, MD.getValue());
1148
1149 auto *L = dyn_cast<LocalAsMetadata>(&MD);
1150 if (!L)
1151 return;
1152
1153 Check(F, "function-local metadata used outside a function", L);
1154
1155 // If this was an instruction, bb, or argument, verify that it is in the
1156 // function that we expect.
1157 Function *ActualF = nullptr;
1158 if (auto *I = dyn_cast<Instruction>(L->getValue())) {
1159 Check(I->getParent(), "function-local metadata not in basic block", L, I);
1160 ActualF = I->getParent()->getParent();
1161 } else if (auto *BB = dyn_cast<BasicBlock>(L->getValue())) {
1162 ActualF = BB->getParent();
1163 } else if (auto *A = dyn_cast<Argument>(L->getValue())) {
1164 ActualF = A->getParent();
1165 }
1166 assert(ActualF && "Unimplemented function local metadata case!");
1167
1168 Check(ActualF == F, "function-local metadata used in wrong function", L);
1169}
1170
1171void Verifier::visitDIArgList(const DIArgList &AL, Function *F) {
1172 for (const ValueAsMetadata *VAM : AL.getArgs())
1173 visitValueAsMetadata(*VAM, F);
1174}
1175
1176void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
1177 Metadata *MD = MDV.getMetadata();
1178 if (auto *N = dyn_cast<MDNode>(MD)) {
1179 visitMDNode(*N, AreDebugLocsAllowed::No);
1180 return;
1181 }
1182
1183 // Only visit each node once. Metadata can be mutually recursive, so this
1184 // avoids infinite recursion here, as well as being an optimization.
1185 if (!MDNodes.insert(MD).second)
1186 return;
1187
1188 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
1189 visitValueAsMetadata(*V, F);
1190
1191 if (auto *AL = dyn_cast<DIArgList>(MD))
1192 visitDIArgList(*AL, F);
1193}
1194
1195static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); }
1196static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); }
1197static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); }
1198static bool isMDTuple(const Metadata *MD) { return !MD || isa<MDTuple>(MD); }
1199
1200void Verifier::visitMDFunctionLocalContext(const MDFunctionLocalContext &N) {
1201 for (auto [Idx, Scope] : enumerate(N.getScopes()))
1202 CheckDI(Scope.get(), "MDFunctionLocalContext contains invalid scope", &N,
1203 Idx);
1204 for (auto [Idx, InlinedCall] : enumerate(N.getInlinedCalls()))
1205 CheckDI(InlinedCall.getInlinee(),
1206 "MDFunctionLocalContext contains InlinedCall with invalid "
1207 "InlineeContext",
1208 &N, Idx);
1209 bool IsNonDebugFLContext = N.isNonDebug();
1210 if (IsNonDebugFLContext) {
1211 CheckDI(N.getScopes().empty(),
1212 "MDFunctionLocalContext that is NonDebug must contain no scopes",
1213 &N);
1214 CheckDI(N.getSrcLocs().empty(),
1215 "MDFunctionLocalContext that is NonDebug must contain no srcLocs",
1216 &N);
1217 CheckDI(!N.getInlinedCalls().empty(),
1218 "MDFunctionLocalContext that is NonDebug must contain at least one "
1219 "inlined call",
1220 &N);
1221 } else {
1222 CheckDI(!N.getScopes().empty(),
1223 "An MDFunctionLocalContext that is not NonDebug must contain its "
1224 "function's subprogram as the first scope",
1225 &N);
1226 CheckDI(isa<DISubprogram>(N.getScopes()[0].get()),
1227 "The first scope in an MDFunctionLocalContext with debug info must "
1228 "be the function DISubprogram",
1229 &N, N.getScopes()[0].get());
1230
1231 DISubprogram *FnSP = cast<DISubprogram>(N.getScope(0).get());
1232 // Validate scopes.
1233 for (FLScope Scope : drop_begin(N.getScopes())) {
1235 "DISubprogram should only appear as the first scope in a "
1236 "function-local context",
1237 Scope, FnSP, &N);
1238 CheckDI(Scope.get()->getSubprogram() == FnSP,
1239 "scope in function-local context points at wrong subprogram for "
1240 "function",
1241 Scope, FnSP, &N);
1242 }
1243
1244 // Validate indexes for SrcLocs and InlinedCalls.
1245 for (FLSrcLoc SrcLoc : N.getSrcLocs())
1246 CheckDI(SrcLoc.ScopeIdx.get() < N.getScopes().size(),
1247 "FLSrcLoc has invalid ScopeIdx", SrcLoc.ScopeIdx.get(), &N);
1248 }
1249 for (auto [Idx, InlinedCall] : enumerate(N.getInlinedCalls())) {
1250 if (!InlinedCall.SrcLocIdx) {
1251 CheckDI(IsNonDebugFLContext && !InlinedCall.isInlined(),
1252 "FLInlinedCall must have a SrcLocIdx unless it is a nodebug "
1253 "inlined call",
1254 &N);
1255 continue;
1256 }
1257 if (InlinedCall.isInlined()) {
1258 CheckDI(InlinedCall.InlinedAtIdx.get() < Idx,
1259 "FLInlinedCall's InlinedAtIdx cannot point to a later "
1260 "FLInlinedCall entry",
1261 InlinedCall.InlinedAtIdx.get(), &N);
1262 auto *InlinedFLMD = InlinedCall.getInlinedAt(&N).InlineeContext;
1263 CheckDI(InlinedCall.SrcLocIdx.get() < InlinedFLMD->getSrcLocs().size(),
1264 "Inlined FLInlinedCall has invalid SrcLocIdx",
1265 InlinedCall.SrcLocIdx.get(), &N, InlinedFLMD);
1266 } else {
1267 CheckDI(InlinedCall.SrcLocIdx.get() < N.getSrcLocs().size(),
1268 "FLInlinedCall has invalid SrcLocIdx",
1269 InlinedCall.SrcLocIdx.get(), &N);
1270 }
1271 }
1272 // Visit referenced MDNodes from here; most of the actual validation for the
1273 // contents of this class happen in vistFunction, where we have more context.
1274 SmallVector<const MDNode *> NodesToVisit;
1275 N.getUsedMDNodes(NodesToVisit);
1276 for (auto *Node : NodesToVisit)
1277 visitMDNode(*Node, AreDebugLocsAllowed::No);
1278}
1279
1280void Verifier::visitDILocation(const DILocation &N) {
1281 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1282 "location requires a valid scope", &N, N.getRawScope());
1283 if (auto *IA = N.getRawInlinedAt())
1284 CheckDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
1285 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1286 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1287 if (auto *L = N.getRawIRLayers())
1288 CheckDI(isa<DILayerLocList>(L), "irlayers must be a DILayerLocList", &N, L);
1289}
1290
1291void Verifier::visitDILayerLoc(const DILayerLoc &N) {
1292 CheckDI(isa_and_nonnull<MDString>(N.getRawKind()),
1293 "layer kind must be a non-null MDString", &N, N.getRawKind());
1294 CheckDI(isa_and_nonnull<DIFile>(N.getRawFile()),
1295 "layer file must be a non-null DIFile", &N, N.getRawFile());
1296}
1297
1298void Verifier::visitDILayerLocList(const DILayerLocList &N) {
1299 CheckDI(N.getNumLayers() > 0, "DILayerLocList must be non-empty", &N);
1300 for (const MDOperand &Op : N.layers())
1302 "DILayerLocList entry must be a DILayerLoc", &N, Op.get());
1303}
1304
1305void Verifier::visitGenericDINode(const GenericDINode &N) {
1306 CheckDI(N.getTag(), "invalid tag", &N);
1307}
1308
1309void Verifier::visitDIScope(const DIScope &N) {
1310 if (auto *F = N.getRawFile())
1311 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1312}
1313
1314void Verifier::visitDIType(const DIType &N) {
1315 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1316 visitDIScope(N);
1317 CheckDI(N.getRawFile() || N.getLine() == 0, "line specified with no file", &N,
1318 N.getLine());
1319}
1320
1321void Verifier::visitDISubrangeType(const DISubrangeType &N) {
1322 visitDIType(N);
1323
1324 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1325 auto *BaseType = N.getRawBaseType();
1326 CheckDI(!BaseType || isType(BaseType), "BaseType must be a type");
1327 auto *LBound = N.getRawLowerBound();
1328 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1329 isa<DIVariable>(LBound) || isa<DIExpression>(LBound) ||
1330 isa<DIDerivedType>(LBound),
1331 "LowerBound must be signed constant or DIVariable or DIExpression or "
1332 "DIDerivedType",
1333 &N);
1334 auto *UBound = N.getRawUpperBound();
1335 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1336 isa<DIVariable>(UBound) || isa<DIExpression>(UBound) ||
1337 isa<DIDerivedType>(UBound),
1338 "UpperBound must be signed constant or DIVariable or DIExpression or "
1339 "DIDerivedType",
1340 &N);
1341 auto *Stride = N.getRawStride();
1342 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1343 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1344 "Stride must be signed constant or DIVariable or DIExpression", &N);
1345 auto *Bias = N.getRawBias();
1346 CheckDI(!Bias || isa<ConstantAsMetadata>(Bias) || isa<DIVariable>(Bias) ||
1347 isa<DIExpression>(Bias),
1348 "Bias must be signed constant or DIVariable or DIExpression", &N);
1349 // Subrange types currently only support constant size.
1350 auto *Size = N.getRawSizeInBits();
1352 "SizeInBits must be a constant");
1353}
1354
1355void Verifier::visitDISubrange(const DISubrange &N) {
1356 CheckDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
1357 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1358 "Subrange can have any one of count or upperBound", &N);
1359 auto *CBound = N.getRawCountNode();
1360 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1361 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1362 "Count must be signed constant or DIVariable or DIExpression", &N);
1363 auto Count = N.getCount();
1365 cast<ConstantInt *>(Count)->getSExtValue() >= -1,
1366 "invalid subrange count", &N);
1367 auto *LBound = N.getRawLowerBound();
1368 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1369 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1370 "LowerBound must be signed constant or DIVariable or DIExpression",
1371 &N);
1372 auto *UBound = N.getRawUpperBound();
1373 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1374 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1375 "UpperBound must be signed constant or DIVariable or DIExpression",
1376 &N);
1377 auto *Stride = N.getRawStride();
1378 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1379 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1380 "Stride must be signed constant or DIVariable or DIExpression", &N);
1381}
1382
1383void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) {
1384 CheckDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N);
1385 CheckDI(!N.getRawCountNode() || !N.getRawUpperBound(),
1386 "GenericSubrange can have any one of count or upperBound", &N);
1387 auto *CBound = N.getRawCountNode();
1388 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1389 "Count must be signed constant or DIVariable or DIExpression", &N);
1390 auto *LBound = N.getRawLowerBound();
1391 CheckDI(LBound, "GenericSubrange must contain lowerBound", &N);
1392 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1393 "LowerBound must be signed constant or DIVariable or DIExpression",
1394 &N);
1395 auto *UBound = N.getRawUpperBound();
1396 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1397 "UpperBound must be signed constant or DIVariable or DIExpression",
1398 &N);
1399 auto *Stride = N.getRawStride();
1400 CheckDI(Stride, "GenericSubrange must contain stride", &N);
1401 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1402 "Stride must be signed constant or DIVariable or DIExpression", &N);
1403}
1404
1405void Verifier::visitDIEnumerator(const DIEnumerator &N) {
1406 CheckDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
1407}
1408
1409void Verifier::visitDIBasicType(const DIBasicType &N) {
1410 visitDIType(N);
1411
1412 CheckDI(N.getTag() == dwarf::DW_TAG_base_type ||
1413 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1414 N.getTag() == dwarf::DW_TAG_string_type,
1415 "invalid tag", &N);
1416 // Basic types currently only support constant size.
1417 auto *Size = N.getRawSizeInBits();
1419 "SizeInBits must be a constant");
1420}
1421
1422void Verifier::visitDIFixedPointType(const DIFixedPointType &N) {
1423 visitDIBasicType(N);
1424
1425 CheckDI(N.getTag() == dwarf::DW_TAG_base_type, "invalid tag", &N);
1426 CheckDI(N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1427 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1428 "invalid encoding", &N);
1432 "invalid kind", &N);
1434 N.getFactorRaw() == 0,
1435 "factor should be 0 for rationals", &N);
1437 (N.getNumeratorRaw() == 0 && N.getDenominatorRaw() == 0),
1438 "numerator and denominator should be 0 for non-rationals", &N);
1439}
1440
1441void Verifier::visitDIStringType(const DIStringType &N) {
1442 visitDIType(N);
1443
1444 CheckDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N);
1445 CheckDI(!(N.isBigEndian() && N.isLittleEndian()), "has conflicting flags",
1446 &N);
1447 if (N.getRawCharType())
1448 CheckDI(isa<DIType>(N.getRawCharType()), "invalid character type", &N,
1449 N.getRawCharType());
1450}
1451
1452void Verifier::visitDIDerivedType(const DIDerivedType &N) {
1453 // Common type checks.
1454 visitDIType(N);
1455
1456 CheckDI(N.getTag() == dwarf::DW_TAG_typedef ||
1457 N.getTag() == dwarf::DW_TAG_pointer_type ||
1458 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1459 N.getTag() == dwarf::DW_TAG_reference_type ||
1460 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1461 N.getTag() == dwarf::DW_TAG_const_type ||
1462 N.getTag() == dwarf::DW_TAG_immutable_type ||
1463 N.getTag() == dwarf::DW_TAG_volatile_type ||
1464 N.getTag() == dwarf::DW_TAG_restrict_type ||
1465 N.getTag() == dwarf::DW_TAG_atomic_type ||
1466 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1467 N.getTag() == dwarf::DW_TAG_member ||
1468 (N.getTag() == dwarf::DW_TAG_variable && N.isStaticMember()) ||
1469 N.getTag() == dwarf::DW_TAG_inheritance ||
1470 N.getTag() == dwarf::DW_TAG_friend ||
1471 N.getTag() == dwarf::DW_TAG_set_type ||
1472 N.getTag() == dwarf::DW_TAG_template_alias,
1473 "invalid tag", &N);
1474 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1475 CheckDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N,
1476 N.getRawExtraData());
1477 } else if (N.getTag() == dwarf::DW_TAG_template_alias) {
1478 CheckDI(isMDTuple(N.getRawExtraData()), "invalid template parameters", &N,
1479 N.getRawExtraData());
1480 } else if (N.getTag() == dwarf::DW_TAG_inheritance ||
1481 N.getTag() == dwarf::DW_TAG_member ||
1482 N.getTag() == dwarf::DW_TAG_variable) {
1483 auto *ExtraData = N.getRawExtraData();
1484 auto IsValidExtraData = [&]() {
1485 if (ExtraData == nullptr)
1486 return true;
1487 if (isa<ConstantAsMetadata>(ExtraData) || isa<MDString>(ExtraData) ||
1488 isa<DIObjCProperty>(ExtraData))
1489 return true;
1490 if (auto *Tuple = dyn_cast<MDTuple>(ExtraData)) {
1491 if (Tuple->getNumOperands() != 1)
1492 return false;
1493 return isa_and_nonnull<ConstantAsMetadata>(Tuple->getOperand(0).get());
1494 }
1495 return false;
1496 };
1497 CheckDI(IsValidExtraData(),
1498 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1499 "or MDTuple with single ConstantAsMetadata operand",
1500 &N, ExtraData);
1501 }
1502
1503 if (N.getTag() == dwarf::DW_TAG_set_type) {
1504 if (auto *T = N.getRawBaseType()) {
1508 CheckDI(
1509 (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1510 (Subrange && Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1511 (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1512 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1513 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1514 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1515 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1516 "invalid set base type", &N, T);
1517 }
1518 }
1519
1520 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1521 N.getRawBaseType());
1522
1523 if (N.getDWARFAddressSpace()) {
1524 CheckDI(N.getTag() == dwarf::DW_TAG_pointer_type ||
1525 N.getTag() == dwarf::DW_TAG_reference_type ||
1526 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1527 "DWARF address space only applies to pointer or reference types",
1528 &N);
1529 }
1530
1531 auto *Size = N.getRawSizeInBits();
1534 "SizeInBits must be a constant or DIVariable or DIExpression");
1535}
1536
1537/// Detect mutually exclusive flags.
1538static bool hasConflictingReferenceFlags(unsigned Flags) {
1539 return ((Flags & DINode::FlagLValueReference) &&
1540 (Flags & DINode::FlagRValueReference)) ||
1541 ((Flags & DINode::FlagTypePassByValue) &&
1542 (Flags & DINode::FlagTypePassByReference));
1543}
1544
1545void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
1546 auto *Params = dyn_cast<MDTuple>(&RawParams);
1547 CheckDI(Params, "invalid template params", &N, &RawParams);
1548 for (Metadata *Op : Params->operands()) {
1549 CheckDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter",
1550 &N, Params, Op);
1551 }
1552}
1553
1554void Verifier::visitDICompositeType(const DICompositeType &N) {
1555 // Common type checks.
1556 visitDIType(N);
1557
1558 CheckDI(N.getTag() == dwarf::DW_TAG_array_type ||
1559 N.getTag() == dwarf::DW_TAG_structure_type ||
1560 N.getTag() == dwarf::DW_TAG_union_type ||
1561 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1562 N.getTag() == dwarf::DW_TAG_class_type ||
1563 N.getTag() == dwarf::DW_TAG_variant_part ||
1564 N.getTag() == dwarf::DW_TAG_variant ||
1565 N.getTag() == dwarf::DW_TAG_namelist,
1566 "invalid tag", &N);
1567
1568 CheckDI(isType(N.getRawBaseType()), "invalid base type", &N,
1569 N.getRawBaseType());
1570
1571 CheckDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
1572 "invalid composite elements", &N, N.getRawElements());
1573 CheckDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N,
1574 N.getRawVTableHolder());
1576 "invalid reference flags", &N);
1577 unsigned DIBlockByRefStruct = 1 << 4;
1578 CheckDI((N.getFlags() & DIBlockByRefStruct) == 0,
1579 "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
1580 CheckDI(llvm::all_of(N.getElements(), [](const DINode *N) { return N; }),
1581 "DISubprogram contains null entry in `elements` field", &N);
1582
1583 if (N.isVector()) {
1584 const DINodeArray Elements = N.getElements();
1585 CheckDI(Elements.size() == 1 &&
1586 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1587 "invalid vector, expected one element of type subrange", &N);
1588 }
1589
1590 if (auto *Params = N.getRawTemplateParams())
1591 visitTemplateParams(N, *Params);
1592
1593 if (auto *D = N.getRawDiscriminator()) {
1594 CheckDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part,
1595 "discriminator can only appear on variant part");
1596 }
1597
1598 if (N.getRawDataLocation()) {
1599 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1600 "dataLocation can only appear in array type");
1601 }
1602
1603 if (N.getRawAssociated()) {
1604 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1605 "associated can only appear in array type");
1606 }
1607
1608 if (N.getRawAllocated()) {
1609 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1610 "allocated can only appear in array type");
1611 }
1612
1613 if (N.getRawRank()) {
1614 CheckDI(N.getTag() == dwarf::DW_TAG_array_type,
1615 "rank can only appear in array type");
1616 }
1617
1618 if (N.getTag() == dwarf::DW_TAG_array_type) {
1619 CheckDI(N.getRawBaseType(), "array types must have a base type", &N);
1620 }
1621
1622 auto *Size = N.getRawSizeInBits();
1625 "SizeInBits must be a constant or DIVariable or DIExpression");
1626}
1627
1628void Verifier::visitDISubroutineType(const DISubroutineType &N) {
1629 visitDIType(N);
1630 CheckDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
1631 if (auto *Types = N.getRawTypeArray()) {
1632 CheckDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
1633 for (Metadata *Ty : N.getTypeArray()->operands()) {
1634 CheckDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty);
1635 }
1636 }
1638 "invalid reference flags", &N);
1639}
1640
1641void Verifier::visitDIFile(const DIFile &N) {
1642 CheckDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
1643 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum();
1644 if (Checksum) {
1645 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1646 "invalid checksum kind", &N);
1647 size_t Size;
1648 switch (Checksum->Kind) {
1649 case DIFile::CSK_MD5:
1650 Size = 32;
1651 break;
1652 case DIFile::CSK_SHA1:
1653 Size = 40;
1654 break;
1655 case DIFile::CSK_SHA256:
1656 Size = 64;
1657 break;
1658 }
1659 CheckDI(Checksum->Value.size() == Size, "invalid checksum length", &N);
1660 CheckDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos,
1661 "invalid checksum", &N);
1662 }
1663}
1664
1665void Verifier::visitDICompileUnit(const DICompileUnit &N) {
1666 CheckDI(N.isDistinct(), "compile units must be distinct", &N);
1667 CheckDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
1668
1669 // Don't bother verifying the compilation directory or producer string
1670 // as those could be empty.
1671 CheckDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
1672 N.getRawFile());
1673 CheckDI(!N.getFile()->getFilename().empty(), "invalid filename", &N,
1674 N.getFile());
1675
1676 CheckDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind),
1677 "invalid emission kind", &N);
1678
1679 CheckDI(N.getSourceLanguage().getDialect() <= dwarf::DW_LLVM_LANG_DIALECT_max,
1680 "invalid language dialect", &N);
1681
1682 if (auto *Array = N.getRawEnumTypes()) {
1683 CheckDI(isa<MDTuple>(Array), "invalid enum list", &N, Array);
1684 for (Metadata *Op : N.getEnumTypes()->operands()) {
1686 CheckDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1687 "invalid enum type", &N, N.getEnumTypes(), Op);
1688 CheckDI(!Enum->getScope() || !isa<DILocalScope>(Enum->getScope()),
1689 "function-local enum in a DICompileUnit's enum list", &N,
1690 N.getEnumTypes(), Op);
1691 }
1692 }
1693 if (auto *Array = N.getRawRetainedTypes()) {
1694 CheckDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
1695 for (Metadata *Op : N.getRetainedTypes()->operands()) {
1696 CheckDI(
1697 Op && (isa<DIType>(Op) || (isa<DISubprogram>(Op) &&
1698 !cast<DISubprogram>(Op)->isDefinition())),
1699 "invalid retained type", &N, Op);
1700 }
1701 }
1702 if (auto *Array = N.getRawGlobalVariables()) {
1703 CheckDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
1704 for (Metadata *Op : N.getGlobalVariables()->operands()) {
1706 CheckDI(GVE, "invalid global variable ref", &N, Op);
1707 CheckDI(!isa_and_nonnull<DILocalScope>(GVE->getVariable()->getScope()),
1708 "function-local variables are not allowed in a DICompileUnit's "
1709 "global variables list",
1710 &N, Op);
1711 }
1712 }
1713 if (auto *Array = N.getRawImportedEntities()) {
1714 CheckDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
1715 for (Metadata *Op : N.getImportedEntities()->operands()) {
1717 CheckDI(IE, "invalid imported entity ref", &N, Op);
1719 "function-local imports are not allowed in a DICompileUnit's "
1720 "imported entities list",
1721 &N, Op);
1722 }
1723 }
1724 if (auto *Array = N.getRawMacros()) {
1725 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1726 for (Metadata *Op : N.getMacros()->operands()) {
1727 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1728 }
1729 }
1730 CUVisited.insert(&N);
1731}
1732
1733void Verifier::visitDISubprogram(const DISubprogram &N) {
1734 CheckDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
1735 CheckDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope());
1736 if (auto *F = N.getRawFile())
1737 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1738 else
1739 CheckDI(N.getLine() == 0, "line specified with no file", &N, N.getLine());
1740 auto *T = N.getRawType();
1741 CheckDI(T, "DISubprogram requires a non-null type", &N);
1742 CheckDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
1743 CheckDI(isType(N.getRawContainingType()), "invalid containing type", &N,
1744 N.getRawContainingType());
1745 if (auto *Params = N.getRawTemplateParams())
1746 visitTemplateParams(N, *Params);
1747 if (auto *S = N.getRawDeclaration())
1748 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1749 "invalid subprogram declaration", &N, S);
1750 if (auto *RawNode = N.getRawRetainedNodes()) {
1751 auto *Node = dyn_cast<MDTuple>(RawNode);
1752 CheckDI(Node, "invalid retained nodes list", &N, RawNode);
1753
1754 DenseMap<unsigned, DILocalVariable *> Args;
1755 for (Metadata *Op : Node->operands()) {
1756 CheckDI(Op, "nullptr in retained nodes", &N, Node);
1757
1758 auto True = [](const Metadata *) { return true; };
1759 auto False = [](const Metadata *) { return false; };
1760 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1761 Op, True, True, True, True, True, False);
1762 CheckDI(IsTypeCorrect,
1763 "invalid retained nodes, expected DILocalVariable, DILabel, "
1764 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1765 &N, Node, Op);
1766
1767 auto *RetainedNode = cast<MDNode>(Op);
1768 auto *RetainedNodeScope = dyn_cast_or_null<DILocalScope>(
1770 CheckDI(RetainedNodeScope,
1771 "invalid retained nodes, retained node is not local", &N, Node,
1772 RetainedNode);
1773
1774 DISubprogram *RetainedNodeSP = getSubprogram(RetainedNodeScope);
1775 DICompileUnit *RetainedNodeUnit =
1776 RetainedNodeSP ? RetainedNodeSP->getUnit() : nullptr;
1777 CheckDI(
1778 RetainedNodeSP == &N,
1779 "invalid retained nodes, retained node does not belong to subprogram",
1780 &N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1781 RetainedNodeUnit);
1782
1783 auto *DV = dyn_cast<DILocalVariable>(RetainedNode);
1784 if (!DV)
1785 continue;
1786 if (unsigned ArgNum = DV->getArg()) {
1787 auto [ArgI, Inserted] = Args.insert({ArgNum, DV});
1788 CheckDI(Inserted || DV == ArgI->second,
1789 "invalid retained nodes, more than one local variable with the "
1790 "same argument index",
1791 &N, N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1792 }
1793 }
1794 }
1796 "invalid reference flags", &N);
1797
1798 auto *Unit = N.getRawUnit();
1799 if (N.isDefinition()) {
1800 // Subprogram definitions (not part of the type hierarchy).
1801 CheckDI(N.isDistinct(), "subprogram definitions must be distinct", &N);
1802 CheckDI(Unit, "subprogram definitions must have a compile unit", &N);
1803 CheckDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit);
1804 // There's no good way to cross the CU boundary to insert a nested
1805 // DISubprogram definition in one CU into a type defined in another CU.
1806 auto *CT = dyn_cast_or_null<DICompositeType>(N.getRawScope());
1807 if (CT && CT->getRawIdentifier() &&
1808 M.getContext().isODRUniquingDebugTypes())
1809 CheckDI(N.getDeclaration(),
1810 "definition subprograms cannot be nested within DICompositeType "
1811 "when enabling ODR",
1812 &N);
1813 } else {
1814 // Subprogram declarations (part of the type hierarchy).
1815 CheckDI(!Unit, "subprogram declarations must not have a compile unit", &N);
1816 CheckDI(!N.getRawDeclaration(),
1817 "subprogram declaration must not have a declaration field");
1818 }
1819
1820 if (auto *RawThrownTypes = N.getRawThrownTypes()) {
1821 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1822 CheckDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes);
1823 for (Metadata *Op : ThrownTypes->operands())
1824 CheckDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes,
1825 Op);
1826 }
1827
1828 if (N.areAllCallsDescribed())
1829 CheckDI(N.isDefinition(),
1830 "DIFlagAllCallsDescribed must be attached to a definition");
1831}
1832
1833void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
1834 CheckDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
1835 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1836 "invalid local scope", &N, N.getRawScope());
1837 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope()))
1838 CheckDI(SP->isDefinition(), "scope points into the type hierarchy", &N);
1839}
1840
1841void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
1842 visitDILexicalBlockBase(N);
1843
1844 CheckDI(N.getLine() || !N.getColumn(),
1845 "cannot have column info without line info", &N);
1846}
1847
1848void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
1849 visitDILexicalBlockBase(N);
1850}
1851
1852void Verifier::visitDICommonBlock(const DICommonBlock &N) {
1853 CheckDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N);
1854 if (auto *S = N.getRawScope())
1855 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1856 if (auto *S = N.getRawDecl())
1857 CheckDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S);
1858}
1859
1860void Verifier::visitDINamespace(const DINamespace &N) {
1861 CheckDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
1862 if (auto *S = N.getRawScope())
1863 CheckDI(isa<DIScope>(S), "invalid scope ref", &N, S);
1864}
1865
1866void Verifier::visitDIMacro(const DIMacro &N) {
1867 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
1868 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
1869 "invalid macinfo type", &N);
1870 CheckDI(!N.getName().empty(), "anonymous macro", &N);
1871 if (!N.getValue().empty()) {
1872 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1873 }
1874}
1875
1876void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1877 CheckDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1878 "invalid macinfo type", &N);
1879 if (auto *F = N.getRawFile())
1880 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1881
1882 if (auto *Array = N.getRawElements()) {
1883 CheckDI(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1884 for (Metadata *Op : N.getElements()->operands()) {
1885 CheckDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1886 }
1887 }
1888}
1889
1890void Verifier::visitDIModule(const DIModule &N) {
1891 CheckDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1892 CheckDI(!N.getName().empty(), "anonymous module", &N);
1893}
1894
1895void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1896 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1897}
1898
1899void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1900 visitDITemplateParameter(N);
1901
1902 CheckDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1903 &N);
1904}
1905
1906void Verifier::visitDITemplateValueParameter(
1907 const DITemplateValueParameter &N) {
1908 visitDITemplateParameter(N);
1909
1910 CheckDI(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1911 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1912 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1913 "invalid tag", &N);
1914}
1915
1916void Verifier::visitDIVariable(const DIVariable &N) {
1917 if (auto *S = N.getRawScope())
1918 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1919 if (auto *F = N.getRawFile())
1920 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1921}
1922
1923void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1924 // Checks common to all variables.
1925 visitDIVariable(N);
1926
1927 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1928 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1929 // Check only if the global variable is not an extern
1930 if (N.isDefinition())
1931 CheckDI(N.getType(), "missing global variable type", &N);
1932 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1934 "invalid static data member declaration", &N, Member);
1935 }
1936}
1937
1938void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1939 // Checks common to all variables.
1940 visitDIVariable(N);
1941
1942 CheckDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType());
1943 CheckDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1944 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1945 "local variable requires a valid scope", &N, N.getRawScope());
1946 if (auto Ty = N.getType())
1947 CheckDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType());
1948}
1949
1950void Verifier::visitDIAssignID(const DIAssignID &N) {
1951 CheckDI(!N.getNumOperands(), "DIAssignID has no arguments", &N);
1952 CheckDI(N.isDistinct(), "DIAssignID must be distinct", &N);
1953}
1954
1955void Verifier::visitDILabel(const DILabel &N) {
1956 if (auto *S = N.getRawScope())
1957 CheckDI(isa<DIScope>(S), "invalid scope", &N, S);
1958 if (auto *F = N.getRawFile())
1959 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1960
1961 CheckDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N);
1962 CheckDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1963 "label requires a valid scope", &N, N.getRawScope());
1964}
1965
1966void Verifier::visitDIExpression(const DIExpression &N) {
1967 CheckDI(N.isValid(), "invalid expression", &N);
1968}
1969
1970void Verifier::visitDIGlobalVariableExpression(
1971 const DIGlobalVariableExpression &GVE) {
1972 CheckDI(GVE.getVariable(), "missing variable");
1973 if (auto *Var = GVE.getVariable())
1974 visitDIGlobalVariable(*Var);
1975 if (auto *Expr = GVE.getExpression()) {
1976 visitDIExpression(*Expr);
1977 if (auto Fragment = Expr->getFragmentInfo())
1978 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE);
1979 }
1980}
1981
1982void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1983 CheckDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1984 if (auto *T = N.getRawType())
1985 CheckDI(isType(T), "invalid type ref", &N, T);
1986 if (auto *F = N.getRawFile())
1987 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1988}
1989
1990void Verifier::visitDIProperty(const DIProperty &N) {
1991 CheckDI(N.getTag() == dwarf::DW_TAG_property, "invalid tag", &N);
1992 if (auto *T = N.getRawType())
1993 CheckDI(isType(T), "invalid type ref", &N, T);
1994 if (auto *F = N.getRawFile())
1995 CheckDI(isa<DIFile>(F), "invalid file", &N, F);
1996 // DWARF allows a property getter to forward to a subprogram, variable, or
1997 // constant too, but the backend only knows how to forward to a member.
1998 if (DINode *BackingStorage = N.getBackingStorage()) {
1999 auto *DT = dyn_cast<DIDerivedType>(BackingStorage);
2000 CheckDI(DT && DT->getTag() == dwarf::DW_TAG_member,
2001 "property backing storage must be a member", &N, BackingStorage);
2002 }
2003}
2004
2005void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
2006 CheckDI(N.getTag() == dwarf::DW_TAG_imported_module ||
2007 N.getTag() == dwarf::DW_TAG_imported_declaration,
2008 "invalid tag", &N);
2009 if (auto *S = N.getRawScope())
2010 CheckDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
2011 CheckDI(isDINode(N.getRawEntity()), "invalid imported entity", &N,
2012 N.getRawEntity());
2013}
2014
2015void Verifier::visitComdat(const Comdat &C) {
2016 // Comdats in COFF modules must have a corresponding global that is not
2017 // private. If the global is private, there will be no symbol table entry.
2018 // We consider unused or dead comdat entries to be valid, since they won't
2019 // make it into the COFF object file.
2020 if (TT.isOSBinFormatCOFF()) {
2021 const GlobalValue *GV = M.getNamedValue(C.getName());
2022 bool IsDefined = GV != nullptr && !GV->isDeclarationForLinker();
2023 if (IsDefined)
2024 Check(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
2025 GV);
2026 else
2027 Check(C.getUsers().empty(),
2028 "COFF comdats must have a defined global value with the same name",
2029 GV);
2030 }
2031}
2032
2033void Verifier::visitModuleIdents() {
2034 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
2035 if (!Idents)
2036 return;
2037
2038 // llvm.ident takes a list of metadata entry. Each entry has only one string.
2039 // Scan each llvm.ident entry and make sure that this requirement is met.
2040 for (const MDNode *N : Idents->operands()) {
2041 Check(N->getNumOperands() == 1,
2042 "incorrect number of operands in llvm.ident metadata", N);
2043 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
2044 ("invalid value for llvm.ident metadata entry operand"
2045 "(the operand should be a string)"),
2046 N->getOperand(0));
2047 }
2048}
2049
2050void Verifier::visitModuleCommandLines() {
2051 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline");
2052 if (!CommandLines)
2053 return;
2054
2055 // llvm.commandline takes a list of metadata entry. Each entry has only one
2056 // string. Scan each llvm.commandline entry and make sure that this
2057 // requirement is met.
2058 for (const MDNode *N : CommandLines->operands()) {
2059 Check(N->getNumOperands() == 1,
2060 "incorrect number of operands in llvm.commandline metadata", N);
2061 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
2062 ("invalid value for llvm.commandline metadata entry operand"
2063 "(the operand should be a string)"),
2064 N->getOperand(0));
2065 }
2066}
2067
2068void Verifier::visitModuleErrnoTBAA() {
2069 const NamedMDNode *ErrnoTBAA = M.getNamedMetadata("llvm.errno.tbaa");
2070 if (!ErrnoTBAA)
2071 return;
2072
2073 Check(ErrnoTBAA->getNumOperands() >= 1,
2074 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
2075
2076 for (const MDNode *N : ErrnoTBAA->operands())
2077 TBAAVerifyHelper.visitTBAAMetadata(nullptr, N);
2078}
2079
2080void Verifier::visitModuleRawSections() {
2081 const NamedMDNode *RawSections = M.getNamedMetadata("llvm.raw.sections");
2082 if (!RawSections)
2083 return;
2084
2085 for (const MDNode *N : RawSections->operands()) {
2086 if (N->getNumOperands() != 4) {
2087 CheckFailed("llvm.raw.sections entry must have four operands", N);
2088 continue;
2089 }
2090 Check(dyn_cast_or_null<MDString>(N->getOperand(0)),
2091 "llvm.raw.sections entry operand 0 must be a string "
2092 "(section name)",
2093 N);
2094 auto *AlignCI = mdconst::dyn_extract_or_null<ConstantInt>(N->getOperand(1));
2095 Check(AlignCI,
2096 "llvm.raw.sections entry operand 1 must be an integer "
2097 "(alignment)",
2098 N);
2099 if (!isPowerOf2_64(AlignCI->getZExtValue())) {
2100 CheckFailed("llvm.raw.sections entry operand 1 must be a power of two "
2101 "(alignment)",
2102 N);
2103 continue;
2104 }
2105 auto *FlagsCI = mdconst::dyn_extract_or_null<ConstantInt>(N->getOperand(2));
2106 Check(FlagsCI,
2107 "llvm.raw.sections entry operand 2 must be an integer "
2108 "(flags)",
2109 N);
2110 if (FlagsCI->getZExtValue() != 0) {
2111 CheckFailed("llvm.raw.sections entry operand 2 must be zero (flags are "
2112 "reserved for future use)",
2113 N);
2114 continue;
2115 }
2116 Check(dyn_cast_or_null<MDString>(N->getOperand(3)),
2117 "llvm.raw.sections entry operand 3 must be a string "
2118 "(section data)",
2119 N);
2120 }
2121}
2122
2123void Verifier::visitModuleFlags() {
2124 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
2125 if (!Flags) return;
2126
2127 // Scan each flag, and track the flags and requirements.
2128 DenseMap<const MDString*, const MDNode*> SeenIDs;
2129 SmallVector<const MDNode*, 16> Requirements;
2130
2131 // Either both aarch64-elf-pauthabi-* flags should be set or none at all.
2132 std::optional<uint64_t> PAuthABIPlatform;
2133 std::optional<uint64_t> PAuthABIVersion;
2134 // Signing of init/fini pointers: address diversity implies basic signing.
2135 uint64_t HasPtrauthInitFini = 0;
2136 uint64_t HasPtrauthInitFiniAddr = 0;
2137
2138 for (const MDNode *MDN : Flags->operands()) {
2139 visitModuleFlag(MDN, SeenIDs, Requirements);
2140 if (MDN->getNumOperands() != 3)
2141 continue;
2142
2143 if (const auto *FlagName = dyn_cast_or_null<MDString>(MDN->getOperand(1))) {
2144 auto GetFlagNamed = [&](StringRef Name) -> std::optional<uint64_t> {
2145 if (FlagName->getString() != Name)
2146 return std::nullopt;
2147 if (const auto *FlagValue =
2149 return FlagValue->getZExtValue();
2150
2151 CheckFailed(Name + ": module flag expects integer value");
2152 return std::nullopt;
2153 };
2154
2155 if (auto Value = GetFlagNamed("aarch64-elf-pauthabi-platform"))
2156 PAuthABIPlatform = *Value;
2157 else if (auto Value = GetFlagNamed("aarch64-elf-pauthabi-version"))
2158 PAuthABIVersion = *Value;
2159 else if (auto Value = GetFlagNamed("ptrauth-init-fini"))
2160 HasPtrauthInitFini = *Value;
2161 else if (auto Value =
2162 GetFlagNamed("ptrauth-init-fini-address-discrimination"))
2163 HasPtrauthInitFiniAddr = *Value;
2164 }
2165 }
2166
2167 Check(llvm::is_contained({0u, 1u}, HasPtrauthInitFini),
2168 "ptrauth-init-fini must be 0 or 1");
2169 Check(llvm::is_contained({0u, 1u}, HasPtrauthInitFiniAddr),
2170 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
2171 if (HasPtrauthInitFiniAddr)
2172 Check(HasPtrauthInitFini, "ptrauth-init-fini-address-discrimination module "
2173 "flag requires ptrauth-init-fini");
2174
2175 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
2176 CheckFailed("either both or no 'aarch64-elf-pauthabi-platform' and "
2177 "'aarch64-elf-pauthabi-version' module flags must be present");
2178
2179 // Validate that the requirements in the module are valid.
2180 for (const MDNode *Requirement : Requirements) {
2181 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
2182 const Metadata *ReqValue = Requirement->getOperand(1);
2183
2184 const MDNode *Op = SeenIDs.lookup(Flag);
2185 if (!Op) {
2186 CheckFailed("invalid requirement on flag, flag is not present in module",
2187 Flag);
2188 continue;
2189 }
2190
2191 if (Op->getOperand(2) != ReqValue) {
2192 CheckFailed(("invalid requirement on flag, "
2193 "flag does not have the required value"),
2194 Flag);
2195 continue;
2196 }
2197 }
2198}
2199
2200void
2201Verifier::visitModuleFlag(const MDNode *Op,
2202 DenseMap<const MDString *, const MDNode *> &SeenIDs,
2203 SmallVectorImpl<const MDNode *> &Requirements) {
2204 // Each module flag should have three arguments, the merge behavior (a
2205 // constant int), the flag ID (an MDString), and the value.
2206 Check(Op->getNumOperands() == 3,
2207 "incorrect number of operands in module flag", Op);
2208 Module::ModFlagBehavior MFB;
2209 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
2211 "invalid behavior operand in module flag (expected constant integer)",
2212 Op->getOperand(0));
2213 Check(false,
2214 "invalid behavior operand in module flag (unexpected constant)",
2215 Op->getOperand(0));
2216 }
2217 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
2218 Check(ID, "invalid ID operand in module flag (expected metadata string)",
2219 Op->getOperand(1));
2220
2221 // Check the values for behaviors with additional requirements.
2222 switch (MFB) {
2223 case Module::Error:
2224 case Module::Warning:
2225 case Module::Override:
2226 // These behavior types accept any value.
2227 break;
2228
2229 case Module::Min: {
2230 auto *V = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2));
2231 Check(V && V->getValue().isNonNegative(),
2232 "invalid value for 'min' module flag (expected constant non-negative "
2233 "integer)",
2234 Op->getOperand(2));
2235 break;
2236 }
2237
2238 case Module::Max: {
2240 "invalid value for 'max' module flag (expected constant integer)",
2241 Op->getOperand(2));
2242 break;
2243 }
2244
2245 case Module::Require: {
2246 // The value should itself be an MDNode with two operands, a flag ID (an
2247 // MDString), and a value.
2248 auto *Value = dyn_cast<MDNode>(Op->getOperand(2));
2249 Check(Value && Value->getNumOperands() == 2,
2250 "invalid value for 'require' module flag (expected metadata pair)",
2251 Op->getOperand(2));
2252 Check(isa<MDString>(Value->getOperand(0)),
2253 ("invalid value for 'require' module flag "
2254 "(first value operand should be a string)"),
2255 Value->getOperand(0));
2256
2257 // Append it to the list of requirements, to check once all module flags are
2258 // scanned.
2259 Requirements.push_back(Value);
2260 break;
2261 }
2262
2263 case Module::Append:
2264 case Module::AppendUnique: {
2265 // These behavior types require the operand be an MDNode.
2266 Check(isa<MDNode>(Op->getOperand(2)),
2267 "invalid value for 'append'-type module flag "
2268 "(expected a metadata node)",
2269 Op->getOperand(2));
2270 break;
2271 }
2272 }
2273
2274 // Unless this is a "requires" flag, check the ID is unique.
2275 if (MFB != Module::Require) {
2276 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
2277 Check(Inserted,
2278 "module flag identifiers must be unique (or of 'require' type)", ID);
2279 }
2280
2281 StringRef Name = ID->getString();
2282 if (Name == "wchar_size") {
2283 ConstantInt *Value
2285 Check(Value && Value->getValue().isStrictlyPositive(),
2286 "wchar_size metadata requires constant positive integer argument");
2287 return;
2288 }
2289
2290 if (Name == "long-double-type") {
2291 Check(MFB == Module::Error,
2292 "long-double-type module flag must use 'error' merge behavior", Op);
2293 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2294 Check(Value, "long-double-type metadata requires a string argument");
2295 if (Value)
2296 Check(parseLongDoubleFormat(Value->getString()).has_value(),
2297 "invalid long-double-type metadata value", Op);
2298 return;
2299 }
2300
2301 if (Name == "float-abi") {
2302 Check(MFB == Module::Error,
2303 "float-abi module flag must use 'error' merge behavior", Op);
2304 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2305 Check(Value, "float-abi metadata requires a string argument");
2306 if (Value)
2307 Check(FloatABI::parseABIType(Value->getString()).has_value(),
2308 "invalid float-abi metadata value", Op);
2309 return;
2310 }
2311
2312 if (Name == "thread-model") {
2313 Check(MFB == Module::Error,
2314 "thread-model module flag must use 'error' merge behavior", Op);
2315 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2316 Check(Value, "thread-model metadata requires a string argument");
2317 if (Value)
2318 Check(parseThreadModel(Value->getString()).has_value(),
2319 "invalid thread-model metadata value", Op);
2320 return;
2321 }
2322
2323 if (Name == "target-abi") {
2324 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2325 Check(Value && !Value->getString().empty(),
2326 "target-abi metadata requires a non-empty string argument", Op);
2327 return;
2328 }
2329
2330 if (ID->getString() == "exception-model") {
2331 Check(MFB == Module::Error,
2332 "exception-model module flag must use 'error' merge behavior", Op);
2333 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2334 Check(Value, "exception-model metadata requires a string argument");
2335 if (Value)
2336 Check(parseExceptionModel(Value->getString()).has_value(),
2337 "invalid exception-model metadata value", Op);
2338 return;
2339 }
2340
2341 if (Name == "debugger-tuning") {
2342 const MDString *Value = dyn_cast_or_null<MDString>(Op->getOperand(2));
2343 Check(Value && !Value->getString().empty(),
2344 "debugger-tuning metadata requires a non-empty string argument", Op);
2345 return;
2346 }
2347
2348 if (Name == "Linker Options") {
2349 // If the llvm.linker.options named metadata exists, we assume that the
2350 // bitcode reader has upgraded the module flag. Otherwise the flag might
2351 // have been created by a client directly.
2352 Check(M.getNamedMetadata("llvm.linker.options"),
2353 "'Linker Options' named metadata no longer supported");
2354 return;
2355 }
2356
2357 if (Name == "SemanticInterposition") {
2358 ConstantInt *Value =
2360 Check(Value,
2361 "SemanticInterposition metadata requires constant integer argument");
2362 return;
2363 }
2364
2365 if (Name == "CG Profile") {
2366 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands())
2367 visitModuleFlagCGProfileEntry(MDO);
2368 return;
2369 }
2370
2371 // Target-specific module flag checks.
2372 verifyAMDGPUModuleFlag(*this, ID, MFB, Op);
2373}
2374
2375void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) {
2376 auto CheckFunction = [&](const MDOperand &FuncMDO) {
2377 if (!FuncMDO)
2378 return;
2379 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
2380 Check(F && isa<Function>(F->getValue()->stripPointerCasts()),
2381 "expected a Function or null", FuncMDO);
2382 };
2383 auto Node = dyn_cast_or_null<MDNode>(MDO);
2384 Check(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO);
2385 CheckFunction(Node->getOperand(0));
2386 CheckFunction(Node->getOperand(1));
2387 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
2388 Check(Count && Count->getType()->isIntegerTy(),
2389 "expected an integer constant", Node->getOperand(2));
2390}
2391
2392void Verifier::verifyAttributeTypes(AttributeSet Attrs, const Value *V) {
2393 for (Attribute A : Attrs) {
2394
2395 if (A.isStringAttribute()) {
2396#define GET_ATTR_NAMES
2397#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2398#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2399 if (A.getKindAsString() == #DISPLAY_NAME) { \
2400 auto V = A.getValueAsString(); \
2401 if (!(V.empty() || V == "true" || V == "false")) \
2402 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2403 ""); \
2404 }
2405
2406#include "llvm/IR/Attributes.inc"
2407 continue;
2408 }
2409
2410 if (A.isIntAttribute() != Attribute::isIntAttrKind(A.getKindAsEnum())) {
2411 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument",
2412 V);
2413 return;
2414 }
2415 }
2416}
2417
2418// VerifyParameterAttrs - Check the given attributes for an argument or return
2419// value of the specified type. The value V is printed in error messages.
2420void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty,
2421 const Value *V) {
2422 if (!Attrs.hasAttributes())
2423 return;
2424
2425 verifyAttributeTypes(Attrs, V);
2426
2427 for (Attribute Attr : Attrs)
2428 Check(Attr.isStringAttribute() ||
2429 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2430 "Attribute '" + Attr.getAsString() + "' does not apply to parameters",
2431 V);
2432
2433 // The remaining checks are for combinations of attributes.
2434 if (Attrs.getNumAttributes() > 1) {
2435 if (Attrs.hasAttribute(Attribute::ImmArg)) {
2436 unsigned AttrCount =
2437 Attrs.getNumAttributes() - Attrs.hasAttribute(Attribute::Range);
2438 Check(
2439 AttrCount == 1,
2440 "Attribute 'immarg' is incompatible with other attributes except the "
2441 "'range' attribute",
2442 V);
2443 }
2444
2445 // Check for mutually incompatible attributes. Only inreg is compatible
2446 // with sret.
2447 unsigned AttrCount = 0;
2448 AttrCount += Attrs.hasAttribute(Attribute::ByVal);
2449 AttrCount += Attrs.hasAttribute(Attribute::InAlloca);
2450 AttrCount += Attrs.hasAttribute(Attribute::Preallocated);
2451 AttrCount += Attrs.hasAttribute(Attribute::StructRet) ||
2452 Attrs.hasAttribute(Attribute::InReg);
2453 AttrCount += Attrs.hasAttribute(Attribute::Nest);
2454 AttrCount += Attrs.hasAttribute(Attribute::ByRef);
2455 Check(AttrCount <= 1,
2456 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2457 "'byref', and 'sret' are incompatible!",
2458 V);
2459
2460 Check(!(Attrs.hasAttribute(Attribute::InAlloca) &&
2461 Attrs.hasAttribute(Attribute::ReadOnly)),
2462 "Attributes "
2463 "'inalloca and readonly' are incompatible!",
2464 V);
2465
2466 Check(!(Attrs.hasAttribute(Attribute::StructRet) &&
2467 Attrs.hasAttribute(Attribute::Returned)),
2468 "Attributes "
2469 "'sret and returned' are incompatible!",
2470 V);
2471
2472 Check(!(Attrs.hasAttribute(Attribute::ZExt) &&
2473 Attrs.hasAttribute(Attribute::SExt)),
2474 "Attributes "
2475 "'zeroext and signext' are incompatible!",
2476 V);
2477
2478 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
2479 Attrs.hasAttribute(Attribute::ReadOnly)),
2480 "Attributes "
2481 "'readnone and readonly' are incompatible!",
2482 V);
2483
2484 Check(!(Attrs.hasAttribute(Attribute::ReadNone) &&
2485 Attrs.hasAttribute(Attribute::WriteOnly)),
2486 "Attributes "
2487 "'readnone and writeonly' are incompatible!",
2488 V);
2489
2490 Check(!(Attrs.hasAttribute(Attribute::ReadOnly) &&
2491 Attrs.hasAttribute(Attribute::WriteOnly)),
2492 "Attributes "
2493 "'readonly and writeonly' are incompatible!",
2494 V);
2495
2496 Check(!(Attrs.hasAttribute(Attribute::NoInline) &&
2497 Attrs.hasAttribute(Attribute::AlwaysInline)),
2498 "Attributes "
2499 "'noinline and alwaysinline' are incompatible!",
2500 V);
2501
2502 Check(!(Attrs.hasAttribute(Attribute::Writable) &&
2503 Attrs.hasAttribute(Attribute::ReadNone)),
2504 "Attributes writable and readnone are incompatible!", V);
2505
2506 Check(!(Attrs.hasAttribute(Attribute::Writable) &&
2507 Attrs.hasAttribute(Attribute::ReadOnly)),
2508 "Attributes writable and readonly are incompatible!", V);
2509 }
2510
2511 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2512 for (Attribute Attr : Attrs) {
2513 if (!Attr.isStringAttribute() &&
2514 IncompatibleAttrs.contains(Attr.getKindAsEnum())) {
2515 CheckFailed("Attribute '" + Attr.getAsString() +
2516 "' applied to incompatible type!", V);
2517 return;
2518 }
2519 }
2520
2521 if (isa<PointerType>(Ty)) {
2522 if (Attrs.hasAttribute(Attribute::Alignment)) {
2523 Align AttrAlign = Attrs.getAlignment().valueOrOne();
2524 Check(AttrAlign.value() <= Value::MaximumAlignment,
2525 "huge alignment values are unsupported", V);
2526 }
2527 if (Attrs.hasAttribute(Attribute::ByVal)) {
2528 Type *ByValTy = Attrs.getByValType();
2529 Check(ByValTy->isSized(),
2530 "Attribute 'byval' does not support unsized types!", V);
2531 // Check if it is or contains a target extension type that disallows being
2532 // used on the stack.
2534 "'byval' argument has illegal target extension type", V);
2535 // The copy is placed in the caller's frame, which needs its size at
2536 // compile time.
2537 Check(!ByValTy->isScalableTy(),
2538 "scalable 'byval' arguments are unsupported", V);
2539 Check(DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2540 "huge 'byval' arguments are unsupported", V);
2541 }
2542 if (Attrs.hasAttribute(Attribute::ByRef)) {
2543 Check(Attrs.getByRefType()->isSized(),
2544 "Attribute 'byref' does not support unsized types!", V);
2545 Check(DL.getTypeAllocSize(Attrs.getByRefType()).getKnownMinValue() <
2546 (1ULL << 32),
2547 "huge 'byref' arguments are unsupported", V);
2548 }
2549 if (Attrs.hasAttribute(Attribute::InAlloca)) {
2550 Check(Attrs.getInAllocaType()->isSized(),
2551 "Attribute 'inalloca' does not support unsized types!", V);
2552 Check(DL.getTypeAllocSize(Attrs.getInAllocaType()).getKnownMinValue() <
2553 (1ULL << 32),
2554 "huge 'inalloca' arguments are unsupported", V);
2555 }
2556 if (Attrs.hasAttribute(Attribute::Preallocated)) {
2557 Check(Attrs.getPreallocatedType()->isSized(),
2558 "Attribute 'preallocated' does not support unsized types!", V);
2559 Check(
2560 DL.getTypeAllocSize(Attrs.getPreallocatedType()).getKnownMinValue() <
2561 (1ULL << 32),
2562 "huge 'preallocated' arguments are unsupported", V);
2563 }
2564 }
2565
2566 if (Attrs.hasAttribute(Attribute::Initializes)) {
2567 auto Inits = Attrs.getAttribute(Attribute::Initializes).getInitializes();
2568 Check(!Inits.empty(), "Attribute 'initializes' does not support empty list",
2569 V);
2571 "Attribute 'initializes' does not support unordered ranges", V);
2572 }
2573
2574 if (Attrs.hasAttribute(Attribute::NoFPClass)) {
2575 uint64_t Val = Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2576 Check(Val != 0, "Attribute 'nofpclass' must have at least one test bit set",
2577 V);
2578 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
2579 "Invalid value for 'nofpclass' test mask", V);
2580 }
2581 if (Attrs.hasAttribute(Attribute::Range)) {
2582 const ConstantRange &CR =
2583 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2585 "Range bit width must match type bit width!", V);
2586 }
2587}
2588
2589void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2590 const Value *V) {
2591 if (Attrs.hasFnAttr(Attr)) {
2592 StringRef S = Attrs.getFnAttr(Attr).getValueAsString();
2593 unsigned N;
2594 if (S.getAsInteger(10, N))
2595 CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V);
2596 }
2597}
2598
2599// Check parameter attributes against a function type.
2600// The value V is printed in error messages.
2601void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2602 const Value *V, bool IsIntrinsic,
2603 bool IsInlineAsm) {
2604 if (Attrs.isEmpty())
2605 return;
2606
2607 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) {
2608 Check(Attrs.hasParentContext(Context),
2609 "Attribute list does not match Module context!", &Attrs, V);
2610 for (const auto &AttrSet : Attrs) {
2611 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2612 "Attribute set does not match Module context!", &AttrSet, V);
2613 for (const auto &A : AttrSet) {
2614 Check(A.hasParentContext(Context),
2615 "Attribute does not match Module context!", &A, V);
2616 }
2617 }
2618 }
2619
2620 bool SawNest = false;
2621 bool SawReturned = false;
2622 bool SawSRet = false;
2623 bool SawSwiftSelf = false;
2624 bool SawSwiftAsync = false;
2625 bool SawSwiftError = false;
2626
2627 // Verify return value attributes.
2628 AttributeSet RetAttrs = Attrs.getRetAttrs();
2629 for (Attribute RetAttr : RetAttrs)
2630 Check(RetAttr.isStringAttribute() ||
2631 Attribute::canUseAsRetAttr(RetAttr.getKindAsEnum()),
2632 "Attribute '" + RetAttr.getAsString() +
2633 "' does not apply to function return values",
2634 V);
2635
2636 unsigned MaxParameterWidth = 0;
2637 auto GetMaxParameterWidth = [&MaxParameterWidth](Type *Ty) {
2638 if (Ty->isVectorTy()) {
2639 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
2640 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2641 if (Size > MaxParameterWidth)
2642 MaxParameterWidth = Size;
2643 }
2644 }
2645 };
2646 GetMaxParameterWidth(FT->getReturnType());
2647 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2648
2649 // Verify parameter attributes.
2650 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2651 Type *Ty = FT->getParamType(i);
2652 AttributeSet ArgAttrs = Attrs.getParamAttrs(i);
2653
2654 if (!IsIntrinsic) {
2655 Check(!ArgAttrs.hasAttribute(Attribute::ImmArg),
2656 "immarg attribute only applies to intrinsics", V);
2657 if (!IsInlineAsm)
2658 Check(!ArgAttrs.hasAttribute(Attribute::ElementType),
2659 "Attribute 'elementtype' can only be applied to intrinsics"
2660 " and inline asm.",
2661 V);
2662 }
2663
2664 verifyParameterAttrs(ArgAttrs, Ty, V);
2665 GetMaxParameterWidth(Ty);
2666
2667 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
2668 Check(!SawNest, "More than one parameter has attribute nest!", V);
2669 SawNest = true;
2670 }
2671
2672 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
2673 Check(!SawReturned, "More than one parameter has attribute returned!", V);
2674 Check(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
2675 "Incompatible argument and return types for 'returned' attribute",
2676 V);
2677 SawReturned = true;
2678 }
2679
2680 if (ArgAttrs.hasAttribute(Attribute::StructRet)) {
2681 Check(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
2682 Check(i == 0 || i == 1,
2683 "Attribute 'sret' is not on first or second parameter!", V);
2684 SawSRet = true;
2685 }
2686
2687 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) {
2688 Check(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V);
2689 SawSwiftSelf = true;
2690 }
2691
2692 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) {
2693 Check(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V);
2694 SawSwiftAsync = true;
2695 }
2696
2697 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) {
2698 Check(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", V);
2699 SawSwiftError = true;
2700 }
2701
2702 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) {
2703 Check(i == FT->getNumParams() - 1,
2704 "inalloca isn't on the last parameter!", V);
2705 }
2706 }
2707
2708 if (!Attrs.hasFnAttrs())
2709 return;
2710
2711 verifyAttributeTypes(Attrs.getFnAttrs(), V);
2712 for (Attribute FnAttr : Attrs.getFnAttrs())
2713 Check(FnAttr.isStringAttribute() ||
2714 Attribute::canUseAsFnAttr(FnAttr.getKindAsEnum()),
2715 "Attribute '" + FnAttr.getAsString() +
2716 "' does not apply to functions!",
2717 V);
2718
2719 Check(!(Attrs.hasFnAttr(Attribute::NoInline) &&
2720 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2721 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2722
2723 if (Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2724 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2725 "Attributes 'optsize and optnone' are incompatible!", V);
2726
2727 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2728 "Attributes 'minsize and optnone' are incompatible!", V);
2729
2730 Check(!Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2731 "Attributes 'optdebug and optnone' are incompatible!", V);
2732 }
2733
2734 Check(!(Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2735 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2736 "Attributes "
2737 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2738 V);
2739
2740 Check(!(Attrs.hasFnAttr(Attribute::SanitizeThread) &&
2741 Attrs.hasFnAttr(Attribute::SanitizeConcurrency)),
2742 "Attributes 'sanitize_thread and sanitize_concurrency' are "
2743 "incompatible!",
2744 V);
2745
2746 if (Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2747 Check(!Attrs.hasFnAttr(Attribute::OptimizeForSize),
2748 "Attributes 'optsize and optdebug' are incompatible!", V);
2749
2750 Check(!Attrs.hasFnAttr(Attribute::MinSize),
2751 "Attributes 'minsize and optdebug' are incompatible!", V);
2752 }
2753
2754 Check(!Attrs.hasAttrSomewhere(Attribute::Writable) ||
2755 isModSet(Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2756 "Attribute writable and memory without argmem: write are incompatible!",
2757 V);
2758
2759 if (Attrs.hasFnAttr("aarch64_pstate_sm_enabled")) {
2760 Check(!Attrs.hasFnAttr("aarch64_pstate_sm_compatible"),
2761 "Attributes 'aarch64_pstate_sm_enabled and "
2762 "aarch64_pstate_sm_compatible' are incompatible!",
2763 V);
2764 }
2765
2766 Check((Attrs.hasFnAttr("aarch64_new_za") + Attrs.hasFnAttr("aarch64_in_za") +
2767 Attrs.hasFnAttr("aarch64_inout_za") +
2768 Attrs.hasFnAttr("aarch64_out_za") +
2769 Attrs.hasFnAttr("aarch64_preserves_za") +
2770 Attrs.hasFnAttr("aarch64_za_state_agnostic")) <= 1,
2771 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2772 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2773 "'aarch64_za_state_agnostic' are mutually exclusive",
2774 V);
2775
2776 Check((Attrs.hasFnAttr("aarch64_new_zt0") +
2777 Attrs.hasFnAttr("aarch64_in_zt0") +
2778 Attrs.hasFnAttr("aarch64_inout_zt0") +
2779 Attrs.hasFnAttr("aarch64_out_zt0") +
2780 Attrs.hasFnAttr("aarch64_preserves_zt0") +
2781 Attrs.hasFnAttr("aarch64_za_state_agnostic")) <= 1,
2782 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2783 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2784 "'aarch64_za_state_agnostic' are mutually exclusive",
2785 V);
2786
2787 if (Attrs.hasFnAttr(Attribute::JumpTable)) {
2788 const GlobalValue *GV = cast<GlobalValue>(V);
2790 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2791 }
2792
2793 if (auto Args = Attrs.getFnAttrs().getAllocSizeArgs()) {
2794 auto CheckParam = [&](StringRef Name, unsigned ParamNo) {
2795 if (ParamNo >= FT->getNumParams()) {
2796 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V);
2797 return false;
2798 }
2799
2800 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2801 CheckFailed("'allocsize' " + Name +
2802 " argument must refer to an integer parameter",
2803 V);
2804 return false;
2805 }
2806
2807 return true;
2808 };
2809
2810 if (!CheckParam("element size", Args->first))
2811 return;
2812
2813 if (Args->second && !CheckParam("number of elements", *Args->second))
2814 return;
2815 }
2816
2817 if (Attrs.hasFnAttr(Attribute::AllocKind)) {
2818 AllocFnKind K = Attrs.getAllocKind();
2820 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2821 if (!is_contained(
2822 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2823 Type))
2824 CheckFailed(
2825 "'allockind()' requires exactly one of alloc, realloc, and free");
2826 if ((Type == AllocFnKind::Free) &&
2827 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2828 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2829 CheckFailed("'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2830 "or aligned modifiers.");
2831 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2832 if ((K & ZeroedUninit) == ZeroedUninit)
2833 CheckFailed("'allockind()' can't be both zeroed and uninitialized");
2834 }
2835
2836 if (Attribute A = Attrs.getFnAttr("alloc-variant-zeroed"); A.isValid()) {
2837 StringRef S = A.getValueAsString();
2838 Check(!S.empty(), "'alloc-variant-zeroed' must not be empty");
2839 Function *Variant = M.getFunction(S);
2840 if (Variant) {
2841 Attribute Family = Attrs.getFnAttr("alloc-family");
2842 Attribute VariantFamily = Variant->getFnAttribute("alloc-family");
2843 if (Family.isValid())
2844 Check(VariantFamily.isValid() &&
2845 VariantFamily.getValueAsString() == Family.getValueAsString(),
2846 "'alloc-variant-zeroed' must name a function belonging to the "
2847 "same 'alloc-family'");
2848
2849 Check(Variant->hasFnAttribute(Attribute::AllocKind) &&
2850 (Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2851 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2852 "'alloc-variant-zeroed' must name a function with "
2853 "'allockind(\"zeroed\")'");
2854
2855 Check(FT == Variant->getFunctionType(),
2856 "'alloc-variant-zeroed' must name a function with the same "
2857 "signature");
2858
2859 if (const auto *F = dyn_cast<Function>(V))
2860 Check(F->getCallingConv() == Variant->getCallingConv(),
2861 "'alloc-variant-zeroed' must name a function with the same "
2862 "calling convention");
2863 }
2864 }
2865
2866 if (Attrs.hasFnAttr(Attribute::VScaleRange)) {
2867 unsigned VScaleMin = Attrs.getFnAttrs().getVScaleRangeMin();
2868 if (VScaleMin == 0)
2869 CheckFailed("'vscale_range' minimum must be greater than 0", V);
2870 else if (!isPowerOf2_32(VScaleMin))
2871 CheckFailed("'vscale_range' minimum must be power-of-two value", V);
2872 std::optional<unsigned> VScaleMax = Attrs.getFnAttrs().getVScaleRangeMax();
2873 if (VScaleMax && VScaleMin > VScaleMax)
2874 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V);
2875 else if (VScaleMax && !isPowerOf2_32(*VScaleMax))
2876 CheckFailed("'vscale_range' maximum must be power-of-two value", V);
2877 }
2878
2879 if (Attribute FPAttr = Attrs.getFnAttr("frame-pointer"); FPAttr.isValid()) {
2880 StringRef FP = FPAttr.getValueAsString();
2881 if (FP != "all" && FP != "non-leaf" && FP != "none" && FP != "reserved" &&
2882 FP != "non-leaf-no-reserve")
2883 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V);
2884 }
2885
2886 checkUnsignedBaseTenFuncAttr(Attrs, "tail-pad-to-size", V);
2887 checkUnsignedBaseTenFuncAttr(Attrs, "tail-pad-value", V);
2888 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V);
2889 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V);
2890 if (Attrs.hasFnAttr("patchable-function-entry-section"))
2891 Check(!Attrs.getFnAttr("patchable-function-entry-section")
2892 .getValueAsString()
2893 .empty(),
2894 "\"patchable-function-entry-section\" must not be empty");
2895 checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V);
2896 checkUnsignedBaseTenFuncAttr(Attrs, "unsafe-stack-size", V);
2897 for (StringLiteral Attr : NVVMAttr::AbiPreserveAttrs)
2898 checkUnsignedBaseTenFuncAttr(Attrs, Attr, V);
2899
2900 if (auto A = Attrs.getFnAttr("sign-return-address"); A.isValid()) {
2901 StringRef S = A.getValueAsString();
2902 if (S != "none" && S != "all" && S != "non-leaf")
2903 CheckFailed("invalid value for 'sign-return-address' attribute: " + S, V);
2904 }
2905
2906 if (auto A = Attrs.getFnAttr("sign-return-address-key"); A.isValid()) {
2907 StringRef S = A.getValueAsString();
2908 if (S != "a_key" && S != "b_key")
2909 CheckFailed("invalid value for 'sign-return-address-key' attribute: " + S,
2910 V);
2911 if (auto AA = Attrs.getFnAttr("sign-return-address"); !AA.isValid()) {
2912 CheckFailed(
2913 "'sign-return-address-key' present without `sign-return-address`");
2914 }
2915 }
2916
2917 if (auto A = Attrs.getFnAttr("sign-return-address-harden"); A.isValid()) {
2918 StringRef S = A.getValueAsString();
2919 if (S != "load-return-address" && S != "none")
2920 CheckFailed(
2921 "invalid value for 'sign-return-address-harden' attribute: " + S, V);
2922 auto SignRetA = Attrs.getFnAttr("sign-return-address");
2923 auto PAuthRetA = Attrs.getFnAttr("ptrauth-returns");
2924 if (!SignRetA.isValid() && !PAuthRetA.isValid())
2925 CheckFailed("'sign-return-address-harden' present without "
2926 "'sign-return-address' or 'ptrauth-returns'");
2927 }
2928
2929 if (auto A = Attrs.getFnAttr("branch-target-enforcement"); A.isValid()) {
2930 StringRef S = A.getValueAsString();
2931 if (S != "" && S != "true" && S != "false")
2932 CheckFailed(
2933 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2934 }
2935
2936 if (auto A = Attrs.getFnAttr("branch-protection-pauth-lr"); A.isValid()) {
2937 StringRef S = A.getValueAsString();
2938 if (S != "" && S != "true" && S != "false")
2939 CheckFailed(
2940 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2941 }
2942
2943 if (auto A = Attrs.getFnAttr("guarded-control-stack"); A.isValid()) {
2944 StringRef S = A.getValueAsString();
2945 if (S != "" && S != "true" && S != "false")
2946 CheckFailed("invalid value for 'guarded-control-stack' attribute: " + S,
2947 V);
2948 }
2949
2950 if (auto A = Attrs.getFnAttr("vector-function-abi-variant"); A.isValid()) {
2951 StringRef S = A.getValueAsString();
2952 const std::optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, FT);
2953 if (!Info)
2954 CheckFailed("invalid name for a VFABI variant: " + S, V);
2955 }
2956
2957 if (auto A = Attrs.getFnAttr("modular-format"); A.isValid()) {
2958 StringRef S = A.getValueAsString();
2960 S.split(Args, ',');
2961 Check(Args.size() >= 5,
2962 "modular-format attribute requires at least 5 arguments", V);
2963 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2964 unsigned FormatIdx;
2965 Check(!Args[1].getAsInteger(10, FormatIdx),
2966 "modular-format attribute format string index is not an integer", V);
2967 Check(FormatIdx > 0,
2968 "modular-format attribute format string index must be greater than 0",
2969 V);
2970 Check(FormatIdx <= UpperBound,
2971 "modular-format attribute format string index is out of bounds", V);
2972 unsigned FirstArgIdx;
2973 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2974 "modular-format attribute first arg index is not an integer", V);
2975 Check(FirstArgIdx <= UpperBound,
2976 "modular-format attribute first arg index is out of bounds", V);
2977 Check(!Args[3].empty(),
2978 "modular-format attribute modular implementation function name "
2979 "cannot be empty",
2980 V);
2981 Check(!Args[4].empty(),
2982 "modular-format attribute implementation name cannot be empty", V);
2983 }
2984
2985 if (auto A = Attrs.getFnAttr("target-features"); A.isValid()) {
2986 StringRef S = A.getValueAsString();
2987 if (!S.empty()) {
2988 for (auto FeatureFlag : split(S, ',')) {
2989 if (FeatureFlag.empty())
2990 CheckFailed(
2991 "target-features attribute should not contain an empty string");
2992 else
2993 Check(FeatureFlag[0] == '+' || FeatureFlag[0] == '-',
2994 "target feature '" + FeatureFlag +
2995 "' must start with a '+' or '-'",
2996 V);
2997 }
2998 }
2999 }
3000
3001 Check(!(Attrs.hasFnAttr(Attribute::Hot) && Attrs.hasFnAttr(Attribute::Cold)),
3002 "Attributes 'hot' and 'cold' are incompatible");
3003
3004 if (Attrs.hasFnAttr("mnop-mcount")) {
3005 auto A = Attrs.getFnAttr("fentry-call");
3006 Check(A.isValid() && A.getValueAsString() == "true",
3007 "mnop-mcount only supported with fentry-call");
3008 }
3009
3010 if (Attrs.hasFnAttr("mrecord-mcount")) {
3011 auto A = Attrs.getFnAttr("fentry-call");
3012 Check(A.isValid() && A.getValueAsString() == "true",
3013 "mrecord-mcount only supported with fentry-call");
3014 }
3015
3016 if (Attrs.hasFnAttr("oracle-function")) {
3017 const auto *F = dyn_cast<Function>(V);
3018 Check(F, "\"oracle-function\" attribute only applies to functions", V);
3019 Check(F->hasLocalLinkage(), "oracle function must have local linkage", V);
3020 Check(F->onlyReadsMemory() && F->onlyAccessesArgMemory() &&
3021 F->doesNotThrow() && F->hasNoSync() && F->willReturn(),
3022 "oracle function must be nounwind, nosync and willreturn, must not "
3023 "have side effects and may only read memory through its arguments",
3024 V);
3025 Check(FT->getReturnType()->isIntegerTy(64),
3026 "oracle function must return i64", V);
3027 Check(!FT->isVarArg(), "oracle function must have a fixed argument list",
3028 V);
3029 if (M.isMaterialized()) {
3030 for (const Use &U : F->uses()) {
3031 auto *II = dyn_cast<IntrinsicInst>(U.getUser());
3032 Check(II && II->getIntrinsicID() == Intrinsic::speculative_load &&
3033 II->isArgOperand(&U) && II->getArgOperandNo(&U) == 2,
3034 "oracle function may only be used as the oracle operand of "
3035 "llvm.speculative.load",
3036 V, U.getUser());
3037 }
3038 }
3039 }
3040}
3041
3042void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
3043 Check(MD->getNumOperands() == 2,
3044 "'unknown' !prof should have a single additional operand", MD);
3045 auto *PassName = dyn_cast<MDString>(MD->getOperand(1));
3046 Check(PassName != nullptr,
3047 "'unknown' !prof should have an additional operand of type "
3048 "string");
3049 Check(!PassName->getString().empty(),
3050 "the 'unknown' !prof operand should not be an empty string");
3051}
3052
3053void Verifier::verifyFunctionMetadata(
3054 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
3055 for (const auto &Pair : MDs) {
3056 if (Pair.first == LLVMContext::MD_prof) {
3057 MDNode *MD = Pair.second;
3058 Check(MD->getNumOperands() >= 2,
3059 "!prof annotations should have no less than 2 operands", MD);
3060 // We may have functions that are synthesized by the compiler, e.g. in
3061 // WPD, that we can't currently determine the entry count.
3062 if (MD->getOperand(0).equalsStr(
3064 verifyUnknownProfileMetadata(MD);
3065 continue;
3066 }
3067
3068 // Check first operand.
3069 Check(MD->getOperand(0) != nullptr, "first operand should not be null",
3070 MD);
3072 "expected string with name of the !prof annotation", MD);
3073 MDString *MDS = cast<MDString>(MD->getOperand(0));
3074 StringRef ProfName = MDS->getString();
3076 "first operand should be 'function_entry_count'", MD);
3077
3078 // Check second operand.
3079 Check(MD->getOperand(1) != nullptr, "second operand should not be null",
3080 MD);
3082 "expected integer argument to function_entry_count", MD);
3083 } else if (Pair.first == LLVMContext::MD_kcfi_type) {
3084 MDNode *MD = Pair.second;
3085 Check(MD->getNumOperands() == 1,
3086 "!kcfi_type must have exactly one operand", MD);
3087 Check(MD->getOperand(0) != nullptr, "!kcfi_type operand must not be null",
3088 MD);
3090 "expected a constant operand for !kcfi_type", MD);
3091 Constant *C = cast<ConstantAsMetadata>(MD->getOperand(0))->getValue();
3092 Check(isa<ConstantInt>(C) && isa<IntegerType>(C->getType()),
3093 "expected a constant integer operand for !kcfi_type", MD);
3095 "expected a 32-bit integer constant operand for !kcfi_type", MD);
3096 } else if (Pair.first == Context.getMDKindID("reqd_work_group_size")) {
3097 MDNode *MD = Pair.second;
3098 Check(MD->getNumOperands() == 3,
3099 "reqd_work_group_size must have exactly three operands", MD);
3100 if (MD->getNumOperands() != 3)
3101 continue;
3102
3103 uint64_t Product = 1;
3104 for (unsigned I = 0; I != 3; ++I) {
3105 ConstantInt *C = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
3106 Check(C, "reqd_work_group_size operands must be integer constants", MD);
3107 if (!C)
3108 break;
3109
3110 const APInt &Value = C->getValue();
3111 Check(Value.getActiveBits() <= 64,
3112 "reqd_work_group_size operands must fit in 64 bits", MD);
3113 if (Value.getActiveBits() > 64)
3114 break;
3115
3116 uint64_t Dim = Value.getZExtValue();
3117 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
3118 "reqd_work_group_size product must fit in 64 bits", MD);
3119 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
3120 break;
3121 Product *= Dim;
3122 }
3123 }
3124 }
3125}
3126
3127void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
3128 if (EntryC->getNumOperands() == 0)
3129 return;
3130
3131 if (!ConstantExprVisited.insert(EntryC).second)
3132 return;
3133
3135 Stack.push_back(EntryC);
3136
3137 while (!Stack.empty()) {
3138 const Constant *C = Stack.pop_back_val();
3139
3140 // Check this constant expression.
3141 if (const auto *CE = dyn_cast<ConstantExpr>(C))
3142 visitConstantExpr(CE);
3143
3144 if (const auto *CPA = dyn_cast<ConstantPtrAuth>(C))
3145 visitConstantPtrAuth(CPA);
3146
3147 if (const auto *GV = dyn_cast<GlobalValue>(C)) {
3148 // Global Values get visited separately, but we do need to make sure
3149 // that the global value is in the correct module
3150 Check(GV->getParent() == &M, "Referencing global in another module!",
3151 EntryC, &M, GV, GV->getParent());
3152 continue;
3153 }
3154
3155 // Visit all sub-expressions.
3156 for (const Use &U : C->operands()) {
3157 const auto *OpC = dyn_cast<Constant>(U);
3158 if (!OpC)
3159 continue;
3160 if (!ConstantExprVisited.insert(OpC).second)
3161 continue;
3162 Stack.push_back(OpC);
3163 }
3164 }
3165}
3166
3167void Verifier::visitConstantExpr(const ConstantExpr *CE) {
3168 if (CE->getOpcode() == Instruction::BitCast) {
3169 Check(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
3170 CE->getType()),
3171 "Invalid bitcast", CE);
3172 Check(DL.getTypeSizeInBits(CE->getOperand(0)->getType()) ==
3173 DL.getTypeSizeInBits(CE->getType()),
3174 "Invalid bitcast", CE);
3175 } else if (CE->getOpcode() == Instruction::PtrToAddr)
3176 checkPtrToAddr(CE->getOperand(0)->getType(), CE->getType(), *CE);
3177 else if (CE->getOpcode() == Instruction::GetElementPtr)
3178 checkGEPOperator(cast<GEPOperator>(*CE));
3179}
3180
3181void Verifier::visitConstantPtrAuth(const ConstantPtrAuth *CPA) {
3182 Check(CPA->getPointer()->getType()->isPointerTy(),
3183 "signed ptrauth constant base pointer must have pointer type");
3184
3185 Check(CPA->getType() == CPA->getPointer()->getType(),
3186 "signed ptrauth constant must have same type as its base pointer");
3187
3188 Check(CPA->getKey()->getBitWidth() == 32,
3189 "signed ptrauth constant key must be i32 constant integer");
3190
3192 "signed ptrauth constant address discriminator must be a pointer");
3193
3194 Check(CPA->getDiscriminator()->getBitWidth() == 64,
3195 "signed ptrauth constant discriminator must be i64 constant integer");
3196
3198 "signed ptrauth constant deactivation symbol must be a pointer");
3199
3202 "signed ptrauth constant deactivation symbol must be a global value "
3203 "or null");
3204}
3205
3206bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) {
3207 // There shouldn't be more attribute sets than there are parameters plus the
3208 // function and return value.
3209 return Attrs.getNumAttrSets() <= Params + 2;
3210}
3211
3212void Verifier::verifyInlineAsmCall(const CallBase &Call) {
3213 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
3214 unsigned ArgNo = 0;
3215 unsigned LabelNo = 0;
3216 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
3217 if (CI.Type == InlineAsm::isLabel) {
3218 ++LabelNo;
3219 continue;
3220 }
3221
3222 // Only deal with constraints that correspond to call arguments.
3223 if (!CI.hasArg())
3224 continue;
3225
3226 if (CI.isIndirect) {
3227 const Value *Arg = Call.getArgOperand(ArgNo);
3228 Check(Arg->getType()->isPointerTy(),
3229 "Operand for indirect constraint must have pointer type", &Call);
3230
3232 "Operand for indirect constraint must have elementtype attribute",
3233 &Call);
3234 } else {
3235 Check(!Call.paramHasAttr(ArgNo, Attribute::ElementType),
3236 "Elementtype attribute can only be applied for indirect "
3237 "constraints",
3238 &Call);
3239 }
3240
3241 ArgNo++;
3242 }
3243
3244 if (auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
3245 Check(LabelNo == CallBr->getNumIndirectDests(),
3246 "Number of label constraints does not match number of callbr dests",
3247 &Call);
3248 } else {
3249 Check(LabelNo == 0, "Label constraints can only be used with callbr",
3250 &Call);
3251 }
3252}
3253
3254/// Verify that statepoint intrinsic is well formed.
3255void Verifier::verifyStatepoint(const CallBase &Call) {
3256 assert(Call.getIntrinsicID() == Intrinsic::experimental_gc_statepoint);
3257
3260 "gc.statepoint must read and write all memory to preserve "
3261 "reordering restrictions required by safepoint semantics",
3262 Call);
3263
3264 const int64_t NumPatchBytes =
3265 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue();
3266 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
3267 Check(NumPatchBytes >= 0,
3268 "gc.statepoint number of patchable bytes must be "
3269 "positive",
3270 Call);
3271
3272 Type *TargetElemType = Call.getParamElementType(2);
3273 Check(TargetElemType,
3274 "gc.statepoint callee argument must have elementtype attribute", Call);
3275 auto *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
3276 Check(TargetFuncType,
3277 "gc.statepoint callee elementtype must be function type", Call);
3278
3279 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue();
3280 Check(NumCallArgs >= 0,
3281 "gc.statepoint number of arguments to underlying call "
3282 "must be positive",
3283 Call);
3284 const int NumParams = (int)TargetFuncType->getNumParams();
3285 if (TargetFuncType->isVarArg()) {
3286 Check(NumCallArgs >= NumParams,
3287 "gc.statepoint mismatch in number of vararg call args", Call);
3288
3289 // TODO: Remove this limitation
3290 Check(TargetFuncType->getReturnType()->isVoidTy(),
3291 "gc.statepoint doesn't support wrapping non-void "
3292 "vararg functions yet",
3293 Call);
3294 } else
3295 Check(NumCallArgs == NumParams,
3296 "gc.statepoint mismatch in number of call args", Call);
3297
3298 const uint64_t Flags
3299 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue();
3300 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
3301 "unknown flag used in gc.statepoint flags argument", Call);
3302
3303 // Verify that the types of the call parameter arguments match
3304 // the type of the wrapped callee.
3305 AttributeList Attrs = Call.getAttributes();
3306 for (int i = 0; i < NumParams; i++) {
3307 Type *ParamType = TargetFuncType->getParamType(i);
3308 Type *ArgType = Call.getArgOperand(5 + i)->getType();
3309 Check(ArgType == ParamType,
3310 "gc.statepoint call argument does not match wrapped "
3311 "function type",
3312 Call);
3313
3314 if (TargetFuncType->isVarArg()) {
3315 AttributeSet ArgAttrs = Attrs.getParamAttrs(5 + i);
3316 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
3317 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
3318 }
3319 }
3320
3321 const int EndCallArgsInx = 4 + NumCallArgs;
3322
3323 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1);
3324 Check(isa<ConstantInt>(NumTransitionArgsV),
3325 "gc.statepoint number of transition arguments "
3326 "must be constant integer",
3327 Call);
3328 const int NumTransitionArgs =
3329 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
3330 Check(NumTransitionArgs == 0,
3331 "gc.statepoint w/inline transition bundle is deprecated", Call);
3332 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
3333
3334 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1);
3335 Check(isa<ConstantInt>(NumDeoptArgsV),
3336 "gc.statepoint number of deoptimization arguments "
3337 "must be constant integer",
3338 Call);
3339 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
3340 Check(NumDeoptArgs == 0,
3341 "gc.statepoint w/inline deopt operands is deprecated", Call);
3342
3343 const int ExpectedNumArgs = 7 + NumCallArgs;
3344 Check(ExpectedNumArgs == (int)Call.arg_size(),
3345 "gc.statepoint too many arguments", Call);
3346
3347 // Check that the only uses of this gc.statepoint are gc.result or
3348 // gc.relocate calls which are tied to this statepoint and thus part
3349 // of the same statepoint sequence
3350 for (const User *U : Call.users()) {
3351 const auto *UserCall = dyn_cast<const CallInst>(U);
3352 Check(UserCall, "illegal use of statepoint token", Call, U);
3353 if (!UserCall)
3354 continue;
3355 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
3356 "gc.result or gc.relocate are the only value uses "
3357 "of a gc.statepoint",
3358 Call, U);
3359 if (isa<GCResultInst>(UserCall)) {
3360 Check(UserCall->getArgOperand(0) == &Call,
3361 "gc.result connected to wrong gc.statepoint", Call, UserCall);
3362 } else if (isa<GCRelocateInst>(Call)) {
3363 Check(UserCall->getArgOperand(0) == &Call,
3364 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
3365 }
3366 }
3367
3368 // Note: It is legal for a single derived pointer to be listed multiple
3369 // times. It's non-optimal, but it is legal. It can also happen after
3370 // insertion if we strip a bitcast away.
3371 // Note: It is really tempting to check that each base is relocated and
3372 // that a derived pointer is never reused as a base pointer. This turns
3373 // out to be problematic since optimizations run after safepoint insertion
3374 // can recognize equality properties that the insertion logic doesn't know
3375 // about. See example statepoint.ll in the verifier subdirectory
3376}
3377
3378void Verifier::verifyFrameRecoverIndices() {
3379 for (auto &Counts : FrameEscapeInfo) {
3380 Function *F = Counts.first;
3381 unsigned EscapedObjectCount = Counts.second.first;
3382 unsigned MaxRecoveredIndex = Counts.second.second;
3383 Check(MaxRecoveredIndex <= EscapedObjectCount,
3384 "all indices passed to llvm.localrecover must be less than the "
3385 "number of arguments passed to llvm.localescape in the parent "
3386 "function",
3387 F);
3388 }
3389}
3390
3391static Instruction *getSuccPad(Instruction *Terminator) {
3392 BasicBlock *UnwindDest;
3393 if (auto *II = dyn_cast<InvokeInst>(Terminator))
3394 UnwindDest = II->getUnwindDest();
3395 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
3396 UnwindDest = CSI->getUnwindDest();
3397 else
3398 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
3399 return &*UnwindDest->getFirstNonPHIIt();
3400}
3401
3402void Verifier::verifySiblingFuncletUnwinds() {
3403 llvm::TimeTraceScope timeScope("Verifier verify sibling funclet unwinds");
3404 SmallPtrSet<Instruction *, 8> Visited;
3405 SmallPtrSet<Instruction *, 8> Active;
3406 for (const auto &Pair : SiblingFuncletInfo) {
3407 Instruction *PredPad = Pair.first;
3408 if (Visited.count(PredPad))
3409 continue;
3410 Active.insert(PredPad);
3411 Instruction *Terminator = Pair.second;
3412 do {
3413 Instruction *SuccPad = getSuccPad(Terminator);
3414 if (Active.count(SuccPad)) {
3415 // Found a cycle; report error
3416 Instruction *CyclePad = SuccPad;
3417 SmallVector<Instruction *, 8> CycleNodes;
3418 do {
3419 CycleNodes.push_back(CyclePad);
3420 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3421 if (CycleTerminator != CyclePad)
3422 CycleNodes.push_back(CycleTerminator);
3423 CyclePad = getSuccPad(CycleTerminator);
3424 } while (CyclePad != SuccPad);
3425 Check(false, "EH pads can't handle each other's exceptions",
3426 ArrayRef<Instruction *>(CycleNodes));
3427 }
3428 // Don't re-walk a node we've already checked
3429 if (!Visited.insert(SuccPad).second)
3430 break;
3431 // Walk to this successor if it has a map entry.
3432 PredPad = SuccPad;
3433 auto TermI = SiblingFuncletInfo.find(PredPad);
3434 if (TermI == SiblingFuncletInfo.end())
3435 break;
3436 Terminator = TermI->second;
3437 Active.insert(PredPad);
3438 } while (true);
3439 // Each node only has one successor, so we've walked all the active
3440 // nodes' successors.
3441 Active.clear();
3442 }
3443}
3444
3445// visitFunction - Verify that a function is ok.
3446//
3447void Verifier::visitFunction(const Function &F) {
3448 visitGlobalValue(F);
3449
3450 // Check function arguments.
3451 FunctionType *FT = F.getFunctionType();
3452 unsigned NumArgs = F.arg_size();
3453
3454 Check(&Context == &F.getContext(),
3455 "Function context does not match Module context!", &F);
3456
3457 Check(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
3458 Check(FT->getNumParams() == NumArgs,
3459 "# formal arguments must match # of arguments for function type!", &F,
3460 FT);
3461 Check(F.getReturnType()->isFirstClassType() ||
3462 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
3463 "Functions cannot return aggregate values!", &F);
3464
3465 Check(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
3466 "Invalid struct return type!", &F);
3467
3468 if (MaybeAlign A = F.getAlign()) {
3469 Check(A->value() <= Value::MaximumAlignment,
3470 "huge alignment values are unsupported", &F);
3471 }
3472
3473 AttributeList Attrs = F.getAttributes();
3474
3475 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3476 "Attribute after last parameter!", &F);
3477
3478 bool IsIntrinsic = F.isIntrinsic();
3479
3480 // Check function attributes.
3481 verifyFunctionAttrs(FT, Attrs, &F, IsIntrinsic, /* IsInlineAsm */ false);
3482
3483 // On function declarations/definitions, we do not support the builtin
3484 // attribute. We do not check this in VerifyFunctionAttrs since that is
3485 // checking for Attributes that can/can not ever be on functions.
3486 Check(!Attrs.hasFnAttr(Attribute::Builtin),
3487 "Attribute 'builtin' can only be applied to a callsite.", &F);
3488
3489 Check(!Attrs.hasAttrSomewhere(Attribute::ElementType),
3490 "Attribute 'elementtype' can only be applied to a callsite.", &F);
3491
3492 if (Attrs.hasFnAttr(Attribute::Naked))
3493 for (const Argument &Arg : F.args())
3494 Check(Arg.use_empty(), "cannot use argument of naked function", &Arg);
3495
3496 // Check that this function meets the restrictions on this calling convention.
3497 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
3498 // restrictions can be lifted.
3499 switch (F.getCallingConv()) {
3500 default:
3501 case CallingConv::C:
3502 break;
3503 case CallingConv::X86_INTR: {
3504 Check(F.arg_empty() || Attrs.hasParamAttr(0, Attribute::ByVal),
3505 "Calling convention parameter requires byval", &F);
3506 break;
3507 }
3508 case CallingConv::AMDGPU_KERNEL:
3509 case CallingConv::SPIR_KERNEL:
3510 case CallingConv::AMDGPU_CS_Chain:
3511 case CallingConv::AMDGPU_CS_ChainPreserve:
3512 Check(F.getReturnType()->isVoidTy(),
3513 "Calling convention requires void return type", &F);
3514 [[fallthrough]];
3515 case CallingConv::AMDGPU_VS:
3516 case CallingConv::AMDGPU_HS:
3517 case CallingConv::AMDGPU_GS:
3518 case CallingConv::AMDGPU_PS:
3519 case CallingConv::AMDGPU_CS:
3520 Check(!F.hasStructRetAttr(), "Calling convention does not allow sret", &F);
3521 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3522 const unsigned StackAS = DL.getAllocaAddrSpace();
3523 unsigned i = 0;
3524 for (const Argument &Arg : F.args()) {
3525 Check(!Attrs.hasParamAttr(i, Attribute::ByVal),
3526 "Calling convention disallows byval", &F);
3527 Check(!Attrs.hasParamAttr(i, Attribute::Preallocated),
3528 "Calling convention disallows preallocated", &F);
3529 Check(!Attrs.hasParamAttr(i, Attribute::InAlloca),
3530 "Calling convention disallows inalloca", &F);
3531
3532 if (Attrs.hasParamAttr(i, Attribute::ByRef)) {
3533 // FIXME: Should also disallow LDS and GDS, but we don't have the enum
3534 // value here.
3535 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3536 "Calling convention disallows stack byref", &F);
3537 }
3538
3539 ++i;
3540 }
3541 }
3542
3543 [[fallthrough]];
3544 case CallingConv::Fast:
3545 case CallingConv::Cold:
3546 case CallingConv::Intel_OCL_BI:
3547 case CallingConv::PTX_Device:
3548 Check(!F.isVarArg(),
3549 "Calling convention does not support varargs or "
3550 "perfect forwarding!",
3551 &F);
3552 break;
3553 case CallingConv::PTX_Kernel:
3554 // PTX permits the abi_preserve directives only between a .func directive
3555 // and its body, so a kernel cannot express them.
3556 for (StringLiteral Attr : NVVMAttr::AbiPreserveAttrs)
3557 Check(!F.hasFnAttribute(Attr),
3558 "'" + Attr + "' is not allowed on kernel functions", &F);
3559 Check(!F.isVarArg(),
3560 "Calling convention does not support varargs or "
3561 "perfect forwarding!",
3562 &F);
3563 break;
3564 case CallingConv::AMDGPU_Gfx_WholeWave:
3565 Check(!F.arg_empty() && F.arg_begin()->getType()->isIntegerTy(1),
3566 "Calling convention requires first argument to be i1", &F);
3567 Check(!F.arg_begin()->hasInRegAttr(),
3568 "Calling convention requires first argument to not be inreg", &F);
3569 Check(!F.isVarArg(),
3570 "Calling convention does not support varargs or "
3571 "perfect forwarding!",
3572 &F);
3573 break;
3574 }
3575
3576 // Check that the argument values match the function type for this function...
3577 unsigned i = 0;
3578 for (const Argument &Arg : F.args()) {
3579 Check(Arg.getType() == FT->getParamType(i),
3580 "Argument value does not match function argument type!", &Arg,
3581 FT->getParamType(i));
3582 Check(Arg.getType()->isFirstClassType(),
3583 "Function arguments must have first-class types!", &Arg);
3584 if (!IsIntrinsic) {
3585 Check(!Arg.getType()->isMetadataTy(),
3586 "Function takes metadata but isn't an intrinsic", &Arg, &F);
3587 Check(!Arg.getType()->isTokenLikeTy(),
3588 "Function takes token but isn't an intrinsic", &Arg, &F);
3589 Check(!Arg.getType()->isX86_AMXTy(),
3590 "Function takes x86_amx but isn't an intrinsic", &Arg, &F);
3591 }
3592
3593 // Check that swifterror argument is only used by loads and stores.
3594 if (Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3595 verifySwiftErrorValue(&Arg);
3596 }
3597 ++i;
3598 }
3599
3600 if (!IsIntrinsic) {
3601 Check(!F.getReturnType()->isTokenLikeTy(),
3602 "Function returns a token but isn't an intrinsic", &F);
3603 Check(!F.getReturnType()->isX86_AMXTy(),
3604 "Function returns a x86_amx but isn't an intrinsic", &F);
3605 }
3606
3607 // Get the function metadata attachments.
3609 F.getAllMetadata(MDs);
3610 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
3611 verifyFunctionMetadata(MDs);
3612
3613 // Target-specific function metadata checks.
3615
3616 // Check validity of the personality function
3617 if (F.hasPersonalityFn()) {
3618 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
3619 if (Per)
3620 Check(Per->getParent() == F.getParent(),
3621 "Referencing personality function in another module!", &F,
3622 F.getParent(), Per, Per->getParent());
3623 }
3624
3625 // EH funclet coloring can be expensive, recompute on-demand
3626 BlockEHFuncletColors.clear();
3627
3628 if (F.isMaterializable()) {
3629 // Function has a body somewhere we can't see.
3630 Check(MDs.empty(), "unmaterialized function cannot have metadata", &F,
3631 MDs.empty() ? nullptr : MDs.front().second);
3632 } else if (F.isDeclaration()) {
3633 for (const auto &I : MDs) {
3634 // This is used for call site debug information.
3635 CheckDI(I.first != LLVMContext::MD_dbg ||
3636 !cast<DISubprogram>(I.second)->isDistinct(),
3637 "function declaration may only have a unique !dbg attachment",
3638 &F);
3639 Check(I.first != LLVMContext::MD_prof,
3640 "function declaration may not have a !prof attachment", &F);
3641
3642 // Verify the metadata itself.
3643 visitMDNode(*I.second, AreDebugLocsAllowed::Yes);
3644 }
3645 Check(!F.hasPersonalityFn(),
3646 "Function declaration shouldn't have a personality routine", &F);
3647 } else {
3648 // Verify that this function (which has a body) is not named "llvm.*". It
3649 // is not legal to define intrinsics.
3650 Check(!IsIntrinsic, "llvm intrinsics cannot be defined!", &F);
3651
3652 // Check the entry node
3653 const BasicBlock *Entry = &F.getEntryBlock();
3654 Check(pred_empty(Entry),
3655 "Entry block to function must not have predecessors!", Entry);
3656
3657 // The address of the entry block cannot be taken, unless it is dead.
3658 if (Entry->hasAddressTaken()) {
3659 Check(!BlockAddress::lookup(Entry)->isConstantUsed(),
3660 "blockaddress may not be used with the entry block!", Entry);
3661 }
3662
3663 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3664 NumKCFIAttachments = 0, NumFLMDAttachments = 0;
3665 // Visit metadata attachments.
3666 for (const auto &I : MDs) {
3667 // Verify that the attachment is legal.
3668 auto AllowLocs = AreDebugLocsAllowed::No;
3669 switch (I.first) {
3670 default:
3671 break;
3672 case LLVMContext::MD_dbg: {
3673 ++NumDebugAttachments;
3674 CheckDI(NumDebugAttachments == 1,
3675 "function must have a single !dbg attachment", &F, I.second);
3676 CheckDI(isa<DISubprogram>(I.second),
3677 "function !dbg attachment must be a subprogram", &F, I.second);
3678 CheckDI(cast<DISubprogram>(I.second)->isDistinct(),
3679 "function definition may only have a distinct !dbg attachment",
3680 &F);
3681
3682 auto *SP = cast<DISubprogram>(I.second);
3683 const Function *&AttachedTo = DISubprogramAttachments[SP];
3684 CheckDI(!AttachedTo || AttachedTo == &F,
3685 "DISubprogram attached to more than one function", SP, &F);
3686 AttachedTo = &F;
3687 AllowLocs = AreDebugLocsAllowed::Yes;
3688 break;
3689 }
3690 case LLVMContext::MD_prof:
3691 ++NumProfAttachments;
3692 Check(NumProfAttachments == 1,
3693 "function must have a single !prof attachment", &F, I.second);
3694 break;
3695 case LLVMContext::MD_kcfi_type:
3696 ++NumKCFIAttachments;
3697 Check(NumKCFIAttachments == 1,
3698 "function must have a single !kcfi_type attachment", &F,
3699 I.second);
3700 break;
3701 case LLVMContext::MD_annotation:
3702 visitAnnotationMetadata(I.second);
3703 break;
3704 case LLVMContext::MD_flmd:
3705 ++NumFLMDAttachments;
3706 Check(NumFLMDAttachments == 1,
3707 "function must have a single !flmd attachment", &F, I.second);
3708 break;
3709 }
3710
3711 // Verify the metadata itself.
3712 visitMDNode(*I.second, AllowLocs);
3713 }
3714 }
3715
3716 // If this function is actually an intrinsic, verify that it is only used in
3717 // direct call/invokes, never having its "address taken".
3718 // Only do this if the module is materialized, otherwise we don't have all the
3719 // uses.
3720 bool isMaterialized = F.getParent()->isMaterialized();
3721 if (F.isIntrinsic() && isMaterialized) {
3722 const User *U;
3723 if (F.hasAddressTaken(&U, false, true, false,
3724 /*IgnoreARCAttachedCall=*/true))
3725 Check(false, "Invalid user of intrinsic instruction!", U);
3726 }
3727
3728 // Verify if the intrinsic's signature and name are valid. We do this if
3729 // the intrinsic has at least one materialized use, or if the module is fully
3730 // materialized.
3731 Intrinsic::ID IID = F.getIntrinsicID();
3732 if (IID && (isMaterialized || !F.materialized_use_empty())) {
3733 // Verify that the intrinsic prototype lines up with what the .td files
3734 // describe.
3735 std::string ErrMsg;
3736 raw_string_ostream ErrOS(ErrMsg);
3737 SmallVector<Type *, 4> OverloadTys;
3738 bool IsValid = Intrinsic::isSignatureValid(IID, FT, OverloadTys, ErrOS);
3739 Printable PrintDecl([&F](raw_ostream &OS) { F.print(OS); });
3740 Check(IsValid, ErrMsg, PrintDecl);
3741
3742 // Now that we have the intrinsic ID and the actual argument types (and we
3743 // know they are legal for the intrinsic!) get the intrinsic name through
3744 // the usual means. This allows us to verify the mangling of argument types
3745 // into the name.
3746 const std::string ExpectedName = Intrinsic::getName(
3747 IID, OverloadTys, const_cast<Module *>(F.getParent()), FT);
3748 Check(ExpectedName == F.getName(),
3749 "Intrinsic name not mangled correctly for type arguments! "
3750 "Should be: " +
3751 ExpectedName,
3752 PrintDecl);
3753 }
3754
3755 auto *N = F.getSubprogram();
3756 HasDebugInfo = (N != nullptr);
3757 if (!HasDebugInfo)
3758 return;
3759
3760 // Check that the debug info recorded in the FLContext is valid.
3761 MDNode *RawFLContext = F.getMetadata(LLVMContext::MD_flmd);
3762 if (RawFLContext) {
3764 "Unexpected !flmd attachment to function", &F, RawFLContext);
3765 auto *FLContext = cast<MDFunctionLocalContext>(RawFLContext);
3766
3767 // Validate that the correct subprogram is present.
3768 CheckDI(!FLContext->getScopes().empty(),
3769 "Function-local context should contain a subprogram pointing at "
3770 "the function",
3771 FLContext, &F);
3772 CheckDI(!FLContext->getScopes().empty() &&
3773 isa_and_nonnull<DISubprogram>(FLContext->getScope(0).get()) &&
3774 cast<DISubprogram>(FLContext->getScope(0).get())->describes(&F),
3775 "First scope in function-local context should be subprogram "
3776 "pointing at the function",
3777 FLContext, &F, FLContext->getScope(0).get());
3778 }
3779
3780 // Check that all !dbg attachments lead to back to N.
3781 //
3782 // FIXME: Check this incrementally while visiting !dbg attachments.
3783 // FIXME: Only check when N is the canonical subprogram for F.
3784 SmallPtrSet<const MDNode *, 32> Seen;
3785 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) {
3786 // Be careful about using DILocation here since we might be dealing with
3787 // broken code (this is the Verifier after all).
3788 const DILocation *DL = dyn_cast_or_null<DILocation>(Node);
3789 if (!DL)
3790 return;
3791 if (!Seen.insert(DL).second)
3792 return;
3793
3794 Metadata *Parent = DL->getRawScope();
3795 CheckDI(Parent && isa<DILocalScope>(Parent),
3796 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, Parent);
3797
3798 DILocalScope *Scope = DL->getInlinedAtScope();
3799 Check(Scope, "Failed to find DILocalScope", DL);
3800
3801 if (!Seen.insert(Scope).second)
3802 return;
3803
3804 // Cycles are diagnosed when the DIScope nodes themselves are visited.
3805 if (hasDIScopeCycle(Scope))
3806 return;
3807
3808 DISubprogram *SP = Scope->getSubprogram();
3809
3810 // Scope and SP could be the same MDNode and we don't want to skip
3811 // validation in that case
3812 if ((Scope != SP) && !Seen.insert(SP).second)
3813 return;
3814
3815 CheckDI(SP->describes(&F),
3816 "!dbg attachment points at wrong subprogram for function", N, &F,
3817 &I, DL, Scope, SP);
3818 };
3819 for (auto &BB : F)
3820 for (auto &I : BB) {
3821 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode());
3822 // The llvm.loop annotations also contain two DILocations.
3823 if (auto MD = I.getMetadata(LLVMContext::MD_loop))
3824 for (unsigned i = 1; i < MD->getNumOperands(); ++i)
3825 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
3826 if (BrokenDebugInfo)
3827 return;
3828 }
3829}
3830
3831// verifyBasicBlock - Verify that a basic block is well formed...
3832//
3833void Verifier::visitBasicBlock(BasicBlock &BB) {
3834 InstsInThisBlock.clear();
3835 ConvergenceVerifyHelper.visit(BB);
3836
3837 // Check constraints that this basic block imposes on all of the PHI nodes in
3838 // it.
3839 if (isa<PHINode>(BB.front())) {
3840 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
3842 llvm::sort(Preds);
3843 for (const PHINode &PN : BB.phis()) {
3844 Check(PN.getNumIncomingValues() == Preds.size(),
3845 "PHINode should have one entry for each predecessor of its "
3846 "parent basic block!",
3847 &PN);
3848
3849 // Get and sort all incoming values in the PHI node...
3850 Values.clear();
3851 Values.reserve(PN.getNumIncomingValues());
3852 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3853 Values.push_back(
3854 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3856
3857 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
3858 // Check to make sure that if there is more than one entry for a
3859 // particular basic block in this PHI node, that the incoming values are
3860 // all identical.
3861 //
3862 Check(i == 0 || Values[i].first != Values[i - 1].first ||
3863 Values[i].second == Values[i - 1].second,
3864 "PHI node has multiple entries for the same basic block with "
3865 "different incoming values!",
3866 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
3867
3868 // Check to make sure that the predecessors and PHI node entries are
3869 // matched up.
3870 Check(Values[i].first == Preds[i],
3871 "PHI node entries do not match predecessors!", &PN,
3872 Values[i].first, Preds[i]);
3873 }
3874 }
3875 }
3876
3877 // Check that all instructions have their parent pointers set up correctly.
3878 for (auto &I : BB)
3879 {
3880 Check(I.getParent() == &BB, "Instruction has bogus parent pointer!");
3881 }
3882
3883 // Confirm that no issues arise from the debug program.
3884 CheckDI(!BB.getTrailingDbgRecords(), "Basic Block has trailing DbgRecords!",
3885 &BB);
3886}
3887
3888void Verifier::visitTerminator(Instruction &I) {
3889 // Ensure that terminators only exist at the end of the basic block.
3890 Check(&I == I.getParent()->getTerminator(),
3891 "Terminator found in the middle of a basic block!", I.getParent());
3892 visitInstruction(I);
3893}
3894
3895void Verifier::visitCondBrInst(CondBrInst &BI) {
3897 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
3898 visitTerminator(BI);
3899}
3900
3901void Verifier::visitReturnInst(ReturnInst &RI) {
3902 Function *F = RI.getParent()->getParent();
3903 unsigned N = RI.getNumOperands();
3904 if (F->getReturnType()->isVoidTy())
3905 Check(N == 0,
3906 "Found return instr that returns non-void in Function of void "
3907 "return type!",
3908 &RI, F->getReturnType());
3909 else
3910 Check(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
3911 "Function return type does not match operand "
3912 "type of return inst!",
3913 &RI, F->getReturnType());
3914
3915 // Check to make sure that the return value has necessary properties for
3916 // terminators...
3917 visitTerminator(RI);
3918}
3919
3920void Verifier::visitSwitchInst(SwitchInst &SI) {
3921 Check(SI.getType()->isVoidTy(), "Switch must have void result type!", &SI);
3922 // Check to make sure that all of the constants in the switch instruction
3923 // have the same type as the switched-on value.
3924 Type *SwitchTy = SI.getCondition()->getType();
3925 SmallPtrSet<ConstantInt*, 32> Constants;
3926 for (auto &Case : SI.cases()) {
3927 Check(isa<ConstantInt>(Case.getCaseValue()),
3928 "Case value is not a constant integer.", &SI);
3929 Check(Case.getCaseValue()->getType() == SwitchTy,
3930 "Switch constants must all be same type as switch value!", &SI);
3931 Check(Constants.insert(Case.getCaseValue()).second,
3932 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3933 }
3934
3935 visitTerminator(SI);
3936}
3937
3938void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3940 "Indirectbr operand must have pointer type!", &BI);
3941 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
3943 "Indirectbr destinations must all have pointer type!", &BI);
3944
3945 visitTerminator(BI);
3946}
3947
3949 // Currently we only support callbr for amdgcn.kill. Add more checks here as
3950 // needed.
3951 return isAMDGPUCallBrIntrinsic(ID);
3952}
3953
3954void Verifier::visitCallBrInst(CallBrInst &CBI) {
3955 if (!CBI.isInlineAsm()) {
3957 "callbr: indirect function / invalid signature");
3958 Check(!CBI.hasOperandBundles(),
3959 "callbr for intrinsics currently doesn't support operand bundles");
3960
3962 CheckFailed(
3963 "callbr currently only supports asm-goto and selected intrinsics");
3964 }
3965 visitIntrinsicCall(CBI.getIntrinsicID(), CBI);
3966 } else {
3967 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand());
3968 Check(!IA->canThrow(), "Unwinding from Callbr is not allowed");
3969
3970 verifyInlineAsmCall(CBI);
3971 }
3972 visitTerminator(CBI);
3973}
3974
3975void Verifier::visitSelectInst(SelectInst &SI) {
3976 Check(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
3977 SI.getOperand(2)),
3978 "Invalid operands for select instruction!", &SI);
3979
3980 Check(SI.getTrueValue()->getType() == SI.getType(),
3981 "Select values must have same type as select instruction!", &SI);
3982 visitInstruction(SI);
3983}
3984
3985/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
3986/// a pass, if any exist, it's an error.
3987///
3988void Verifier::visitUserOp1(Instruction &I) {
3989 Check(false, "User-defined operators should not live outside of a pass!", &I);
3990}
3991
3992void Verifier::visitTruncInst(TruncInst &I) {
3993 // Get the source and destination types
3994 Type *SrcTy = I.getOperand(0)->getType();
3995 Type *DestTy = I.getType();
3996
3997 // Get the size of the types in bits, we'll need this later
3998 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3999 unsigned DestBitSize = DestTy->getScalarSizeInBits();
4000
4001 Check(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
4002 Check(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
4003 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
4004 "trunc source and destination must both be a vector or neither", &I);
4005 Check(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
4006
4007 visitInstruction(I);
4008}
4009
4010void Verifier::visitZExtInst(ZExtInst &I) {
4011 // Get the source and destination types
4012 Type *SrcTy = I.getOperand(0)->getType();
4013 Type *DestTy = I.getType();
4014
4015 // Get the size of the types in bits, we'll need this later
4016 Check(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
4017 Check(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
4018 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
4019 "zext source and destination must both be a vector or neither", &I);
4020 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
4021 unsigned DestBitSize = DestTy->getScalarSizeInBits();
4022
4023 Check(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
4024
4025 visitInstruction(I);
4026}
4027
4028void Verifier::visitSExtInst(SExtInst &I) {
4029 // Get the source and destination types
4030 Type *SrcTy = I.getOperand(0)->getType();
4031 Type *DestTy = I.getType();
4032
4033 // Get the size of the types in bits, we'll need this later
4034 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
4035 unsigned DestBitSize = DestTy->getScalarSizeInBits();
4036
4037 Check(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
4038 Check(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
4039 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
4040 "sext source and destination must both be a vector or neither", &I);
4041 Check(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
4042
4043 visitInstruction(I);
4044}
4045
4046void Verifier::visitFPTruncInst(FPTruncInst &I) {
4047 // Get the source and destination types
4048 Type *SrcTy = I.getOperand(0)->getType();
4049 Type *DestTy = I.getType();
4050 // Get the size of the types in bits, we'll need this later
4051 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
4052 unsigned DestBitSize = DestTy->getScalarSizeInBits();
4053
4054 Check(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
4055 Check(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
4056 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
4057 "fptrunc source and destination must both be a vector or neither", &I);
4058 Check(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
4059
4060 visitInstruction(I);
4061}
4062
4063void Verifier::visitFPExtInst(FPExtInst &I) {
4064 // Get the source and destination types
4065 Type *SrcTy = I.getOperand(0)->getType();
4066 Type *DestTy = I.getType();
4067
4068 // Get the size of the types in bits, we'll need this later
4069 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
4070 unsigned DestBitSize = DestTy->getScalarSizeInBits();
4071
4072 Check(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
4073 Check(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
4074 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(),
4075 "fpext source and destination must both be a vector or neither", &I);
4076 Check(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
4077
4078 visitInstruction(I);
4079}
4080
4081void Verifier::visitUIToFPInst(UIToFPInst &I) {
4082 // Get the source and destination types
4083 Type *SrcTy = I.getOperand(0)->getType();
4084 Type *DestTy = I.getType();
4085
4086 bool SrcVec = SrcTy->isVectorTy();
4087 bool DstVec = DestTy->isVectorTy();
4088
4089 Check(SrcVec == DstVec,
4090 "UIToFP source and dest must both be vector or scalar", &I);
4091 Check(SrcTy->isIntOrIntVectorTy(),
4092 "UIToFP source must be integer or integer vector", &I);
4093 Check(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
4094 &I);
4095
4096 if (SrcVec && DstVec)
4097 Check(cast<VectorType>(SrcTy)->getElementCount() ==
4098 cast<VectorType>(DestTy)->getElementCount(),
4099 "UIToFP source and dest vector length mismatch", &I);
4100
4101 visitInstruction(I);
4102}
4103
4104void Verifier::visitSIToFPInst(SIToFPInst &I) {
4105 // Get the source and destination types
4106 Type *SrcTy = I.getOperand(0)->getType();
4107 Type *DestTy = I.getType();
4108
4109 bool SrcVec = SrcTy->isVectorTy();
4110 bool DstVec = DestTy->isVectorTy();
4111
4112 Check(SrcVec == DstVec,
4113 "SIToFP source and dest must both be vector or scalar", &I);
4114 Check(SrcTy->isIntOrIntVectorTy(),
4115 "SIToFP source must be integer or integer vector", &I);
4116 Check(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
4117 &I);
4118
4119 if (SrcVec && DstVec)
4120 Check(cast<VectorType>(SrcTy)->getElementCount() ==
4121 cast<VectorType>(DestTy)->getElementCount(),
4122 "SIToFP source and dest vector length mismatch", &I);
4123
4124 visitInstruction(I);
4125}
4126
4127void Verifier::visitFPToUIInst(FPToUIInst &I) {
4128 // Get the source and destination types
4129 Type *SrcTy = I.getOperand(0)->getType();
4130 Type *DestTy = I.getType();
4131
4132 bool SrcVec = SrcTy->isVectorTy();
4133 bool DstVec = DestTy->isVectorTy();
4134
4135 Check(SrcVec == DstVec,
4136 "FPToUI source and dest must both be vector or scalar", &I);
4137 Check(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", &I);
4138 Check(DestTy->isIntOrIntVectorTy(),
4139 "FPToUI result must be integer or integer vector", &I);
4140
4141 if (SrcVec && DstVec)
4142 Check(cast<VectorType>(SrcTy)->getElementCount() ==
4143 cast<VectorType>(DestTy)->getElementCount(),
4144 "FPToUI source and dest vector length mismatch", &I);
4145
4146 visitInstruction(I);
4147}
4148
4149void Verifier::visitFPToSIInst(FPToSIInst &I) {
4150 // Get the source and destination types
4151 Type *SrcTy = I.getOperand(0)->getType();
4152 Type *DestTy = I.getType();
4153
4154 bool SrcVec = SrcTy->isVectorTy();
4155 bool DstVec = DestTy->isVectorTy();
4156
4157 Check(SrcVec == DstVec,
4158 "FPToSI source and dest must both be vector or scalar", &I);
4159 Check(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", &I);
4160 Check(DestTy->isIntOrIntVectorTy(),
4161 "FPToSI result must be integer or integer vector", &I);
4162
4163 if (SrcVec && DstVec)
4164 Check(cast<VectorType>(SrcTy)->getElementCount() ==
4165 cast<VectorType>(DestTy)->getElementCount(),
4166 "FPToSI source and dest vector length mismatch", &I);
4167
4168 visitInstruction(I);
4169}
4170
4171void Verifier::checkPtrToAddr(Type *SrcTy, Type *DestTy, const Value &V) {
4172 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToAddr source must be pointer", V);
4173 Check(DestTy->isIntOrIntVectorTy(), "PtrToAddr result must be integral", V);
4174 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToAddr type mismatch",
4175 V);
4176
4177 if (SrcTy->isVectorTy()) {
4178 auto *VSrc = cast<VectorType>(SrcTy);
4179 auto *VDest = cast<VectorType>(DestTy);
4180 Check(VSrc->getElementCount() == VDest->getElementCount(),
4181 "PtrToAddr vector length mismatch", V);
4182 }
4183
4184 Type *AddrTy = DL.getAddressType(SrcTy);
4185 Check(AddrTy == DestTy, "PtrToAddr result must be address width", V);
4186}
4187
4188void Verifier::visitPtrToAddrInst(PtrToAddrInst &I) {
4189 checkPtrToAddr(I.getOperand(0)->getType(), I.getType(), I);
4190 visitInstruction(I);
4191}
4192
4193void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
4194 // Get the source and destination types
4195 Type *SrcTy = I.getOperand(0)->getType();
4196 Type *DestTy = I.getType();
4197
4198 Check(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I);
4199
4200 Check(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I);
4201 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
4202 &I);
4203
4204 if (SrcTy->isVectorTy()) {
4205 auto *VSrc = cast<VectorType>(SrcTy);
4206 auto *VDest = cast<VectorType>(DestTy);
4207 Check(VSrc->getElementCount() == VDest->getElementCount(),
4208 "PtrToInt Vector length mismatch", &I);
4209 }
4210
4211 visitInstruction(I);
4212}
4213
4214void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
4215 // Get the source and destination types
4216 Type *SrcTy = I.getOperand(0)->getType();
4217 Type *DestTy = I.getType();
4218
4219 Check(SrcTy->isIntOrIntVectorTy(), "IntToPtr source must be an integral", &I);
4220 Check(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I);
4221
4222 Check(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
4223 &I);
4224 if (SrcTy->isVectorTy()) {
4225 auto *VSrc = cast<VectorType>(SrcTy);
4226 auto *VDest = cast<VectorType>(DestTy);
4227 Check(VSrc->getElementCount() == VDest->getElementCount(),
4228 "IntToPtr Vector length mismatch", &I);
4229 }
4230 visitInstruction(I);
4231}
4232
4233void Verifier::visitBitCastInst(BitCastInst &I) {
4234 Check(
4235 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
4236 "Invalid bitcast", &I);
4237 Check(DL.getTypeSizeInBits(I.getSrcTy()) ==
4238 DL.getTypeSizeInBits(I.getDestTy()),
4239 "Invalid bitcast", &I);
4240 visitInstruction(I);
4241}
4242
4243void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
4244 Type *SrcTy = I.getOperand(0)->getType();
4245 Type *DestTy = I.getType();
4246
4247 Check(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
4248 &I);
4249 Check(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
4250 &I);
4252 "AddrSpaceCast must be between different address spaces", &I);
4253 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
4254 Check(SrcVTy->getElementCount() ==
4255 cast<VectorType>(DestTy)->getElementCount(),
4256 "AddrSpaceCast vector pointer number of elements mismatch", &I);
4257 visitInstruction(I);
4258}
4259
4260/// visitPHINode - Ensure that a PHI node is well formed.
4261///
4262void Verifier::visitPHINode(PHINode &PN) {
4263 // Ensure that the PHI nodes are all grouped together at the top of the block.
4264 // This can be tested by checking whether the instruction before this is
4265 // either nonexistent (because this is begin()) or is a PHI node. If not,
4266 // then there is some other instruction before a PHI.
4267 Check(&PN == &PN.getParent()->front() ||
4269 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
4270
4271 // Check that a PHI doesn't yield a Token.
4272 Check(!PN.getType()->isTokenLikeTy(), "PHI nodes cannot have token type!");
4273
4274 // Check that all of the values of the PHI node have the same type as the
4275 // result.
4276 for (Value *IncValue : PN.incoming_values()) {
4277 Check(PN.getType() == IncValue->getType(),
4278 "PHI node operands are not the same type as the result!", &PN);
4279 }
4280
4281 // All other PHI node constraints are checked in the visitBasicBlock method.
4282
4283 visitInstruction(PN);
4284}
4285
4286void Verifier::visitCallBase(CallBase &Call) {
4288 "Called function must be a pointer!", Call);
4289 FunctionType *FTy = Call.getFunctionType();
4290
4291 // Verify that the correct number of arguments are being passed
4292 if (FTy->isVarArg())
4293 Check(Call.arg_size() >= FTy->getNumParams(),
4294 "Called function requires more parameters than were provided!", Call);
4295 else
4296 Check(Call.arg_size() == FTy->getNumParams(),
4297 "Incorrect number of arguments passed to called function!", Call);
4298
4299 // Verify that all arguments to the call match the function type.
4300 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
4301 Check(Call.getArgOperand(i)->getType() == FTy->getParamType(i),
4302 "Call parameter type does not match function signature!",
4303 Call.getArgOperand(i), FTy->getParamType(i), Call);
4304
4305 AttributeList Attrs = Call.getAttributes();
4306
4307 Check(verifyAttributeCount(Attrs, Call.arg_size()),
4308 "Attribute after last parameter!", Call);
4309
4310 auto *Callee =
4312 bool IsIntrinsic = Callee && Callee->isIntrinsic();
4313 if (IsIntrinsic)
4314 Check(Callee->getFunctionType() == FTy,
4315 "Intrinsic called with incompatible signature", Call);
4316
4317 // Verify if the calling convention of the callee is callable.
4319 "calling convention does not permit calls", Call);
4320
4321 // Disallow passing/returning values with alignment higher than we can
4322 // represent.
4323 // FIXME: Consider making DataLayout cap the alignment, so this isn't
4324 // necessary.
4325 auto VerifyTypeAlign = [&](Type *Ty, const Twine &Message) {
4326 if (!Ty->isSized())
4327 return;
4328 Align ABIAlign = DL.getABITypeAlign(Ty);
4329 Check(ABIAlign.value() <= Value::MaximumAlignment,
4330 "Incorrect alignment of " + Message + " to called function!", Call);
4331 };
4332
4333 if (!IsIntrinsic) {
4334 VerifyTypeAlign(FTy->getReturnType(), "return type");
4335 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4336 Type *Ty = FTy->getParamType(i);
4337 VerifyTypeAlign(Ty, "argument passed");
4338 }
4339 }
4340
4341 if (Attrs.hasFnAttr(Attribute::Speculatable)) {
4342 // Don't allow speculatable on call sites, unless the underlying function
4343 // declaration is also speculatable.
4344 Check(Callee && Callee->isSpeculatable(),
4345 "speculatable attribute may not apply to call sites", Call);
4346 }
4347
4348 if (Attrs.hasFnAttr(Attribute::Preallocated)) {
4349 Check(Call.getIntrinsicID() == Intrinsic::call_preallocated_arg,
4350 "preallocated as a call site attribute can only be on "
4351 "llvm.call.preallocated.arg");
4352 }
4353
4354 Check(!Attrs.hasFnAttr(Attribute::DenormalFPEnv),
4355 "denormal_fpenv attribute may not apply to call sites", Call);
4356
4357 // Verify call attributes.
4358 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic, Call.isInlineAsm());
4359
4360 // Conservatively check the inalloca argument.
4361 // We have a bug if we can find that there is an underlying alloca without
4362 // inalloca.
4363 if (Call.hasInAllocaArgument()) {
4364 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1);
4365 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
4366 Check(AI->isUsedWithInAlloca(),
4367 "inalloca argument for call has mismatched alloca", AI, Call);
4368 }
4369
4370 // For each argument of the callsite, if it has the swifterror argument,
4371 // make sure the underlying alloca/parameter it comes from has a swifterror as
4372 // well.
4373 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4374 if (Call.paramHasAttr(i, Attribute::SwiftError)) {
4375 Value *SwiftErrorArg = Call.getArgOperand(i);
4376 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) {
4377 Check(AI->isSwiftError(),
4378 "swifterror argument for call has mismatched alloca", AI, Call);
4379 continue;
4380 }
4381 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
4382 Check(ArgI, "swifterror argument should come from an alloca or parameter",
4383 SwiftErrorArg, Call);
4384 Check(ArgI->hasSwiftErrorAttr(),
4385 "swifterror argument for call has mismatched parameter", ArgI,
4386 Call);
4387 }
4388
4389 if (Attrs.hasParamAttr(i, Attribute::ImmArg)) {
4390 // Don't allow immarg on call sites, unless the underlying declaration
4391 // also has the matching immarg.
4392 Check(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg),
4393 "immarg may not apply only to call sites", Call.getArgOperand(i),
4394 Call);
4395 }
4396
4397 if (Call.paramHasAttr(i, Attribute::ImmArg)) {
4398 Value *ArgVal = Call.getArgOperand(i);
4399 Check((isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal)) &&
4400 !isa<VectorType>(ArgVal->getType()),
4401 "immarg operand has non-immediate parameter", ArgVal, Call);
4402
4403 // If the imm-arg is an integer and also has a range attached,
4404 // check if the given value is within the range.
4405 if (Call.paramHasAttr(i, Attribute::Range)) {
4406 if (auto *CI = dyn_cast<ConstantInt>(ArgVal)) {
4407 const ConstantRange &CR =
4408 Call.getParamAttr(i, Attribute::Range).getValueAsConstantRange();
4409 Check(CR.contains(CI->getValue()),
4410 formatv("immarg value {} for arg {} out of range {}",
4411 CI->getValue(), i, CR),
4412 Call);
4413 }
4414 }
4415 if (auto *CI = dyn_cast<ConstantInt>(ArgVal))
4417 CI->getValue()),
4418 formatv("immarg value {} for arg {} out of range set",
4419 CI->getValue(), i),
4420 Call);
4421 }
4422
4423 if (Call.paramHasAttr(i, Attribute::Preallocated)) {
4424 Value *ArgVal = Call.getArgOperand(i);
4425 bool hasOB =
4427 bool isMustTail = Call.isMustTailCall();
4428 Check(hasOB != isMustTail,
4429 "preallocated operand either requires a preallocated bundle or "
4430 "the call to be musttail (but not both)",
4431 ArgVal, Call);
4432 }
4433 }
4434
4435 if (FTy->isVarArg()) {
4436 // FIXME? is 'nest' even legal here?
4437 bool SawNest = false;
4438 bool SawReturned = false;
4439
4440 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
4441 if (Attrs.hasParamAttr(Idx, Attribute::Nest))
4442 SawNest = true;
4443 if (Attrs.hasParamAttr(Idx, Attribute::Returned))
4444 SawReturned = true;
4445 }
4446
4447 // Check attributes on the varargs part.
4448 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) {
4449 Type *Ty = Call.getArgOperand(Idx)->getType();
4450 AttributeSet ArgAttrs = Attrs.getParamAttrs(Idx);
4451 verifyParameterAttrs(ArgAttrs, Ty, &Call);
4452
4453 if (ArgAttrs.hasAttribute(Attribute::Nest)) {
4454 Check(!SawNest, "More than one parameter has attribute nest!", Call);
4455 SawNest = true;
4456 }
4457
4458 if (ArgAttrs.hasAttribute(Attribute::Returned)) {
4459 Check(!SawReturned, "More than one parameter has attribute returned!",
4460 Call);
4461 Check(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
4462 "Incompatible argument and return types for 'returned' "
4463 "attribute",
4464 Call);
4465 SawReturned = true;
4466 }
4467
4468 // Statepoint intrinsic is vararg but the wrapped function may be not.
4469 // Allow sret here and check the wrapped function in verifyStatepoint.
4470 if (Call.getIntrinsicID() != Intrinsic::experimental_gc_statepoint)
4471 Check(!ArgAttrs.hasAttribute(Attribute::StructRet),
4472 "Attribute 'sret' cannot be used for vararg call arguments!",
4473 Call);
4474
4475 if (ArgAttrs.hasAttribute(Attribute::InAlloca))
4476 Check(Idx == Call.arg_size() - 1,
4477 "inalloca isn't on the last argument!", Call);
4478 }
4479 }
4480
4481 // Verify that there's no metadata unless it's a direct call to an intrinsic.
4482 if (!IsIntrinsic) {
4483 for (Type *ParamTy : FTy->params()) {
4484 Check(!ParamTy->isMetadataTy(),
4485 "Function has metadata parameter but isn't an intrinsic", Call);
4486 Check(!ParamTy->isTokenLikeTy(),
4487 "Function has token parameter but isn't an intrinsic", Call);
4488 }
4489 }
4490
4491 // Verify that indirect calls don't return tokens.
4492 if (!Call.getCalledFunction()) {
4493 Check(!FTy->getReturnType()->isTokenLikeTy(),
4494 "Return type cannot be token for indirect call!");
4495 Check(!FTy->getReturnType()->isX86_AMXTy(),
4496 "Return type cannot be x86_amx for indirect call!");
4497 }
4498
4500 visitIntrinsicCall(ID, Call);
4501
4502 // Verify that a callsite has at most one "deopt", at most one "funclet", at
4503 // most one "gc-transition", at most one "cfguardtarget", at most one
4504 // "preallocated" operand bundle, and at most one "ptrauth" operand bundle.
4505 bool FoundDeoptBundle = false, FoundFuncletBundle = false,
4506 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false,
4507 FoundPreallocatedBundle = false, FoundGCLiveBundle = false,
4508 FoundPtrauthBundle = false, FoundKCFIBundle = false,
4509 FoundAttachedCallBundle = false;
4510 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) {
4511 OperandBundleUse BU = Call.getOperandBundleAt(i);
4512 for (const Value *Input : BU.Inputs)
4513 Check(!Input->getType()->isLabelTy(),
4514 "Operand bundle operands cannot be labels", Call);
4515 uint32_t Tag = BU.getTagID();
4516 if (Tag == LLVMContext::OB_deopt) {
4517 Check(!FoundDeoptBundle, "Multiple deopt operand bundles", Call);
4518 FoundDeoptBundle = true;
4519 } else if (Tag == LLVMContext::OB_gc_transition) {
4520 Check(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles",
4521 Call);
4522 FoundGCTransitionBundle = true;
4523 } else if (Tag == LLVMContext::OB_funclet) {
4524 Check(!FoundFuncletBundle, "Multiple funclet operand bundles", Call);
4525 FoundFuncletBundle = true;
4526 Check(BU.Inputs.size() == 1,
4527 "Expected exactly one funclet bundle operand", Call);
4528 Check(isa<FuncletPadInst>(BU.Inputs.front()),
4529 "Funclet bundle operands should correspond to a FuncletPadInst",
4530 Call);
4531 } else if (Tag == LLVMContext::OB_cfguardtarget) {
4532 Check(!FoundCFGuardTargetBundle, "Multiple CFGuardTarget operand bundles",
4533 Call);
4534 FoundCFGuardTargetBundle = true;
4535 Check(BU.Inputs.size() == 1,
4536 "Expected exactly one cfguardtarget bundle operand", Call);
4537 } else if (Tag == LLVMContext::OB_ptrauth) {
4538 Check(!FoundPtrauthBundle, "Multiple ptrauth operand bundles", Call);
4539 FoundPtrauthBundle = true;
4540 Check(BU.Inputs.size() == 2,
4541 "Expected exactly two ptrauth bundle operands", Call);
4542 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4543 BU.Inputs[0]->getType()->isIntegerTy(32),
4544 "Ptrauth bundle key operand must be an i32 constant", Call);
4545 Check(BU.Inputs[1]->getType()->isIntegerTy(64),
4546 "Ptrauth bundle discriminator operand must be an i64", Call);
4547 } else if (Tag == LLVMContext::OB_kcfi) {
4548 Check(!FoundKCFIBundle, "Multiple kcfi operand bundles", Call);
4549 FoundKCFIBundle = true;
4550 Check(BU.Inputs.size() == 1, "Expected exactly one kcfi bundle operand",
4551 Call);
4552 Check(isa<ConstantInt>(BU.Inputs[0]) &&
4553 BU.Inputs[0]->getType()->isIntegerTy(32),
4554 "Kcfi bundle operand must be an i32 constant", Call);
4555 } else if (Tag == LLVMContext::OB_preallocated) {
4556 Check(!FoundPreallocatedBundle, "Multiple preallocated operand bundles",
4557 Call);
4558 FoundPreallocatedBundle = true;
4559 Check(BU.Inputs.size() == 1,
4560 "Expected exactly one preallocated bundle operand", Call);
4561 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front());
4562 Check(Input &&
4563 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4564 "\"preallocated\" argument must be a token from "
4565 "llvm.call.preallocated.setup",
4566 Call);
4567 } else if (Tag == LLVMContext::OB_gc_live) {
4568 Check(!FoundGCLiveBundle, "Multiple gc-live operand bundles", Call);
4569 FoundGCLiveBundle = true;
4571 Check(!FoundAttachedCallBundle,
4572 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
4573 FoundAttachedCallBundle = true;
4574 verifyAttachedCallBundle(Call, BU);
4575 }
4576 }
4577
4578 // Verify that callee and callsite agree on whether to use pointer auth.
4579 Check(!(Call.getCalledFunction() && FoundPtrauthBundle),
4580 "Direct call cannot have a ptrauth bundle", Call);
4581
4582 // Verify that each inlinable callsite of a debug-info-bearing function in a
4583 // debug-info-bearing function has a debug location attached to it. Failure to
4584 // do so causes assertion failures when the inliner sets up inline scope info
4585 // (Interposable functions are not inlinable, neither are functions without
4586 // definitions. noipa does not prevent inlining, so it is ignored here.)
4588 !Call.getCalledFunction()->isInterposable(/*CheckNoIPA=*/false) &&
4592 "inlinable function call in a function with "
4593 "debug info must have a !dbg location",
4594 Call);
4595
4596 if (Call.isInlineAsm())
4597 verifyInlineAsmCall(Call);
4598
4599 ConvergenceVerifyHelper.visit(Call);
4600
4601 visitInstruction(Call);
4602}
4603
4604void Verifier::verifyTailCCMustTailAttrs(const AttrBuilder &Attrs,
4605 StringRef Context) {
4606 Check(!Attrs.contains(Attribute::InAlloca),
4607 Twine("inalloca attribute not allowed in ") + Context);
4608 Check(!Attrs.contains(Attribute::InReg),
4609 Twine("inreg attribute not allowed in ") + Context);
4610 Check(!Attrs.contains(Attribute::SwiftError),
4611 Twine("swifterror attribute not allowed in ") + Context);
4612 Check(!Attrs.contains(Attribute::Preallocated),
4613 Twine("preallocated attribute not allowed in ") + Context);
4614 Check(!Attrs.contains(Attribute::ByRef),
4615 Twine("byref attribute not allowed in ") + Context);
4616}
4617
4618static AttrBuilder getParameterABIAttributes(LLVMContext& C, unsigned I, AttributeList Attrs) {
4619 static const Attribute::AttrKind ABIAttrs[] = {
4620 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4621 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4622 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4623 Attribute::ByRef};
4624 AttrBuilder Copy(C);
4625 for (auto AK : ABIAttrs) {
4626 Attribute Attr = Attrs.getParamAttrs(I).getAttribute(AK);
4627 if (Attr.isValid())
4628 Copy.addAttribute(Attr);
4629 }
4630
4631 // `align` is ABI-affecting only in combination with `byval` or `byref`.
4632 if (Attrs.hasParamAttr(I, Attribute::Alignment) &&
4633 (Attrs.hasParamAttr(I, Attribute::ByVal) ||
4634 Attrs.hasParamAttr(I, Attribute::ByRef)))
4635 Copy.addAlignmentAttr(Attrs.getParamAlignment(I));
4636 return Copy;
4637}
4638
4639void Verifier::verifyMustTailCall(CallInst &CI) {
4640 Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
4641
4642 Function *F = CI.getParent()->getParent();
4643 FunctionType *CallerTy = F->getFunctionType();
4644 FunctionType *CalleeTy = CI.getFunctionType();
4645 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4646 "cannot guarantee tail call due to mismatched varargs", &CI);
4647 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4648 "cannot guarantee tail call due to mismatched return types", &CI);
4649
4650 // - The calling conventions of the caller and callee must match.
4651 Check(F->getCallingConv() == CI.getCallingConv(),
4652 "cannot guarantee tail call due to mismatched calling conv", &CI);
4653
4654 // - The call must immediately precede a :ref:`ret <i_ret>` instruction.
4655 // - The ret instruction must return the value produced by the call or void.
4657
4658 // Check the return.
4659 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
4660 Check(Ret, "musttail call must precede a ret", &CI);
4661 Check(!Ret->getReturnValue() || Ret->getReturnValue() == &CI ||
4663 "musttail call result must be returned", Ret);
4664
4665 AttributeList CallerAttrs = F->getAttributes();
4666 AttributeList CalleeAttrs = CI.getAttributes();
4667 if (CI.getCallingConv() == CallingConv::SwiftTail ||
4668 CI.getCallingConv() == CallingConv::Tail) {
4669 StringRef CCName =
4670 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc";
4671
4672 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes
4673 // are allowed in swifttailcc call
4674 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4675 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4676 SmallString<32> Context{CCName, StringRef(" musttail caller")};
4677 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4678 }
4679 for (unsigned I = 0, E = CalleeTy->getNumParams(); I != E; ++I) {
4680 AttrBuilder ABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4681 SmallString<32> Context{CCName, StringRef(" musttail callee")};
4682 verifyTailCCMustTailAttrs(ABIAttrs, Context);
4683 }
4684 // - Varargs functions are not allowed
4685 Check(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName +
4686 " tail call for varargs function");
4687 return;
4688 }
4689
4690 // - The caller and callee prototypes must match.
4691 if (!CI.getIntrinsicID()) {
4692 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4693 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4694 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4695 Check(CallerTy->getParamType(I) == CalleeTy->getParamType(I),
4696 "cannot guarantee tail call due to mismatched parameter types",
4697 &CI);
4698 }
4699 }
4700
4701 // - All ABI-impacting function attributes, such as sret, byval, inreg,
4702 // returned, preallocated, and inalloca, must match.
4703 for (unsigned I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
4704 AttrBuilder CallerABIAttrs = getParameterABIAttributes(F->getContext(), I, CallerAttrs);
4705 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(F->getContext(), I, CalleeAttrs);
4706 Check(CallerABIAttrs == CalleeABIAttrs,
4707 "cannot guarantee tail call due to mismatched ABI impacting "
4708 "function attributes",
4709 &CI, CI.getOperand(I));
4710 }
4711}
4712
4713void Verifier::visitCallInst(CallInst &CI) {
4714 visitCallBase(CI);
4715
4716 if (CI.isMustTailCall())
4717 verifyMustTailCall(CI);
4718}
4719
4720void Verifier::visitInvokeInst(InvokeInst &II) {
4721 visitCallBase(II);
4722
4723 // Verify that the first non-PHI instruction of the unwind destination is an
4724 // exception handling instruction.
4725 Check(
4726 II.getUnwindDest()->isEHPad(),
4727 "The unwind destination does not have an exception handling instruction!",
4728 &II);
4729
4730 visitTerminator(II);
4731}
4732
4733/// visitUnaryOperator - Check the argument to the unary operator.
4734///
4735void Verifier::visitUnaryOperator(UnaryOperator &U) {
4736 Check(U.getType() == U.getOperand(0)->getType(),
4737 "Unary operators must have same type for"
4738 "operands and result!",
4739 &U);
4740
4741 switch (U.getOpcode()) {
4742 // Check that floating-point arithmetic operators are only used with
4743 // floating-point operands.
4744 case Instruction::FNeg:
4745 Check(U.getType()->isFPOrFPVectorTy(),
4746 "FNeg operator only works with float types!", &U);
4747 break;
4748 default:
4749 llvm_unreachable("Unknown UnaryOperator opcode!");
4750 }
4751
4752 visitInstruction(U);
4753}
4754
4755/// visitBinaryOperator - Check that both arguments to the binary operator are
4756/// of the same type!
4757///
4758void Verifier::visitBinaryOperator(BinaryOperator &B) {
4759 Check(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
4760 "Both operands to a binary operator are not of the same type!", &B);
4761
4762 switch (B.getOpcode()) {
4763 // Check that integer arithmetic operators are only used with
4764 // integral operands.
4765 case Instruction::Add:
4766 case Instruction::Sub:
4767 case Instruction::Mul:
4768 case Instruction::SDiv:
4769 case Instruction::UDiv:
4770 case Instruction::SRem:
4771 case Instruction::URem:
4772 Check(B.getType()->isIntOrIntVectorTy(),
4773 "Integer arithmetic operators only work with integral types!", &B);
4774 Check(B.getType() == B.getOperand(0)->getType(),
4775 "Integer arithmetic operators must have same type "
4776 "for operands and result!",
4777 &B);
4778 break;
4779 // Check that floating-point arithmetic operators are only used with
4780 // floating-point operands.
4781 case Instruction::FAdd:
4782 case Instruction::FSub:
4783 case Instruction::FMul:
4784 case Instruction::FDiv:
4785 case Instruction::FRem:
4786 Check(B.getType()->isFPOrFPVectorTy(),
4787 "Floating-point arithmetic operators only work with "
4788 "floating-point types!",
4789 &B);
4790 Check(B.getType() == B.getOperand(0)->getType(),
4791 "Floating-point arithmetic operators must have same type "
4792 "for operands and result!",
4793 &B);
4794 break;
4795 // Check that logical operators are only used with integral operands.
4796 case Instruction::And:
4797 case Instruction::Or:
4798 case Instruction::Xor:
4799 Check(B.getType()->isIntOrIntVectorTy(),
4800 "Logical operators only work with integral types!", &B);
4801 Check(B.getType() == B.getOperand(0)->getType(),
4802 "Logical operators must have same type for operands and result!", &B);
4803 break;
4804 case Instruction::Shl:
4805 case Instruction::LShr:
4806 case Instruction::AShr:
4807 Check(B.getType()->isIntOrIntVectorTy(),
4808 "Shifts only work with integral types!", &B);
4809 Check(B.getType() == B.getOperand(0)->getType(),
4810 "Shift return type must be same as operands!", &B);
4811 break;
4812 default:
4813 llvm_unreachable("Unknown BinaryOperator opcode!");
4814 }
4815
4816 visitInstruction(B);
4817}
4818
4819void Verifier::visitICmpInst(ICmpInst &IC) {
4820 // Check that the operands are the same type
4821 Type *Op0Ty = IC.getOperand(0)->getType();
4822 Type *Op1Ty = IC.getOperand(1)->getType();
4823 Check(Op0Ty == Op1Ty,
4824 "Both operands to ICmp instruction are not of the same type!", &IC);
4825 // Check that the operands are the right type
4826 Check(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(),
4827 "Invalid operand types for ICmp instruction", &IC);
4828 // Check that the predicate is valid.
4829 Check(IC.isIntPredicate(), "Invalid predicate in ICmp instruction!", &IC);
4830
4831 visitInstruction(IC);
4832}
4833
4834void Verifier::visitFCmpInst(FCmpInst &FC) {
4835 // Check that the operands are the same type
4836 Type *Op0Ty = FC.getOperand(0)->getType();
4837 Type *Op1Ty = FC.getOperand(1)->getType();
4838 Check(Op0Ty == Op1Ty,
4839 "Both operands to FCmp instruction are not of the same type!", &FC);
4840 // Check that the operands are the right type
4841 Check(Op0Ty->isFPOrFPVectorTy(), "Invalid operand types for FCmp instruction",
4842 &FC);
4843 // Check that the predicate is valid.
4844 Check(FC.isFPPredicate(), "Invalid predicate in FCmp instruction!", &FC);
4845
4846 visitInstruction(FC);
4847}
4848
4849void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4851 "Invalid extractelement operands!", &EI);
4852 visitInstruction(EI);
4853}
4854
4855void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4856 Check(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
4857 IE.getOperand(2)),
4858 "Invalid insertelement operands!", &IE);
4859 visitInstruction(IE);
4860}
4861
4862void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4863 Check(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
4864 SV.getShuffleMask()),
4865 "Invalid shufflevector operands!", &SV);
4866 visitInstruction(SV);
4867}
4868
4869void Verifier::visitBitInsertInst(BitInsertInst &BII) {
4870 if (const char *Reason = BitInsertInst::areInvalidOperands(
4871 BII.getOperand(0), BII.getOperand(1), BII.getOperand(2)))
4872 Check(false, Reason, &BII);
4873 Check(DL.getTypeSizeInBits(BII.getOperand(0)->getType()->getScalarType()) >=
4874 DL.getTypeSizeInBits(BII.getOperand(1)->getType()->getScalarType()),
4875 "bitinsert val type cannot be wider than base type!", &BII);
4876 visitInstruction(BII);
4877}
4878
4879void Verifier::visitVAArgInst(VAArgInst &VAA) {
4880 // No target can lower va_arg of an aggregate, so frontends expand it.
4881 Check(!VAA.getType()->isAggregateType(),
4882 "va_arg with an aggregate type is not supported", &VAA);
4883 visitInstruction(VAA);
4884}
4885
4886void Verifier::visitBitExtractInst(BitExtractInst &BEI) {
4887 if (const char *Reason = BitExtractInst::areInvalidOperands(
4888 BEI.getType(), BEI.getOperand(0), BEI.getOperand(1)))
4889 Check(false, Reason, &BEI);
4890 Check(DL.getTypeSizeInBits(BEI.getType()->getScalarType()) <=
4891 DL.getTypeSizeInBits(BEI.getOperand(0)->getType()->getScalarType()),
4892 "bitextract result type cannot be wider than source type!", &BEI);
4893 visitInstruction(BEI);
4894}
4895
4896void Verifier::checkGEPOperator(const GEPOperator &GEP) {
4897 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
4898
4899 Check(isa<PointerType>(TargetTy),
4900 "GEP base pointer is not a vector or a vector of pointers", &GEP);
4901 Check(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
4902
4903 Type *SrcTy = GEP.getSourceElementType();
4904 while (auto *ATy = dyn_cast<ArrayType>(SrcTy))
4905 SrcTy = ATy->getElementType();
4906 Check(!isa<StructType>(SrcTy) || !SrcTy->isScalableTy(),
4907 "getelementptr cannot target structure that contains scalable vector "
4908 "type",
4909 &GEP);
4910
4911 SmallVector<Value *, 16> Idxs(GEP.indices());
4912 Check(
4913 all_of(Idxs, [](Value *V) { return V->getType()->isIntOrIntVectorTy(); }),
4914 "GEP indexes must be integers", &GEP);
4915 Type *ElTy =
4916 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
4917 Check(ElTy, "Invalid indices for GEP pointer type!", &GEP);
4918
4919 auto *PtrTy = dyn_cast<PointerType>(GEP.getType()->getScalarType());
4920
4921 Check(PtrTy && GEP.getResultElementType() == ElTy,
4922 "GEP is not of right type for indices!", &GEP, ElTy);
4923
4924 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) {
4925 // Additional checks for vector GEPs.
4926 ElementCount GEPWidth = GEPVTy->getElementCount();
4927 if (GEP.getPointerOperandType()->isVectorTy())
4928 Check(
4929 GEPWidth ==
4930 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(),
4931 "Vector GEP result width doesn't match operand's", &GEP);
4932 for (Value *Idx : Idxs) {
4933 Type *IndexTy = Idx->getType();
4934 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
4935 ElementCount IndexWidth = IndexVTy->getElementCount();
4936 Check(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
4937 }
4938 Check(IndexTy->isIntOrIntVectorTy(),
4939 "All GEP indices should be of integer type");
4940 }
4941 }
4942
4943 // Check that GEP does not index into a vector with non-byte-addressable
4944 // elements.
4946 GTI != GTE; ++GTI) {
4947 if (GTI.isVector()) {
4948 Type *ElemTy = GTI.getIndexedType();
4949 Check(DL.typeSizeEqualsStoreSize(ElemTy),
4950 "GEP into vector with non-byte-addressable element type", &GEP);
4951 }
4952 }
4953
4954 Check(GEP.getPointerAddressSpace() == PtrTy->getAddressSpace(),
4955 "GEP address space doesn't match type", &GEP);
4956}
4957
4958void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
4960 GEP.getModule()->getModuleFlag("require-logical-pointer")))
4961 Check(!MD->getZExtValue(),
4962 "Non-logical getelementptr disallowed for this module.");
4963
4964 checkGEPOperator(cast<GEPOperator>(GEP));
4965 visitInstruction(GEP);
4966}
4967
4968static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
4969 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
4970}
4971
4972/// Verify !range and !absolute_symbol metadata. These have the same
4973/// restrictions, except !absolute_symbol allows the full set.
4974void Verifier::verifyRangeLikeMetadata(const Value &I, const MDNode *Range,
4975 Type *Ty, RangeLikeMetadataKind Kind) {
4976 unsigned NumOperands = Range->getNumOperands();
4977 Check(NumOperands % 2 == 0, "Unfinished range!", Range);
4978 unsigned NumRanges = NumOperands / 2;
4979 Check(NumRanges >= 1, "It should have at least one range!", Range);
4980
4981 ConstantRange LastRange(1, true); // Dummy initial value
4982 for (unsigned i = 0; i < NumRanges; ++i) {
4983 ConstantInt *Low =
4984 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
4985 Check(Low, "The lower limit must be an integer!", Low);
4986 ConstantInt *High =
4987 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
4988 Check(High, "The upper limit must be an integer!", High);
4989
4990 Check(High->getType() == Low->getType(), "Range pair types must match!",
4991 &I);
4992
4993 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4994 Check(High->getType()->isIntegerTy(32),
4995 "noalias.addrspace type must be i32!", &I);
4996 } else {
4997 Check(High->getType() == Ty->getScalarType(),
4998 "Range types must match instruction type!", &I);
4999 }
5000
5001 APInt HighV = High->getValue();
5002 APInt LowV = Low->getValue();
5003
5004 // ConstantRange asserts if the ranges are the same except for the min/max
5005 // value. Leave the cases it tolerates for the empty range error below.
5006 Check(LowV != HighV || LowV.isMaxValue() || LowV.isMinValue(),
5007 "The upper and lower limits cannot be the same value", &I);
5008
5009 ConstantRange CurRange(LowV, HighV);
5010 Check(!CurRange.isEmptySet() &&
5011 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
5012 !CurRange.isFullSet()),
5013 "Range must not be empty!", Range);
5014 if (i != 0) {
5015 Check(CurRange.intersectWith(LastRange).isEmptySet(),
5016 "Intervals are overlapping", Range);
5017 Check(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
5018 Range);
5019 Check(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
5020 Range);
5021 }
5022 LastRange = ConstantRange(LowV, HighV);
5023 }
5024 if (NumRanges > 2) {
5025 APInt FirstLow =
5026 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
5027 APInt FirstHigh =
5028 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
5029 ConstantRange FirstRange(FirstLow, FirstHigh);
5030 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
5031 "Intervals are overlapping", Range);
5032 Check(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
5033 Range);
5034 }
5035}
5036
5037void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) {
5038 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) &&
5039 "precondition violation");
5040 verifyRangeLikeMetadata(I, Range, Ty, RangeLikeMetadataKind::Range);
5041}
5042
5043void Verifier::visitNoFPClassMetadata(Instruction &I, MDNode *NoFPClass,
5044 Type *Ty) {
5045 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
5046 "nofpclass only applies to floating-point typed loads", I);
5047
5048 Check(NoFPClass->getNumOperands() == 1,
5049 "nofpclass must have exactly one entry", NoFPClass);
5050 ConstantInt *MaskVal =
5052 Check(MaskVal && MaskVal->getType()->isIntegerTy(32),
5053 "nofpclass entry must be a constant i32", NoFPClass);
5054 uint32_t Val = MaskVal->getZExtValue();
5055 Check(Val != 0, "'nofpclass' must have at least one test bit set", NoFPClass,
5056 I);
5057
5058 Check((Val & ~static_cast<unsigned>(fcAllFlags)) == 0,
5059 "Invalid value for 'nofpclass' test mask", NoFPClass, I);
5060}
5061
5062void Verifier::visitNoaliasAddrspaceMetadata(Instruction &I, MDNode *Range,
5063 Type *Ty) {
5064 assert(Range && Range == I.getMetadata(LLVMContext::MD_noalias_addrspace) &&
5065 "precondition violation");
5066 verifyRangeLikeMetadata(I, Range, Ty,
5067 RangeLikeMetadataKind::NoaliasAddrspace);
5068}
5069
5070void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) {
5071 unsigned Size = DL.getTypeSizeInBits(Ty).getFixedValue();
5072 Check(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
5073 Check(!(Size & (Size - 1)),
5074 "atomic memory access' operand must have a power-of-two size", Ty, I);
5075}
5076
5077void Verifier::visitLoadInst(LoadInst &LI) {
5078 auto *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
5079 Check(PTy, "Load operand must be a pointer.", &LI);
5080 Type *ElTy = LI.getType();
5081 if (MaybeAlign A = LI.getAlign()) {
5082 Check(A->value() <= Value::MaximumAlignment,
5083 "huge alignment values are unsupported", &LI);
5084 }
5085 Check(ElTy->isSized(), "loading unsized types is not allowed", &LI);
5086 if (LI.isAtomic()) {
5087 Check(LI.getOrdering() != AtomicOrdering::Release &&
5088 LI.getOrdering() != AtomicOrdering::AcquireRelease,
5089 "Load cannot have Release ordering", &LI);
5090
5091 if (LI.isElementwise()) {
5092 Check(LI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
5093 "atomic elementwise load cannot be sequentially consistent.", &LI);
5094 auto *VecTy = dyn_cast<FixedVectorType>(ElTy);
5095 Check(VecTy,
5096 "atomic elementwise load operand must have fixed vector type!", &LI,
5097 ElTy);
5098 if (VecTy)
5099 checkAtomicMemAccessSize(VecTy->getElementType(), &LI);
5100 }
5101
5102 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
5103 ElTy->getScalarType()->isByteTy() ||
5105 "atomic load operand must have integer, byte, pointer, floating "
5106 "point, or vector type!",
5107 ElTy, &LI);
5108
5109 checkAtomicMemAccessSize(ElTy, &LI);
5110 } else {
5111 Check(!LI.isElementwise(), "non-atomic load cannot be elementwise", &LI);
5113 "Non-atomic load cannot have SynchronizationScope specified", &LI);
5114 }
5115
5116 visitInstruction(LI);
5117}
5118
5119void Verifier::visitStoreInst(StoreInst &SI) {
5120 auto *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
5121 Check(PTy, "Store operand must be a pointer.", &SI);
5122 Type *ElTy = SI.getOperand(0)->getType();
5123 if (MaybeAlign A = SI.getAlign()) {
5124 Check(A->value() <= Value::MaximumAlignment,
5125 "huge alignment values are unsupported", &SI);
5126 }
5127 Check(ElTy->isSized(), "storing unsized types is not allowed", &SI);
5128 if (SI.isAtomic()) {
5129 Check(SI.getOrdering() != AtomicOrdering::Acquire &&
5130 SI.getOrdering() != AtomicOrdering::AcquireRelease,
5131 "Store cannot have Acquire ordering", &SI);
5132
5133 if (SI.isElementwise()) {
5134 Check(SI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
5135 "atomic elementwise store cannot be sequentially consistent.", &SI);
5136
5137 auto *VecTy = dyn_cast<FixedVectorType>(ElTy);
5138 Check(VecTy,
5139 "atomic elementwise store operand must have fixed vector type!",
5140 &SI, ElTy);
5141 if (VecTy)
5142 checkAtomicMemAccessSize(VecTy->getElementType(), &SI);
5143 }
5144
5145 Check(ElTy->getScalarType()->isIntOrPtrTy() ||
5146 ElTy->getScalarType()->isByteTy() ||
5148 "atomic store operand must have integer, byte, pointer, floating "
5149 "point, or vector type!",
5150 ElTy, &SI);
5151 checkAtomicMemAccessSize(ElTy, &SI);
5152 } else {
5153 Check(!SI.isElementwise(), "non-atomic store cannot be elementwise", &SI);
5154 Check(SI.getSyncScopeID() == SyncScope::System,
5155 "Non-atomic store cannot have SynchronizationScope specified", &SI);
5156 }
5157 visitInstruction(SI);
5158}
5159
5160/// Check that SwiftErrorVal is used as a swifterror argument in CS.
5161void Verifier::verifySwiftErrorCall(CallBase &Call,
5162 const Value *SwiftErrorVal) {
5163 for (const auto &I : llvm::enumerate(Call.args())) {
5164 if (I.value() == SwiftErrorVal) {
5165 Check(Call.paramHasAttr(I.index(), Attribute::SwiftError),
5166 "swifterror value when used in a callsite should be marked "
5167 "with swifterror attribute",
5168 SwiftErrorVal, Call);
5169 }
5170 }
5171}
5172
5173void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) {
5174 // Check that swifterror value is only used by loads, stores, or as
5175 // a swifterror argument.
5176 for (const User *U : SwiftErrorVal->users()) {
5178 isa<InvokeInst>(U),
5179 "swifterror value can only be loaded and stored from, or "
5180 "as a swifterror argument!",
5181 SwiftErrorVal, U);
5182 // If it is used by a store, check it is the second operand.
5183 if (auto StoreI = dyn_cast<StoreInst>(U))
5184 Check(StoreI->getOperand(1) == SwiftErrorVal,
5185 "swifterror value should be the second operand when used "
5186 "by stores",
5187 SwiftErrorVal, U);
5188 if (auto *Call = dyn_cast<CallBase>(U))
5189 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
5190 }
5191}
5192
5193void Verifier::visitAllocaInst(AllocaInst &AI) {
5195 AI.getModule()->getModuleFlag("require-logical-pointer")))
5196 Check(!MD->getZExtValue(),
5197 "Non-logical alloca disallowed for this module.");
5198
5199 Type *Ty = AI.getAllocatedType();
5200 Check(Ty->isSized(), "Cannot allocate unsized type", &AI);
5201 // Check if it's a target extension type that disallows being used on the
5202 // stack.
5204 "Alloca has illegal target extension type", &AI);
5206 "Alloca array size must have integer type", &AI);
5207 if (MaybeAlign A = AI.getAlign()) {
5208 Check(A->value() <= Value::MaximumAlignment,
5209 "huge alignment values are unsupported", &AI);
5210 }
5211
5212 if (AI.isSwiftError()) {
5213 Check(Ty->isPointerTy(), "swifterror alloca must have pointer type", &AI);
5215 "swifterror alloca must not be array allocation", &AI);
5216 verifySwiftErrorValue(&AI);
5217 }
5218
5219 visitInstruction(AI);
5220
5221 // Target-specific alloca checks.
5222 verifyAMDGPUAlloca(*this, AI);
5223}
5224
5225void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
5226 Type *ElTy = CXI.getOperand(1)->getType();
5227 Check(ElTy->isIntOrPtrTy(),
5228 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
5229 checkAtomicMemAccessSize(ElTy, &CXI);
5230 visitInstruction(CXI);
5231}
5232
5233void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
5234 Check(RMWI.getOrdering() != AtomicOrdering::Unordered,
5235 "atomicrmw instructions cannot be unordered.", &RMWI);
5236 auto Op = RMWI.getOperation();
5237 Type *ElTy = RMWI.getOperand(1)->getType();
5238 Check(!ElTy->isScalableTy(), "atomicrmw operand may not be scalable", &RMWI);
5239 if (RMWI.isElementwise()) {
5240 Check(RMWI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
5241 "atomicrmw elementwise cannot be sequentially consistent.", &RMWI);
5242 auto *VecTy = dyn_cast<FixedVectorType>(ElTy);
5243 Check(VecTy, "atomicrmw elementwise operand must have fixed vector type!",
5244 &RMWI, ElTy);
5245 if (VecTy)
5246 checkAtomicMemAccessSize(VecTy->getElementType(), &RMWI);
5247 }
5248
5249 if (Op == AtomicRMWInst::Xchg) {
5250 Check((ElTy->isIntOrIntVectorTy() || ElTy->isFPOrFPVectorTy() ||
5251 ElTy->isPtrOrPtrVectorTy()),
5252 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
5253 " operand must be an integer type, a floating-point type, a "
5254 "pointer type, or a fixed vector of any of these types!",
5255 &RMWI, ElTy);
5256 } else if (AtomicRMWInst::isFPOperation(Op)) {
5257 Check(ElTy->isFPOrFPVectorTy(),
5258 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
5259 " operand must have floating-point or fixed vector of "
5260 "floating-point "
5261 "type!",
5262 &RMWI, ElTy);
5263 } else {
5264 Check(ElTy->isIntOrIntVectorTy(),
5265 "atomicrmw " + AtomicRMWInst::getOperationName(Op) +
5266 " operand must have integer or fixed vector of integer type!",
5267 &RMWI, ElTy);
5268 }
5269 checkAtomicMemAccessSize(ElTy, &RMWI);
5271 "Invalid binary operation!", &RMWI);
5272 visitInstruction(RMWI);
5273}
5274
5275void Verifier::visitFenceInst(FenceInst &FI) {
5276 const AtomicOrdering Ordering = FI.getOrdering();
5277 Check(Ordering == AtomicOrdering::Acquire ||
5278 Ordering == AtomicOrdering::Release ||
5279 Ordering == AtomicOrdering::AcquireRelease ||
5280 Ordering == AtomicOrdering::SequentiallyConsistent,
5281 "fence instructions may only have acquire, release, acq_rel, or "
5282 "seq_cst ordering.",
5283 &FI);
5284 visitInstruction(FI);
5285}
5286
5287void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
5289 EVI.getIndices()) == EVI.getType(),
5290 "Invalid ExtractValueInst operands!", &EVI);
5291
5292 visitInstruction(EVI);
5293}
5294
5295void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
5297 IVI.getIndices()) ==
5298 IVI.getOperand(1)->getType(),
5299 "Invalid InsertValueInst operands!", &IVI);
5300
5301 visitInstruction(IVI);
5302}
5303
5304static Value *getParentPad(Value *EHPad) {
5305 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
5306 return FPI->getParentPad();
5307
5308 return cast<CatchSwitchInst>(EHPad)->getParentPad();
5309}
5310
5311void Verifier::visitEHPadPredecessors(Instruction &I) {
5312 assert(I.isEHPad());
5313
5314 BasicBlock *BB = I.getParent();
5315 Function *F = BB->getParent();
5316
5317 Check(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
5318
5319 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
5320 // The landingpad instruction defines its parent as a landing pad block. The
5321 // landing pad block may be branched to only by the unwind edge of an
5322 // invoke.
5323 for (BasicBlock *PredBB : predecessors(BB)) {
5324 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
5325 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
5326 "Block containing LandingPadInst must be jumped to "
5327 "only by the unwind edge of an invoke.",
5328 LPI);
5329 }
5330 return;
5331 }
5332 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
5333 if (!pred_empty(BB))
5334 Check(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
5335 "Block containg CatchPadInst must be jumped to "
5336 "only by its catchswitch.",
5337 CPI);
5338 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
5339 "Catchswitch cannot unwind to one of its catchpads",
5340 CPI->getCatchSwitch(), CPI);
5341 return;
5342 }
5343
5344 // Verify that each pred has a legal terminator with a legal to/from EH
5345 // pad relationship.
5346 Instruction *ToPad = &I;
5347 Value *ToPadParent = getParentPad(ToPad);
5348 for (BasicBlock *PredBB : predecessors(BB)) {
5349 Instruction *TI = PredBB->getTerminator();
5350 Value *FromPad;
5351 if (auto *II = dyn_cast<InvokeInst>(TI)) {
5352 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
5353 "EH pad must be jumped to via an unwind edge", ToPad, II);
5354 auto *CalledFn =
5355 dyn_cast<Function>(II->getCalledOperand()->stripPointerCasts());
5356 if (CalledFn && CalledFn->isIntrinsic() && II->doesNotThrow() &&
5357 !IntrinsicInst::mayLowerToFunctionCall(CalledFn->getIntrinsicID()))
5358 continue;
5359 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
5360 FromPad = Bundle->Inputs[0];
5361 else
5362 FromPad = ConstantTokenNone::get(II->getContext());
5363 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
5364 FromPad = CRI->getOperand(0);
5365 Check(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
5366 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
5367 FromPad = CSI;
5368 } else {
5369 Check(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
5370 }
5371
5372 // The edge may exit from zero or more nested pads.
5373 SmallPtrSet<Value *, 8> Seen;
5374 for (;; FromPad = getParentPad(FromPad)) {
5375 Check(FromPad != ToPad,
5376 "EH pad cannot handle exceptions raised within it", FromPad, TI);
5377 if (FromPad == ToPadParent) {
5378 // This is a legal unwind edge.
5379 break;
5380 }
5381 Check(!isa<ConstantTokenNone>(FromPad),
5382 "A single unwind edge may only enter one EH pad", TI);
5383 Check(Seen.insert(FromPad).second, "EH pad jumps through a cycle of pads",
5384 FromPad);
5385
5386 // This will be diagnosed on the corresponding instruction already. We
5387 // need the extra check here to make sure getParentPad() works.
5388 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
5389 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
5390 }
5391 }
5392}
5393
5394void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
5395 // The landingpad instruction is ill-formed if it doesn't have any clauses and
5396 // isn't a cleanup.
5397 Check(LPI.getNumClauses() > 0 || LPI.isCleanup(),
5398 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
5399
5400 visitEHPadPredecessors(LPI);
5401
5402 if (!LandingPadResultTy)
5403 LandingPadResultTy = LPI.getType();
5404 else
5405 Check(LandingPadResultTy == LPI.getType(),
5406 "The landingpad instruction should have a consistent result type "
5407 "inside a function.",
5408 &LPI);
5409
5410 Function *F = LPI.getParent()->getParent();
5411 Check(F->hasPersonalityFn(),
5412 "LandingPadInst needs to be in a function with a personality.", &LPI);
5413
5414 // The landingpad instruction must be the first non-PHI instruction in the
5415 // block.
5416 Check(LPI.getParent()->getLandingPadInst() == &LPI,
5417 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
5418
5419 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
5420 Constant *Clause = LPI.getClause(i);
5421 if (LPI.isCatch(i)) {
5422 Check(isa<PointerType>(Clause->getType()),
5423 "Catch operand does not have pointer type!", &LPI);
5424 } else {
5425 Check(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
5427 "Filter operand is not an array of constants!", &LPI);
5428 }
5429 }
5430
5431 visitInstruction(LPI);
5432}
5433
5434void Verifier::visitResumeInst(ResumeInst &RI) {
5436 "ResumeInst needs to be in a function with a personality.", &RI);
5437
5438 if (!LandingPadResultTy)
5439 LandingPadResultTy = RI.getValue()->getType();
5440 else
5441 Check(LandingPadResultTy == RI.getValue()->getType(),
5442 "The resume instruction should have a consistent result type "
5443 "inside a function.",
5444 &RI);
5445
5446 visitTerminator(RI);
5447}
5448
5449void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5450 BasicBlock *BB = CPI.getParent();
5451
5452 Function *F = BB->getParent();
5453 Check(F->hasPersonalityFn(),
5454 "CatchPadInst needs to be in a function with a personality.", &CPI);
5455
5457 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5458 CPI.getParentPad());
5459
5460 // The catchpad instruction must be the first non-PHI instruction in the
5461 // block.
5462 Check(&*BB->getFirstNonPHIIt() == &CPI,
5463 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5464
5466 [](Use &U) {
5467 auto *V = U.get();
5468 return isa<Constant>(V) || isa<AllocaInst>(V);
5469 }),
5470 "Argument operand must be alloca or constant.", &CPI);
5471
5472 visitEHPadPredecessors(CPI);
5473 visitFuncletPadInst(CPI);
5474}
5475
5476void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5477 Check(isa<CatchPadInst>(CatchReturn.getOperand(0)),
5478 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5479 CatchReturn.getOperand(0));
5480
5481 visitTerminator(CatchReturn);
5482}
5483
5484void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5485 BasicBlock *BB = CPI.getParent();
5486
5487 Function *F = BB->getParent();
5488 Check(F->hasPersonalityFn(),
5489 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5490
5491 // The cleanuppad instruction must be the first non-PHI instruction in the
5492 // block.
5493 Check(&*BB->getFirstNonPHIIt() == &CPI,
5494 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5495
5496 auto *ParentPad = CPI.getParentPad();
5497 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5498 "CleanupPadInst has an invalid parent.", &CPI);
5499
5500 visitEHPadPredecessors(CPI);
5501 visitFuncletPadInst(CPI);
5502}
5503
5504void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5505 User *FirstUser = nullptr;
5506 Value *FirstUnwindPad = nullptr;
5507 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
5508 SmallPtrSet<FuncletPadInst *, 8> Seen;
5509
5510 while (!Worklist.empty()) {
5511 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5512 Check(Seen.insert(CurrentPad).second,
5513 "FuncletPadInst must not be nested within itself", CurrentPad);
5514 Value *UnresolvedAncestorPad = nullptr;
5515 for (User *U : CurrentPad->users()) {
5516 BasicBlock *UnwindDest;
5517 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
5518 UnwindDest = CRI->getUnwindDest();
5519 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
5520 // We allow catchswitch unwind to caller to nest
5521 // within an outer pad that unwinds somewhere else,
5522 // because catchswitch doesn't have a nounwind variant.
5523 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
5524 if (CSI->unwindsToCaller())
5525 continue;
5526 UnwindDest = CSI->getUnwindDest();
5527 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
5528 UnwindDest = II->getUnwindDest();
5529 } else if (isa<CallInst>(U)) {
5530 // Calls which don't unwind may be found inside funclet
5531 // pads that unwind somewhere else. We don't *require*
5532 // such calls to be annotated nounwind.
5533 continue;
5534 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
5535 // The unwind dest for a cleanup can only be found by
5536 // recursive search. Add it to the worklist, and we'll
5537 // search for its first use that determines where it unwinds.
5538 Worklist.push_back(CPI);
5539 continue;
5540 } else {
5541 Check(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
5542 continue;
5543 }
5544
5545 Value *UnwindPad;
5546 bool ExitsFPI;
5547 if (UnwindDest) {
5548 UnwindPad = &*UnwindDest->getFirstNonPHIIt();
5549 if (!cast<Instruction>(UnwindPad)->isEHPad())
5550 continue;
5551 Value *UnwindParent = getParentPad(UnwindPad);
5552 // Ignore unwind edges that don't exit CurrentPad.
5553 if (UnwindParent == CurrentPad)
5554 continue;
5555 // Determine whether the original funclet pad is exited,
5556 // and if we are scanning nested pads determine how many
5557 // of them are exited so we can stop searching their
5558 // children.
5559 Value *ExitedPad = CurrentPad;
5560 ExitsFPI = false;
5561 do {
5562 if (ExitedPad == &FPI) {
5563 ExitsFPI = true;
5564 // Now we can resolve any ancestors of CurrentPad up to
5565 // FPI, but not including FPI since we need to make sure
5566 // to check all direct users of FPI for consistency.
5567 UnresolvedAncestorPad = &FPI;
5568 break;
5569 }
5570 Value *ExitedParent = getParentPad(ExitedPad);
5571 if (ExitedParent == UnwindParent) {
5572 // ExitedPad is the ancestor-most pad which this unwind
5573 // edge exits, so we can resolve up to it, meaning that
5574 // ExitedParent is the first ancestor still unresolved.
5575 UnresolvedAncestorPad = ExitedParent;
5576 break;
5577 }
5578 ExitedPad = ExitedParent;
5579 } while (!isa<ConstantTokenNone>(ExitedPad));
5580 } else {
5581 // Unwinding to caller exits all pads.
5582 UnwindPad = ConstantTokenNone::get(FPI.getContext());
5583 ExitsFPI = true;
5584 UnresolvedAncestorPad = &FPI;
5585 }
5586
5587 if (ExitsFPI) {
5588 // This unwind edge exits FPI. Make sure it agrees with other
5589 // such edges.
5590 if (FirstUser) {
5591 Check(UnwindPad == FirstUnwindPad,
5592 "Unwind edges out of a funclet "
5593 "pad must have the same unwind "
5594 "dest",
5595 &FPI, U, FirstUser);
5596 } else {
5597 FirstUser = U;
5598 FirstUnwindPad = UnwindPad;
5599 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
5600 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
5601 getParentPad(UnwindPad) == getParentPad(&FPI))
5602 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
5603 }
5604 }
5605 // Make sure we visit all uses of FPI, but for nested pads stop as
5606 // soon as we know where they unwind to.
5607 if (CurrentPad != &FPI)
5608 break;
5609 }
5610 if (UnresolvedAncestorPad) {
5611 if (CurrentPad == UnresolvedAncestorPad) {
5612 // When CurrentPad is FPI itself, we don't mark it as resolved even if
5613 // we've found an unwind edge that exits it, because we need to verify
5614 // all direct uses of FPI.
5615 assert(CurrentPad == &FPI);
5616 continue;
5617 }
5618 // Pop off the worklist any nested pads that we've found an unwind
5619 // destination for. The pads on the worklist are the uncles,
5620 // great-uncles, etc. of CurrentPad. We've found an unwind destination
5621 // for all ancestors of CurrentPad up to but not including
5622 // UnresolvedAncestorPad.
5623 Value *ResolvedPad = CurrentPad;
5624 while (!Worklist.empty()) {
5625 Value *UnclePad = Worklist.back();
5626 Value *AncestorPad = getParentPad(UnclePad);
5627 // Walk ResolvedPad up the ancestor list until we either find the
5628 // uncle's parent or the last resolved ancestor.
5629 while (ResolvedPad != AncestorPad) {
5630 Value *ResolvedParent = getParentPad(ResolvedPad);
5631 if (ResolvedParent == UnresolvedAncestorPad) {
5632 break;
5633 }
5634 ResolvedPad = ResolvedParent;
5635 }
5636 // If the resolved ancestor search didn't find the uncle's parent,
5637 // then the uncle is not yet resolved.
5638 if (ResolvedPad != AncestorPad)
5639 break;
5640 // This uncle is resolved, so pop it from the worklist.
5641 Worklist.pop_back();
5642 }
5643 }
5644 }
5645
5646 if (FirstUnwindPad) {
5647 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
5648 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5649 Value *SwitchUnwindPad;
5650 if (SwitchUnwindDest)
5651 SwitchUnwindPad = &*SwitchUnwindDest->getFirstNonPHIIt();
5652 else
5653 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
5654 Check(SwitchUnwindPad == FirstUnwindPad,
5655 "Unwind edges out of a catch must have the same unwind dest as "
5656 "the parent catchswitch",
5657 &FPI, FirstUser, CatchSwitch);
5658 }
5659 }
5660
5661 visitInstruction(FPI);
5662}
5663
5664void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5665 BasicBlock *BB = CatchSwitch.getParent();
5666
5667 Function *F = BB->getParent();
5668 Check(F->hasPersonalityFn(),
5669 "CatchSwitchInst needs to be in a function with a personality.",
5670 &CatchSwitch);
5671
5672 // The catchswitch instruction must be the first non-PHI instruction in the
5673 // block.
5674 Check(&*BB->getFirstNonPHIIt() == &CatchSwitch,
5675 "CatchSwitchInst not the first non-PHI instruction in the block.",
5676 &CatchSwitch);
5677
5678 auto *ParentPad = CatchSwitch.getParentPad();
5679 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
5680 "CatchSwitchInst has an invalid parent.", ParentPad);
5681
5682 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
5683 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5684 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5685 "CatchSwitchInst must unwind to an EH block which is not a "
5686 "landingpad.",
5687 &CatchSwitch);
5688
5689 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
5690 if (getParentPad(&*I) == ParentPad)
5691 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5692 }
5693
5694 Check(CatchSwitch.getNumHandlers() != 0,
5695 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5696
5697 for (BasicBlock *Handler : CatchSwitch.handlers()) {
5698 Check(isa<CatchPadInst>(Handler->getFirstNonPHIIt()),
5699 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5700 }
5701
5702 visitEHPadPredecessors(CatchSwitch);
5703 visitTerminator(CatchSwitch);
5704}
5705
5706void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5708 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5709 CRI.getOperand(0));
5710
5711 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
5712 BasicBlock::iterator I = UnwindDest->getFirstNonPHIIt();
5713 Check(I->isEHPad() && !isa<LandingPadInst>(I),
5714 "CleanupReturnInst must unwind to an EH block which is not a "
5715 "landingpad.",
5716 &CRI);
5717 }
5718
5719 visitTerminator(CRI);
5720}
5721
5722void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
5723 Instruction *Op = cast<Instruction>(I.getOperand(i));
5724 // If the we have an invalid invoke, don't try to compute the dominance.
5725 // We already reject it in the invoke specific checks and the dominance
5726 // computation doesn't handle multiple edges.
5727 if (auto *II = dyn_cast<InvokeInst>(Op)) {
5728 if (II->getNormalDest() == II->getUnwindDest())
5729 return;
5730 }
5731
5732 // Quick check whether the def has already been encountered in the same block.
5733 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
5734 // uses are defined to happen on the incoming edge, not at the instruction.
5735 //
5736 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
5737 // wrapping an SSA value, assert that we've already encountered it. See
5738 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
5739 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
5740 return;
5741
5742 const Use &U = I.getOperandUse(i);
5743 Check(DT.dominates(Op, U), "Instruction does not dominate all uses!", Op, &I);
5744}
5745
5746void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
5747 Check(I.getType()->isPointerTy(),
5748 "dereferenceable, dereferenceable_or_null "
5749 "apply only to pointer types",
5750 &I);
5752 "dereferenceable, dereferenceable_or_null apply only to load"
5753 " and inttoptr instructions, use attributes for calls or invokes",
5754 &I);
5755 Check(MD->getNumOperands() == 1,
5756 "dereferenceable, dereferenceable_or_null "
5757 "take one operand!",
5758 &I);
5759 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
5760 Check(CI && CI->getType()->isIntegerTy(64),
5761 "dereferenceable, "
5762 "dereferenceable_or_null metadata value must be an i64!",
5763 &I);
5764}
5765
5766void Verifier::visitNoFreeObjMetadata(Instruction &I, MDNode *MD) {
5767 Check(I.getType()->isPointerTy(), "nofreeobj applies only to pointer types",
5768 &I);
5770 "nofreeobj applies only to inttoptr instruction", &I);
5771 Check(MD->getNumOperands() == 0, "nofreeobj metadata must be empty", &I);
5772}
5773
5774void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) {
5775 auto GetBranchingTerminatorNumOperands = [&]() {
5776 unsigned ExpectedNumOperands = 0;
5777 if (auto *BI = dyn_cast<CondBrInst>(&I))
5778 ExpectedNumOperands = BI->getNumSuccessors();
5779 else if (auto *SI = dyn_cast<SwitchInst>(&I))
5780 ExpectedNumOperands = SI->getNumSuccessors();
5781 else if (isa<CallInst>(&I))
5782 ExpectedNumOperands = 1;
5783 else if (auto *IBI = dyn_cast<IndirectBrInst>(&I))
5784 ExpectedNumOperands = IBI->getNumDestinations();
5785 else if (isa<SelectInst>(&I))
5786 ExpectedNumOperands = 2;
5787 else if (auto *CI = dyn_cast<CallBrInst>(&I))
5788 ExpectedNumOperands = CI->getNumSuccessors();
5789 return ExpectedNumOperands;
5790 };
5791 Check(MD->getNumOperands() >= 1,
5792 "!prof annotations should have at least 1 operand", MD);
5793 // Check first operand.
5794 Check(MD->getOperand(0) != nullptr, "first operand should not be null", MD);
5796 "expected string with name of the !prof annotation", MD);
5797 MDString *MDS = cast<MDString>(MD->getOperand(0));
5798 StringRef ProfName = MDS->getString();
5799
5801 Check(GetBranchingTerminatorNumOperands() != 0 || isa<InvokeInst>(I),
5802 "'unknown' !prof should only appear on instructions on which "
5803 "'branch_weights' would",
5804 MD);
5805 verifyUnknownProfileMetadata(MD);
5806 return;
5807 }
5808
5809 Check(MD->getNumOperands() >= 2,
5810 "!prof annotations should have no less than 2 operands", MD);
5811
5812 // Check consistency of !prof branch_weights metadata.
5813 if (ProfName == MDProfLabels::BranchWeights) {
5814 unsigned NumBranchWeights = getNumBranchWeights(*MD);
5815 if (isa<InvokeInst>(&I)) {
5816 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5817 "Wrong number of InvokeInst branch_weights operands", MD);
5818 } else {
5819 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5820 if (ExpectedNumOperands == 0)
5821 CheckFailed("!prof branch_weights are not allowed for this instruction",
5822 MD);
5823
5824 Check(NumBranchWeights == ExpectedNumOperands, "Wrong number of operands",
5825 MD);
5826 }
5827 for (unsigned i = getBranchWeightOffset(MD); i < MD->getNumOperands();
5828 ++i) {
5829 auto &MDO = MD->getOperand(i);
5830 Check(MDO, "second operand should not be null", MD);
5832 "!prof brunch_weights operand is not a const int");
5833 }
5834 } else if (ProfName == MDProfLabels::ValueProfile) {
5835 Check(isValueProfileMD(MD), "invalid value profiling metadata", MD);
5836 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
5837 Check(KindInt, "VP !prof missing kind argument", MD);
5838
5839 auto Kind = KindInt->getZExtValue();
5840 Check(Kind >= InstrProfValueKind::IPVK_First &&
5841 Kind <= InstrProfValueKind::IPVK_Last,
5842 "Invalid VP !prof kind", MD);
5843 Check(MD->getNumOperands() % 2 == 1,
5844 "VP !prof should have an even number "
5845 "of arguments after 'VP'",
5846 MD);
5847 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5848 Kind == InstrProfValueKind::IPVK_MemOPSize)
5850 "VP !prof indirect call or memop size expected to be applied to "
5851 "CallBase instructions only",
5852 MD);
5853
5854 DenseSet<uint64_t> ProfileValues;
5855 for (unsigned I = 3; I < MD->getNumOperands(); I += 2) {
5856 ConstantInt *ProfileValue =
5858 Check(ProfileValue, "VP !prof value operand is not a const int", MD);
5859 uint64_t ProfileValueInt = ProfileValue->getZExtValue();
5860 auto [ValueIt, Inserted] = ProfileValues.insert(ProfileValueInt);
5861 Check(Inserted, "VP !prof should not have duplicate profile values", MD);
5862 }
5863 } else {
5864 CheckFailed("expected either branch_weights or VP profile name", MD);
5865 }
5866}
5867
5868void Verifier::visitDIAssignIDMetadata(Instruction &I, MDNode *MD) {
5869 assert(I.hasMetadata(LLVMContext::MD_DIAssignID));
5870 // DIAssignID metadata must be attached to either an alloca or some form of
5871 // store/memory-writing instruction.
5872 // FIXME: We allow all intrinsic insts here to avoid trying to enumerate all
5873 // possible store intrinsics.
5874 bool ExpectedInstTy =
5876 CheckDI(ExpectedInstTy, "!DIAssignID attached to unexpected instruction kind",
5877 I, MD);
5878 for (DbgVariableRecord *DVR : at::getAssignmentMarkers(cast<DIAssignID>(MD)))
5879 CheckDI(DVR->getFunction() == I.getFunction(),
5880 "DVRAssign not in same function as inst", DVR, &I);
5881}
5882
5883void Verifier::visitMMRAMetadata(Instruction &I, MDNode *MD) {
5885 "!mmra metadata attached to unexpected instruction kind", I, MD);
5886
5887 // MMRA Metadata should either be a tag, e.g. !{!"foo", !"bar"}, or a
5888 // list of tags such as !2 in the following example:
5889 // !0 = !{!"a", !"b"}
5890 // !1 = !{!"c", !"d"}
5891 // !2 = !{!0, !1}
5892 if (MMRAMetadata::isTagMD(MD))
5893 return;
5894
5895 Check(isa<MDTuple>(MD), "!mmra expected to be a metadata tuple", I, MD);
5896 for (const MDOperand &MDOp : MD->operands())
5897 Check(MMRAMetadata::isTagMD(MDOp.get()),
5898 "!mmra metadata tuple operand is not an MMRA tag", I, MDOp.get());
5899}
5900
5901void Verifier::visitCallStackMetadata(MDNode *MD) {
5902 // Call stack metadata should consist of a list of at least 1 constant int
5903 // (representing a hash of the location).
5904 Check(MD->getNumOperands() >= 1,
5905 "call stack metadata should have at least 1 operand", MD);
5906
5907 for (const auto &Op : MD->operands())
5909 "call stack metadata operand should be constant integer", Op);
5910}
5911
5912void Verifier::visitMemProfMetadata(Instruction &I, MDNode *MD) {
5913 Check(isa<CallBase>(I), "!memprof metadata should only exist on calls", &I);
5914 if (isa<CallBase>(I))
5915 Check(I.hasMetadata(LLVMContext::MD_callsite),
5916 "!memprof metadata requires !callsite metadata", &I, MD);
5917 Check(MD->getNumOperands() >= 1,
5918 "!memprof annotations should have at least 1 metadata operand "
5919 "(MemInfoBlock)",
5920 MD);
5921
5922 // Check each MIB
5923 for (auto &MIBOp : MD->operands()) {
5924 auto *MIB = dyn_cast<MDNode>(MIBOp);
5925 // The first operand of an MIB should be the call stack metadata.
5926 // There rest of the operands should be MDString tags, and there should be
5927 // at least one.
5928 Check(MIB->getNumOperands() >= 2,
5929 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5930
5931 // Check call stack metadata (first operand).
5932 Check(MIB->getOperand(0) != nullptr,
5933 "!memprof MemInfoBlock first operand should not be null", MIB);
5934 Check(isa<MDNode>(MIB->getOperand(0)),
5935 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5936 auto *StackMD = dyn_cast<MDNode>(MIB->getOperand(0));
5937 visitCallStackMetadata(StackMD);
5938
5939 // The second MIB operand should be MDString.
5940 Check(isa<MDString>(MIB->getOperand(1)),
5941 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5942
5943 // Any remaining should be MDNode that are pairs of integers
5944 for (unsigned I = 2; I < MIB->getNumOperands(); ++I) {
5945 auto *OpNode = dyn_cast<MDNode>(MIB->getOperand(I));
5946 Check(OpNode, "Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5947 MIB);
5948 Check(OpNode->getNumOperands() == 2,
5949 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5950 "operands",
5951 MIB);
5952 // Check that all of Op's operands are ConstantInt.
5953 Check(llvm::all_of(OpNode->operands(),
5954 [](const MDOperand &Op) {
5955 return mdconst::hasa<ConstantInt>(Op);
5956 }),
5957 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5958 "ConstantInt operands",
5959 MIB);
5960 }
5961 }
5962}
5963
5964void Verifier::visitCallsiteMetadata(Instruction &I, MDNode *MD) {
5965 Check(isa<CallBase>(I), "!callsite metadata should only exist on calls", &I);
5966 // Verify the partial callstack annotated from memprof profiles. This callsite
5967 // is a part of a profiled allocation callstack.
5968 visitCallStackMetadata(MD);
5969}
5970
5971void Verifier::visitCalleeTypeMetadata(Instruction &I, MDNode *MD) {
5972 Check(isa<CallBase>(I), "!callee_type metadata should only exist on calls",
5973 &I);
5974 for (Metadata *Op : MD->operands()) {
5976 "The callee_type metadata must be a list of callgraph metadata nodes",
5977 Op);
5978 auto *CallgraphMD = cast<MDNode>(Op);
5979 Check(CallgraphMD->getNumOperands() == 1,
5980 "Well-formed callgraph metadata must contain exactly one "
5981 "operand",
5982 Op);
5983 Check(isa<MDString>(CallgraphMD->getOperand(0)),
5984 "The operand of callgraph metadata for functions must be an MDString",
5985 Op);
5986 }
5987}
5988
5989void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5990 Check(isa<MDTuple>(Annotation), "annotation must be a tuple");
5991 Check(Annotation->getNumOperands() >= 1,
5992 "annotation must have at least one operand");
5993 for (const MDOperand &Op : Annotation->operands()) {
5994 bool TupleOfStrings =
5995 isa<MDTuple>(Op.get()) &&
5996 all_of(cast<MDTuple>(Op)->operands(), [](auto &Annotation) {
5997 return isa<MDString>(Annotation.get());
5998 });
5999 Check(isa<MDString>(Op.get()) || TupleOfStrings,
6000 "operands must be a string or a tuple of strings");
6001 }
6002}
6003
6004void Verifier::visitAliasScopeMetadata(const MDNode *MD) {
6005 unsigned NumOps = MD->getNumOperands();
6006 Check(NumOps >= 2 && NumOps <= 3, "scope must have two or three operands",
6007 MD);
6008 Check(MD->getOperand(0).get() == MD || isa<MDString>(MD->getOperand(0)),
6009 "first scope operand must be self-referential or string", MD);
6010 if (NumOps == 3)
6012 "third scope operand must be string (if used)", MD);
6013
6014 auto *Domain = dyn_cast<MDNode>(MD->getOperand(1));
6015 Check(Domain != nullptr, "second scope operand must be MDNode", MD);
6016
6017 unsigned NumDomainOps = Domain->getNumOperands();
6018 Check(NumDomainOps >= 2 && NumDomainOps <= 3,
6019 "domain must have two or three operands", Domain);
6020 Check(Domain->getOperand(0).get() == Domain ||
6021 isa<MDString>(Domain->getOperand(0)),
6022 "first domain operand must be self-referential or string", Domain);
6023 const auto *Disjoint =
6025 Check(Disjoint && Disjoint->getBitWidth() == 1,
6026 "second domain operand must be an i1 constant", Domain);
6027 if (NumDomainOps == 3)
6028 Check(isa<MDString>(Domain->getOperand(2)),
6029 "third domain operand must be string (if used)", Domain);
6030}
6031
6032void Verifier::visitAliasScopeListMetadata(const MDNode *MD) {
6033 for (const MDOperand &Op : MD->operands()) {
6034 const auto *OpMD = dyn_cast<MDNode>(Op);
6035 Check(OpMD != nullptr, "scope list must consist of MDNodes", MD);
6036 visitAliasScopeMetadata(OpMD);
6037 }
6038}
6039
6040void Verifier::visitAccessGroupMetadata(const MDNode *MD) {
6041 auto IsValidAccessScope = [](const MDNode *MD) {
6042 return MD->getNumOperands() == 0 && MD->isDistinct();
6043 };
6044
6045 // An empty node is an access scope, and it must be 'distinct'. It is never a
6046 // list, because an empty list is not allowed: it would look the same as an
6047 // access scope.
6048 if (MD->getNumOperands() == 0) {
6049 Check(MD->isDistinct(), "Access scope must be 'distinct'", MD);
6050 return;
6051 }
6052
6053 // A non-empty node is a list of access scopes.
6054 for (const MDOperand &Op : MD->operands()) {
6055 const auto *OpMD = dyn_cast<MDNode>(Op);
6056 Check(OpMD != nullptr, "Access scope list must consist of MDNodes", MD);
6057 Check(IsValidAccessScope(OpMD),
6058 "Access scope list contains invalid access scope", MD);
6059 }
6060}
6061
6062void Verifier::visitCapturesMetadata(Instruction &I, const MDNode *Captures) {
6063 static const char *ValidArgs[] = {"address_is_null", "address",
6064 "read_provenance", "provenance"};
6065
6066 auto *SI = dyn_cast<StoreInst>(&I);
6067 Check(SI, "!captures metadata can only be applied to store instructions", &I);
6068 Check(SI->getValueOperand()->getType()->isPointerTy(),
6069 "!captures metadata can only be applied to store with value operand of "
6070 "pointer type",
6071 &I);
6072 Check(Captures->getNumOperands() != 0, "!captures metadata cannot be empty",
6073 &I);
6074
6075 for (Metadata *Op : Captures->operands()) {
6076 auto *Str = dyn_cast<MDString>(Op);
6077 Check(Str, "!captures metadata must be a list of strings", &I);
6078 Check(is_contained(ValidArgs, Str->getString()),
6079 "invalid entry in !captures metadata", &I, Str);
6080 }
6081}
6082
6083void Verifier::visitAllocTokenMetadata(Instruction &I, MDNode *MD) {
6084 Check(isa<CallBase>(I), "!alloc_token should only exist on calls", &I);
6085 Check(MD->getNumOperands() == 2 || MD->getNumOperands() == 3,
6086 "!alloc_token must have 2 or 3 operands", MD);
6087 Check(isa_and_nonnull<MDString>(MD->getOperand(0)), "expected string", MD);
6089 "expected integer constant", MD);
6090 if (MD->getNumOperands() == 3)
6092 "expected function name string", MD);
6093}
6094
6095void Verifier::visitInlineHistoryMetadata(Instruction &I, MDNode *MD) {
6096 Check(isa<CallBase>(I), "!inline_history should only exist on calls", &I);
6097 for (Metadata *Op : MD->operands()) {
6098 // Can be null when a function is erased.
6099 if (!Op)
6100 continue;
6103 ->getValue()
6104 ->stripPointerCastsAndAliases()),
6105 "!inline_history operands must be functions or null", MD);
6106 }
6107}
6108
6109void Verifier::visitMemCacheHintMetadata(Instruction &I, MDNode *MD) {
6110 Check(I.mayReadOrWriteMemory(),
6111 "!mem.cache_hint is only valid on memory operations", &I);
6112
6113 Check(MD->getNumOperands() % 2 == 0,
6114 "!mem.cache_hint must have even number of operands "
6115 "(operand_no, hint_node pairs)",
6116 MD);
6117
6118 const auto *CB = dyn_cast<CallBase>(&I);
6119 if (CB)
6120 Check(CB->getIntrinsicID() != Intrinsic::not_intrinsic,
6121 "!mem.cache_hint is not supported on non-intrinsic calls", &I);
6122
6123 unsigned NumOperands = CB ? CB->arg_size() : I.getNumOperands();
6124
6125 SmallDenseSet<unsigned, 4> SeenOperandNos;
6126 std::optional<uint64_t> LastOperandNo;
6127
6128 // Top-level metadata alternates: i32 operand_no, MDNode hint_node.
6129 for (unsigned J = 0; J + 1 < MD->getNumOperands(); J += 2) {
6130 auto *OpNoCI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(J));
6131 Check(OpNoCI,
6132 "!mem.cache_hint must alternate between i32 operand numbers and "
6133 "metadata hint nodes",
6134 MD);
6135
6136 Check(OpNoCI->getValue().isNonNegative(),
6137 "!mem.cache_hint operand number must be non-negative", MD);
6138
6139 uint64_t OperandNo = OpNoCI->getZExtValue();
6140 Check(OperandNo < NumOperands,
6141 "!mem.cache_hint operand number is out of range", &I);
6142
6143 Value *Operand =
6144 CB ? CB->getArgOperand(OperandNo) : I.getOperand(OperandNo);
6145 Check(Operand->getType()->isPtrOrPtrVectorTy(),
6146 "!mem.cache_hint operand number must refer to a pointer operand", &I);
6147
6148 bool Inserted = SeenOperandNos.insert(OperandNo).second;
6149 Check(Inserted, "!mem.cache_hint contains duplicate operand number", MD);
6150
6151 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
6152 "!mem.cache_hint operand numbers must be in increasing order", MD);
6153 LastOperandNo = OperandNo;
6154
6155 const auto *Node = dyn_cast<MDNode>(MD->getOperand(J + 1));
6156 Check(Node,
6157 "!mem.cache_hint must alternate between i32 operand numbers and "
6158 "metadata hint nodes",
6159 MD);
6160
6161 Check(Node->getNumOperands() % 2 == 0,
6162 "!mem.cache_hint hint node must have even number of operands "
6163 "(key-value pairs)",
6164 Node);
6165
6166 StringSet<> SeenKeys;
6167 for (unsigned K = 0; K + 1 < Node->getNumOperands(); K += 2) {
6168 const auto *Key = dyn_cast<MDString>(Node->getOperand(K));
6169 Check(Key, "!mem.cache_hint key must be a string", Node);
6170
6171 StringRef KeyStr = Key->getString();
6172 Check(SeenKeys.insert(KeyStr).second,
6173 "!mem.cache_hint hint node contains duplicate key", Node);
6174
6175 const Metadata *Value = Node->getOperand(K + 1).get();
6178 "!mem.cache_hint value must be a string or integer", Node);
6179 }
6180 }
6181}
6182
6183/// verifyInstruction - Verify that an instruction is well formed.
6184///
6185void Verifier::visitInstruction(Instruction &I) {
6186 BasicBlock *BB = I.getParent();
6187 Check(BB, "Instruction not embedded in basic block!", &I);
6188
6189 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
6190 for (User *U : I.users()) {
6191 Check(U != (User *)&I || !DT.isReachableFromEntry(BB),
6192 "Only PHI nodes may reference their own value!", &I);
6193 }
6194 }
6195
6196 // Check that void typed values don't have names
6197 Check(!I.getType()->isVoidTy() || !I.hasName(),
6198 "Instruction has a name, but provides a void value!", &I);
6199
6200 // Check that the return value of the instruction is either void or a legal
6201 // value type.
6202 Check(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
6203 "Instruction returns a non-scalar type!", &I);
6204
6205 // Check that the instruction doesn't produce metadata. Calls are already
6206 // checked against the callee type.
6207 Check(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
6208 "Invalid use of metadata!", &I);
6209
6210 // Check that all uses of the instruction, if they are instructions
6211 // themselves, actually have parent basic blocks. If the use is not an
6212 // instruction, it is an error!
6213 for (Use &U : I.uses()) {
6214 if (auto *Used = dyn_cast<Instruction>(U.getUser()))
6215 Check(Used->getParent() != nullptr,
6216 "Instruction referencing"
6217 " instruction not embedded in a basic block!",
6218 &I, Used);
6219 else {
6220 CheckFailed("Use of instruction is not an instruction!", U);
6221 return;
6222 }
6223 }
6224
6225 // Get a pointer to the call base of the instruction if it is some form of
6226 // call.
6227 const auto *CBI = dyn_cast<CallBase>(&I);
6228
6229 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
6230 Check(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
6231
6232 // Check to make sure that only first-class-values are operands to
6233 // instructions.
6234 if (!I.getOperand(i)->getType()->isFirstClassType()) {
6235 Check(false, "Instruction operands must be first-class values!", &I);
6236 }
6237
6238 if (auto *F = dyn_cast<Function>(I.getOperand(i))) {
6239 // This code checks whether the function is used as the operand of a
6240 // clang_arc_attachedcall operand bundle.
6241 auto IsAttachedCallOperand = [](Function *F, const CallBase *CBI,
6242 int Idx) {
6243 return CBI && CBI->isOperandBundleOfType(
6245 };
6246
6247 // Check to make sure that the "address of" an intrinsic function is never
6248 // taken. Ignore cases where the address of the intrinsic function is used
6249 // as the argument of operand bundle "clang.arc.attachedcall" as those
6250 // cases are handled in verifyAttachedCallBundle.
6251 Check((!F->isIntrinsic() ||
6252 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)) ||
6253 IsAttachedCallOperand(F, CBI, i)),
6254 "Cannot take the address of an intrinsic!", &I);
6255 Check(!F->isIntrinsic() || isa<CallInst>(I) || isa<CallBrInst>(I) ||
6256 F->getIntrinsicID() == Intrinsic::donothing ||
6257 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
6258 F->getIntrinsicID() == Intrinsic::seh_try_end ||
6259 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
6260 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
6261 F->getIntrinsicID() == Intrinsic::coro_resume ||
6262 F->getIntrinsicID() == Intrinsic::coro_destroy ||
6263 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
6264 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
6265 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
6266 F->getIntrinsicID() ==
6267 Intrinsic::experimental_patchpoint_void ||
6268 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
6269 F->getIntrinsicID() == Intrinsic::fake_use ||
6270 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
6271 F->getIntrinsicID() == Intrinsic::wasm_throw ||
6272 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
6273 F->getIntrinsicID() == Intrinsic::bpf_unwind_exit ||
6274 IsAttachedCallOperand(F, CBI, i),
6275 "Cannot invoke an intrinsic other than donothing, patchpoint, "
6276 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall, "
6277 "wasm.(re)throw or bpf.unwind.exit",
6278 &I);
6279 Check(F->getParent() == &M, "Referencing function in another module!", &I,
6280 &M, F, F->getParent());
6281 } else if (auto *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
6282 Check(OpBB->getParent() == BB->getParent(),
6283 "Referring to a basic block in another function!", &I);
6284 } else if (auto *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
6285 Check(OpArg->getParent() == BB->getParent(),
6286 "Referring to an argument in another function!", &I);
6287 } else if (auto *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
6288 Check(GV->getParent() == &M, "Referencing global in another module!", &I,
6289 &M, GV, GV->getParent());
6290 } else if (auto *OpInst = dyn_cast<Instruction>(I.getOperand(i))) {
6291 Check(OpInst->getFunction() == BB->getParent(),
6292 "Referring to an instruction in another function!", &I);
6293 verifyDominatesUse(I, i);
6294 } else if (isa<InlineAsm>(I.getOperand(i))) {
6295 Check(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i),
6296 "Cannot take the address of an inline asm!", &I);
6297 } else if (auto *C = dyn_cast<Constant>(I.getOperand(i))) {
6298 visitConstantExprsRecursively(C);
6299 }
6300 }
6301
6303 I.getAllMetadataOtherThanDebugLoc(MDs);
6304 for (auto [Kind, MD] : MDs) {
6305 switch (Kind) {
6306 case LLVMContext::MD_fpmath:
6308 "fpmath requires a floating point result!", &I);
6309 Check(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
6310 if (ConstantFP *CFP0 =
6312 const APFloat &Accuracy = CFP0->getValueAPF();
6313 Check(&Accuracy.getSemantics() == &APFloat::IEEEsingle(),
6314 "fpmath accuracy must have float type", &I);
6315 Check(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
6316 "fpmath accuracy not a positive number!", &I);
6317 } else {
6318 Check(false, "invalid fpmath accuracy!", &I);
6319 }
6320 break;
6321 case LLVMContext::MD_range:
6323 "Ranges are only for loads, calls, invokes and phi nodes!", &I);
6324 visitRangeMetadata(I, MD, I.getType());
6325 break;
6326 case LLVMContext::MD_nofpclass:
6328 "nofpclass is only for loads and phi nodes", &I);
6329 visitNoFPClassMetadata(I, MD, I.getType());
6330 break;
6331 case LLVMContext::MD_noalias_addrspace:
6334 "noalias.addrspace are only for memory operations!", &I);
6335 visitNoaliasAddrspaceMetadata(I, MD, I.getType());
6336 break;
6337 case LLVMContext::MD_invariant_group:
6339 "invariant.group metadata is only for loads and stores", &I);
6340 break;
6341 case LLVMContext::MD_invariant_load: {
6342 auto *II = dyn_cast<IntrinsicInst>(&I);
6343 Check(isa<LoadInst>(I) || (II && II->onlyReadsMemory()),
6344 "invariant.load metadata is only for loads and readonly "
6345 "intrinsic calls",
6346 &I);
6347 break;
6348 }
6349 case LLVMContext::MD_nonnull:
6350 Check(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
6351 &I);
6353 "nonnull applies only to load instructions or phi nodes, use "
6354 "attributes for calls or invokes",
6355 &I);
6356 Check(MD->getNumOperands() == 0, "nonnull metadata must be empty", &I);
6357 break;
6358 case LLVMContext::MD_noundef:
6360 "noundef applies only to load instructions or phi nodes", &I);
6361 Check(MD->getNumOperands() == 0, "noundef metadata must be empty", &I);
6362 break;
6363 case LLVMContext::MD_dereferenceable:
6364 case LLVMContext::MD_dereferenceable_or_null:
6365 visitDereferenceableMetadata(I, MD);
6366 break;
6367 case LLVMContext::MD_nofreeobj:
6368 visitNoFreeObjMetadata(I, MD);
6369 break;
6370 case LLVMContext::MD_tbaa:
6371 TBAAVerifyHelper.visitTBAAMetadata(&I, MD);
6372 break;
6373 case LLVMContext::MD_tbaa_struct:
6374 TBAAVerifyHelper.visitTBAAStructMetadata(&I, MD);
6375 break;
6376 case LLVMContext::MD_noalias:
6377 case LLVMContext::MD_alias_scope:
6378 visitAliasScopeListMetadata(MD);
6379 break;
6380 case LLVMContext::MD_access_group:
6381 visitAccessGroupMetadata(MD);
6382 break;
6383 case LLVMContext::MD_align: {
6384 Check(I.getType()->isPointerTy(), "align applies only to pointer types",
6385 &I);
6387 "align applies only to load instructions or phi nodes, "
6388 "use attributes for calls or invokes",
6389 &I);
6390 Check(MD->getNumOperands() == 1, "align takes one operand!", &I);
6391 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
6392 Check(CI && CI->getType()->isIntegerTy(64),
6393 "align metadata value must be an i64!", &I);
6394 uint64_t Align = CI->getZExtValue();
6395 Check(isPowerOf2_64(Align), "align metadata value must be a power of 2!",
6396 &I);
6397 Check(Align <= Value::MaximumAlignment,
6398 "alignment is larger that implementation defined limit", &I);
6399 break;
6400 }
6401 case LLVMContext::MD_prof:
6402 visitProfMetadata(I, MD);
6403 break;
6404 case LLVMContext::MD_memprof:
6405 visitMemProfMetadata(I, MD);
6406 break;
6407 case LLVMContext::MD_callsite:
6408 visitCallsiteMetadata(I, MD);
6409 break;
6410 case LLVMContext::MD_callee_type:
6411 visitCalleeTypeMetadata(I, MD);
6412 break;
6413 case LLVMContext::MD_DIAssignID:
6414 visitDIAssignIDMetadata(I, MD);
6415 break;
6416 case LLVMContext::MD_mmra:
6417 visitMMRAMetadata(I, MD);
6418 break;
6419 case LLVMContext::MD_annotation:
6420 visitAnnotationMetadata(MD);
6421 break;
6422 case LLVMContext::MD_captures:
6423 visitCapturesMetadata(I, MD);
6424 break;
6425 case LLVMContext::MD_alloc_token:
6426 visitAllocTokenMetadata(I, MD);
6427 break;
6428 case LLVMContext::MD_inline_history:
6429 visitInlineHistoryMetadata(I, MD);
6430 break;
6431 case LLVMContext::MD_mem_cache_hint:
6432 visitMemCacheHintMetadata(I, MD);
6433 break;
6434 default:
6435 if (Kind == MDAMDGPUExpectedActiveLanes) {
6436 Check(MD->getNumOperands() == 1,
6437 "!amdgpu.expected.active.lanes must have exactly one operand", &I,
6438 MD);
6439 ConstantInt *CI =
6441 Check(CI && CI->getType()->isIntegerTy(32),
6442 "!amdgpu.expected.active.lanes operand must be an i32 constant",
6443 &I, MD);
6444 } else if (Kind == MDAMDGPUCFS) {
6445 Check(MD->getNumOperands() == 1,
6446 "!amdgpu.cfs must have exactly one operand", &I, MD);
6447 ConstantInt *CI =
6449 Check(CI && CI->getType()->isIntegerTy(32),
6450 "!amdgpu.cfs operand must be an i32 constant", &I, MD);
6451 Check(CI->getZExtValue() <= 3,
6452 "!amdgpu.cfs operand must be in the range [0, 3]", &I, MD);
6453 }
6454 break;
6455 }
6456 }
6457
6458 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
6459 CheckDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
6460 visitMDNode(*N, AreDebugLocsAllowed::Yes);
6461
6462 if (auto *DL = dyn_cast<DILocation>(N)) {
6463 if (DL->getAtomGroup()) {
6464 DISubprogram *SP = getSubprogram(DL->getRawScope());
6465 CheckDI(SP && SP->getKeyInstructionsEnabled(),
6466 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6467 "Instructions enabled",
6468 DL, SP);
6469 }
6470 }
6471 }
6472
6473 for (auto [Kind, MD] : MDs) {
6474 auto AllowLocs = Kind == LLVMContext::MD_loop ? AreDebugLocsAllowed::Yes
6475 : AreDebugLocsAllowed::No;
6476 visitMDNode(*MD, AllowLocs);
6477 }
6478
6479 InstsInThisBlock.insert(&I);
6480}
6481
6482/// Allow intrinsics to be verified in different ways.
6483void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) {
6484 // If the intrinsic takes MDNode arguments, verify that they are either global
6485 // or are local to *this* function.
6486 for (Value *V : Call.args()) {
6487 if (auto *MD = dyn_cast<MetadataAsValue>(V))
6488 visitMetadataAsValue(*MD, Call.getCaller());
6489 if (auto *Const = dyn_cast<Constant>(V))
6490 Check(!Const->getType()->isX86_AMXTy(),
6491 "const x86_amx is not allowed in argument!");
6492 }
6493
6494 // Verify intrinsic signature, so following checks can rely on it. The actual
6495 // error is reported at the intrinsic declaration.
6496 SmallVector<Type *, 4> OverloadTys;
6497 if (!Intrinsic::isSignatureValid(ID, Call.getFunctionType(), OverloadTys))
6498 return;
6499
6500 switch (ID) {
6501 default:
6502 break;
6503 case Intrinsic::assume: {
6504 if (Call.hasOperandBundles()) {
6506 Check(Cond && Cond->isOne(),
6507 "assume with operand bundles must have i1 true condition", Call);
6508 }
6509 for (auto OBU : Call.operand_bundles()) {
6510 // Separate storage assumptions are special insofar as they're the only
6511 // operand bundles allowed on assumes that aren't parameter attributes.
6512
6513 auto GetTypeAt = [&](unsigned Index) {
6514 return OBU.Inputs[Index]->getType();
6515 };
6516
6517 switch (getBundleAttrFromOBU(OBU)) {
6518 case BundleAttr::None:
6519 CheckFailed("tags must be valid attribute names", Call);
6520 break;
6521 case BundleAttr::Align:
6522 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6523 "alignment assumptions should have 2 or 3 arguments", Call);
6524 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6525 Call);
6526 Check(GetTypeAt(1)->isIntegerTy() &&
6527 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6528 "second argument should be an integer with a maximum width of 64 "
6529 "bits",
6530 Call);
6531 Check(OBU.Inputs.size() < 3 ||
6532 (GetTypeAt(2)->isIntegerTy() &&
6533 GetTypeAt(2)->getIntegerBitWidth() <= 64),
6534 "third argument should be an integer with a maximum width of 64 "
6535 "bits if present",
6536 Call);
6537 break;
6538 case BundleAttr::Cold:
6539 Check(OBU.Inputs.size() == 0,
6540 "cold assumptions should have no arguments", Call);
6541 break;
6542 case BundleAttr::Dereferenceable:
6543 case BundleAttr::DereferenceableOrNull:
6544 Check(OBU.Inputs.size() == 2,
6545 "dereferenceable assumptions should have 2 arguments", Call);
6546 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6547 Call);
6548 Check(GetTypeAt(1)->isIntegerTy() &&
6549 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6550 "second argument should be an integer with a maximum width of 64 "
6551 "bits",
6552 Call);
6553 break;
6554 case BundleAttr::Ignore:
6555 break;
6556 case BundleAttr::NonNull:
6557 Check(OBU.Inputs.size() == 1,
6558 "nonnull assumptions should have 1 argument", Call);
6559 Check(GetTypeAt(0)->isPointerTy(), "first argument should be a pointer",
6560 Call);
6561 break;
6562 case BundleAttr::NoUndef:
6563 Check(OBU.Inputs.size() == 1,
6564 "noundef assumptions should have 1 argument", Call);
6565 break;
6566 case BundleAttr::Range: {
6567 Check(OBU.Inputs.size() == 3,
6568 "range assumptions should have 3 arguments", Call);
6569 Check(GetTypeAt(0)->isIntegerTy(),
6570 "first argument should be an integer", Call);
6571 auto *LowerBound = dyn_cast<ConstantInt>(OBU.Inputs[1]);
6572 Check(LowerBound, "second argument should be a constant integer", Call);
6573 auto *UpperBound = dyn_cast<ConstantInt>(OBU.Inputs[2]);
6574 Check(UpperBound, "third argument should be a constant integer", Call);
6575 Check(LowerBound != UpperBound || LowerBound->isZero(),
6576 "an empty range has to be represented as `0, 0`");
6577 Check(GetTypeAt(0)->getIntegerBitWidth() ==
6578 GetTypeAt(1)->getIntegerBitWidth() &&
6579 GetTypeAt(1)->getIntegerBitWidth() ==
6580 GetTypeAt(2)->getIntegerBitWidth(),
6581 "all arguments should have the same bit width", Call);
6582 } break;
6583 case BundleAttr::SeparateStorage:
6584 Check(OBU.Inputs.size() == 2,
6585 "separate_storage assumptions should have 2 arguments", Call);
6586 Check(GetTypeAt(0)->isPointerTy() && GetTypeAt(1)->isPointerTy(),
6587 "arguments to separate_storage assumptions should be pointers",
6588 Call);
6589 break;
6590 }
6591 }
6592 break;
6593 }
6594 case Intrinsic::ucmp:
6595 case Intrinsic::scmp: {
6596 Type *DestTy = Call.getType();
6597 Check(DestTy->getScalarSizeInBits() >= 2,
6598 "result type must be at least 2 bits wide", Call);
6599 break;
6600 }
6601 case Intrinsic::coro_begin:
6602 case Intrinsic::coro_begin_custom_abi:
6604 "id argument of llvm.coro.begin must refer to coro.id");
6605 break;
6606 case Intrinsic::coro_id: {
6608 "align argument only accepts constants");
6609 auto *Promise = Call.getArgOperand(1);
6610 Check(isa<ConstantPointerNull>(Promise) || isa<AllocaInst>(Promise),
6611 "promise argument must refer to an alloca");
6612
6613 auto *CoroAddr = Call.getArgOperand(2)->stripPointerCastsAndAliases();
6614 bool BeforeCoroEarly = isa<ConstantPointerNull>(CoroAddr);
6615 Check(BeforeCoroEarly || isa<Function>(CoroAddr),
6616 "coro argument must refer to a function");
6617
6618 auto *InfoArg = Call.getArgOperand(3);
6619 bool BeforeCoroSplit = isa<ConstantPointerNull>(InfoArg);
6620 if (BeforeCoroSplit)
6621 break;
6622
6623 Check(!BeforeCoroEarly, "cannot run CoroSplit before CoroEarly");
6624 auto *GV = dyn_cast<GlobalVariable>(InfoArg);
6625 Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
6626 "info argument of llvm.coro.id must refer to an initialized "
6627 "constant");
6628 Constant *Init = GV->getInitializer();
6630 "info argument of llvm.coro.id must refer to either a struct or "
6631 "an array");
6632 break;
6633 }
6634 case Intrinsic::is_fpclass: {
6635 const ConstantInt *TestMask = cast<ConstantInt>(Call.getOperand(1));
6636 Check((TestMask->getZExtValue() & ~static_cast<unsigned>(fcAllFlags)) == 0,
6637 "unsupported bits for llvm.is.fpclass test mask");
6638 break;
6639 }
6640 case Intrinsic::fptrunc_round: {
6641 // Check the rounding mode
6642 Metadata *MD = nullptr;
6644 if (MAV)
6645 MD = MAV->getMetadata();
6646
6647 Check(MD != nullptr, "missing rounding mode argument", Call);
6648
6649 Check(isa<MDString>(MD),
6650 ("invalid value for llvm.fptrunc.round metadata operand"
6651 " (the operand should be a string)"),
6652 MD);
6653
6654 std::optional<RoundingMode> RoundMode =
6655 convertStrToRoundingMode(cast<MDString>(MD)->getString());
6656 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6657 "unsupported rounding mode argument", Call);
6658 break;
6659 }
6660 case Intrinsic::convert_to_arbitrary_fp: {
6661 Type *IntTy = Call.getType();
6662
6663 // Check interpretation metadata (argoperand 1).
6664 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6665 Check(InterpMAV, "missing interpretation metadata operand", Call);
6666 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6667 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6668 StringRef Interp = InterpStr->getString();
6669
6670 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6671 Call);
6672
6673 // Valid interpretation strings: mini-float format names.
6675 "unsupported interpretation metadata string", Call);
6676
6677 // The integer type width must equal the arbitrary FP format width.
6678 if (unsigned FormatBits =
6680 Check(IntTy->getScalarSizeInBits() == FormatBits,
6681 "integer type bit width must equal the arbitrary FP format width",
6682 Call);
6683
6684 // Check rounding mode metadata (argoperand 2).
6685 auto *RoundingMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(2));
6686 Check(RoundingMAV, "missing rounding mode metadata operand", Call);
6687 auto *RoundingStr = dyn_cast<MDString>(RoundingMAV->getMetadata());
6688 Check(RoundingStr, "rounding mode metadata operand must be a string", Call);
6689
6690 std::optional<RoundingMode> RM =
6691 convertStrToRoundingMode(RoundingStr->getString());
6692 Check(RM && *RM != RoundingMode::Dynamic,
6693 "unsupported rounding mode argument", Call);
6694 break;
6695 }
6696 case Intrinsic::convert_from_arbitrary_fp: {
6697 Type *IntTy = Call.getArgOperand(0)->getType();
6698
6699 // Check interpretation metadata (argoperand 1).
6700 auto *InterpMAV = dyn_cast<MetadataAsValue>(Call.getArgOperand(1));
6701 Check(InterpMAV, "missing interpretation metadata operand", Call);
6702 auto *InterpStr = dyn_cast<MDString>(InterpMAV->getMetadata());
6703 Check(InterpStr, "interpretation metadata operand must be a string", Call);
6704 StringRef Interp = InterpStr->getString();
6705
6706 Check(!Interp.empty(), "interpretation metadata string must not be empty",
6707 Call);
6708
6709 // Valid interpretation strings: mini-float format names.
6711 "unsupported interpretation metadata string", Call);
6712
6713 // The integer type width must equal the arbitrary FP format width.
6714 if (unsigned FormatBits =
6716 Check(IntTy->getScalarSizeInBits() == FormatBits,
6717 "integer type bit width must equal the arbitrary FP format width",
6718 Call);
6719 break;
6720 }
6721#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6722#include "llvm/IR/VPIntrinsics.def"
6723#undef BEGIN_REGISTER_VP_INTRINSIC
6724 visitVPIntrinsic(cast<VPIntrinsic>(Call));
6725 break;
6726#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6727 case Intrinsic::INTRINSIC:
6728#include "llvm/IR/ConstrainedOps.def"
6729#undef INSTRUCTION
6730 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
6731 break;
6732 case Intrinsic::dbg_declare: // llvm.dbg.declare
6733 case Intrinsic::dbg_value: // llvm.dbg.value
6734 case Intrinsic::dbg_assign: // llvm.dbg.assign
6735 case Intrinsic::dbg_label: // llvm.dbg.label
6736 // We no longer interpret debug intrinsics (the old variable-location
6737 // design). They're meaningless as far as LLVM is concerned we could make
6738 // it an error for them to appear, but it's possible we'll have users
6739 // converting back to intrinsics for the forseeable future (such as DXIL),
6740 // so tolerate their existance.
6741 break;
6742 case Intrinsic::memcpy:
6743 case Intrinsic::memcpy_inline:
6744 case Intrinsic::memmove:
6745 case Intrinsic::memset:
6746 case Intrinsic::memset_inline:
6747 break;
6748 case Intrinsic::experimental_memset_pattern: {
6749 const auto Memset = cast<MemSetPatternInst>(&Call);
6750 Check(Memset->getValue()->getType()->isSized(),
6751 "unsized types cannot be used as memset patterns", Call);
6752 break;
6753 }
6754 case Intrinsic::memcpy_element_unordered_atomic:
6755 case Intrinsic::memmove_element_unordered_atomic:
6756 case Intrinsic::memset_element_unordered_atomic: {
6757 const auto *AMI = cast<AnyMemIntrinsic>(&Call);
6758
6759 ConstantInt *ElementSizeCI =
6760 cast<ConstantInt>(AMI->getRawElementSizeInBytes());
6761 const APInt &ElementSizeVal = ElementSizeCI->getValue();
6762 Check(ElementSizeVal.isPowerOf2(),
6763 "element size of the element-wise atomic memory intrinsic "
6764 "must be a power of 2",
6765 Call);
6766
6767 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6768 return Alignment && ElementSizeVal.ule(Alignment->value());
6769 };
6770 Check(IsValidAlignment(AMI->getDestAlign()),
6771 "incorrect alignment of the destination argument", Call);
6772 if (const auto *AMT = dyn_cast<AnyMemTransferInst>(AMI)) {
6773 Check(IsValidAlignment(AMT->getSourceAlign()),
6774 "incorrect alignment of the source argument", Call);
6775 }
6776 break;
6777 }
6778 case Intrinsic::call_preallocated_setup: {
6779 auto *NumArgs = cast<ConstantInt>(Call.getArgOperand(0));
6780 bool FoundCall = false;
6781 for (User *U : Call.users()) {
6782 auto *UseCall = dyn_cast<CallBase>(U);
6783 Check(UseCall != nullptr,
6784 "Uses of llvm.call.preallocated.setup must be calls");
6785 Intrinsic::ID IID = UseCall->getIntrinsicID();
6786 if (IID == Intrinsic::call_preallocated_arg) {
6787 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1));
6788 Check(AllocArgIndex != nullptr,
6789 "llvm.call.preallocated.alloc arg index must be a constant");
6790 auto AllocArgIndexInt = AllocArgIndex->getValue();
6791 Check(AllocArgIndexInt.sge(0) &&
6792 AllocArgIndexInt.slt(NumArgs->getValue()),
6793 "llvm.call.preallocated.alloc arg index must be between 0 and "
6794 "corresponding "
6795 "llvm.call.preallocated.setup's argument count");
6796 } else if (IID == Intrinsic::call_preallocated_teardown) {
6797 // nothing to do
6798 } else {
6799 Check(!FoundCall, "Can have at most one call corresponding to a "
6800 "llvm.call.preallocated.setup");
6801 FoundCall = true;
6802 size_t NumPreallocatedArgs = 0;
6803 for (unsigned i = 0; i < UseCall->arg_size(); i++) {
6804 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6805 ++NumPreallocatedArgs;
6806 }
6807 }
6808 Check(NumPreallocatedArgs != 0,
6809 "cannot use preallocated intrinsics on a call without "
6810 "preallocated arguments");
6811 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6812 "llvm.call.preallocated.setup arg size must be equal to number "
6813 "of preallocated arguments "
6814 "at call site",
6815 Call, *UseCall);
6816 // getOperandBundle() cannot be called if more than one of the operand
6817 // bundle exists. There is already a check elsewhere for this, so skip
6818 // here if we see more than one.
6819 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) >
6820 1) {
6821 return;
6822 }
6823 auto PreallocatedBundle =
6824 UseCall->getOperandBundle(LLVMContext::OB_preallocated);
6825 Check(PreallocatedBundle,
6826 "Use of llvm.call.preallocated.setup outside intrinsics "
6827 "must be in \"preallocated\" operand bundle");
6828 Check(PreallocatedBundle->Inputs.front().get() == &Call,
6829 "preallocated bundle must have token from corresponding "
6830 "llvm.call.preallocated.setup");
6831 }
6832 }
6833 break;
6834 }
6835 case Intrinsic::call_preallocated_arg: {
6836 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6837 Check(Token &&
6838 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6839 "llvm.call.preallocated.arg token argument must be a "
6840 "llvm.call.preallocated.setup");
6841 Check(Call.hasFnAttr(Attribute::Preallocated),
6842 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6843 "call site attribute");
6844 break;
6845 }
6846 case Intrinsic::call_preallocated_teardown: {
6847 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0));
6848 Check(Token &&
6849 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6850 "llvm.call.preallocated.teardown token argument must be a "
6851 "llvm.call.preallocated.setup");
6852 break;
6853 }
6854 case Intrinsic::gcroot:
6855 case Intrinsic::gcwrite:
6856 case Intrinsic::gcread:
6857 if (ID == Intrinsic::gcroot) {
6858 auto *AI =
6860 Check(AI, "llvm.gcroot parameter #1 must be an alloca.", Call);
6862 "llvm.gcroot parameter #2 must be a constant.", Call);
6863 if (!AI->getAllocatedType()->isPointerTy()) {
6865 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6866 "or argument #2 must be a non-null constant.",
6867 Call);
6868 }
6869 }
6870
6871 Check(Call.getParent()->getParent()->hasGC(),
6872 "Enclosing function does not use GC.", Call);
6873 break;
6874 case Intrinsic::init_trampoline:
6876 "llvm.init_trampoline parameter #2 must resolve to a function.",
6877 Call);
6878 break;
6879 case Intrinsic::reloc_none: {
6881 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata()),
6882 "llvm.reloc.none argument must be a metadata string", &Call);
6883 break;
6884 }
6885 case Intrinsic::stackprotector:
6887 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
6888 break;
6889 case Intrinsic::localescape: {
6890 BasicBlock *BB = Call.getParent();
6891 Check(BB->isEntryBlock(), "llvm.localescape used outside of entry block",
6892 Call);
6893 Check(!SawFrameEscape, "multiple calls to llvm.localescape in one function",
6894 Call);
6895 for (Value *Arg : Call.args()) {
6896 if (isa<ConstantPointerNull>(Arg))
6897 continue; // Null values are allowed as placeholders.
6898 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
6899 Check(AI && AI->isStaticAlloca(),
6900 "llvm.localescape only accepts static allocas", Call);
6901 }
6902 FrameEscapeInfo[BB->getParent()].first = Call.arg_size();
6903 SawFrameEscape = true;
6904 break;
6905 }
6906 case Intrinsic::localrecover: {
6908 auto *Fn = dyn_cast<Function>(FnArg);
6909 Check(Fn && !Fn->isDeclaration(),
6910 "llvm.localrecover first "
6911 "argument must be function defined in this module",
6912 Call);
6913 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2));
6914 auto &Entry = FrameEscapeInfo[Fn];
6915 Entry.second = unsigned(
6916 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6917 break;
6918 }
6919
6920 case Intrinsic::experimental_gc_statepoint:
6921 if (auto *CI = dyn_cast<CallInst>(&Call))
6922 Check(!CI->isInlineAsm(),
6923 "gc.statepoint support for inline assembly unimplemented", CI);
6924 Check(Call.getParent()->getParent()->hasGC(),
6925 "Enclosing function does not use GC.", Call);
6926
6927 verifyStatepoint(Call);
6928 break;
6929 case Intrinsic::experimental_gc_result: {
6930 Check(Call.getParent()->getParent()->hasGC(),
6931 "Enclosing function does not use GC.", Call);
6932
6933 auto *Statepoint = Call.getArgOperand(0);
6934 if (isa<UndefValue>(Statepoint))
6935 break;
6936
6937 // Are we tied to a statepoint properly?
6938 const auto *StatepointCall = dyn_cast<CallBase>(Statepoint);
6939 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6940 Intrinsic::experimental_gc_statepoint,
6941 "gc.result operand #1 must be from a statepoint", Call,
6942 Call.getArgOperand(0));
6943
6944 // Check that result type matches wrapped callee.
6945 auto *TargetFuncType =
6946 cast<FunctionType>(StatepointCall->getParamElementType(2));
6947 Check(Call.getType() == TargetFuncType->getReturnType(),
6948 "gc.result result type does not match wrapped callee", Call);
6949 break;
6950 }
6951 case Intrinsic::experimental_gc_relocate: {
6953 "gc.relocate must return a pointer or a vector of pointers", Call);
6954
6955 // Check that this relocate is correctly tied to the statepoint
6956
6957 // This is case for relocate on the unwinding path of an invoke statepoint
6958 if (auto *LandingPad = dyn_cast<LandingPadInst>(Call.getArgOperand(0))) {
6959
6960 const BasicBlock *InvokeBB =
6961 LandingPad->getParent()->getUniquePredecessor();
6962
6963 // Landingpad relocates should have only one predecessor with invoke
6964 // statepoint terminator
6965 Check(InvokeBB, "safepoints should have unique landingpads",
6966 LandingPad->getParent());
6968 "gc relocate should be linked to a statepoint", InvokeBB);
6969 } else {
6970 // In all other cases relocate should be tied to the statepoint directly.
6971 // This covers relocates on a normal return path of invoke statepoint and
6972 // relocates of a call statepoint.
6973 auto *Token = Call.getArgOperand(0);
6975 "gc relocate is incorrectly tied to the statepoint", Call, Token);
6976 }
6977
6978 // Verify rest of the relocate arguments.
6979 const Value &StatepointCall = *cast<GCRelocateInst>(Call).getStatepoint();
6980
6981 // Both the base and derived must be piped through the safepoint.
6984 "gc.relocate operand #2 must be integer offset", Call);
6985
6986 Value *Derived = Call.getArgOperand(2);
6987 Check(isa<ConstantInt>(Derived),
6988 "gc.relocate operand #3 must be integer offset", Call);
6989
6990 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
6991 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
6992
6993 // Check the bounds
6994 if (isa<UndefValue>(StatepointCall))
6995 break;
6996 if (auto Opt = cast<GCStatepointInst>(StatepointCall)
6997 .getOperandBundle(LLVMContext::OB_gc_live)) {
6998 Check(BaseIndex < Opt->Inputs.size(),
6999 "gc.relocate: statepoint base index out of bounds", Call);
7000 Check(DerivedIndex < Opt->Inputs.size(),
7001 "gc.relocate: statepoint derived index out of bounds", Call);
7002 }
7003
7004 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call);
7005 auto *DerivedType = Relocate.getDerivedPtr()->getType();
7006 auto *BaseType = Relocate.getBasePtr()->getType();
7007
7008 Check(BaseType->isPtrOrPtrVectorTy(),
7009 "gc.relocate: relocated value must be a pointer", Call);
7010 Check(DerivedType->isPtrOrPtrVectorTy(),
7011 "gc.relocate: relocated value must be a pointer", Call);
7012 Check(Call.getType() == DerivedType,
7013 "gc.relocate: must return the type of the relocated value", Call);
7014
7015 auto GC = llvm::getGCStrategy(Relocate.getFunction()->getGC());
7016 Check(GC, "gc.relocate: calling function must have GCStrategy",
7017 Call.getFunction());
7018 if (GC) {
7019 auto isGCPtr = [&GC](Type *PTy) {
7020 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(true);
7021 };
7022 Check(isGCPtr(BaseType),
7023 "gc.relocate: relocated value must be a gc pointer", Call);
7024 Check(isGCPtr(DerivedType),
7025 "gc.relocate: relocated value must be a gc pointer", Call);
7026 }
7027 break;
7028 }
7029 case Intrinsic::experimental_patchpoint: {
7030 if (Call.getCallingConv() == CallingConv::AnyReg) {
7032 "patchpoint: invalid return type used with anyregcc", Call);
7033 }
7034 break;
7035 }
7036 case Intrinsic::eh_exceptioncode:
7037 case Intrinsic::eh_exceptionpointer: {
7039 "eh.exceptionpointer argument must be a catchpad", Call);
7040 break;
7041 }
7042 case Intrinsic::get_active_lane_mask: {
7043 Type *ElemTy = Call.getType()->getScalarType();
7044 Check(ElemTy->isIntegerTy(1),
7045 "get_active_lane_mask: element type is not i1", Call);
7046 break;
7047 }
7048 case Intrinsic::mask_beforefirst: {
7050 "mask.beforefirst element type must be i1", Call);
7051 break;
7052 }
7053 case Intrinsic::experimental_get_vector_length: {
7054 auto *VF = cast<ConstantInt>(Call.getArgOperand(1));
7055 Check(!VF->isNegative() && !VF->isZero(),
7056 "get_vector_length: VF must be positive", Call);
7057 break;
7058 }
7059 case Intrinsic::experimental_guard: {
7060 Check(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call);
7062 "experimental_guard must have exactly one "
7063 "\"deopt\" operand bundle");
7064 break;
7065 }
7066
7067 case Intrinsic::experimental_deoptimize: {
7068 Check(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked",
7069 Call);
7071 "experimental_deoptimize must have exactly one "
7072 "\"deopt\" operand bundle");
7074 "experimental_deoptimize return type must match caller return type");
7075
7076 if (isa<CallInst>(Call)) {
7078 Check(RI,
7079 "calls to experimental_deoptimize must be followed by a return");
7080
7081 if (!Call.getType()->isVoidTy() && RI)
7082 Check(RI->getReturnValue() == &Call,
7083 "calls to experimental_deoptimize must be followed by a return "
7084 "of the value computed by experimental_deoptimize");
7085 }
7086
7087 break;
7088 }
7089 case Intrinsic::vastart: {
7091 "va_start called in a non-varargs function");
7092 break;
7093 }
7094 case Intrinsic::get_dynamic_area_offset: {
7095 Check(DL.getPointerSizeInBits(DL.getAllocaAddrSpace()) ==
7097 "get_dynamic_area_offset result type must match alloca address "
7098 "space width",
7099 Call);
7100 break;
7101 }
7102 case Intrinsic::smul_fix:
7103 case Intrinsic::smul_fix_sat:
7104 case Intrinsic::umul_fix:
7105 case Intrinsic::umul_fix_sat:
7106 case Intrinsic::sdiv_fix:
7107 case Intrinsic::sdiv_fix_sat:
7108 case Intrinsic::udiv_fix:
7109 case Intrinsic::udiv_fix_sat: {
7110 Value *Op1 = Call.getArgOperand(0);
7111 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2));
7112
7113 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
7114 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
7115 Check(Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(),
7116 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
7117 "the operands");
7118 } else {
7119 Check(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(),
7120 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
7121 "to the width of the operands");
7122 }
7123 break;
7124 }
7125 case Intrinsic::bswap: {
7126 Type *Ty = Call.getType();
7127 unsigned Size = Ty->getScalarSizeInBits();
7128 Check(Size % 16 == 0, "bswap must be an even number of bytes", &Call);
7129 break;
7130 }
7131 case Intrinsic::invariant_start: {
7132 auto *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0));
7133 Check(InvariantSize &&
7134 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
7135 "invariant_start parameter must be -1, 0 or a positive number",
7136 &Call);
7137 break;
7138 }
7139 case Intrinsic::matrix_multiply:
7140 case Intrinsic::matrix_transpose:
7141 case Intrinsic::matrix_column_major_load:
7142 case Intrinsic::matrix_column_major_store: {
7144 Value *Stride = nullptr;
7145 ConstantInt *NumRows;
7146 ConstantInt *NumColumns;
7147 FixedVectorType *ResultTy;
7148 Type *Op0ElemTy = nullptr;
7149 Type *Op1ElemTy = nullptr;
7150 switch (ID) {
7151 case Intrinsic::matrix_multiply: {
7152 NumRows = cast<ConstantInt>(Call.getArgOperand(2));
7153 ConstantInt *N = cast<ConstantInt>(Call.getArgOperand(3));
7154 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
7157 auto *RetTy = dyn_cast<FixedVectorType>(Call.getType());
7158 Check(Op0Ty && Op1Ty && RetTy,
7159 "Matrix operations require fixed-length vectors!", &Call);
7160 Check(Op0Ty->getNumElements() ==
7161 NumRows->getZExtValue() * N->getZExtValue(),
7162 "First argument of a matrix operation does not match specified "
7163 "shape!");
7164 Check(Op1Ty->getNumElements() ==
7165 N->getZExtValue() * NumColumns->getZExtValue(),
7166 "Second argument of a matrix operation does not match specified "
7167 "shape!");
7168
7169 ResultTy = RetTy;
7170 Op0ElemTy = Op0Ty->getElementType();
7171 Op1ElemTy = Op1Ty->getElementType();
7172 break;
7173 }
7174 case Intrinsic::matrix_transpose: {
7175 NumRows = cast<ConstantInt>(Call.getArgOperand(1));
7176 NumColumns = cast<ConstantInt>(Call.getArgOperand(2));
7178 auto *RetTy = dyn_cast<FixedVectorType>(Call.getType());
7179 Check(Op0Ty && RetTy, "Matrix operations require fixed-length vectors!",
7180 &Call);
7181 ResultTy = RetTy;
7182 Op0ElemTy = Op0Ty->getElementType();
7183 break;
7184 }
7185 case Intrinsic::matrix_column_major_load: {
7186 Stride = Call.getArgOperand(1);
7187 NumRows = cast<ConstantInt>(Call.getArgOperand(3));
7188 NumColumns = cast<ConstantInt>(Call.getArgOperand(4));
7189 auto *RetTy = dyn_cast<FixedVectorType>(Call.getType());
7190 Check(RetTy, "Matrix operations require fixed-length vectors!", &Call);
7191 ResultTy = RetTy;
7192 break;
7193 }
7194 case Intrinsic::matrix_column_major_store: {
7195 Stride = Call.getArgOperand(2);
7196 NumRows = cast<ConstantInt>(Call.getArgOperand(4));
7197 NumColumns = cast<ConstantInt>(Call.getArgOperand(5));
7199 Check(Op0Ty, "Matrix operations require fixed-length vectors!", &Call);
7200 ResultTy = Op0Ty;
7201 Op0ElemTy = Op0Ty->getElementType();
7202 break;
7203 }
7204 default:
7205 llvm_unreachable("unexpected intrinsic");
7206 }
7207
7208 Check(ResultTy->getElementType()->isIntegerTy() ||
7209 ResultTy->getElementType()->isFloatingPointTy(),
7210 "Result type must be an integer or floating-point type!", IF);
7211
7212 if (Op0ElemTy)
7213 Check(ResultTy->getElementType() == Op0ElemTy,
7214 "Vector element type mismatch of the result and first operand "
7215 "vector!",
7216 IF);
7217
7218 if (Op1ElemTy)
7219 Check(ResultTy->getElementType() == Op1ElemTy,
7220 "Vector element type mismatch of the result and second operand "
7221 "vector!",
7222 IF);
7223
7224 Check(ResultTy->getNumElements() ==
7225 NumRows->getZExtValue() * NumColumns->getZExtValue(),
7226 "Result of a matrix operation does not fit in the returned vector!");
7227
7228 if (Stride)
7229 Check(Stride->getType()->getIntegerBitWidth() <= 64,
7230 "Stride bitwidth cannot exceed 64!", IF);
7231
7232 break;
7233 }
7234 case Intrinsic::stepvector: {
7235 auto *VecTy = cast<VectorType>(Call.getType());
7236 Check(VecTy->getScalarSizeInBits() >= 8,
7237 "stepvector only supported for vectors of integers "
7238 "with a bitwidth of at least 8.",
7239 &Call);
7240 break;
7241 }
7242 case Intrinsic::experimental_vector_match: {
7243 Value *Op1 = Call.getArgOperand(0);
7244 Value *Op2 = Call.getArgOperand(1);
7245
7246 auto *Op1Ty = cast<VectorType>(Op1->getType());
7247 auto *Op2Ty = cast<VectorType>(Op2->getType());
7248
7250 "Second operand must be a fixed length vector.", &Call);
7251 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
7252 "First two operands must have the same element type.", &Call);
7253 break;
7254 }
7255 case Intrinsic::speculative_load: {
7256 Type *LoadTy = Call.getType();
7257 Check(LoadTy->isByteTy() || LoadTy->isVectorTy(),
7258 "llvm.speculative.load return type must be a byte type or a "
7259 "vector type",
7260 &Call);
7261 if (LoadTy->isByteOrByteVectorTy()) {
7262 unsigned BitWidth = LoadTy->getScalarType()->getByteBitWidth();
7263 Check((BitWidth % 8) == 0,
7264 "llvm.speculative.load byte type must have a bit width that is "
7265 "a multiple of 8",
7266 &Call);
7267 }
7268
7269 uint64_t MinSizeInBits = DL.getTypeSizeInBits(LoadTy).getKnownMinValue();
7270 Check((MinSizeInBits % 8) == 0 && isPowerOf2_64(MinSizeInBits / 8),
7271 "llvm.speculative.load return type size in bytes must be a "
7272 "positive power of 2",
7273 &Call);
7274
7275 constexpr unsigned NumFixedArgs = 3;
7276 unsigned NumArgs = Call.arg_size();
7277 Check(NumArgs >= NumFixedArgs,
7278 "llvm.speculative.load requires at least 3 arguments", &Call);
7279
7280 Value *PayloadArg = Call.getArgOperand(NumFixedArgs - 1);
7281 if (PayloadArg->getType()->isIntegerTy(64)) {
7282 // Direct form: (ptr, i1 from_end, i64 num_accessible_bytes)
7283 Check(NumArgs == NumFixedArgs,
7284 "llvm.speculative.load direct form has too many arguments", &Call);
7285 } else {
7286 // Oracle form: (ptr, i1 from_end, oracle_fn_ptr, args...)
7287 auto *OracleFn = dyn_cast<Function>(PayloadArg);
7288 Check(OracleFn,
7289 "llvm.speculative.load third argument must be i64 or a direct "
7290 "reference to an oracle function",
7291 &Call);
7292
7293 Check(OracleFn->hasFnAttribute("oracle-function"),
7294 "llvm.speculative.load oracle function must have the "
7295 "\"oracle-function\" attribute",
7296 &Call);
7297
7298 FunctionType *FTy = OracleFn->getFunctionType();
7299 Check(NumArgs - NumFixedArgs == FTy->getNumParams(),
7300 "llvm.speculative.load oracle function argument count mismatch",
7301 &Call);
7302 for (auto [ParamTy, Arg] :
7303 zip_equal(FTy->params(), drop_begin(Call.args(), NumFixedArgs)))
7304 Check(ParamTy == Arg->getType(),
7305 "llvm.speculative.load oracle function argument type mismatch",
7306 &Call);
7307 }
7308 break;
7309 }
7310 case Intrinsic::vector_repeat: {
7311 auto *ResultTy = dyn_cast<ScalableVectorType>(Call.getType());
7313
7314 Check(ArgTy, "vector_repeat argument must be a fixed-length vector.",
7315 &Call);
7316 Check(ResultTy, "vector_repeat result must be a scalable vector.", &Call);
7317 Check(ResultTy->getElementType() == ArgTy->getElementType(),
7318 "vector_repeat argument and result must have the same element "
7319 "type.",
7320 &Call);
7321 Check(ArgTy->getNumElements() == ResultTy->getMinNumElements(),
7322 "vector_repeat argument and result must have the same minimum "
7323 "element count.",
7324 &Call);
7325 break;
7326 }
7327 case Intrinsic::vector_shuffle: {
7328 auto *RetTy = cast<VectorType>(Call.getType());
7329 auto *MaskTy = cast<VectorType>(Call.getArgOperand(1)->getType());
7330
7331 Check(MaskTy->getElementCount() == RetTy->getElementCount(),
7332 "vector_shuffle mask must have the same number of elements as the "
7333 "result.",
7334 &Call);
7335 break;
7336 }
7337 case Intrinsic::vector_insert: {
7338 Value *Vec = Call.getArgOperand(0);
7339 Value *SubVec = Call.getArgOperand(1);
7341 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
7342
7343 VectorType *VecTy = cast<VectorType>(Vec->getType());
7345
7346 ElementCount VecEC = VecTy->getElementCount();
7347 ElementCount SubVecEC = SubVecTy->getElementCount();
7348 Check(VecTy->getElementType() == SubVecTy->getElementType(),
7349 "vector_insert parameters must have the same element "
7350 "type.",
7351 &Call);
7352 Check(IdxN % SubVecEC.getKnownMinValue() == 0,
7353 "vector_insert index must be a constant multiple of "
7354 "the subvector's known minimum vector length.");
7355
7356 // The only allowed 'mixed' case is inserting a fixed vector into a
7357 // scalable vector.
7358 if (SubVecEC.isScalable()) {
7359 Check(VecEC.isScalable(), "cannot vector_insert a scalable vector into "
7360 "a fixed vector.");
7361 }
7362
7363 // If this insertion is not the 'mixed' case where a fixed vector is
7364 // inserted into a scalable vector, ensure that the insertion of the
7365 // subvector does not overrun the parent vector.
7366 if (VecEC.isScalable() == SubVecEC.isScalable()) {
7367 Check(IdxN < VecEC.getKnownMinValue() &&
7368 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
7369 "subvector operand of vector_insert would overrun the "
7370 "vector being inserted into.");
7371 }
7372 break;
7373 }
7374 case Intrinsic::vector_extract: {
7375 Value *Vec = Call.getArgOperand(0);
7377 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
7378
7379 VectorType *ResultTy = cast<VectorType>(Call.getType());
7380 VectorType *VecTy = cast<VectorType>(Vec->getType());
7381
7382 ElementCount VecEC = VecTy->getElementCount();
7383 ElementCount ResultEC = ResultTy->getElementCount();
7384
7385 Check(ResultTy->getElementType() == VecTy->getElementType(),
7386 "vector_extract result must have the same element "
7387 "type as the input vector.",
7388 &Call);
7389 Check(IdxN % ResultEC.getKnownMinValue() == 0,
7390 "vector_extract index must be a constant multiple of "
7391 "the result type's known minimum vector length.");
7392
7393 // The only allowed 'mixed' case is extracting a fixed vector from a
7394 // scalable vector.
7395 if (ResultEC.isScalable()) {
7396 Check(VecEC.isScalable(), "cannot vector_extract a scalable vector from "
7397 "a fixed vector.");
7398 }
7399
7400 // If this extraction is not the 'mixed' case where a fixed vector is
7401 // extracted from a scalable vector, ensure that the extraction does not
7402 // overrun the parent vector.
7403 if (VecEC.isScalable() == ResultEC.isScalable()) {
7404 Check(IdxN < VecEC.getKnownMinValue() &&
7405 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(),
7406 "vector_extract would overrun.");
7407 }
7408 break;
7409 }
7410 case Intrinsic::vector_partial_reduce_fadd:
7411 case Intrinsic::vector_partial_reduce_add: {
7414
7415 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
7416 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
7417
7418 Check((VecWidth % AccWidth) == 0,
7419 "Invalid vector widths for partial "
7420 "reduction. The width of the input vector "
7421 "must be a positive integer multiple of "
7422 "the width of the accumulator vector.");
7423
7424 Check(AccTy->getElementType() == VecTy->getElementType(),
7425 "The element type of the input vector must match the element type "
7426 "of the accumulator vector.",
7427 &Call);
7428 break;
7429 }
7430 case Intrinsic::experimental_noalias_scope_decl: {
7431 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call));
7432 break;
7433 }
7434 case Intrinsic::preserve_array_access_index:
7435 case Intrinsic::preserve_struct_access_index:
7436 case Intrinsic::aarch64_ldaxr:
7437 case Intrinsic::aarch64_ldxr:
7438 case Intrinsic::arm_ldaex:
7439 case Intrinsic::arm_ldrex: {
7440 Type *ElemTy = Call.getParamElementType(0);
7441 Check(ElemTy, "Intrinsic requires elementtype attribute on first argument.",
7442 &Call);
7443 break;
7444 }
7445 case Intrinsic::aarch64_stlxr:
7446 case Intrinsic::aarch64_stxr:
7447 case Intrinsic::arm_stlex:
7448 case Intrinsic::arm_strex: {
7449 Type *ElemTy = Call.getAttributes().getParamElementType(1);
7450 Check(ElemTy,
7451 "Intrinsic requires elementtype attribute on second argument.",
7452 &Call);
7453 break;
7454 }
7455 case Intrinsic::aarch64_prefetch: {
7456 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
7457 "write argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7458 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4,
7459 "target argument to llvm.aarch64.prefetch must be 0-3", Call);
7460 Check(cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue() < 2,
7461 "stream argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7462 Check(cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue() < 2,
7463 "isdata argument to llvm.aarch64.prefetch must be 0 or 1", Call);
7464 break;
7465 }
7466 case Intrinsic::aarch64_range_prefetch: {
7467 Check(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2,
7468 "write argument to llvm.aarch64.range.prefetch must be 0 or 1", Call);
7469 Check(cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 2,
7470 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7471 Call);
7472 break;
7473 }
7474 case Intrinsic::riscv_vsetvli:
7475 case Intrinsic::riscv_vsetvlimax: {
7476 // The result models VLMAX (or a VL bounded by it) and is only defined for
7477 // XLen (i32/i64). Narrower types cannot represent the architectural VLMAX
7478 // range of [1, 65536], which value analyses rely on.
7480 "llvm.riscv.vsetvli/vsetvlimax result must be i32 or i64", &Call);
7481
7482 // VSEW and VLMUL select the vtype and must encode a valid SEW/LMUL pair.
7483 bool HasAVL = ID == Intrinsic::riscv_vsetvli;
7484 unsigned Offset = HasAVL ? 1 : 0;
7485 uint64_t VSEW =
7486 cast<ConstantInt>(Call.getArgOperand(Offset))->getZExtValue();
7487 uint64_t VLMUL =
7488 cast<ConstantInt>(Call.getArgOperand(Offset + 1))->getZExtValue();
7489 Check(VSEW <= 3, "llvm.riscv.vsetvli/vsetvlimax VSEW must be 0-3", &Call);
7490 Check(VLMUL <= 7 && VLMUL != RISCVVType::LMUL_RESERVED,
7491 "llvm.riscv.vsetvli/vsetvlimax VLMUL is reserved", &Call);
7492 break;
7493 }
7494 case Intrinsic::riscv_sati: {
7495 unsigned BitWidth = Call.getType()->getScalarSizeInBits();
7496 uint64_t Imm = cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue();
7497 Check(Imm >= 1 && Imm <= BitWidth,
7498 "llvm.riscv.sati immediate must be in the range [1, bitwidth]",
7499 &Call);
7500 break;
7501 }
7502 case Intrinsic::riscv_usati: {
7503 unsigned BitWidth = Call.getType()->getScalarSizeInBits();
7504 uint64_t Imm = cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue();
7505 Check(Imm < BitWidth,
7506 "llvm.riscv.usati immediate must be in the range [0, bitwidth-1]",
7507 &Call);
7508 break;
7509 }
7510 case Intrinsic::callbr_landingpad: {
7511 const auto *CBR = dyn_cast<CallBrInst>(Call.getOperand(0));
7512 Check(CBR, "intrinstic requires callbr operand", &Call);
7513 if (!CBR)
7514 break;
7515
7516 const BasicBlock *LandingPadBB = Call.getParent();
7517 const BasicBlock *PredBB = LandingPadBB->getUniquePredecessor();
7518 if (!PredBB) {
7519 CheckFailed("Intrinsic in block must have 1 unique predecessor", &Call);
7520 break;
7521 }
7522 if (!isa<CallBrInst>(PredBB->getTerminator())) {
7523 CheckFailed("Intrinsic must have corresponding callbr in predecessor",
7524 &Call);
7525 break;
7526 }
7527 Check(llvm::is_contained(CBR->getIndirectDests(), LandingPadBB),
7528 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7529 "block in indirect destination list",
7530 &Call);
7531 const Instruction &First = *LandingPadBB->begin();
7532 Check(&First == &Call, "No other instructions may proceed intrinsic",
7533 &Call);
7534 break;
7535 }
7536 case Intrinsic::structured_gep: {
7537 // Parser should refuse those 2 cases.
7538 assert(Call.arg_size() >= 1);
7540
7541 Check(Call.paramHasAttr(0, Attribute::ElementType),
7542 "Intrinsic first parameter is missing an ElementType attribute",
7543 &Call);
7544
7545 Type *T = Call.getParamAttr(0, Attribute::ElementType).getValueAsType();
7546 for (unsigned I = 1; I < Call.arg_size(); ++I) {
7548 auto *CI = dyn_cast<ConstantInt>(Index);
7549 Check(Index->getType()->isIntegerTy(),
7550 "Index operand type must be an integer", &Call);
7551
7552 if (auto *AT = dyn_cast<ArrayType>(T)) {
7553 T = AT->getElementType();
7554 } else if (auto *ST = dyn_cast<StructType>(T)) {
7555 Check(CI, "Indexing into a struct requires a constant int", &Call);
7556 Check(CI->getZExtValue() < ST->getNumElements(),
7557 "Indexing in a struct should be inbounds", &Call);
7558 T = ST->getElementType(CI->getZExtValue());
7559 } else if (auto *VT = dyn_cast<VectorType>(T)) {
7560 T = VT->getElementType();
7561 } else {
7562 CheckFailed("Reached a non-composite type with more indices to process",
7563 &Call);
7564 }
7565 }
7566 break;
7567 }
7568 case Intrinsic::structured_alloca:
7569 Check(Call.hasRetAttr(Attribute::ElementType),
7570 "@llvm.structured.alloca calls require elementtype attribute.",
7571 &Call);
7572 break;
7573 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7574 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7575 Value *V = Call.getArgOperand(0);
7576 unsigned RegCount = cast<ConstantInt>(V)->getZExtValue();
7577 Check(RegCount % 8 == 0,
7578 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7579 break;
7580 }
7581 case Intrinsic::nvvm_cp_async_bulk_global_to_shared_cta:
7582 case Intrinsic::nvvm_cp_async_bulk_global_to_shared_cta_relaxed: {
7583 const unsigned ArgSize = Call.arg_size();
7584 const unsigned FlagValidPatternIndex = ArgSize - 1;
7585 const unsigned IgnoreOOBFlagIndex = 8;
7586 bool IgnoreOOB =
7587 cast<ConstantInt>(Call.getArgOperand(IgnoreOOBFlagIndex))->isOne();
7588 const auto *FlagValidPattern =
7589 cast<ConstantInt>(Call.getArgOperand(FlagValidPatternIndex));
7590 Check(!IgnoreOOB || FlagValidPattern->isZero(),
7591 "flag_valid_pattern must be 0 (disabled) when ignore_oob is enabled",
7592 &Call);
7593 break;
7594 }
7595 case Intrinsic::experimental_convergence_entry:
7596 case Intrinsic::experimental_convergence_anchor:
7597 break;
7598 case Intrinsic::experimental_convergence_loop:
7599 break;
7600 case Intrinsic::ptrmask: {
7601 Type *Ty0 = Call.getArgOperand(0)->getType();
7602 Type *Ty1 = Call.getArgOperand(1)->getType();
7604 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7605 "of pointers",
7606 &Call);
7607 Check(DL.getIndexTypeSizeInBits(Ty0) == Ty1->getScalarSizeInBits(),
7608 "llvm.ptrmask intrinsic second argument bitwidth must match "
7609 "pointer index type size of first argument",
7610 &Call);
7611 break;
7612 }
7613 case Intrinsic::thread_pointer: {
7615 DL.getDefaultGlobalsAddressSpace(),
7616 "llvm.thread.pointer intrinsic return type must be for the globals "
7617 "address space",
7618 &Call);
7619 break;
7620 }
7621 case Intrinsic::threadlocal_address: {
7622 const Value &Arg0 = *Call.getArgOperand(0);
7623 Check(isa<GlobalValue>(Arg0),
7624 "llvm.threadlocal.address first argument must be a GlobalValue");
7625 Check(cast<GlobalValue>(Arg0).isThreadLocal(),
7626 "llvm.threadlocal.address operand isThreadLocal() must be true");
7627 break;
7628 }
7629 case Intrinsic::lifetime_start:
7630 case Intrinsic::lifetime_end: {
7631 Value *Ptr = Call.getArgOperand(0);
7632 auto *II = dyn_cast<IntrinsicInst>(Ptr);
7633 Check(isa<AllocaInst>(Ptr) || isa<PoisonValue>(Ptr) ||
7634 (II && II->getIntrinsicID() == Intrinsic::structured_alloca),
7635 "llvm.lifetime.start/end can only be used on alloca or poison",
7636 &Call);
7637 break;
7638 }
7639 case Intrinsic::sponentry: {
7640 const unsigned StackAS = DL.getAllocaAddrSpace();
7641 const Type *RetTy = Call.getFunctionType()->getReturnType();
7642 Check(RetTy->getPointerAddressSpace() == StackAS,
7643 "llvm.sponentry must return a pointer to the stack", &Call);
7644 break;
7645 }
7646 case Intrinsic::write_volatile_register: {
7647 auto *MD = cast<MDNode>(
7648 cast<MetadataAsValue>(Call.getArgOperand(0))->getMetadata());
7649 Check(MD->getNumOperands() == 1 && isa<MDString>(MD->getOperand(0)),
7650 "llvm.write_volatile_register metadata must be a single MDString",
7651 &Call);
7652 break;
7653 }
7654 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7655 // Verify that the auth key is IA (0) or IB (1), not DA (2) or DB (3)
7656 auto *AuthKey = cast<ConstantInt>(Call.getArgOperand(1));
7657 uint64_t Key = AuthKey->getZExtValue();
7658 Check(Key == 0 || Key == 1,
7659 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7660 &Call);
7661 break;
7662 }
7663 };
7664
7665 // Verify that there aren't any unmediated control transfers between funclets.
7667 Function *F = Call.getParent()->getParent();
7668 if (F->hasPersonalityFn() &&
7669 isScopedEHPersonality(classifyEHPersonality(F->getPersonalityFn()))) {
7670 // Run EH funclet coloring on-demand and cache results for other intrinsic
7671 // calls in this function
7672 if (BlockEHFuncletColors.empty())
7673 BlockEHFuncletColors = colorEHFunclets(*F);
7674
7675 // colorEHFunclets() leaves unreachable blocks colorless. Such a call
7676 // is in no funclet and WinEHPrepare will not see it, so there is
7677 // nothing to check.
7678 BasicBlock *CallBB = Call.getParent();
7679 auto ColorsIt = BlockEHFuncletColors.find(CallBB);
7680 if (ColorsIt != BlockEHFuncletColors.end()) {
7681 // Check for catch-/cleanup-pad in first funclet block
7682 bool InEHFunclet = false;
7683 const ColorVector &CV = ColorsIt->second;
7684 assert(CV.size() > 0 && "Uncolored block");
7685 for (BasicBlock *ColorFirstBB : CV)
7686 if (auto It = ColorFirstBB->getFirstNonPHIIt();
7687 It != ColorFirstBB->end())
7689 InEHFunclet = true;
7690
7691 // Check for funclet operand bundle
7692 bool HasToken = false;
7693 for (unsigned I = 0, E = Call.getNumOperandBundles(); I != E; ++I)
7695 HasToken = true;
7696
7697 // This would cause silent code truncation in WinEHPrepare
7698 if (InEHFunclet)
7699 Check(HasToken, "Missing funclet token on intrinsic call", &Call);
7700 }
7701 }
7702 }
7703
7704 // Target-specific intrinsic call checks.
7705 verifyAMDGPUIntrinsicCall(*this, ID, Call);
7706 verifyNVVMIntrinsicCall(*this, ID, Call);
7707}
7708
7709/// Carefully grab the subprogram from a local scope.
7710///
7711/// This carefully grabs the subprogram from a local scope, avoiding the
7712/// built-in assertions that would typically fire.
7713DISubprogram *Verifier::getSubprogram(Metadata *LocalScope) {
7714 if (hasDIScopeCycle(LocalScope))
7715 return nullptr;
7716
7717 if (!LocalScope)
7718 return nullptr;
7719
7720 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
7721 return SP;
7722
7723 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
7724 return getSubprogram(LB->getRawScope());
7725
7726 // Just return null; broken scope chains are checked elsewhere.
7727 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
7728 return nullptr;
7729}
7730
7731void Verifier::visit(DbgLabelRecord &DLR) {
7733 "invalid #dbg_label intrinsic variable", &DLR, DLR.getRawLabel());
7734
7735 // Ignore broken !dbg attachments; they're checked elsewhere.
7736 if (MDNode *N = DLR.getDebugLoc().getAsMDNode())
7737 if (!isa<DILocation>(N))
7738 return;
7739
7740 BasicBlock *BB = DLR.getParent();
7741 Function *F = BB ? BB->getParent() : nullptr;
7742
7743 // The scopes for variables and !dbg attachments must agree.
7744 DILabel *Label = DLR.getLabel();
7745 DILocation *Loc = DLR.getDebugLoc();
7746 CheckDI(Loc, "#dbg_label record requires a !dbg attachment", &DLR, BB, F);
7747
7748 DISubprogram *LabelSP = getSubprogram(Label->getRawScope());
7749 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7750 if (!LabelSP || !LocSP)
7751 return;
7752
7753 CheckDI(LabelSP == LocSP,
7754 "mismatched subprogram between #dbg_label label and !dbg attachment",
7755 &DLR, BB, F, Label, Label->getScope()->getSubprogram(), Loc,
7756 Loc->getScope()->getSubprogram());
7757}
7758
7759void Verifier::visit(DbgVariableRecord &DVR) {
7760 BasicBlock *BB = DVR.getParent();
7761 Function *F = BB->getParent();
7762
7763 CheckDI(DVR.getType() == DbgVariableRecord::LocationType::Value ||
7764 DVR.getType() == DbgVariableRecord::LocationType::Declare ||
7765 DVR.getType() == DbgVariableRecord::LocationType::DeclareValue ||
7766 DVR.getType() == DbgVariableRecord::LocationType::Assign,
7767 "invalid #dbg record type", &DVR, DVR.getType(), BB, F);
7768
7769 // The location for a DbgVariableRecord must be either a ValueAsMetadata,
7770 // DIArgList, or an empty MDNode (which is a legacy representation for an
7771 // "undef" location).
7772 auto *MD = DVR.getRawLocation();
7773 CheckDI(MD && (isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) ||
7774 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands())),
7775 "invalid #dbg record address/value", &DVR, MD, BB, F);
7776 CheckDI(DVR.isDbgAssign() || !isa<DIAssignID>(MD),
7777 "!DIAssignID should only be used by Assign DVRs.", MD, &DVR);
7778 if (auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
7779 visitValueAsMetadata(*VAM, F);
7780 if (DVR.isDbgDeclare()) {
7781 // Allow integers here to support inttoptr salvage.
7782 Type *Ty = VAM->getValue()->getType();
7783 CheckDI(Ty->isPointerTy() || Ty->isIntegerTy(),
7784 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7785 F);
7786 }
7787 } else if (auto *AL = dyn_cast<DIArgList>(MD)) {
7788 visitDIArgList(*AL, F);
7789 }
7790
7792 "invalid #dbg record variable", &DVR, DVR.getRawVariable(), BB, F);
7793 visitMDNode(*DVR.getRawVariable(), AreDebugLocsAllowed::No);
7794
7796 "invalid #dbg record expression", &DVR, DVR.getRawExpression(), BB,
7797 F);
7798 visitMDNode(*DVR.getExpression(), AreDebugLocsAllowed::No);
7799
7800 const DIExpression *Expr = DVR.getExpression();
7801 if (Expr->isValid() && !DVR.isKillLocation() &&
7802 (isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD))) {
7803 unsigned NumLocationOps = DVR.getNumVariableLocationOps();
7804 for (DIExpression::ExprOperand Op : Expr->expr_ops()) {
7805 if (Op.getOp() != dwarf::DW_OP_LLVM_arg)
7806 continue;
7807 CheckDI(Op.getArg(0) < NumLocationOps,
7808 "#dbg record expression references nonexistent location operand",
7809 &DVR, Expr, BB, F);
7810 }
7811 }
7812
7813 if (DVR.isDbgAssign()) {
7815 "invalid #dbg_assign DIAssignID", &DVR, DVR.getRawAssignID(), BB,
7816 F);
7817 visitMDNode(*cast<DIAssignID>(DVR.getRawAssignID()),
7818 AreDebugLocsAllowed::No);
7819
7820 const auto *RawAddr = DVR.getRawAddress();
7821 // Similarly to the location above, the address for an assign
7822 // DbgVariableRecord must be a ValueAsMetadata or an empty MDNode, which
7823 // represents an undef address.
7824 CheckDI(
7825 isa<ValueAsMetadata>(RawAddr) ||
7826 (isa<MDNode>(RawAddr) && !cast<MDNode>(RawAddr)->getNumOperands()),
7827 "invalid #dbg_assign address", &DVR, DVR.getRawAddress(), BB, F);
7828 if (auto *VAM = dyn_cast<ValueAsMetadata>(RawAddr))
7829 visitValueAsMetadata(*VAM, F);
7830
7832 "invalid #dbg_assign address expression", &DVR,
7833 DVR.getRawAddressExpression(), BB, F);
7834 visitMDNode(*DVR.getAddressExpression(), AreDebugLocsAllowed::No);
7835
7836 // All of the linked instructions should be in the same function as DVR.
7837 for (Instruction *I : at::getAssignmentInsts(&DVR))
7838 CheckDI(DVR.getFunction() == I->getFunction(),
7839 "inst not in same function as #dbg_assign", I, &DVR, BB, F);
7840 }
7841
7842 // This check is redundant with one in visitLocalVariable().
7843 DILocalVariable *Var = DVR.getVariable();
7844 CheckDI(isType(Var->getRawType()), "invalid type ref", Var, Var->getRawType(),
7845 BB, F);
7846
7847 auto *DLNode = DVR.getDebugLoc().getAsMDNode();
7848 CheckDI(isa_and_nonnull<DILocation>(DLNode), "invalid #dbg record DILocation",
7849 &DVR, DLNode, BB, F);
7850 DILocation *Loc = DVR.getDebugLoc();
7851
7852 // The scopes for variables and !dbg attachments must agree.
7853 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
7854 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
7855 if (!VarSP || !LocSP)
7856 return; // Broken scope chains are checked elsewhere.
7857
7858 CheckDI(VarSP == LocSP,
7859 "mismatched subprogram between #dbg record variable and DILocation",
7860 &DVR, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
7861 Loc->getScope()->getSubprogram(), BB, F);
7862
7863 verifyFnArgs(DVR);
7864}
7865
7866void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7867 switch (VPI.getIntrinsicID()) {
7868 case Intrinsic::experimental_vp_splice: {
7869 VectorType *VecTy = cast<VectorType>(VPI.getType());
7870 int64_t Idx = cast<ConstantInt>(VPI.getArgOperand(2))->getSExtValue();
7871 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7872 if (VPI.getParent() && VPI.getParent()->getParent()) {
7873 AttributeList Attrs = VPI.getParent()->getParent()->getAttributes();
7874 if (Attrs.hasFnAttr(Attribute::VScaleRange))
7875 KnownMinNumElements *= Attrs.getFnAttrs().getVScaleRangeMin();
7876 }
7877 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7878 (Idx >= 0 && Idx < KnownMinNumElements),
7879 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7880 "known minimum number of elements in the vector. For scalable "
7881 "vectors the minimum number of elements is determined from "
7882 "vscale_range.",
7883 &VPI);
7884 break;
7885 }
7886 }
7887}
7888
7889void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7890 switch (FPI.getIntrinsicID()) {
7891 case Intrinsic::experimental_constrained_fcmp:
7892 case Intrinsic::experimental_constrained_fcmps: {
7893 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate();
7895 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7896 break;
7897 }
7898
7899 case Intrinsic::experimental_constrained_fptrunc:
7900 case Intrinsic::experimental_constrained_fpext: {
7901 Type *OperandTy = FPI.getArgOperand(0)->getType();
7902 Type *ResultTy = FPI.getType();
7903 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7904 Check(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(),
7905 "Intrinsic first argument's type must be larger than result type",
7906 &FPI);
7907 } else {
7908 Check(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(),
7909 "Intrinsic first argument's type must be smaller than result type",
7910 &FPI);
7911 }
7912 break;
7913 }
7914
7915 default:
7916 break;
7917 }
7918
7919 // If a non-metadata argument is passed in a metadata slot then the
7920 // error will be caught earlier when the incorrect argument doesn't
7921 // match the specification in the intrinsic call table. Thus, no
7922 // argument type check is needed here.
7923
7924 Check(FPI.getExceptionBehavior().has_value(),
7925 "invalid exception behavior argument", &FPI);
7927 Check(FPI.getRoundingMode().has_value(), "invalid rounding mode argument",
7928 &FPI);
7929 }
7930}
7931
7932void Verifier::verifyFragmentExpression(const DbgVariableRecord &DVR) {
7933 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(DVR.getRawVariable());
7934 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
7935
7936 // We don't know whether this intrinsic verified correctly.
7937 if (!V || !E || !E->isValid())
7938 return;
7939
7940 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
7941 auto Fragment = E->getFragmentInfo();
7942 if (!Fragment)
7943 return;
7944
7945 // The frontend helps out GDB by emitting the members of local anonymous
7946 // unions as artificial local variables with shared storage. When SROA splits
7947 // the storage for artificial local variables that are smaller than the entire
7948 // union, the overhang piece will be outside of the allotted space for the
7949 // variable and this check fails.
7950 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
7951 if (V->isArtificial())
7952 return;
7953
7954 verifyFragmentExpression(*V, *Fragment, &DVR);
7955}
7956
7957template <typename ValueOrMetadata>
7958void Verifier::verifyFragmentExpression(const DIVariable &V,
7960 ValueOrMetadata *Desc) {
7961 // If there's no size, the type is broken, but that should be checked
7962 // elsewhere.
7963 auto VarSize = V.getSizeInBits();
7964 if (!VarSize)
7965 return;
7966
7967 unsigned FragSize = Fragment.SizeInBits;
7968 unsigned FragOffset = Fragment.OffsetInBits;
7969 CheckDI(FragSize + FragOffset <= *VarSize,
7970 "fragment is larger than or outside of variable", Desc, &V);
7971 CheckDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V);
7972}
7973
7974void Verifier::verifyFnArgs(const DbgVariableRecord &DVR) {
7975 // This function does not take the scope of noninlined function arguments into
7976 // account. Don't run it if current function is nodebug, because it may
7977 // contain inlined debug intrinsics.
7978 if (!HasDebugInfo)
7979 return;
7980
7981 // For performance reasons only check non-inlined ones.
7982 if (DVR.getDebugLoc()->getInlinedAt())
7983 return;
7984
7985 DILocalVariable *Var = DVR.getVariable();
7986 CheckDI(Var, "#dbg record without variable");
7987
7988 unsigned ArgNo = Var->getArg();
7989 if (!ArgNo)
7990 return;
7991
7992 // Verify there are no duplicate function argument debug info entries.
7993 // These will cause hard-to-debug assertions in the DWARF backend.
7994 if (DebugFnArgs.size() < ArgNo)
7995 DebugFnArgs.resize(ArgNo, nullptr);
7996
7997 auto *Prev = DebugFnArgs[ArgNo - 1];
7998 DebugFnArgs[ArgNo - 1] = Var;
7999 CheckDI(!Prev || (Prev == Var), "conflicting debug info for argument", &DVR,
8000 Prev, Var);
8001}
8002
8003void Verifier::verifyNotEntryValue(const DbgVariableRecord &DVR) {
8004 DIExpression *E = dyn_cast_or_null<DIExpression>(DVR.getRawExpression());
8005
8006 // We don't know whether this intrinsic verified correctly.
8007 if (!E || !E->isValid())
8008 return;
8009
8011 Value *VarValue = DVR.getVariableLocationOp(0);
8012 if (isa<UndefValue>(VarValue) || isa<PoisonValue>(VarValue))
8013 return;
8014 // We allow EntryValues for swift async arguments, as they have an
8015 // ABI-guarantee to be turned into a specific register.
8016 if (auto *ArgLoc = dyn_cast_or_null<Argument>(VarValue);
8017 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
8018 return;
8019 }
8020
8021 CheckDI(!E->isEntryValue(),
8022 "Entry values are only allowed in MIR unless they target a "
8023 "swiftasync Argument",
8024 &DVR);
8025}
8026
8027void Verifier::verifyCompileUnits() {
8028 // When more than one Module is imported into the same context, such as during
8029 // an LTO build before linking the modules, ODR type uniquing may cause types
8030 // to point to a different CU. This check does not make sense in this case.
8031 if (M.getContext().isODRUniquingDebugTypes())
8032 return;
8033 auto *CUs = M.getNamedMetadata("llvm.dbg.cu");
8034 SmallPtrSet<const Metadata *, 2> Listed;
8035 if (CUs)
8036 Listed.insert_range(CUs->operands());
8037 for (const auto *CU : CUVisited)
8038 CheckDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU);
8039 CUVisited.clear();
8040}
8041
8042void Verifier::verifyDeoptimizeCallingConvs() {
8043 if (DeoptimizeDeclarations.empty())
8044 return;
8045
8046 const Function *First = DeoptimizeDeclarations[0];
8047 for (const auto *F : ArrayRef(DeoptimizeDeclarations).slice(1)) {
8048 Check(First->getCallingConv() == F->getCallingConv(),
8049 "All llvm.experimental.deoptimize declarations must have the same "
8050 "calling convention",
8051 First, F);
8052 }
8053}
8054
8055void Verifier::verifyAttachedCallBundle(const CallBase &Call,
8056 const OperandBundleUse &BU) {
8057 FunctionType *FTy = Call.getFunctionType();
8058
8059 Check((FTy->getReturnType()->isPointerTy() ||
8060 (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())),
8061 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
8062 "function returning a pointer or a non-returning function that has a "
8063 "void return type",
8064 Call);
8065
8066 Check(BU.Inputs.size() == 1 && isa<Function>(BU.Inputs.front()),
8067 "operand bundle \"clang.arc.attachedcall\" requires one function as "
8068 "an argument",
8069 Call);
8070
8071 auto *Fn = cast<Function>(BU.Inputs.front());
8072 Intrinsic::ID IID = Fn->getIntrinsicID();
8073
8074 if (IID) {
8075 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
8076 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
8077 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
8078 "invalid function argument", Call);
8079 } else {
8080 StringRef FnName = Fn->getName();
8081 Check((FnName == "objc_retainAutoreleasedReturnValue" ||
8082 FnName == "objc_claimAutoreleasedReturnValue" ||
8083 FnName == "objc_unsafeClaimAutoreleasedReturnValue"),
8084 "invalid function argument", Call);
8085 }
8086}
8087
8088void Verifier::verifyNoAliasScopeDecl() {
8089 if (NoAliasScopeDecls.empty())
8090 return;
8091
8092 // only a single scope must be declared at a time.
8093 for (auto *II : NoAliasScopeDecls) {
8094 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
8095 "Not a llvm.experimental.noalias.scope.decl ?");
8096 const auto *ScopeListMV = dyn_cast<MetadataAsValue>(
8098 Check(ScopeListMV != nullptr,
8099 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
8100 "argument",
8101 II);
8102
8103 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata());
8104 Check(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", II);
8105 Check(ScopeListMD->getNumOperands() == 1,
8106 "!id.scope.list must point to a list with a single scope", II);
8107 visitAliasScopeListMetadata(ScopeListMD);
8108 }
8109
8110 // Only check the domination rule when requested. Once all passes have been
8111 // adapted this option can go away.
8112 if (!getIROptions(M.getContext()).verify_noalias_scope_decl_dom)
8113 return;
8114
8115 // Now sort the intrinsics based on the scope MDNode so that declarations of
8116 // the same scopes are next to each other.
8117 auto GetScope = [](IntrinsicInst *II) {
8118 const auto *ScopeListMV = cast<MetadataAsValue>(
8120 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
8121 };
8122
8123 // We are sorting on MDNode pointers here. For valid input IR this is ok.
8124 // TODO: Sort on Metadata ID to avoid non-deterministic error messages.
8125 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
8126 return GetScope(Lhs) < GetScope(Rhs);
8127 };
8128
8129 llvm::sort(NoAliasScopeDecls, Compare);
8130
8131 // Go over the intrinsics and check that for the same scope, they are not
8132 // dominating each other.
8133 auto ItCurrent = NoAliasScopeDecls.begin();
8134 while (ItCurrent != NoAliasScopeDecls.end()) {
8135 auto CurScope = GetScope(*ItCurrent);
8136 auto ItNext = ItCurrent;
8137 do {
8138 ++ItNext;
8139 } while (ItNext != NoAliasScopeDecls.end() &&
8140 GetScope(*ItNext) == CurScope);
8141
8142 // [ItCurrent, ItNext) represents the declarations for the same scope.
8143 // Ensure they are not dominating each other.. but only if it is not too
8144 // expensive.
8145 if (ItNext - ItCurrent < 32)
8146 for (auto *I : llvm::make_range(ItCurrent, ItNext))
8147 for (auto *J : llvm::make_range(ItCurrent, ItNext))
8148 if (I != J)
8149 Check(!DT.dominates(I, J),
8150 "llvm.experimental.noalias.scope.decl dominates another one "
8151 "with the same scope",
8152 I);
8153 ItCurrent = ItNext;
8154 }
8155}
8156
8157//===----------------------------------------------------------------------===//
8158// Implement the public interfaces to this file...
8159//===----------------------------------------------------------------------===//
8160
8162 Function &F = const_cast<Function &>(f);
8163
8164 // Don't use a raw_null_ostream. Printing IR is expensive.
8165 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent());
8166
8167 // Note that this function's return value is inverted from what you would
8168 // expect of a function called "verify".
8169 return !V.verify(F);
8170}
8171
8173 bool *BrokenDebugInfo) {
8174 // Don't use a raw_null_ostream. Printing IR is expensive.
8175 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M);
8176
8177 bool Broken = false;
8178 for (const Function &F : M)
8179 Broken |= !V.verify(F);
8180
8181 Broken |= !V.verify();
8182 if (BrokenDebugInfo)
8183 *BrokenDebugInfo = V.hasBrokenDebugInfo();
8184 // Note that this function's return value is inverted from what you would
8185 // expect of a function called "verify".
8186 return Broken;
8187}
8188
8189namespace {
8190
8191struct VerifierLegacyPass : public FunctionPass {
8192 static char ID;
8193
8194 std::unique_ptr<Verifier> V;
8195 bool FatalErrors = true;
8196
8197 VerifierLegacyPass() : FunctionPass(ID) {}
8198 explicit VerifierLegacyPass(bool FatalErrors)
8199 : FunctionPass(ID), FatalErrors(FatalErrors) {}
8200
8201 bool doInitialization(Module &M) override {
8202 V = std::make_unique<Verifier>(
8203 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M);
8204 return false;
8205 }
8206
8207 bool runOnFunction(Function &F) override {
8208 if (!V->verify(F) && FatalErrors) {
8209 errs() << "in function " << F.getName() << '\n';
8210 report_fatal_error("Broken function found, compilation aborted!");
8211 }
8212 return false;
8213 }
8214
8215 bool doFinalization(Module &M) override {
8216 bool HasErrors = false;
8217 for (Function &F : M)
8218 if (F.isDeclaration())
8219 HasErrors |= !V->verify(F);
8220
8221 HasErrors |= !V->verify();
8222 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
8223 report_fatal_error("Broken module found, compilation aborted!");
8224 return false;
8225 }
8226
8227 void getAnalysisUsage(AnalysisUsage &AU) const override {
8228 AU.setPreservesAll();
8229 }
8230};
8231
8232} // end anonymous namespace
8233
8234/// Helper to issue failure from the TBAA verification
8235template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) {
8236 if (Diagnostic)
8237 return Diagnostic->CheckFailed(Args...);
8238}
8239
8240#define CheckTBAA(C, ...) \
8241 do { \
8242 if (!(C)) { \
8243 CheckFailed(__VA_ARGS__); \
8244 return false; \
8245 } \
8246 } while (false)
8247
8248/// Verify that \p BaseNode can be used as the "base type" in the struct-path
8249/// TBAA scheme. This means \p BaseNode is either a scalar node, or a
8250/// struct-type node describing an aggregate data structure (like a struct).
8251TBAAVerifier::TBAABaseNodeSummary
8252TBAAVerifier::verifyTBAABaseNode(const Instruction *I, const MDNode *BaseNode,
8253 bool IsNewFormat) {
8254 if (BaseNode->getNumOperands() < 2) {
8255 CheckFailed("Base nodes must have at least two operands", I, BaseNode);
8256 return {true, ~0u};
8257 }
8258
8259 auto Itr = TBAABaseNodes.find(BaseNode);
8260 if (Itr != TBAABaseNodes.end())
8261 return Itr->second;
8262
8263 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
8264 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
8265 (void)InsertResult;
8266 assert(InsertResult.second && "We just checked!");
8267 return Result;
8268}
8269
8270TBAAVerifier::TBAABaseNodeSummary
8271TBAAVerifier::verifyTBAABaseNodeImpl(const Instruction *I,
8272 const MDNode *BaseNode, bool IsNewFormat) {
8273 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u};
8274
8275 if (BaseNode->getNumOperands() == 2) {
8276 // Scalar nodes can only be accessed at offset 0.
8277 return isValidScalarTBAANode(BaseNode)
8278 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
8279 : InvalidNode;
8280 }
8281
8282 if (IsNewFormat) {
8283 if (BaseNode->getNumOperands() % 3 != 0) {
8284 CheckFailed("Access tag nodes must have the number of operands that is a "
8285 "multiple of 3!", BaseNode);
8286 return InvalidNode;
8287 }
8288 } else {
8289 if (BaseNode->getNumOperands() % 2 != 1) {
8290 CheckFailed("Struct tag nodes must have an odd number of operands!",
8291 BaseNode);
8292 return InvalidNode;
8293 }
8294 }
8295
8296 // Check the type size field.
8297 if (IsNewFormat) {
8298 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8299 BaseNode->getOperand(1));
8300 if (!TypeSizeNode) {
8301 CheckFailed("Type size nodes must be constants!", I, BaseNode);
8302 return InvalidNode;
8303 }
8304 }
8305
8306 // Check the type name field. In the new format it can be anything.
8307 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) {
8308 CheckFailed("Struct tag nodes have a string as their first operand",
8309 BaseNode);
8310 return InvalidNode;
8311 }
8312
8313 bool Failed = false;
8314
8315 std::optional<APInt> PrevOffset;
8316 unsigned BitWidth = ~0u;
8317
8318 // We've already checked that BaseNode is not a degenerate root node with one
8319 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
8320 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8321 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8322 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8323 Idx += NumOpsPerField) {
8324 const MDOperand &FieldTy = BaseNode->getOperand(Idx);
8325 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1);
8326 if (!isa<MDNode>(FieldTy)) {
8327 CheckFailed("Incorrect field entry in struct type node!", I, BaseNode);
8328 Failed = true;
8329 continue;
8330 }
8331
8332 auto *OffsetEntryCI =
8334 if (!OffsetEntryCI) {
8335 CheckFailed("Offset entries must be constants!", I, BaseNode);
8336 Failed = true;
8337 continue;
8338 }
8339
8340 if (BitWidth == ~0u)
8341 BitWidth = OffsetEntryCI->getBitWidth();
8342
8343 if (OffsetEntryCI->getBitWidth() != BitWidth) {
8344 CheckFailed(
8345 "Bitwidth between the offsets and struct type entries must match", I,
8346 BaseNode);
8347 Failed = true;
8348 continue;
8349 }
8350
8351 // NB! As far as I can tell, we generate a non-strictly increasing offset
8352 // sequence only from structs that have zero size bit fields. When
8353 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
8354 // pick the field lexically the latest in struct type metadata node. This
8355 // mirrors the actual behavior of the alias analysis implementation.
8356 bool IsAscending =
8357 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8358
8359 if (!IsAscending) {
8360 CheckFailed("Offsets must be increasing!", I, BaseNode);
8361 Failed = true;
8362 }
8363
8364 PrevOffset = OffsetEntryCI->getValue();
8365
8366 if (IsNewFormat) {
8367 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8368 BaseNode->getOperand(Idx + 2));
8369 if (!MemberSizeNode) {
8370 CheckFailed("Member size entries must be constants!", I, BaseNode);
8371 Failed = true;
8372 continue;
8373 }
8374 }
8375 }
8376
8377 return Failed ? InvalidNode
8378 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth);
8379}
8380
8381static bool IsRootTBAANode(const MDNode *MD) {
8382 return MD->getNumOperands() < 2;
8383}
8384
8385static bool IsScalarTBAANodeImpl(const MDNode *MD,
8387 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3)
8388 return false;
8389
8390 if (!isa<MDString>(MD->getOperand(0)))
8391 return false;
8392
8393 if (MD->getNumOperands() == 3) {
8395 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0))))
8396 return false;
8397 }
8398
8399 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8400 return Parent && Visited.insert(Parent).second &&
8401 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited));
8402}
8403
8404bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) {
8405 auto ResultIt = TBAAScalarNodes.find(MD);
8406 if (ResultIt != TBAAScalarNodes.end())
8407 return ResultIt->second;
8408
8409 SmallPtrSet<const MDNode *, 4> Visited;
8410 bool Result = IsScalarTBAANodeImpl(MD, Visited);
8411 auto InsertResult = TBAAScalarNodes.insert({MD, Result});
8412 (void)InsertResult;
8413 assert(InsertResult.second && "Just checked!");
8414
8415 return Result;
8416}
8417
8418/// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
8419/// Offset in place to be the offset within the field node returned.
8420///
8421/// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
8422MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(const Instruction *I,
8423 const MDNode *BaseNode,
8424 APInt &Offset,
8425 bool IsNewFormat) {
8426 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!");
8427
8428 // Scalar nodes have only one possible "field" -- their parent in the access
8429 // hierarchy. Offset must be zero at this point, but our caller is supposed
8430 // to check that.
8431 if (BaseNode->getNumOperands() == 2)
8432 return cast<MDNode>(BaseNode->getOperand(1));
8433
8434 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8435 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8436 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands();
8437 Idx += NumOpsPerField) {
8438 auto *OffsetEntryCI =
8439 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1));
8440 if (OffsetEntryCI->getValue().ugt(Offset)) {
8441 if (Idx == FirstFieldOpNo) {
8442 CheckFailed("Could not find TBAA parent in struct type node", I,
8443 BaseNode, &Offset);
8444 return nullptr;
8445 }
8446
8447 unsigned PrevIdx = Idx - NumOpsPerField;
8448 auto *PrevOffsetEntryCI =
8449 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1));
8450 Offset -= PrevOffsetEntryCI->getValue();
8451 return cast<MDNode>(BaseNode->getOperand(PrevIdx));
8452 }
8453 }
8454
8455 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField;
8456 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
8457 BaseNode->getOperand(LastIdx + 1));
8458 Offset -= LastOffsetEntryCI->getValue();
8459 return cast<MDNode>(BaseNode->getOperand(LastIdx));
8460}
8461
8463 if (!Type || Type->getNumOperands() < 3)
8464 return false;
8465
8466 // In the new format type nodes shall have a reference to the parent type as
8467 // its first operand.
8468 return isa_and_nonnull<MDNode>(Type->getOperand(0));
8469}
8470
8471/// Returns true if the parent chain of the TBAA type node \p MD is acyclic.
8472static bool hasAcyclicTBAAParentChain(const MDNode *MD) {
8474 for (const MDNode *N = MD; N;) {
8475 if (!Visited.insert(N).second)
8476 return false;
8478 N = cast<MDNode>(N->getOperand(0));
8479 } else {
8480 N = IsRootTBAANode(N) ? nullptr
8481 : dyn_cast_or_null<MDNode>(N->getOperand(1));
8482 }
8483 }
8484 return true;
8485}
8486
8488 CheckTBAA(MD->getNumOperands() > 0, "TBAA metadata cannot have 0 operands", I,
8489 MD);
8490
8491 if (I)
8495 "This instruction shall not have a TBAA access tag!", I);
8496
8497 bool IsStructPathTBAA =
8498 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
8499
8500 CheckTBAA(IsStructPathTBAA,
8501 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8502 I);
8503
8504 auto *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0));
8505 auto *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1));
8506
8507 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType);
8508
8509 if (IsNewFormat) {
8510 CheckTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5,
8511 "Access tag metadata must have either 4 or 5 operands", I, MD);
8512 } else {
8513 CheckTBAA(MD->getNumOperands() < 5,
8514 "Struct tag metadata must have either 3 or 4 operands", I, MD);
8515 }
8516
8517 // Check the access size field.
8518 if (IsNewFormat) {
8519 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
8520 MD->getOperand(3));
8521 CheckTBAA(AccessSizeNode, "Access size field must be a constant", I, MD);
8522 }
8523
8524 // Check the immutability flag.
8525 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8526 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) {
8527 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
8528 MD->getOperand(ImmutabilityFlagOpNo));
8529 CheckTBAA(IsImmutableCI,
8530 "Immutability tag on struct tag metadata must be a constant", I,
8531 MD);
8532 CheckTBAA(
8533 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8534 "Immutability part of the struct tag metadata must be either 0 or 1", I,
8535 MD);
8536 }
8537
8538 CheckTBAA(BaseNode && AccessType,
8539 "Malformed struct tag metadata: base and access-type "
8540 "should be non-null and point to Metadata nodes",
8541 I, MD, BaseNode, AccessType);
8542
8543 if (!IsNewFormat) {
8544 CheckTBAA(isValidScalarTBAANode(AccessType),
8545 "Access type node must be a valid scalar type", I, MD,
8546 AccessType);
8547 } else {
8549 "Cycle detected in access type parent chain", I, MD, AccessType);
8550 }
8551
8553 CheckTBAA(OffsetCI, "Offset must be constant integer", I, MD);
8554
8555 APInt Offset = OffsetCI->getValue();
8556 bool SeenAccessTypeInPath = false;
8557
8558 SmallPtrSet<MDNode *, 4> StructPath;
8559
8560 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode);
8561 BaseNode =
8562 getFieldNodeFromTBAABaseNode(I, BaseNode, Offset, IsNewFormat)) {
8563 if (!StructPath.insert(BaseNode).second) {
8564 CheckFailed("Cycle detected in struct path", I, MD);
8565 return false;
8566 }
8567
8568 bool Invalid;
8569 unsigned BaseNodeBitWidth;
8570 std::tie(Invalid, BaseNodeBitWidth) =
8571 verifyTBAABaseNode(I, BaseNode, IsNewFormat);
8572
8573 // If the base node is invalid in itself, then we've already printed all the
8574 // errors we wanted to print.
8575 if (Invalid)
8576 return false;
8577
8578 SeenAccessTypeInPath |= BaseNode == AccessType;
8579
8580 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8581 CheckTBAA(Offset == 0, "Offset not zero at the point of scalar access", I,
8582 MD, &Offset);
8583
8584 CheckTBAA(BaseNodeBitWidth == Offset.getBitWidth() ||
8585 (BaseNodeBitWidth == 0 && Offset == 0) ||
8586 (IsNewFormat && BaseNodeBitWidth == ~0u),
8587 "Access bit-width not the same as description bit-width", I, MD,
8588 BaseNodeBitWidth, Offset.getBitWidth());
8589
8590 if (IsNewFormat && SeenAccessTypeInPath)
8591 break;
8592 }
8593
8594 CheckTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", I,
8595 MD);
8596 return true;
8597}
8598
8600 const MDNode *MD) {
8601 // !tbaa.struct is a list of (offset, size, tag) triples with ascending
8602 // offsets. Offset and size must be constants; a tag must be null or a valid
8603 // access tag.
8604 CheckTBAA(MD->getNumOperands() % 3 == 0,
8605 "!tbaa.struct operands must come in groups of three", I, MD);
8606
8607 std::optional<APInt> PrevOffset;
8608 for (unsigned Idx = 0, E = MD->getNumOperands(); Idx != E; Idx += 3) {
8609 auto *OffsetCI =
8611 CheckTBAA(OffsetCI, "!tbaa.struct field offset must be a constant integer",
8612 I, MD);
8613 CheckTBAA(
8615 "!tbaa.struct field size must be a constant integer", I, MD);
8616 if (const Metadata *TagMD = MD->getOperand(Idx + 2)) {
8617 auto *Tag = dyn_cast<MDNode>(TagMD);
8618 CheckTBAA(Tag, "!tbaa.struct field tag must be null or an MDNode", I, MD);
8619 if (!visitTBAAMetadata(I, Tag))
8620 return false;
8621 }
8622
8623 const APInt &Offset = OffsetCI->getValue();
8624 if (PrevOffset) {
8625 unsigned Width =
8626 std::max(PrevOffset->getBitWidth(), Offset.getBitWidth());
8627 CheckTBAA(PrevOffset->zext(Width).ule(Offset.zext(Width)),
8628 "!tbaa.struct field offsets must be non-decreasing", I, MD);
8629 }
8630 PrevOffset = Offset;
8631 }
8632 return true;
8633}
8634
8635char VerifierLegacyPass::ID = 0;
8636INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
8637
8639 return new VerifierLegacyPass(FatalErrors);
8640}
8641
8642AnalysisKey VerifierAnalysis::Key;
8649
8654
8656 auto Res = AM.getResult<VerifierAnalysis>(M);
8657 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8658 report_fatal_error("Broken module found, compilation aborted!");
8659
8660 return PreservedAnalyses::all();
8661}
8662
8664 auto res = AM.getResult<VerifierAnalysis>(F);
8665 if (res.IRBroken && FatalErrors)
8666 report_fatal_error("Broken function found, compilation aborted!");
8667
8668 return PreservedAnalyses::all();
8669}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
Atomic ordering constants.
@ RetAttr
@ FnAttr
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericConvergenceVerifier template.
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This file contains the declarations of entities that describe floating point environment and related ...
#define Check(C,...)
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
uint64_t IntrinsicInst * II
ppc ctr loops verify
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
Definition Verifier.cpp:533
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
Definition Verifier.cpp:574
static const Metadata * getRawDIScopeParent(const Metadata *S)
Parent scope operand of S, or null if S has no parent (a DIFile, DICompileUnit, or non-scope).
Definition Verifier.cpp:988
static bool isDINode(const Metadata *MD)
static bool isSupportedCallBrIntrinsic(Intrinsic::ID ID)
static bool isScope(const Metadata *MD)
static bool hasAcyclicTBAAParentChain(const MDNode *MD)
Returns true if the parent chain of the TBAA type node MD is acyclic.
#define CheckTBAA(C,...)
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static bool isNewFormatTBAATypeNode(const MDNode *Type)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
Definition APFloat.cpp:6392
static LLVM_ABI unsigned getArbitraryFPFormatSizeInBits(StringRef Format)
Returns the size in bits of a valid arbitrary floating-point format string, or 0 if the string is not...
Definition APFloat.cpp:6375
bool isFiniteNonZero() const
Definition APFloat.h:1622
bool isNegative() const
Definition APFloat.h:1612
const fltSemantics & getSemantics() const
Definition APFloat.h:1620
Class for arbitrary precision integers.
Definition APInt.h:78
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition APInt.h:413
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition APInt.h:395
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition Attributes.h:532
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:107
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:126
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
Definition BasicBlock.h:463
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class represents a no-op cast from one type to another.
static LLVM_ABI const char * areInvalidOperands(const Type *Ty, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitextract operation, otherwise return nu...
static LLVM_ABI const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
auto operand_bundles() const
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
Definition InstrTypes.h:845
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
Conditional Branch instruction.
Value * getCondition() const
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1264
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
Definition Constants.h:1251
ConstantInt * getKey() const
The Key ID, an i32 constant.
Definition Constants.h:1254
Constant * getDeactivationSymbol() const
Definition Constants.h:1273
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1257
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
iterator_range< expr_op_iterator > expr_ops() const
DbgVariableFragmentInfo FragmentInfo
LLVM_ABI bool isValid() const
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static LLVM_ABI const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for types.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
LLVM_ABI BasicBlock * getParent()
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI bool isKillLocation() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
LLVM_ABI unsigned getNumVariableLocationOps() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition DebugLoc.cpp:81
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
This instruction extracts a single (scalar) element from a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
Definition Operator.h:302
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
unsigned getNumElements() const
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:899
const Function & getFunction() const
Definition Function.h:167
const std::string & getGC() const
Definition Function.cpp:821
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
const Constant * getAliasee() const
Definition GlobalAlias.h:87
LLVM_ABI const Function * getResolverFunction() const
Definition Globals.cpp:759
static bool isValidLinkage(LinkageTypes L)
Definition GlobalIFunc.h:86
const Constant * getResolver() const
Definition GlobalIFunc.h:73
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
bool hasComdat() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasExternalLinkage() const
bool isDSOLocal() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
bool hasComdat() const
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool mayHaveConstantUsers() const
Return true if a constant other than a GlobalValue may use this global, that is, if removeDeadConstan...
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
Definition InstVisitor.h:78
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
An instruction for reading from memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
bool isAtomic() const
Return true if this load has an atomic ordering.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool isElementwise() const
Return true if this is an elementwise atomic load.
Align getAlign() const
Return the alignment of the access that is being performed.
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
bool isTemporary() const
Definition Metadata.h:1271
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1449
bool isDistinct() const
Definition Metadata.h:1270
bool isResolved() const
Check if node is fully resolved.
Definition Metadata.h:1267
LLVMContext & getContext() const
Definition Metadata.h:1251
bool equalsStr(StringRef Str) const
Definition Metadata.h:930
Metadata * get() const
Definition Metadata.h:937
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
static LLVM_ABI bool isTagMD(const Metadata *MD)
Metadata * getMetadata() const
Definition Metadata.h:203
Root of the metadata hierarchy.
Definition Metadata.h:65
unsigned getMetadataID() const
Definition Metadata.h:105
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:377
LLVM_ABI StringRef getName() const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
op_range incoming_values()
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Return a value (possibly void), from a function.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
This class represents the LLVM 'select' instruction.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator insert(iterator I, T &&Elt)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:728
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:41
Multiway switch.
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
LLVM_ABI bool visitTBAAStructMetadata(const Instruction *I, const MDNode *MD)
unsigned size() const
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:225
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
Definition Type.cpp:1108
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:306
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Definition Type.cpp:143
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
Definition Type.h:243
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
LLVM_ABI unsigned getByteBitWidth() const
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI bool containsNonLocalTargetExtType() const
Return true if this type is or contains a target extension type that disallows being used as a local.
Definition Type.cpp:86
LLVM_ABI bool containsNonGlobalTargetExtType() const
Return true if this type is or contains a target extension type that disallows being used as a global...
Definition Type.cpp:76
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:228
This class represents a cast unsigned integer to floating point.
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
Value * getValue() const
Definition Metadata.h:511
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > materialized_users()
Definition Value.h:422
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:711
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:823
iterator_range< user_iterator > users()
Definition Value.h:428
bool materialized_use_empty() const
Definition Value.h:353
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
Type * getElementType() const
Check a module for errors, and report separate error states for IR and debug info errors.
Definition Verifier.h:110
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents zero extension of integer types.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ Entry
Definition COFF.h:862
std::optional< ABIType > parseABIType(StringRef S)
Parse the string spelling used by the "float-abi" IR module flag into an ABIType.
Definition CodeGen.h:167
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
static const int NoAliasScopeDeclScopeArg
Definition Intrinsics.h:44
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
LLVM_ABI bool isImmArgValueInRangeSet(ID IID, unsigned ArgIdx, const APInt &Value)
Returns true if Value satisfies the range constraints specified for argument ArgIdx of intrinsic IID.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Definition DwarfDebug.h:190
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr MCPhysReg SP
constexpr StringLiteral AbiPreserveAttrs[]
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
LLVM_ABI std::optional< VFInfo > tryDemangleForVFABI(StringRef MangledName, const FunctionType *FTy)
Function to construct a VFInfo out of a mangled names in the following format:
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
Definition DebugInfo.h:190
SmallVector< DbgVariableRecord * > getAssignmentMarkers(DIAssignID *ID)
Definition DebugInfo.h:202
@ DW_LLVM_LANG_DIALECT_max
Definition Dwarf.h:212
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
@ DW_MACINFO_undef
Definition Dwarf.h:921
@ DW_MACINFO_start_file
Definition Dwarf.h:922
@ DW_MACINFO_define
Definition Dwarf.h:920
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:721
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:695
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:708
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
std::optional< LongDoubleFormat > parseLongDoubleFormat(StringRef Name)
Parses an IR floating-point type name into a LongDoubleFormat, returning std::nullopt if it does not ...
Definition CodeGen.h:144
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
AllocFnKind
Definition Attributes.h:55
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
void verifyAMDGPUAlloca(VerifierSupport &VS, const AllocaInst &AI)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
Op::Description Desc
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
void verifyAMDGPUFunctionMetadata(VerifierSupport &VS, const Function &F)
std::optional< ExceptionHandling > parseExceptionModel(StringRef Name)
Parses the string spelling used by the "exception-model" IR module flag into an ExceptionHandling val...
Definition CodeGen.h:98
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
void verifyAMDGPUIntrinsicCall(VerifierSupport &VS, Intrinsic::ID ID, CallBase &Call)
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:373
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
constexpr BooleanLoopTags OldBooleanLoopTags[]
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI FunctionPass * createVerifierPass(bool FatalErrors=true)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
std::optional< ThreadModel > parseThreadModel(StringRef S)
Parse the string spelling used by the "thread-model" IR module flag into a ThreadModel.
Definition CodeGen.h:198
ArrayRef(const T &OneElt) -> ArrayRef< T >
const IROptions & getIROptions(const LLVMContext &C)
Definition IROptions.h:27
constexpr unsigned BitWidth
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:25
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::unique_ptr< GCStrategy > getGCStrategy(const StringRef Name)
Lookup the GCStrategy object associated with the given gc name.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
void verifyNVVMIntrinsicCall(VerifierSupport &VS, Intrinsic::ID ID, CallBase &Call)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
void verifyAMDGPUGlobalVariable(VerifierSupport &VS, const GlobalVariable &GV)
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
void verifyAMDGPUModuleFlag(VerifierSupport &VS, const MDString *ID, Module::ModFlagBehavior MFB, const MDNode *Op)
bool isAMDGPUCallBrIntrinsic(Intrinsic::ID ID)
constexpr bool isCallableCC(CallingConv::ID CC)
LLVM_ABI bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
StringLiteral Disable
StringLiteral Enable
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
ArrayRef< Use > Inputs