1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
13 // Note that this does not provide full `Java style' security and verifications,
14 // instead it just tries to ensure that code is well-formed.
16 // * Both of a binary operator's parameters are of the same type
17 // * Verify that the indices of mem access instructions match other operands
18 // * Verify that arithmetic and other things are only performed on first-class
19 // types. Verify that shifts & logicals only happen on integrals f.e.
20 // * All of the constants in a switch statement are of the correct type
21 // * The code is in valid SSA form
22 // * It should be illegal to put a label into any other type (like a structure)
23 // or to return one. [except constant arrays!]
24 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
25 // * PHI nodes must have an entry for each predecessor, with no extras.
26 // * PHI nodes must be the first thing in a basic block, all grouped together
27 // * PHI nodes must have at least one entry
28 // * All basic blocks should only end with terminator insts, not contain them
29 // * The entry node to a function must not have predecessors
30 // * All Instructions must be embedded into a basic block
31 // * Functions cannot take a void-typed parameter
32 // * Verify that a function's argument list agrees with it's declared type.
33 // * It is illegal to specify a name for a void value.
34 // * It is illegal to have a internal global value with no initializer
35 // * It is illegal to have a ret instruction that returns a value that does not
36 // agree with the function return value type.
37 // * Function call argument types match the function prototype
38 // * A landing pad is defined by a landingpad instruction, and can be jumped to
39 // only by the unwind edge of an invoke instruction.
40 // * A landingpad instruction must be the first non-PHI instruction in the
42 // * Landingpad instructions must be in a function with a personality function.
43 // * All other things that are tested by asserts spread about the code...
45 //===----------------------------------------------------------------------===//
47 #include "llvm/IR/Verifier.h"
48 #include "llvm/ADT/MapVector.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/ConstantRange.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugInfo.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Dominators.h"
63 #include "llvm/IR/InlineAsm.h"
64 #include "llvm/IR/InstIterator.h"
65 #include "llvm/IR/InstVisitor.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/IR/Metadata.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PassManager.h"
71 #include "llvm/IR/Statepoint.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/raw_ostream.h"
81 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
84 struct VerifierSupport {
88 /// \brief Track the brokenness of the module while recursively visiting.
91 explicit VerifierSupport(raw_ostream &OS)
92 : OS(OS), M(nullptr), Broken(false) {}
95 template <class NodeTy> void Write(const ilist_iterator<NodeTy> &I) {
99 void Write(const Module *M) {
102 OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
105 void Write(const Value *V) {
108 if (isa<Instruction>(V)) {
111 V->printAsOperand(OS, true, M);
115 void Write(ImmutableCallSite CS) {
116 Write(CS.getInstruction());
119 void Write(const Metadata *MD) {
126 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
130 void Write(const NamedMDNode *NMD) {
137 void Write(Type *T) {
143 void Write(const Comdat *C) {
149 template <typename T> void Write(ArrayRef<T> Vs) {
150 for (const T &V : Vs)
154 template <typename T1, typename... Ts>
155 void WriteTs(const T1 &V1, const Ts &... Vs) {
160 template <typename... Ts> void WriteTs() {}
163 /// \brief A check failed, so printout out the condition and the message.
165 /// This provides a nice place to put a breakpoint if you want to see why
166 /// something is not correct.
167 void CheckFailed(const Twine &Message) {
168 OS << Message << '\n';
172 /// \brief A check failed (with values to print).
174 /// This calls the Message-only version so that the above is easier to set a
176 template <typename T1, typename... Ts>
177 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
178 CheckFailed(Message);
183 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
184 friend class InstVisitor<Verifier>;
186 LLVMContext *Context;
189 /// \brief When verifying a basic block, keep track of all of the
190 /// instructions we have seen so far.
192 /// This allows us to do efficient dominance checks for the case when an
193 /// instruction has an operand that is an instruction in the same block.
194 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
196 /// \brief Keep track of the metadata nodes that have been checked already.
197 SmallPtrSet<const Metadata *, 32> MDNodes;
199 /// \brief Track unresolved string-based type references.
200 SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs;
202 /// \brief The result type for a landingpad.
203 Type *LandingPadResultTy;
205 /// \brief Whether we've seen a call to @llvm.localescape in this function
209 /// Stores the count of how many objects were passed to llvm.localescape for a
210 /// given function and the largest index passed to llvm.localrecover.
211 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
213 // Maps catchswitches and cleanuppads that unwind to siblings to the
214 // terminators that indicate the unwind, used to detect cycles therein.
215 MapVector<Instruction *, TerminatorInst *> SiblingFuncletInfo;
217 /// Cache of constants visited in search of ConstantExprs.
218 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
220 void checkAtomicMemAccessSize(const Module *M, Type *Ty,
221 const Instruction *I);
223 explicit Verifier(raw_ostream &OS)
224 : VerifierSupport(OS), Context(nullptr), LandingPadResultTy(nullptr),
225 SawFrameEscape(false) {}
227 bool verify(const Function &F) {
229 Context = &M->getContext();
231 // First ensure the function is well-enough formed to compute dominance
234 OS << "Function '" << F.getName()
235 << "' does not contain an entry block!\n";
238 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
239 if (I->empty() || !I->back().isTerminator()) {
240 OS << "Basic Block in function '" << F.getName()
241 << "' does not have terminator!\n";
242 I->printAsOperand(OS, true);
248 // Now directly compute a dominance tree. We don't rely on the pass
249 // manager to provide this as it isolates us from a potentially
250 // out-of-date dominator tree and makes it significantly more complex to
251 // run this code outside of a pass manager.
252 // FIXME: It's really gross that we have to cast away constness here.
253 DT.recalculate(const_cast<Function &>(F));
256 // FIXME: We strip const here because the inst visitor strips const.
257 visit(const_cast<Function &>(F));
258 verifySiblingFuncletUnwinds();
259 InstsInThisBlock.clear();
260 LandingPadResultTy = nullptr;
261 SawFrameEscape = false;
262 SiblingFuncletInfo.clear();
267 bool verify(const Module &M) {
269 Context = &M.getContext();
272 // Scan through, checking all of the external function's linkage now...
273 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
274 visitGlobalValue(*I);
276 // Check to make sure function prototypes are okay.
277 if (I->isDeclaration())
281 // Now that we've visited every function, verify that we never asked to
282 // recover a frame index that wasn't escaped.
283 verifyFrameRecoverIndices();
285 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
287 visitGlobalVariable(*I);
289 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
291 visitGlobalAlias(*I);
293 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
294 E = M.named_metadata_end();
296 visitNamedMDNode(*I);
298 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
299 visitComdat(SMEC.getValue());
302 visitModuleIdents(M);
304 // Verify type referneces last.
311 // Verification methods...
312 void visitGlobalValue(const GlobalValue &GV);
313 void visitGlobalVariable(const GlobalVariable &GV);
314 void visitGlobalAlias(const GlobalAlias &GA);
315 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
316 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
317 const GlobalAlias &A, const Constant &C);
318 void visitNamedMDNode(const NamedMDNode &NMD);
319 void visitMDNode(const MDNode &MD);
320 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
321 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
322 void visitComdat(const Comdat &C);
323 void visitModuleIdents(const Module &M);
324 void visitModuleFlags(const Module &M);
325 void visitModuleFlag(const MDNode *Op,
326 DenseMap<const MDString *, const MDNode *> &SeenIDs,
327 SmallVectorImpl<const MDNode *> &Requirements);
328 void visitFunction(const Function &F);
329 void visitBasicBlock(BasicBlock &BB);
330 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
331 void visitDereferenceableMetadata(Instruction& I, MDNode* MD);
333 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
334 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
335 #include "llvm/IR/Metadata.def"
336 void visitDIScope(const DIScope &N);
337 void visitDIVariable(const DIVariable &N);
338 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
339 void visitDITemplateParameter(const DITemplateParameter &N);
341 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
343 /// \brief Check for a valid string-based type reference.
345 /// Checks if \c MD is a string-based type reference. If it is, keeps track
346 /// of it (and its user, \c N) for error messages later.
347 bool isValidUUID(const MDNode &N, const Metadata *MD);
349 /// \brief Check for a valid type reference.
351 /// Checks for subclasses of \a DIType, or \a isValidUUID().
352 bool isTypeRef(const MDNode &N, const Metadata *MD);
354 /// \brief Check for a valid scope reference.
356 /// Checks for subclasses of \a DIScope, or \a isValidUUID().
357 bool isScopeRef(const MDNode &N, const Metadata *MD);
359 /// \brief Check for a valid debug info reference.
361 /// Checks for subclasses of \a DINode, or \a isValidUUID().
362 bool isDIRef(const MDNode &N, const Metadata *MD);
364 // InstVisitor overrides...
365 using InstVisitor<Verifier>::visit;
366 void visit(Instruction &I);
368 void visitTruncInst(TruncInst &I);
369 void visitZExtInst(ZExtInst &I);
370 void visitSExtInst(SExtInst &I);
371 void visitFPTruncInst(FPTruncInst &I);
372 void visitFPExtInst(FPExtInst &I);
373 void visitFPToUIInst(FPToUIInst &I);
374 void visitFPToSIInst(FPToSIInst &I);
375 void visitUIToFPInst(UIToFPInst &I);
376 void visitSIToFPInst(SIToFPInst &I);
377 void visitIntToPtrInst(IntToPtrInst &I);
378 void visitPtrToIntInst(PtrToIntInst &I);
379 void visitBitCastInst(BitCastInst &I);
380 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
381 void visitPHINode(PHINode &PN);
382 void visitBinaryOperator(BinaryOperator &B);
383 void visitICmpInst(ICmpInst &IC);
384 void visitFCmpInst(FCmpInst &FC);
385 void visitExtractElementInst(ExtractElementInst &EI);
386 void visitInsertElementInst(InsertElementInst &EI);
387 void visitShuffleVectorInst(ShuffleVectorInst &EI);
388 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
389 void visitCallInst(CallInst &CI);
390 void visitInvokeInst(InvokeInst &II);
391 void visitGetElementPtrInst(GetElementPtrInst &GEP);
392 void visitLoadInst(LoadInst &LI);
393 void visitStoreInst(StoreInst &SI);
394 void verifyDominatesUse(Instruction &I, unsigned i);
395 void visitInstruction(Instruction &I);
396 void visitTerminatorInst(TerminatorInst &I);
397 void visitBranchInst(BranchInst &BI);
398 void visitReturnInst(ReturnInst &RI);
399 void visitSwitchInst(SwitchInst &SI);
400 void visitIndirectBrInst(IndirectBrInst &BI);
401 void visitSelectInst(SelectInst &SI);
402 void visitUserOp1(Instruction &I);
403 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
404 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
405 template <class DbgIntrinsicTy>
406 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
407 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
408 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
409 void visitFenceInst(FenceInst &FI);
410 void visitAllocaInst(AllocaInst &AI);
411 void visitExtractValueInst(ExtractValueInst &EVI);
412 void visitInsertValueInst(InsertValueInst &IVI);
413 void visitEHPadPredecessors(Instruction &I);
414 void visitLandingPadInst(LandingPadInst &LPI);
415 void visitCatchPadInst(CatchPadInst &CPI);
416 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
417 void visitCleanupPadInst(CleanupPadInst &CPI);
418 void visitFuncletPadInst(FuncletPadInst &FPI);
419 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
420 void visitCleanupReturnInst(CleanupReturnInst &CRI);
422 void VerifyCallSite(CallSite CS);
423 void verifyMustTailCall(CallInst &CI);
424 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
425 unsigned ArgNo, std::string &Suffix);
426 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
427 SmallVectorImpl<Type *> &ArgTys);
428 bool VerifyIntrinsicIsVarArg(bool isVarArg,
429 ArrayRef<Intrinsic::IITDescriptor> &Infos);
430 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
431 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
433 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
434 bool isReturnValue, const Value *V);
435 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
437 void VerifyFunctionMetadata(
438 const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs);
440 void visitConstantExprsRecursively(const Constant *EntryC);
441 void visitConstantExpr(const ConstantExpr *CE);
442 void VerifyStatepoint(ImmutableCallSite CS);
443 void verifyFrameRecoverIndices();
444 void verifySiblingFuncletUnwinds();
446 // Module-level debug info verification...
447 void verifyTypeRefs();
448 template <class MapTy>
449 void verifyDIExpression(const DbgInfoIntrinsic &I, const MapTy &TypeRefs);
450 void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
452 } // End anonymous namespace
454 // Assert - We know that cond should be true, if not print an error message.
455 #define Assert(C, ...) \
456 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
458 void Verifier::visit(Instruction &I) {
459 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
460 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
461 InstVisitor<Verifier>::visit(I);
465 void Verifier::visitGlobalValue(const GlobalValue &GV) {
466 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
467 GV.hasExternalWeakLinkage(),
468 "Global is external, but doesn't have external or weak linkage!", &GV);
470 Assert(GV.getAlignment() <= Value::MaximumAlignment,
471 "huge alignment values are unsupported", &GV);
472 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
473 "Only global variables can have appending linkage!", &GV);
475 if (GV.hasAppendingLinkage()) {
476 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
477 Assert(GVar && GVar->getValueType()->isArrayTy(),
478 "Only global arrays can have appending linkage!", GVar);
481 if (GV.isDeclarationForLinker())
482 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
485 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
486 if (GV.hasInitializer()) {
487 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
488 "Global variable initializer type does not match global "
492 // If the global has common linkage, it must have a zero initializer and
493 // cannot be constant.
494 if (GV.hasCommonLinkage()) {
495 Assert(GV.getInitializer()->isNullValue(),
496 "'common' global must have a zero initializer!", &GV);
497 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
499 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
502 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
503 "invalid linkage type for global declaration", &GV);
506 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
507 GV.getName() == "llvm.global_dtors")) {
508 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
509 "invalid linkage for intrinsic global variable", &GV);
510 // Don't worry about emitting an error for it not being an array,
511 // visitGlobalValue will complain on appending non-array.
512 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
513 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
514 PointerType *FuncPtrTy =
515 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
516 // FIXME: Reject the 2-field form in LLVM 4.0.
518 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
519 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
520 STy->getTypeAtIndex(1) == FuncPtrTy,
521 "wrong type for intrinsic global variable", &GV);
522 if (STy->getNumElements() == 3) {
523 Type *ETy = STy->getTypeAtIndex(2);
524 Assert(ETy->isPointerTy() &&
525 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
526 "wrong type for intrinsic global variable", &GV);
531 if (GV.hasName() && (GV.getName() == "llvm.used" ||
532 GV.getName() == "llvm.compiler.used")) {
533 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
534 "invalid linkage for intrinsic global variable", &GV);
535 Type *GVType = GV.getValueType();
536 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
537 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
538 Assert(PTy, "wrong type for intrinsic global variable", &GV);
539 if (GV.hasInitializer()) {
540 const Constant *Init = GV.getInitializer();
541 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
542 Assert(InitArray, "wrong initalizer for intrinsic global variable",
544 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
545 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
546 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
548 "invalid llvm.used member", V);
549 Assert(V->hasName(), "members of llvm.used must be named", V);
555 Assert(!GV.hasDLLImportStorageClass() ||
556 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
557 GV.hasAvailableExternallyLinkage(),
558 "Global is marked as dllimport, but not external", &GV);
560 if (!GV.hasInitializer()) {
561 visitGlobalValue(GV);
565 // Walk any aggregate initializers looking for bitcasts between address spaces
566 visitConstantExprsRecursively(GV.getInitializer());
568 visitGlobalValue(GV);
571 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
572 SmallPtrSet<const GlobalAlias*, 4> Visited;
574 visitAliaseeSubExpr(Visited, GA, C);
577 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
578 const GlobalAlias &GA, const Constant &C) {
579 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
580 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
583 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
584 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
586 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
589 // Only continue verifying subexpressions of GlobalAliases.
590 // Do not recurse into global initializers.
595 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
596 visitConstantExprsRecursively(CE);
598 for (const Use &U : C.operands()) {
600 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
601 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
602 else if (const auto *C2 = dyn_cast<Constant>(V))
603 visitAliaseeSubExpr(Visited, GA, *C2);
607 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
608 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
609 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
610 "weak_odr, or external linkage!",
612 const Constant *Aliasee = GA.getAliasee();
613 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
614 Assert(GA.getType() == Aliasee->getType(),
615 "Alias and aliasee types should match!", &GA);
617 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
618 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
620 visitAliaseeSubExpr(GA, *Aliasee);
622 visitGlobalValue(GA);
625 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
626 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
627 MDNode *MD = NMD.getOperand(i);
629 if (NMD.getName() == "llvm.dbg.cu") {
630 Assert(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
640 void Verifier::visitMDNode(const MDNode &MD) {
641 // Only visit each node once. Metadata can be mutually recursive, so this
642 // avoids infinite recursion here, as well as being an optimization.
643 if (!MDNodes.insert(&MD).second)
646 switch (MD.getMetadataID()) {
648 llvm_unreachable("Invalid MDNode subclass");
649 case Metadata::MDTupleKind:
651 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
652 case Metadata::CLASS##Kind: \
653 visit##CLASS(cast<CLASS>(MD)); \
655 #include "llvm/IR/Metadata.def"
658 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
659 Metadata *Op = MD.getOperand(i);
662 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
664 if (auto *N = dyn_cast<MDNode>(Op)) {
668 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
669 visitValueAsMetadata(*V, nullptr);
674 // Check these last, so we diagnose problems in operands first.
675 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
676 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
679 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
680 Assert(MD.getValue(), "Expected valid value", &MD);
681 Assert(!MD.getValue()->getType()->isMetadataTy(),
682 "Unexpected metadata round-trip through values", &MD, MD.getValue());
684 auto *L = dyn_cast<LocalAsMetadata>(&MD);
688 Assert(F, "function-local metadata used outside a function", L);
690 // If this was an instruction, bb, or argument, verify that it is in the
691 // function that we expect.
692 Function *ActualF = nullptr;
693 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
694 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
695 ActualF = I->getParent()->getParent();
696 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
697 ActualF = BB->getParent();
698 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
699 ActualF = A->getParent();
700 assert(ActualF && "Unimplemented function local metadata case!");
702 Assert(ActualF == F, "function-local metadata used in wrong function", L);
705 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
706 Metadata *MD = MDV.getMetadata();
707 if (auto *N = dyn_cast<MDNode>(MD)) {
712 // Only visit each node once. Metadata can be mutually recursive, so this
713 // avoids infinite recursion here, as well as being an optimization.
714 if (!MDNodes.insert(MD).second)
717 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
718 visitValueAsMetadata(*V, F);
721 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
722 auto *S = dyn_cast<MDString>(MD);
725 if (S->getString().empty())
728 // Keep track of names of types referenced via UUID so we can check that they
730 UnresolvedTypeRefs.insert(std::make_pair(S, &N));
734 /// \brief Check if a value can be a reference to a type.
735 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
736 return !MD || isValidUUID(N, MD) || isa<DIType>(MD);
739 /// \brief Check if a value can be a ScopeRef.
740 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
741 return !MD || isValidUUID(N, MD) || isa<DIScope>(MD);
744 /// \brief Check if a value can be a debug info ref.
745 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
746 return !MD || isValidUUID(N, MD) || isa<DINode>(MD);
750 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
751 for (Metadata *MD : N.operands()) {
764 bool isValidMetadataArray(const MDTuple &N) {
765 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
769 bool isValidMetadataNullArray(const MDTuple &N) {
770 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
773 void Verifier::visitDILocation(const DILocation &N) {
774 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
775 "location requires a valid scope", &N, N.getRawScope());
776 if (auto *IA = N.getRawInlinedAt())
777 Assert(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
780 void Verifier::visitGenericDINode(const GenericDINode &N) {
781 Assert(N.getTag(), "invalid tag", &N);
784 void Verifier::visitDIScope(const DIScope &N) {
785 if (auto *F = N.getRawFile())
786 Assert(isa<DIFile>(F), "invalid file", &N, F);
789 void Verifier::visitDISubrange(const DISubrange &N) {
790 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
791 Assert(N.getCount() >= -1, "invalid subrange count", &N);
794 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
795 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
798 void Verifier::visitDIBasicType(const DIBasicType &N) {
799 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
800 N.getTag() == dwarf::DW_TAG_unspecified_type,
804 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
805 // Common scope checks.
808 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
809 N.getTag() == dwarf::DW_TAG_pointer_type ||
810 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
811 N.getTag() == dwarf::DW_TAG_reference_type ||
812 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
813 N.getTag() == dwarf::DW_TAG_const_type ||
814 N.getTag() == dwarf::DW_TAG_volatile_type ||
815 N.getTag() == dwarf::DW_TAG_restrict_type ||
816 N.getTag() == dwarf::DW_TAG_member ||
817 N.getTag() == dwarf::DW_TAG_inheritance ||
818 N.getTag() == dwarf::DW_TAG_friend,
820 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
821 Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
825 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
826 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
830 static bool hasConflictingReferenceFlags(unsigned Flags) {
831 return (Flags & DINode::FlagLValueReference) &&
832 (Flags & DINode::FlagRValueReference);
835 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
836 auto *Params = dyn_cast<MDTuple>(&RawParams);
837 Assert(Params, "invalid template params", &N, &RawParams);
838 for (Metadata *Op : Params->operands()) {
839 Assert(Op && isa<DITemplateParameter>(Op), "invalid template parameter", &N,
844 void Verifier::visitDICompositeType(const DICompositeType &N) {
845 // Common scope checks.
848 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
849 N.getTag() == dwarf::DW_TAG_structure_type ||
850 N.getTag() == dwarf::DW_TAG_union_type ||
851 N.getTag() == dwarf::DW_TAG_enumeration_type ||
852 N.getTag() == dwarf::DW_TAG_class_type,
855 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
856 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
859 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
860 "invalid composite elements", &N, N.getRawElements());
861 Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
862 N.getRawVTableHolder());
863 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
865 if (auto *Params = N.getRawTemplateParams())
866 visitTemplateParams(N, *Params);
868 if (N.getTag() == dwarf::DW_TAG_class_type ||
869 N.getTag() == dwarf::DW_TAG_union_type) {
870 Assert(N.getFile() && !N.getFile()->getFilename().empty(),
871 "class/union requires a filename", &N, N.getFile());
875 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
876 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
877 if (auto *Types = N.getRawTypeArray()) {
878 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
879 for (Metadata *Ty : N.getTypeArray()->operands()) {
880 Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
883 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
887 void Verifier::visitDIFile(const DIFile &N) {
888 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
891 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
892 Assert(N.isDistinct(), "compile units must be distinct", &N);
893 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
895 // Don't bother verifying the compilation directory or producer string
896 // as those could be empty.
897 Assert(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
899 Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
902 if (auto *Array = N.getRawEnumTypes()) {
903 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
904 for (Metadata *Op : N.getEnumTypes()->operands()) {
905 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
906 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
907 "invalid enum type", &N, N.getEnumTypes(), Op);
910 if (auto *Array = N.getRawRetainedTypes()) {
911 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
912 for (Metadata *Op : N.getRetainedTypes()->operands()) {
913 Assert(Op && isa<DIType>(Op), "invalid retained type", &N, Op);
916 if (auto *Array = N.getRawSubprograms()) {
917 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
918 for (Metadata *Op : N.getSubprograms()->operands()) {
919 Assert(Op && isa<DISubprogram>(Op), "invalid subprogram ref", &N, Op);
922 if (auto *Array = N.getRawGlobalVariables()) {
923 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
924 for (Metadata *Op : N.getGlobalVariables()->operands()) {
925 Assert(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", &N,
929 if (auto *Array = N.getRawImportedEntities()) {
930 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
931 for (Metadata *Op : N.getImportedEntities()->operands()) {
932 Assert(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", &N,
936 if (auto *Array = N.getRawMacros()) {
937 Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array);
938 for (Metadata *Op : N.getMacros()->operands()) {
939 Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
944 void Verifier::visitDISubprogram(const DISubprogram &N) {
945 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
946 Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
947 if (auto *T = N.getRawType())
948 Assert(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
949 Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
950 N.getRawContainingType());
951 if (auto *Params = N.getRawTemplateParams())
952 visitTemplateParams(N, *Params);
953 if (auto *S = N.getRawDeclaration()) {
954 Assert(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
955 "invalid subprogram declaration", &N, S);
957 if (auto *RawVars = N.getRawVariables()) {
958 auto *Vars = dyn_cast<MDTuple>(RawVars);
959 Assert(Vars, "invalid variable list", &N, RawVars);
960 for (Metadata *Op : Vars->operands()) {
961 Assert(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, Vars,
965 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
968 if (N.isDefinition())
969 Assert(N.isDistinct(), "subprogram definitions must be distinct", &N);
972 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
973 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
974 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
975 "invalid local scope", &N, N.getRawScope());
978 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
979 visitDILexicalBlockBase(N);
981 Assert(N.getLine() || !N.getColumn(),
982 "cannot have column info without line info", &N);
985 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
986 visitDILexicalBlockBase(N);
989 void Verifier::visitDINamespace(const DINamespace &N) {
990 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
991 if (auto *S = N.getRawScope())
992 Assert(isa<DIScope>(S), "invalid scope ref", &N, S);
995 void Verifier::visitDIMacro(const DIMacro &N) {
996 Assert(N.getMacinfoType() == dwarf::DW_MACINFO_define ||
997 N.getMacinfoType() == dwarf::DW_MACINFO_undef,
998 "invalid macinfo type", &N);
999 Assert(!N.getName().empty(), "anonymous macro", &N);
1000 if (!N.getValue().empty()) {
1001 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1005 void Verifier::visitDIMacroFile(const DIMacroFile &N) {
1006 Assert(N.getMacinfoType() == dwarf::DW_MACINFO_start_file,
1007 "invalid macinfo type", &N);
1008 if (auto *F = N.getRawFile())
1009 Assert(isa<DIFile>(F), "invalid file", &N, F);
1011 if (auto *Array = N.getRawElements()) {
1012 Assert(isa<MDTuple>(Array), "invalid macro list", &N, Array);
1013 for (Metadata *Op : N.getElements()->operands()) {
1014 Assert(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op);
1019 void Verifier::visitDIModule(const DIModule &N) {
1020 Assert(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
1021 Assert(!N.getName().empty(), "anonymous module", &N);
1024 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
1025 Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
1028 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
1029 visitDITemplateParameter(N);
1031 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1035 void Verifier::visitDITemplateValueParameter(
1036 const DITemplateValueParameter &N) {
1037 visitDITemplateParameter(N);
1039 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1040 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1041 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1045 void Verifier::visitDIVariable(const DIVariable &N) {
1046 if (auto *S = N.getRawScope())
1047 Assert(isa<DIScope>(S), "invalid scope", &N, S);
1048 Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1049 if (auto *F = N.getRawFile())
1050 Assert(isa<DIFile>(F), "invalid file", &N, F);
1053 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1054 // Checks common to all variables.
1057 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1058 Assert(!N.getName().empty(), "missing global variable name", &N);
1059 if (auto *V = N.getRawVariable()) {
1060 Assert(isa<ConstantAsMetadata>(V) &&
1061 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1062 "invalid global varaible ref", &N, V);
1064 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1065 Assert(isa<DIDerivedType>(Member), "invalid static data member declaration",
1070 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1071 // Checks common to all variables.
1074 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1075 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1076 "local variable requires a valid scope", &N, N.getRawScope());
1079 void Verifier::visitDIExpression(const DIExpression &N) {
1080 Assert(N.isValid(), "invalid expression", &N);
1083 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1084 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1085 if (auto *T = N.getRawType())
1086 Assert(isTypeRef(N, T), "invalid type ref", &N, T);
1087 if (auto *F = N.getRawFile())
1088 Assert(isa<DIFile>(F), "invalid file", &N, F);
1091 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1092 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1093 N.getTag() == dwarf::DW_TAG_imported_declaration,
1095 if (auto *S = N.getRawScope())
1096 Assert(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1097 Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1101 void Verifier::visitComdat(const Comdat &C) {
1102 // The Module is invalid if the GlobalValue has private linkage. Entities
1103 // with private linkage don't have entries in the symbol table.
1104 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1105 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1109 void Verifier::visitModuleIdents(const Module &M) {
1110 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1114 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1115 // Scan each llvm.ident entry and make sure that this requirement is met.
1116 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1117 const MDNode *N = Idents->getOperand(i);
1118 Assert(N->getNumOperands() == 1,
1119 "incorrect number of operands in llvm.ident metadata", N);
1120 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1121 ("invalid value for llvm.ident metadata entry operand"
1122 "(the operand should be a string)"),
1127 void Verifier::visitModuleFlags(const Module &M) {
1128 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1131 // Scan each flag, and track the flags and requirements.
1132 DenseMap<const MDString*, const MDNode*> SeenIDs;
1133 SmallVector<const MDNode*, 16> Requirements;
1134 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1135 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1138 // Validate that the requirements in the module are valid.
1139 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1140 const MDNode *Requirement = Requirements[I];
1141 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1142 const Metadata *ReqValue = Requirement->getOperand(1);
1144 const MDNode *Op = SeenIDs.lookup(Flag);
1146 CheckFailed("invalid requirement on flag, flag is not present in module",
1151 if (Op->getOperand(2) != ReqValue) {
1152 CheckFailed(("invalid requirement on flag, "
1153 "flag does not have the required value"),
1161 Verifier::visitModuleFlag(const MDNode *Op,
1162 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1163 SmallVectorImpl<const MDNode *> &Requirements) {
1164 // Each module flag should have three arguments, the merge behavior (a
1165 // constant int), the flag ID (an MDString), and the value.
1166 Assert(Op->getNumOperands() == 3,
1167 "incorrect number of operands in module flag", Op);
1168 Module::ModFlagBehavior MFB;
1169 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1171 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1172 "invalid behavior operand in module flag (expected constant integer)",
1175 "invalid behavior operand in module flag (unexpected constant)",
1178 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1179 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1182 // Sanity check the values for behaviors with additional requirements.
1185 case Module::Warning:
1186 case Module::Override:
1187 // These behavior types accept any value.
1190 case Module::Require: {
1191 // The value should itself be an MDNode with two operands, a flag ID (an
1192 // MDString), and a value.
1193 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1194 Assert(Value && Value->getNumOperands() == 2,
1195 "invalid value for 'require' module flag (expected metadata pair)",
1197 Assert(isa<MDString>(Value->getOperand(0)),
1198 ("invalid value for 'require' module flag "
1199 "(first value operand should be a string)"),
1200 Value->getOperand(0));
1202 // Append it to the list of requirements, to check once all module flags are
1204 Requirements.push_back(Value);
1208 case Module::Append:
1209 case Module::AppendUnique: {
1210 // These behavior types require the operand be an MDNode.
1211 Assert(isa<MDNode>(Op->getOperand(2)),
1212 "invalid value for 'append'-type module flag "
1213 "(expected a metadata node)",
1219 // Unless this is a "requires" flag, check the ID is unique.
1220 if (MFB != Module::Require) {
1221 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1223 "module flag identifiers must be unique (or of 'require' type)", ID);
1227 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1228 bool isFunction, const Value *V) {
1229 unsigned Slot = ~0U;
1230 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1231 if (Attrs.getSlotIndex(I) == Idx) {
1236 assert(Slot != ~0U && "Attribute set inconsistency!");
1238 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1240 if (I->isStringAttribute())
1243 if (I->getKindAsEnum() == Attribute::NoReturn ||
1244 I->getKindAsEnum() == Attribute::NoUnwind ||
1245 I->getKindAsEnum() == Attribute::NoInline ||
1246 I->getKindAsEnum() == Attribute::AlwaysInline ||
1247 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1248 I->getKindAsEnum() == Attribute::StackProtect ||
1249 I->getKindAsEnum() == Attribute::StackProtectReq ||
1250 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1251 I->getKindAsEnum() == Attribute::SafeStack ||
1252 I->getKindAsEnum() == Attribute::NoRedZone ||
1253 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1254 I->getKindAsEnum() == Attribute::Naked ||
1255 I->getKindAsEnum() == Attribute::InlineHint ||
1256 I->getKindAsEnum() == Attribute::StackAlignment ||
1257 I->getKindAsEnum() == Attribute::UWTable ||
1258 I->getKindAsEnum() == Attribute::NonLazyBind ||
1259 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1260 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1261 I->getKindAsEnum() == Attribute::SanitizeThread ||
1262 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1263 I->getKindAsEnum() == Attribute::MinSize ||
1264 I->getKindAsEnum() == Attribute::NoDuplicate ||
1265 I->getKindAsEnum() == Attribute::Builtin ||
1266 I->getKindAsEnum() == Attribute::NoBuiltin ||
1267 I->getKindAsEnum() == Attribute::Cold ||
1268 I->getKindAsEnum() == Attribute::OptimizeNone ||
1269 I->getKindAsEnum() == Attribute::JumpTable ||
1270 I->getKindAsEnum() == Attribute::Convergent ||
1271 I->getKindAsEnum() == Attribute::ArgMemOnly ||
1272 I->getKindAsEnum() == Attribute::NoRecurse ||
1273 I->getKindAsEnum() == Attribute::InaccessibleMemOnly ||
1274 I->getKindAsEnum() == Attribute::InaccessibleMemOrArgMemOnly) {
1276 CheckFailed("Attribute '" + I->getAsString() +
1277 "' only applies to functions!", V);
1280 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1281 I->getKindAsEnum() == Attribute::ReadNone) {
1283 CheckFailed("Attribute '" + I->getAsString() +
1284 "' does not apply to function returns");
1287 } else if (isFunction) {
1288 CheckFailed("Attribute '" + I->getAsString() +
1289 "' does not apply to functions!", V);
1295 // VerifyParameterAttrs - Check the given attributes for an argument or return
1296 // value of the specified type. The value V is printed in error messages.
1297 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1298 bool isReturnValue, const Value *V) {
1299 if (!Attrs.hasAttributes(Idx))
1302 VerifyAttributeTypes(Attrs, Idx, false, V);
1305 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1306 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1307 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1308 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1309 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1310 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1311 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1312 "'returned' do not apply to return values!",
1315 // Check for mutually incompatible attributes. Only inreg is compatible with
1317 unsigned AttrCount = 0;
1318 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1319 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1320 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1321 Attrs.hasAttribute(Idx, Attribute::InReg);
1322 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1323 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1324 "and 'sret' are incompatible!",
1327 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1328 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1330 "'inalloca and readonly' are incompatible!",
1333 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1334 Attrs.hasAttribute(Idx, Attribute::Returned)),
1336 "'sret and returned' are incompatible!",
1339 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1340 Attrs.hasAttribute(Idx, Attribute::SExt)),
1342 "'zeroext and signext' are incompatible!",
1345 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1346 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1348 "'readnone and readonly' are incompatible!",
1351 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1352 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1354 "'noinline and alwaysinline' are incompatible!",
1357 Assert(!AttrBuilder(Attrs, Idx)
1358 .overlaps(AttributeFuncs::typeIncompatible(Ty)),
1359 "Wrong types for attribute: " +
1360 AttributeSet::get(*Context, Idx,
1361 AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx),
1364 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1365 SmallPtrSet<Type*, 4> Visited;
1366 if (!PTy->getElementType()->isSized(&Visited)) {
1367 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1368 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1369 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1373 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1374 "Attribute 'byval' only applies to parameters with pointer type!",
1379 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1380 // The value V is printed in error messages.
1381 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1383 if (Attrs.isEmpty())
1386 bool SawNest = false;
1387 bool SawReturned = false;
1388 bool SawSRet = false;
1390 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1391 unsigned Idx = Attrs.getSlotIndex(i);
1395 Ty = FT->getReturnType();
1396 else if (Idx-1 < FT->getNumParams())
1397 Ty = FT->getParamType(Idx-1);
1399 break; // VarArgs attributes, verified elsewhere.
1401 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1406 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1407 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1411 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1412 Assert(!SawReturned, "More than one parameter has attribute returned!",
1414 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1416 "argument and return types for 'returned' attribute",
1421 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1422 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1423 Assert(Idx == 1 || Idx == 2,
1424 "Attribute 'sret' is not on first or second parameter!", V);
1428 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1429 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1434 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1437 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1440 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1441 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1442 "Attributes 'readnone and readonly' are incompatible!", V);
1445 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1446 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1447 Attribute::InaccessibleMemOrArgMemOnly)),
1448 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are incompatible!", V);
1451 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1452 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1453 Attribute::InaccessibleMemOnly)),
1454 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
1457 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1458 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1459 Attribute::AlwaysInline)),
1460 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1462 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1463 Attribute::OptimizeNone)) {
1464 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1465 "Attribute 'optnone' requires 'noinline'!", V);
1467 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1468 Attribute::OptimizeForSize),
1469 "Attributes 'optsize and optnone' are incompatible!", V);
1471 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1472 "Attributes 'minsize and optnone' are incompatible!", V);
1475 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1476 Attribute::JumpTable)) {
1477 const GlobalValue *GV = cast<GlobalValue>(V);
1478 Assert(GV->hasUnnamedAddr(),
1479 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1483 void Verifier::VerifyFunctionMetadata(
1484 const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs) {
1488 for (unsigned i = 0; i < MDs.size(); i++) {
1489 if (MDs[i].first == LLVMContext::MD_prof) {
1490 MDNode *MD = MDs[i].second;
1491 Assert(MD->getNumOperands() == 2,
1492 "!prof annotations should have exactly 2 operands", MD);
1494 // Check first operand.
1495 Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1497 Assert(isa<MDString>(MD->getOperand(0)),
1498 "expected string with name of the !prof annotation", MD);
1499 MDString *MDS = cast<MDString>(MD->getOperand(0));
1500 StringRef ProfName = MDS->getString();
1501 Assert(ProfName.equals("function_entry_count"),
1502 "first operand should be 'function_entry_count'", MD);
1504 // Check second operand.
1505 Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1507 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1508 "expected integer argument to function_entry_count", MD);
1513 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) {
1514 if (!ConstantExprVisited.insert(EntryC).second)
1517 SmallVector<const Constant *, 16> Stack;
1518 Stack.push_back(EntryC);
1520 while (!Stack.empty()) {
1521 const Constant *C = Stack.pop_back_val();
1523 // Check this constant expression.
1524 if (const auto *CE = dyn_cast<ConstantExpr>(C))
1525 visitConstantExpr(CE);
1527 // Visit all sub-expressions.
1528 for (const Use &U : C->operands()) {
1529 const auto *OpC = dyn_cast<Constant>(U);
1532 if (isa<GlobalValue>(OpC))
1533 continue; // Global values get visited separately.
1534 if (!ConstantExprVisited.insert(OpC).second)
1536 Stack.push_back(OpC);
1541 void Verifier::visitConstantExpr(const ConstantExpr *CE) {
1542 if (CE->getOpcode() != Instruction::BitCast)
1545 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1547 "Invalid bitcast", CE);
1550 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1551 if (Attrs.getNumSlots() == 0)
1554 unsigned LastSlot = Attrs.getNumSlots() - 1;
1555 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1556 if (LastIndex <= Params
1557 || (LastIndex == AttributeSet::FunctionIndex
1558 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1564 /// \brief Verify that statepoint intrinsic is well formed.
1565 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1566 assert(CS.getCalledFunction() &&
1567 CS.getCalledFunction()->getIntrinsicID() ==
1568 Intrinsic::experimental_gc_statepoint);
1570 const Instruction &CI = *CS.getInstruction();
1572 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1573 !CS.onlyAccessesArgMemory(),
1574 "gc.statepoint must read and write all memory to preserve "
1575 "reordering restrictions required by safepoint semantics",
1578 const Value *IDV = CS.getArgument(0);
1579 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1582 const Value *NumPatchBytesV = CS.getArgument(1);
1583 Assert(isa<ConstantInt>(NumPatchBytesV),
1584 "gc.statepoint number of patchable bytes must be a constant integer",
1586 const int64_t NumPatchBytes =
1587 cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1588 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1589 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1593 const Value *Target = CS.getArgument(2);
1594 auto *PT = dyn_cast<PointerType>(Target->getType());
1595 Assert(PT && PT->getElementType()->isFunctionTy(),
1596 "gc.statepoint callee must be of function pointer type", &CI, Target);
1597 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1599 const Value *NumCallArgsV = CS.getArgument(3);
1600 Assert(isa<ConstantInt>(NumCallArgsV),
1601 "gc.statepoint number of arguments to underlying call "
1602 "must be constant integer",
1604 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1605 Assert(NumCallArgs >= 0,
1606 "gc.statepoint number of arguments to underlying call "
1609 const int NumParams = (int)TargetFuncType->getNumParams();
1610 if (TargetFuncType->isVarArg()) {
1611 Assert(NumCallArgs >= NumParams,
1612 "gc.statepoint mismatch in number of vararg call args", &CI);
1614 // TODO: Remove this limitation
1615 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1616 "gc.statepoint doesn't support wrapping non-void "
1617 "vararg functions yet",
1620 Assert(NumCallArgs == NumParams,
1621 "gc.statepoint mismatch in number of call args", &CI);
1623 const Value *FlagsV = CS.getArgument(4);
1624 Assert(isa<ConstantInt>(FlagsV),
1625 "gc.statepoint flags must be constant integer", &CI);
1626 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1627 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1628 "unknown flag used in gc.statepoint flags argument", &CI);
1630 // Verify that the types of the call parameter arguments match
1631 // the type of the wrapped callee.
1632 for (int i = 0; i < NumParams; i++) {
1633 Type *ParamType = TargetFuncType->getParamType(i);
1634 Type *ArgType = CS.getArgument(5 + i)->getType();
1635 Assert(ArgType == ParamType,
1636 "gc.statepoint call argument does not match wrapped "
1641 const int EndCallArgsInx = 4 + NumCallArgs;
1643 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1644 Assert(isa<ConstantInt>(NumTransitionArgsV),
1645 "gc.statepoint number of transition arguments "
1646 "must be constant integer",
1648 const int NumTransitionArgs =
1649 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1650 Assert(NumTransitionArgs >= 0,
1651 "gc.statepoint number of transition arguments must be positive", &CI);
1652 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1654 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
1655 Assert(isa<ConstantInt>(NumDeoptArgsV),
1656 "gc.statepoint number of deoptimization arguments "
1657 "must be constant integer",
1659 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1660 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1664 const int ExpectedNumArgs =
1665 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
1666 Assert(ExpectedNumArgs <= (int)CS.arg_size(),
1667 "gc.statepoint too few arguments according to length fields", &CI);
1669 // Check that the only uses of this gc.statepoint are gc.result or
1670 // gc.relocate calls which are tied to this statepoint and thus part
1671 // of the same statepoint sequence
1672 for (const User *U : CI.users()) {
1673 const CallInst *Call = dyn_cast<const CallInst>(U);
1674 Assert(Call, "illegal use of statepoint token", &CI, U);
1675 if (!Call) continue;
1676 Assert(isa<GCRelocateInst>(Call) || isGCResult(Call),
1677 "gc.result or gc.relocate are the only value uses"
1678 "of a gc.statepoint",
1680 if (isGCResult(Call)) {
1681 Assert(Call->getArgOperand(0) == &CI,
1682 "gc.result connected to wrong gc.statepoint", &CI, Call);
1683 } else if (isa<GCRelocateInst>(Call)) {
1684 Assert(Call->getArgOperand(0) == &CI,
1685 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1689 // Note: It is legal for a single derived pointer to be listed multiple
1690 // times. It's non-optimal, but it is legal. It can also happen after
1691 // insertion if we strip a bitcast away.
1692 // Note: It is really tempting to check that each base is relocated and
1693 // that a derived pointer is never reused as a base pointer. This turns
1694 // out to be problematic since optimizations run after safepoint insertion
1695 // can recognize equality properties that the insertion logic doesn't know
1696 // about. See example statepoint.ll in the verifier subdirectory
1699 void Verifier::verifyFrameRecoverIndices() {
1700 for (auto &Counts : FrameEscapeInfo) {
1701 Function *F = Counts.first;
1702 unsigned EscapedObjectCount = Counts.second.first;
1703 unsigned MaxRecoveredIndex = Counts.second.second;
1704 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1705 "all indices passed to llvm.localrecover must be less than the "
1706 "number of arguments passed ot llvm.localescape in the parent "
1712 static Instruction *getSuccPad(TerminatorInst *Terminator) {
1713 BasicBlock *UnwindDest;
1714 if (auto *II = dyn_cast<InvokeInst>(Terminator))
1715 UnwindDest = II->getUnwindDest();
1716 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
1717 UnwindDest = CSI->getUnwindDest();
1719 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
1720 return UnwindDest->getFirstNonPHI();
1723 void Verifier::verifySiblingFuncletUnwinds() {
1724 SmallPtrSet<Instruction *, 8> Visited;
1725 SmallPtrSet<Instruction *, 8> Active;
1726 for (const auto &Pair : SiblingFuncletInfo) {
1727 Instruction *PredPad = Pair.first;
1728 if (Visited.count(PredPad))
1730 Active.insert(PredPad);
1731 TerminatorInst *Terminator = Pair.second;
1733 Instruction *SuccPad = getSuccPad(Terminator);
1734 if (Active.count(SuccPad)) {
1735 // Found a cycle; report error
1736 Instruction *CyclePad = SuccPad;
1737 SmallVector<Instruction *, 8> CycleNodes;
1739 CycleNodes.push_back(CyclePad);
1740 TerminatorInst *CycleTerminator = SiblingFuncletInfo[CyclePad];
1741 if (CycleTerminator != CyclePad)
1742 CycleNodes.push_back(CycleTerminator);
1743 CyclePad = getSuccPad(CycleTerminator);
1744 } while (CyclePad != SuccPad);
1745 Assert(false, "EH pads can't handle each other's exceptions",
1746 ArrayRef<Instruction *>(CycleNodes));
1748 // Don't re-walk a node we've already checked
1749 if (!Visited.insert(SuccPad).second)
1751 // Walk to this successor if it has a map entry.
1753 auto TermI = SiblingFuncletInfo.find(PredPad);
1754 if (TermI == SiblingFuncletInfo.end())
1756 Terminator = TermI->second;
1757 Active.insert(PredPad);
1759 // Each node only has one successor, so we've walked all the active
1760 // nodes' successors.
1765 // visitFunction - Verify that a function is ok.
1767 void Verifier::visitFunction(const Function &F) {
1768 // Check function arguments.
1769 FunctionType *FT = F.getFunctionType();
1770 unsigned NumArgs = F.arg_size();
1772 Assert(Context == &F.getContext(),
1773 "Function context does not match Module context!", &F);
1775 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1776 Assert(FT->getNumParams() == NumArgs,
1777 "# formal arguments must match # of arguments for function type!", &F,
1779 Assert(F.getReturnType()->isFirstClassType() ||
1780 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1781 "Functions cannot return aggregate values!", &F);
1783 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1784 "Invalid struct return type!", &F);
1786 AttributeSet Attrs = F.getAttributes();
1788 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1789 "Attribute after last parameter!", &F);
1791 // Check function attributes.
1792 VerifyFunctionAttrs(FT, Attrs, &F);
1794 // On function declarations/definitions, we do not support the builtin
1795 // attribute. We do not check this in VerifyFunctionAttrs since that is
1796 // checking for Attributes that can/can not ever be on functions.
1797 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1798 "Attribute 'builtin' can only be applied to a callsite.", &F);
1800 // Check that this function meets the restrictions on this calling convention.
1801 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1802 // restrictions can be lifted.
1803 switch (F.getCallingConv()) {
1805 case CallingConv::C:
1807 case CallingConv::Fast:
1808 case CallingConv::Cold:
1809 case CallingConv::Intel_OCL_BI:
1810 case CallingConv::PTX_Kernel:
1811 case CallingConv::PTX_Device:
1812 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1813 "perfect forwarding!",
1818 bool isLLVMdotName = F.getName().size() >= 5 &&
1819 F.getName().substr(0, 5) == "llvm.";
1821 // Check that the argument values match the function type for this function...
1823 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1825 Assert(I->getType() == FT->getParamType(i),
1826 "Argument value does not match function argument type!", I,
1827 FT->getParamType(i));
1828 Assert(I->getType()->isFirstClassType(),
1829 "Function arguments must have first-class types!", I);
1830 if (!isLLVMdotName) {
1831 Assert(!I->getType()->isMetadataTy(),
1832 "Function takes metadata but isn't an intrinsic", I, &F);
1833 Assert(!I->getType()->isTokenTy(),
1834 "Function takes token but isn't an intrinsic", I, &F);
1839 Assert(!F.getReturnType()->isTokenTy(),
1840 "Functions returns a token but isn't an intrinsic", &F);
1842 // Get the function metadata attachments.
1843 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1844 F.getAllMetadata(MDs);
1845 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
1846 VerifyFunctionMetadata(MDs);
1848 // Check validity of the personality function
1849 if (F.hasPersonalityFn()) {
1850 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
1852 Assert(Per->getParent() == F.getParent(),
1853 "Referencing personality function in another module!",
1854 &F, F.getParent(), Per, Per->getParent());
1857 if (F.isMaterializable()) {
1858 // Function has a body somewhere we can't see.
1859 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
1860 MDs.empty() ? nullptr : MDs.front().second);
1861 } else if (F.isDeclaration()) {
1862 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1863 "invalid linkage type for function declaration", &F);
1864 Assert(MDs.empty(), "function without a body cannot have metadata", &F,
1865 MDs.empty() ? nullptr : MDs.front().second);
1866 Assert(!F.hasPersonalityFn(),
1867 "Function declaration shouldn't have a personality routine", &F);
1869 // Verify that this function (which has a body) is not named "llvm.*". It
1870 // is not legal to define intrinsics.
1871 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1873 // Check the entry node
1874 const BasicBlock *Entry = &F.getEntryBlock();
1875 Assert(pred_empty(Entry),
1876 "Entry block to function must not have predecessors!", Entry);
1878 // The address of the entry block cannot be taken, unless it is dead.
1879 if (Entry->hasAddressTaken()) {
1880 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1881 "blockaddress may not be used with the entry block!", Entry);
1884 // Visit metadata attachments.
1885 for (const auto &I : MDs) {
1886 // Verify that the attachment is legal.
1890 case LLVMContext::MD_dbg:
1891 Assert(isa<DISubprogram>(I.second),
1892 "function !dbg attachment must be a subprogram", &F, I.second);
1896 // Verify the metadata itself.
1897 visitMDNode(*I.second);
1901 // If this function is actually an intrinsic, verify that it is only used in
1902 // direct call/invokes, never having its "address taken".
1903 // Only do this if the module is materialized, otherwise we don't have all the
1905 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
1907 if (F.hasAddressTaken(&U))
1908 Assert(0, "Invalid user of intrinsic instruction!", U);
1911 Assert(!F.hasDLLImportStorageClass() ||
1912 (F.isDeclaration() && F.hasExternalLinkage()) ||
1913 F.hasAvailableExternallyLinkage(),
1914 "Function is marked as dllimport, but not external.", &F);
1916 auto *N = F.getSubprogram();
1920 // Check that all !dbg attachments lead to back to N (or, at least, another
1921 // subprogram that describes the same function).
1923 // FIXME: Check this incrementally while visiting !dbg attachments.
1924 // FIXME: Only check when N is the canonical subprogram for F.
1925 SmallPtrSet<const MDNode *, 32> Seen;
1927 for (auto &I : BB) {
1928 // Be careful about using DILocation here since we might be dealing with
1929 // broken code (this is the Verifier after all).
1931 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
1934 if (!Seen.insert(DL).second)
1937 DILocalScope *Scope = DL->getInlinedAtScope();
1938 if (Scope && !Seen.insert(Scope).second)
1941 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
1943 // Scope and SP could be the same MDNode and we don't want to skip
1944 // validation in that case
1945 if (SP && ((Scope != SP) && !Seen.insert(SP).second))
1948 // FIXME: Once N is canonical, check "SP == &N".
1949 Assert(SP->describes(&F),
1950 "!dbg attachment points at wrong subprogram for function", N, &F,
1955 // verifyBasicBlock - Verify that a basic block is well formed...
1957 void Verifier::visitBasicBlock(BasicBlock &BB) {
1958 InstsInThisBlock.clear();
1960 // Ensure that basic blocks have terminators!
1961 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1963 // Check constraints that this basic block imposes on all of the PHI nodes in
1965 if (isa<PHINode>(BB.front())) {
1966 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1967 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1968 std::sort(Preds.begin(), Preds.end());
1970 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1971 // Ensure that PHI nodes have at least one entry!
1972 Assert(PN->getNumIncomingValues() != 0,
1973 "PHI nodes must have at least one entry. If the block is dead, "
1974 "the PHI should be removed!",
1976 Assert(PN->getNumIncomingValues() == Preds.size(),
1977 "PHINode should have one entry for each predecessor of its "
1978 "parent basic block!",
1981 // Get and sort all incoming values in the PHI node...
1983 Values.reserve(PN->getNumIncomingValues());
1984 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1985 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1986 PN->getIncomingValue(i)));
1987 std::sort(Values.begin(), Values.end());
1989 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1990 // Check to make sure that if there is more than one entry for a
1991 // particular basic block in this PHI node, that the incoming values are
1994 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1995 Values[i].second == Values[i - 1].second,
1996 "PHI node has multiple entries for the same basic block with "
1997 "different incoming values!",
1998 PN, Values[i].first, Values[i].second, Values[i - 1].second);
2000 // Check to make sure that the predecessors and PHI node entries are
2002 Assert(Values[i].first == Preds[i],
2003 "PHI node entries do not match predecessors!", PN,
2004 Values[i].first, Preds[i]);
2009 // Check that all instructions have their parent pointers set up correctly.
2012 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
2016 void Verifier::visitTerminatorInst(TerminatorInst &I) {
2017 // Ensure that terminators only exist at the end of the basic block.
2018 Assert(&I == I.getParent()->getTerminator(),
2019 "Terminator found in the middle of a basic block!", I.getParent());
2020 visitInstruction(I);
2023 void Verifier::visitBranchInst(BranchInst &BI) {
2024 if (BI.isConditional()) {
2025 Assert(BI.getCondition()->getType()->isIntegerTy(1),
2026 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
2028 visitTerminatorInst(BI);
2031 void Verifier::visitReturnInst(ReturnInst &RI) {
2032 Function *F = RI.getParent()->getParent();
2033 unsigned N = RI.getNumOperands();
2034 if (F->getReturnType()->isVoidTy())
2036 "Found return instr that returns non-void in Function of void "
2038 &RI, F->getReturnType());
2040 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
2041 "Function return type does not match operand "
2042 "type of return inst!",
2043 &RI, F->getReturnType());
2045 // Check to make sure that the return value has necessary properties for
2047 visitTerminatorInst(RI);
2050 void Verifier::visitSwitchInst(SwitchInst &SI) {
2051 // Check to make sure that all of the constants in the switch instruction
2052 // have the same type as the switched-on value.
2053 Type *SwitchTy = SI.getCondition()->getType();
2054 SmallPtrSet<ConstantInt*, 32> Constants;
2055 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
2056 Assert(i.getCaseValue()->getType() == SwitchTy,
2057 "Switch constants must all be same type as switch value!", &SI);
2058 Assert(Constants.insert(i.getCaseValue()).second,
2059 "Duplicate integer as switch case", &SI, i.getCaseValue());
2062 visitTerminatorInst(SI);
2065 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
2066 Assert(BI.getAddress()->getType()->isPointerTy(),
2067 "Indirectbr operand must have pointer type!", &BI);
2068 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
2069 Assert(BI.getDestination(i)->getType()->isLabelTy(),
2070 "Indirectbr destinations must all have pointer type!", &BI);
2072 visitTerminatorInst(BI);
2075 void Verifier::visitSelectInst(SelectInst &SI) {
2076 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
2078 "Invalid operands for select instruction!", &SI);
2080 Assert(SI.getTrueValue()->getType() == SI.getType(),
2081 "Select values must have same type as select instruction!", &SI);
2082 visitInstruction(SI);
2085 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2086 /// a pass, if any exist, it's an error.
2088 void Verifier::visitUserOp1(Instruction &I) {
2089 Assert(0, "User-defined operators should not live outside of a pass!", &I);
2092 void Verifier::visitTruncInst(TruncInst &I) {
2093 // Get the source and destination types
2094 Type *SrcTy = I.getOperand(0)->getType();
2095 Type *DestTy = I.getType();
2097 // Get the size of the types in bits, we'll need this later
2098 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2099 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2101 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
2102 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
2103 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2104 "trunc source and destination must both be a vector or neither", &I);
2105 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
2107 visitInstruction(I);
2110 void Verifier::visitZExtInst(ZExtInst &I) {
2111 // Get the source and destination types
2112 Type *SrcTy = I.getOperand(0)->getType();
2113 Type *DestTy = I.getType();
2115 // Get the size of the types in bits, we'll need this later
2116 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
2117 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
2118 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2119 "zext source and destination must both be a vector or neither", &I);
2120 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2121 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2123 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
2125 visitInstruction(I);
2128 void Verifier::visitSExtInst(SExtInst &I) {
2129 // Get the source and destination types
2130 Type *SrcTy = I.getOperand(0)->getType();
2131 Type *DestTy = I.getType();
2133 // Get the size of the types in bits, we'll need this later
2134 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2135 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2137 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2138 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2139 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2140 "sext source and destination must both be a vector or neither", &I);
2141 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2143 visitInstruction(I);
2146 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2147 // Get the source and destination types
2148 Type *SrcTy = I.getOperand(0)->getType();
2149 Type *DestTy = I.getType();
2150 // Get the size of the types in bits, we'll need this later
2151 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2152 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2154 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2155 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2156 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2157 "fptrunc source and destination must both be a vector or neither", &I);
2158 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2160 visitInstruction(I);
2163 void Verifier::visitFPExtInst(FPExtInst &I) {
2164 // Get the source and destination types
2165 Type *SrcTy = I.getOperand(0)->getType();
2166 Type *DestTy = I.getType();
2168 // Get the size of the types in bits, we'll need this later
2169 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2170 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2172 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2173 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2174 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2175 "fpext source and destination must both be a vector or neither", &I);
2176 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2178 visitInstruction(I);
2181 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2182 // Get the source and destination types
2183 Type *SrcTy = I.getOperand(0)->getType();
2184 Type *DestTy = I.getType();
2186 bool SrcVec = SrcTy->isVectorTy();
2187 bool DstVec = DestTy->isVectorTy();
2189 Assert(SrcVec == DstVec,
2190 "UIToFP source and dest must both be vector or scalar", &I);
2191 Assert(SrcTy->isIntOrIntVectorTy(),
2192 "UIToFP source must be integer or integer vector", &I);
2193 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2196 if (SrcVec && DstVec)
2197 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2198 cast<VectorType>(DestTy)->getNumElements(),
2199 "UIToFP source and dest vector length mismatch", &I);
2201 visitInstruction(I);
2204 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2205 // Get the source and destination types
2206 Type *SrcTy = I.getOperand(0)->getType();
2207 Type *DestTy = I.getType();
2209 bool SrcVec = SrcTy->isVectorTy();
2210 bool DstVec = DestTy->isVectorTy();
2212 Assert(SrcVec == DstVec,
2213 "SIToFP source and dest must both be vector or scalar", &I);
2214 Assert(SrcTy->isIntOrIntVectorTy(),
2215 "SIToFP source must be integer or integer vector", &I);
2216 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2219 if (SrcVec && DstVec)
2220 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2221 cast<VectorType>(DestTy)->getNumElements(),
2222 "SIToFP source and dest vector length mismatch", &I);
2224 visitInstruction(I);
2227 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2228 // Get the source and destination types
2229 Type *SrcTy = I.getOperand(0)->getType();
2230 Type *DestTy = I.getType();
2232 bool SrcVec = SrcTy->isVectorTy();
2233 bool DstVec = DestTy->isVectorTy();
2235 Assert(SrcVec == DstVec,
2236 "FPToUI source and dest must both be vector or scalar", &I);
2237 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2239 Assert(DestTy->isIntOrIntVectorTy(),
2240 "FPToUI result must be integer or integer vector", &I);
2242 if (SrcVec && DstVec)
2243 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2244 cast<VectorType>(DestTy)->getNumElements(),
2245 "FPToUI source and dest vector length mismatch", &I);
2247 visitInstruction(I);
2250 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2251 // Get the source and destination types
2252 Type *SrcTy = I.getOperand(0)->getType();
2253 Type *DestTy = I.getType();
2255 bool SrcVec = SrcTy->isVectorTy();
2256 bool DstVec = DestTy->isVectorTy();
2258 Assert(SrcVec == DstVec,
2259 "FPToSI source and dest must both be vector or scalar", &I);
2260 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2262 Assert(DestTy->isIntOrIntVectorTy(),
2263 "FPToSI result must be integer or integer vector", &I);
2265 if (SrcVec && DstVec)
2266 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2267 cast<VectorType>(DestTy)->getNumElements(),
2268 "FPToSI source and dest vector length mismatch", &I);
2270 visitInstruction(I);
2273 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2274 // Get the source and destination types
2275 Type *SrcTy = I.getOperand(0)->getType();
2276 Type *DestTy = I.getType();
2278 Assert(SrcTy->getScalarType()->isPointerTy(),
2279 "PtrToInt source must be pointer", &I);
2280 Assert(DestTy->getScalarType()->isIntegerTy(),
2281 "PtrToInt result must be integral", &I);
2282 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2285 if (SrcTy->isVectorTy()) {
2286 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2287 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2288 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2289 "PtrToInt Vector width mismatch", &I);
2292 visitInstruction(I);
2295 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2296 // Get the source and destination types
2297 Type *SrcTy = I.getOperand(0)->getType();
2298 Type *DestTy = I.getType();
2300 Assert(SrcTy->getScalarType()->isIntegerTy(),
2301 "IntToPtr source must be an integral", &I);
2302 Assert(DestTy->getScalarType()->isPointerTy(),
2303 "IntToPtr result must be a pointer", &I);
2304 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2306 if (SrcTy->isVectorTy()) {
2307 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2308 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2309 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2310 "IntToPtr Vector width mismatch", &I);
2312 visitInstruction(I);
2315 void Verifier::visitBitCastInst(BitCastInst &I) {
2317 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2318 "Invalid bitcast", &I);
2319 visitInstruction(I);
2322 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2323 Type *SrcTy = I.getOperand(0)->getType();
2324 Type *DestTy = I.getType();
2326 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2328 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2330 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2331 "AddrSpaceCast must be between different address spaces", &I);
2332 if (SrcTy->isVectorTy())
2333 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2334 "AddrSpaceCast vector pointer number of elements mismatch", &I);
2335 visitInstruction(I);
2338 /// visitPHINode - Ensure that a PHI node is well formed.
2340 void Verifier::visitPHINode(PHINode &PN) {
2341 // Ensure that the PHI nodes are all grouped together at the top of the block.
2342 // This can be tested by checking whether the instruction before this is
2343 // either nonexistent (because this is begin()) or is a PHI node. If not,
2344 // then there is some other instruction before a PHI.
2345 Assert(&PN == &PN.getParent()->front() ||
2346 isa<PHINode>(--BasicBlock::iterator(&PN)),
2347 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2349 // Check that a PHI doesn't yield a Token.
2350 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2352 // Check that all of the values of the PHI node have the same type as the
2353 // result, and that the incoming blocks are really basic blocks.
2354 for (Value *IncValue : PN.incoming_values()) {
2355 Assert(PN.getType() == IncValue->getType(),
2356 "PHI node operands are not the same type as the result!", &PN);
2359 // All other PHI node constraints are checked in the visitBasicBlock method.
2361 visitInstruction(PN);
2364 void Verifier::VerifyCallSite(CallSite CS) {
2365 Instruction *I = CS.getInstruction();
2367 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2368 "Called function must be a pointer!", I);
2369 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2371 Assert(FPTy->getElementType()->isFunctionTy(),
2372 "Called function is not pointer to function type!", I);
2374 Assert(FPTy->getElementType() == CS.getFunctionType(),
2375 "Called function is not the same type as the call!", I);
2377 FunctionType *FTy = CS.getFunctionType();
2379 // Verify that the correct number of arguments are being passed
2380 if (FTy->isVarArg())
2381 Assert(CS.arg_size() >= FTy->getNumParams(),
2382 "Called function requires more parameters than were provided!", I);
2384 Assert(CS.arg_size() == FTy->getNumParams(),
2385 "Incorrect number of arguments passed to called function!", I);
2387 // Verify that all arguments to the call match the function type.
2388 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2389 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2390 "Call parameter type does not match function signature!",
2391 CS.getArgument(i), FTy->getParamType(i), I);
2393 AttributeSet Attrs = CS.getAttributes();
2395 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2396 "Attribute after last parameter!", I);
2398 // Verify call attributes.
2399 VerifyFunctionAttrs(FTy, Attrs, I);
2401 // Conservatively check the inalloca argument.
2402 // We have a bug if we can find that there is an underlying alloca without
2404 if (CS.hasInAllocaArgument()) {
2405 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2406 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2407 Assert(AI->isUsedWithInAlloca(),
2408 "inalloca argument for call has mismatched alloca", AI, I);
2411 if (FTy->isVarArg()) {
2412 // FIXME? is 'nest' even legal here?
2413 bool SawNest = false;
2414 bool SawReturned = false;
2416 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2417 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2419 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2423 // Check attributes on the varargs part.
2424 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2425 Type *Ty = CS.getArgument(Idx-1)->getType();
2426 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2428 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2429 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2433 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2434 Assert(!SawReturned, "More than one parameter has attribute returned!",
2436 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2437 "Incompatible argument and return types for 'returned' "
2443 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2444 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2446 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2447 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2451 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2452 if (CS.getCalledFunction() == nullptr ||
2453 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2454 for (Type *ParamTy : FTy->params()) {
2455 Assert(!ParamTy->isMetadataTy(),
2456 "Function has metadata parameter but isn't an intrinsic", I);
2457 Assert(!ParamTy->isTokenTy(),
2458 "Function has token parameter but isn't an intrinsic", I);
2462 // Verify that indirect calls don't return tokens.
2463 if (CS.getCalledFunction() == nullptr)
2464 Assert(!FTy->getReturnType()->isTokenTy(),
2465 "Return type cannot be token for indirect call!");
2467 if (Function *F = CS.getCalledFunction())
2468 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2469 visitIntrinsicCallSite(ID, CS);
2471 // Verify that a callsite has at most one "deopt" and one "funclet" operand
2473 bool FoundDeoptBundle = false, FoundFuncletBundle = false;
2474 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
2475 OperandBundleUse BU = CS.getOperandBundleAt(i);
2476 uint32_t Tag = BU.getTagID();
2477 if (Tag == LLVMContext::OB_deopt) {
2478 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2479 FoundDeoptBundle = true;
2481 if (Tag == LLVMContext::OB_funclet) {
2482 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I);
2483 FoundFuncletBundle = true;
2484 Assert(BU.Inputs.size() == 1,
2485 "Expected exactly one funclet bundle operand", I);
2486 Assert(isa<FuncletPadInst>(BU.Inputs.front()),
2487 "Funclet bundle operands should correspond to a FuncletPadInst",
2492 visitInstruction(*I);
2495 /// Two types are "congruent" if they are identical, or if they are both pointer
2496 /// types with different pointee types and the same address space.
2497 static bool isTypeCongruent(Type *L, Type *R) {
2500 PointerType *PL = dyn_cast<PointerType>(L);
2501 PointerType *PR = dyn_cast<PointerType>(R);
2504 return PL->getAddressSpace() == PR->getAddressSpace();
2507 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2508 static const Attribute::AttrKind ABIAttrs[] = {
2509 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2510 Attribute::InReg, Attribute::Returned};
2512 for (auto AK : ABIAttrs) {
2513 if (Attrs.hasAttribute(I + 1, AK))
2514 Copy.addAttribute(AK);
2516 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2517 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2521 void Verifier::verifyMustTailCall(CallInst &CI) {
2522 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2524 // - The caller and callee prototypes must match. Pointer types of
2525 // parameters or return types may differ in pointee type, but not
2527 Function *F = CI.getParent()->getParent();
2528 FunctionType *CallerTy = F->getFunctionType();
2529 FunctionType *CalleeTy = CI.getFunctionType();
2530 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2531 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2532 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2533 "cannot guarantee tail call due to mismatched varargs", &CI);
2534 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2535 "cannot guarantee tail call due to mismatched return types", &CI);
2536 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2538 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2539 "cannot guarantee tail call due to mismatched parameter types", &CI);
2542 // - The calling conventions of the caller and callee must match.
2543 Assert(F->getCallingConv() == CI.getCallingConv(),
2544 "cannot guarantee tail call due to mismatched calling conv", &CI);
2546 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2547 // returned, and inalloca, must match.
2548 AttributeSet CallerAttrs = F->getAttributes();
2549 AttributeSet CalleeAttrs = CI.getAttributes();
2550 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2551 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2552 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2553 Assert(CallerABIAttrs == CalleeABIAttrs,
2554 "cannot guarantee tail call due to mismatched ABI impacting "
2555 "function attributes",
2556 &CI, CI.getOperand(I));
2559 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2560 // or a pointer bitcast followed by a ret instruction.
2561 // - The ret instruction must return the (possibly bitcasted) value
2562 // produced by the call or void.
2563 Value *RetVal = &CI;
2564 Instruction *Next = CI.getNextNode();
2566 // Handle the optional bitcast.
2567 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2568 Assert(BI->getOperand(0) == RetVal,
2569 "bitcast following musttail call must use the call", BI);
2571 Next = BI->getNextNode();
2574 // Check the return.
2575 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2576 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2578 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2579 "musttail call result must be returned", Ret);
2582 void Verifier::visitCallInst(CallInst &CI) {
2583 VerifyCallSite(&CI);
2585 if (CI.isMustTailCall())
2586 verifyMustTailCall(CI);
2589 void Verifier::visitInvokeInst(InvokeInst &II) {
2590 VerifyCallSite(&II);
2592 // Verify that the first non-PHI instruction of the unwind destination is an
2593 // exception handling instruction.
2595 II.getUnwindDest()->isEHPad(),
2596 "The unwind destination does not have an exception handling instruction!",
2599 visitTerminatorInst(II);
2602 /// visitBinaryOperator - Check that both arguments to the binary operator are
2603 /// of the same type!
2605 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2606 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2607 "Both operands to a binary operator are not of the same type!", &B);
2609 switch (B.getOpcode()) {
2610 // Check that integer arithmetic operators are only used with
2611 // integral operands.
2612 case Instruction::Add:
2613 case Instruction::Sub:
2614 case Instruction::Mul:
2615 case Instruction::SDiv:
2616 case Instruction::UDiv:
2617 case Instruction::SRem:
2618 case Instruction::URem:
2619 Assert(B.getType()->isIntOrIntVectorTy(),
2620 "Integer arithmetic operators only work with integral types!", &B);
2621 Assert(B.getType() == B.getOperand(0)->getType(),
2622 "Integer arithmetic operators must have same type "
2623 "for operands and result!",
2626 // Check that floating-point arithmetic operators are only used with
2627 // floating-point operands.
2628 case Instruction::FAdd:
2629 case Instruction::FSub:
2630 case Instruction::FMul:
2631 case Instruction::FDiv:
2632 case Instruction::FRem:
2633 Assert(B.getType()->isFPOrFPVectorTy(),
2634 "Floating-point arithmetic operators only work with "
2635 "floating-point types!",
2637 Assert(B.getType() == B.getOperand(0)->getType(),
2638 "Floating-point arithmetic operators must have same type "
2639 "for operands and result!",
2642 // Check that logical operators are only used with integral operands.
2643 case Instruction::And:
2644 case Instruction::Or:
2645 case Instruction::Xor:
2646 Assert(B.getType()->isIntOrIntVectorTy(),
2647 "Logical operators only work with integral types!", &B);
2648 Assert(B.getType() == B.getOperand(0)->getType(),
2649 "Logical operators must have same type for operands and result!",
2652 case Instruction::Shl:
2653 case Instruction::LShr:
2654 case Instruction::AShr:
2655 Assert(B.getType()->isIntOrIntVectorTy(),
2656 "Shifts only work with integral types!", &B);
2657 Assert(B.getType() == B.getOperand(0)->getType(),
2658 "Shift return type must be same as operands!", &B);
2661 llvm_unreachable("Unknown BinaryOperator opcode!");
2664 visitInstruction(B);
2667 void Verifier::visitICmpInst(ICmpInst &IC) {
2668 // Check that the operands are the same type
2669 Type *Op0Ty = IC.getOperand(0)->getType();
2670 Type *Op1Ty = IC.getOperand(1)->getType();
2671 Assert(Op0Ty == Op1Ty,
2672 "Both operands to ICmp instruction are not of the same type!", &IC);
2673 // Check that the operands are the right type
2674 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2675 "Invalid operand types for ICmp instruction", &IC);
2676 // Check that the predicate is valid.
2677 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2678 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2679 "Invalid predicate in ICmp instruction!", &IC);
2681 visitInstruction(IC);
2684 void Verifier::visitFCmpInst(FCmpInst &FC) {
2685 // Check that the operands are the same type
2686 Type *Op0Ty = FC.getOperand(0)->getType();
2687 Type *Op1Ty = FC.getOperand(1)->getType();
2688 Assert(Op0Ty == Op1Ty,
2689 "Both operands to FCmp instruction are not of the same type!", &FC);
2690 // Check that the operands are the right type
2691 Assert(Op0Ty->isFPOrFPVectorTy(),
2692 "Invalid operand types for FCmp instruction", &FC);
2693 // Check that the predicate is valid.
2694 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2695 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2696 "Invalid predicate in FCmp instruction!", &FC);
2698 visitInstruction(FC);
2701 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2703 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2704 "Invalid extractelement operands!", &EI);
2705 visitInstruction(EI);
2708 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2709 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2711 "Invalid insertelement operands!", &IE);
2712 visitInstruction(IE);
2715 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2716 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2718 "Invalid shufflevector operands!", &SV);
2719 visitInstruction(SV);
2722 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2723 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2725 Assert(isa<PointerType>(TargetTy),
2726 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2727 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
2728 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2730 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2731 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2733 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2734 GEP.getResultElementType() == ElTy,
2735 "GEP is not of right type for indices!", &GEP, ElTy);
2737 if (GEP.getType()->isVectorTy()) {
2738 // Additional checks for vector GEPs.
2739 unsigned GEPWidth = GEP.getType()->getVectorNumElements();
2740 if (GEP.getPointerOperandType()->isVectorTy())
2741 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
2742 "Vector GEP result width doesn't match operand's", &GEP);
2743 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2744 Type *IndexTy = Idxs[i]->getType();
2745 if (IndexTy->isVectorTy()) {
2746 unsigned IndexWidth = IndexTy->getVectorNumElements();
2747 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
2749 Assert(IndexTy->getScalarType()->isIntegerTy(),
2750 "All GEP indices should be of integer type");
2753 visitInstruction(GEP);
2756 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2757 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2760 void Verifier::visitRangeMetadata(Instruction& I,
2761 MDNode* Range, Type* Ty) {
2763 Range == I.getMetadata(LLVMContext::MD_range) &&
2764 "precondition violation");
2766 unsigned NumOperands = Range->getNumOperands();
2767 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2768 unsigned NumRanges = NumOperands / 2;
2769 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2771 ConstantRange LastRange(1); // Dummy initial value
2772 for (unsigned i = 0; i < NumRanges; ++i) {
2774 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2775 Assert(Low, "The lower limit must be an integer!", Low);
2777 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2778 Assert(High, "The upper limit must be an integer!", High);
2779 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2780 "Range types must match instruction type!", &I);
2782 APInt HighV = High->getValue();
2783 APInt LowV = Low->getValue();
2784 ConstantRange CurRange(LowV, HighV);
2785 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2786 "Range must not be empty!", Range);
2788 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2789 "Intervals are overlapping", Range);
2790 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2792 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2795 LastRange = ConstantRange(LowV, HighV);
2797 if (NumRanges > 2) {
2799 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2801 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2802 ConstantRange FirstRange(FirstLow, FirstHigh);
2803 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2804 "Intervals are overlapping", Range);
2805 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2810 void Verifier::checkAtomicMemAccessSize(const Module *M, Type *Ty,
2811 const Instruction *I) {
2812 unsigned Size = M->getDataLayout().getTypeSizeInBits(Ty);
2813 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I);
2814 Assert(!(Size & (Size - 1)),
2815 "atomic memory access' operand must have a power-of-two size", Ty, I);
2818 void Verifier::visitLoadInst(LoadInst &LI) {
2819 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2820 Assert(PTy, "Load operand must be a pointer.", &LI);
2821 Type *ElTy = LI.getType();
2822 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2823 "huge alignment values are unsupported", &LI);
2824 if (LI.isAtomic()) {
2825 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2826 "Load cannot have Release ordering", &LI);
2827 Assert(LI.getAlignment() != 0,
2828 "Atomic load must specify explicit alignment", &LI);
2829 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
2830 ElTy->isFloatingPointTy(),
2831 "atomic load operand must have integer, pointer, or floating point "
2834 checkAtomicMemAccessSize(M, ElTy, &LI);
2836 Assert(LI.getSynchScope() == CrossThread,
2837 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2840 visitInstruction(LI);
2843 void Verifier::visitStoreInst(StoreInst &SI) {
2844 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2845 Assert(PTy, "Store operand must be a pointer.", &SI);
2846 Type *ElTy = PTy->getElementType();
2847 Assert(ElTy == SI.getOperand(0)->getType(),
2848 "Stored value type does not match pointer operand type!", &SI, ElTy);
2849 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2850 "huge alignment values are unsupported", &SI);
2851 if (SI.isAtomic()) {
2852 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2853 "Store cannot have Acquire ordering", &SI);
2854 Assert(SI.getAlignment() != 0,
2855 "Atomic store must specify explicit alignment", &SI);
2856 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() ||
2857 ElTy->isFloatingPointTy(),
2858 "atomic store operand must have integer, pointer, or floating point "
2861 checkAtomicMemAccessSize(M, ElTy, &SI);
2863 Assert(SI.getSynchScope() == CrossThread,
2864 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2866 visitInstruction(SI);
2869 void Verifier::visitAllocaInst(AllocaInst &AI) {
2870 SmallPtrSet<Type*, 4> Visited;
2871 PointerType *PTy = AI.getType();
2872 Assert(PTy->getAddressSpace() == 0,
2873 "Allocation instruction pointer not in the generic address space!",
2875 Assert(AI.getAllocatedType()->isSized(&Visited),
2876 "Cannot allocate unsized type", &AI);
2877 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2878 "Alloca array size must have integer type", &AI);
2879 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2880 "huge alignment values are unsupported", &AI);
2882 visitInstruction(AI);
2885 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2887 // FIXME: more conditions???
2888 Assert(CXI.getSuccessOrdering() != NotAtomic,
2889 "cmpxchg instructions must be atomic.", &CXI);
2890 Assert(CXI.getFailureOrdering() != NotAtomic,
2891 "cmpxchg instructions must be atomic.", &CXI);
2892 Assert(CXI.getSuccessOrdering() != Unordered,
2893 "cmpxchg instructions cannot be unordered.", &CXI);
2894 Assert(CXI.getFailureOrdering() != Unordered,
2895 "cmpxchg instructions cannot be unordered.", &CXI);
2896 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2897 "cmpxchg instructions be at least as constrained on success as fail",
2899 Assert(CXI.getFailureOrdering() != Release &&
2900 CXI.getFailureOrdering() != AcquireRelease,
2901 "cmpxchg failure ordering cannot include release semantics", &CXI);
2903 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2904 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2905 Type *ElTy = PTy->getElementType();
2906 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2908 checkAtomicMemAccessSize(M, ElTy, &CXI);
2909 Assert(ElTy == CXI.getOperand(1)->getType(),
2910 "Expected value type does not match pointer operand type!", &CXI,
2912 Assert(ElTy == CXI.getOperand(2)->getType(),
2913 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2914 visitInstruction(CXI);
2917 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2918 Assert(RMWI.getOrdering() != NotAtomic,
2919 "atomicrmw instructions must be atomic.", &RMWI);
2920 Assert(RMWI.getOrdering() != Unordered,
2921 "atomicrmw instructions cannot be unordered.", &RMWI);
2922 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2923 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2924 Type *ElTy = PTy->getElementType();
2925 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2927 checkAtomicMemAccessSize(M, ElTy, &RMWI);
2928 Assert(ElTy == RMWI.getOperand(1)->getType(),
2929 "Argument value type does not match pointer operand type!", &RMWI,
2931 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2932 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2933 "Invalid binary operation!", &RMWI);
2934 visitInstruction(RMWI);
2937 void Verifier::visitFenceInst(FenceInst &FI) {
2938 const AtomicOrdering Ordering = FI.getOrdering();
2939 Assert(Ordering == Acquire || Ordering == Release ||
2940 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2941 "fence instructions may only have "
2942 "acquire, release, acq_rel, or seq_cst ordering.",
2944 visitInstruction(FI);
2947 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2948 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2949 EVI.getIndices()) == EVI.getType(),
2950 "Invalid ExtractValueInst operands!", &EVI);
2952 visitInstruction(EVI);
2955 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2956 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2957 IVI.getIndices()) ==
2958 IVI.getOperand(1)->getType(),
2959 "Invalid InsertValueInst operands!", &IVI);
2961 visitInstruction(IVI);
2964 static Value *getParentPad(Value *EHPad) {
2965 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
2966 return FPI->getParentPad();
2968 return cast<CatchSwitchInst>(EHPad)->getParentPad();
2971 void Verifier::visitEHPadPredecessors(Instruction &I) {
2972 assert(I.isEHPad());
2974 BasicBlock *BB = I.getParent();
2975 Function *F = BB->getParent();
2977 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
2979 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
2980 // The landingpad instruction defines its parent as a landing pad block. The
2981 // landing pad block may be branched to only by the unwind edge of an
2983 for (BasicBlock *PredBB : predecessors(BB)) {
2984 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
2985 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2986 "Block containing LandingPadInst must be jumped to "
2987 "only by the unwind edge of an invoke.",
2992 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) {
2993 if (!pred_empty(BB))
2994 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
2995 "Block containg CatchPadInst must be jumped to "
2996 "only by its catchswitch.",
2998 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
2999 "Catchswitch cannot unwind to one of its catchpads",
3000 CPI->getCatchSwitch(), CPI);
3004 // Verify that each pred has a legal terminator with a legal to/from EH
3005 // pad relationship.
3006 Instruction *ToPad = &I;
3007 Value *ToPadParent = getParentPad(ToPad);
3008 for (BasicBlock *PredBB : predecessors(BB)) {
3009 TerminatorInst *TI = PredBB->getTerminator();
3011 if (auto *II = dyn_cast<InvokeInst>(TI)) {
3012 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
3013 "EH pad must be jumped to via an unwind edge", ToPad, II);
3014 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet))
3015 FromPad = Bundle->Inputs[0];
3017 FromPad = ConstantTokenNone::get(II->getContext());
3018 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3019 FromPad = CRI->getCleanupPad();
3020 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI);
3021 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3024 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI);
3027 // The edge may exit from zero or more nested pads.
3028 for (;; FromPad = getParentPad(FromPad)) {
3029 Assert(FromPad != ToPad,
3030 "EH pad cannot handle exceptions raised within it", FromPad, TI);
3031 if (FromPad == ToPadParent) {
3032 // This is a legal unwind edge.
3035 Assert(!isa<ConstantTokenNone>(FromPad),
3036 "A single unwind edge may only enter one EH pad", TI);
3041 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
3042 // The landingpad instruction is ill-formed if it doesn't have any clauses and
3044 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
3045 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
3047 visitEHPadPredecessors(LPI);
3049 if (!LandingPadResultTy)
3050 LandingPadResultTy = LPI.getType();
3052 Assert(LandingPadResultTy == LPI.getType(),
3053 "The landingpad instruction should have a consistent result type "
3054 "inside a function.",
3057 Function *F = LPI.getParent()->getParent();
3058 Assert(F->hasPersonalityFn(),
3059 "LandingPadInst needs to be in a function with a personality.", &LPI);
3061 // The landingpad instruction must be the first non-PHI instruction in the
3063 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
3064 "LandingPadInst not the first non-PHI instruction in the block.",
3067 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
3068 Constant *Clause = LPI.getClause(i);
3069 if (LPI.isCatch(i)) {
3070 Assert(isa<PointerType>(Clause->getType()),
3071 "Catch operand does not have pointer type!", &LPI);
3073 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
3074 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
3075 "Filter operand is not an array of constants!", &LPI);
3079 visitInstruction(LPI);
3082 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
3083 visitEHPadPredecessors(CPI);
3085 BasicBlock *BB = CPI.getParent();
3087 Function *F = BB->getParent();
3088 Assert(F->hasPersonalityFn(),
3089 "CatchPadInst needs to be in a function with a personality.", &CPI);
3091 Assert(isa<CatchSwitchInst>(CPI.getParentPad()),
3092 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
3093 CPI.getParentPad());
3095 // The catchpad instruction must be the first non-PHI instruction in the
3097 Assert(BB->getFirstNonPHI() == &CPI,
3098 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
3100 visitFuncletPadInst(CPI);
3103 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
3104 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)),
3105 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
3106 CatchReturn.getOperand(0));
3108 visitTerminatorInst(CatchReturn);
3111 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
3112 visitEHPadPredecessors(CPI);
3114 BasicBlock *BB = CPI.getParent();
3116 Function *F = BB->getParent();
3117 Assert(F->hasPersonalityFn(),
3118 "CleanupPadInst needs to be in a function with a personality.", &CPI);
3120 // The cleanuppad instruction must be the first non-PHI instruction in the
3122 Assert(BB->getFirstNonPHI() == &CPI,
3123 "CleanupPadInst not the first non-PHI instruction in the block.",
3126 auto *ParentPad = CPI.getParentPad();
3127 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3128 "CleanupPadInst has an invalid parent.", &CPI);
3130 visitFuncletPadInst(CPI);
3133 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
3134 User *FirstUser = nullptr;
3135 Value *FirstUnwindPad = nullptr;
3136 SmallVector<FuncletPadInst *, 8> Worklist({&FPI});
3137 while (!Worklist.empty()) {
3138 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
3139 Value *UnresolvedAncestorPad = nullptr;
3140 for (User *U : CurrentPad->users()) {
3141 BasicBlock *UnwindDest;
3142 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
3143 UnwindDest = CRI->getUnwindDest();
3144 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
3145 // We allow catchswitch unwind to caller to nest
3146 // within an outer pad that unwinds somewhere else,
3147 // because catchswitch doesn't have a nounwind variant.
3148 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
3149 if (CSI->unwindsToCaller())
3151 UnwindDest = CSI->getUnwindDest();
3152 } else if (auto *II = dyn_cast<InvokeInst>(U)) {
3153 UnwindDest = II->getUnwindDest();
3154 } else if (isa<CallInst>(U)) {
3155 // Calls which don't unwind may be found inside funclet
3156 // pads that unwind somewhere else. We don't *require*
3157 // such calls to be annotated nounwind.
3159 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) {
3160 // The unwind dest for a cleanup can only be found by
3161 // recursive search. Add it to the worklist, and we'll
3162 // search for its first use that determines where it unwinds.
3163 Worklist.push_back(CPI);
3166 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U);
3173 UnwindPad = UnwindDest->getFirstNonPHI();
3174 Value *UnwindParent = getParentPad(UnwindPad);
3175 // Ignore unwind edges that don't exit CurrentPad.
3176 if (UnwindParent == CurrentPad)
3178 // Determine whether the original funclet pad is exited,
3179 // and if we are scanning nested pads determine how many
3180 // of them are exited so we can stop searching their
3182 Value *ExitedPad = CurrentPad;
3185 if (ExitedPad == &FPI) {
3187 // Now we can resolve any ancestors of CurrentPad up to
3188 // FPI, but not including FPI since we need to make sure
3189 // to check all direct users of FPI for consistency.
3190 UnresolvedAncestorPad = &FPI;
3193 Value *ExitedParent = getParentPad(ExitedPad);
3194 if (ExitedParent == UnwindParent) {
3195 // ExitedPad is the ancestor-most pad which this unwind
3196 // edge exits, so we can resolve up to it, meaning that
3197 // ExitedParent is the first ancestor still unresolved.
3198 UnresolvedAncestorPad = ExitedParent;
3201 ExitedPad = ExitedParent;
3202 } while (!isa<ConstantTokenNone>(ExitedPad));
3204 // Unwinding to caller exits all pads.
3205 UnwindPad = ConstantTokenNone::get(FPI.getContext());
3207 UnresolvedAncestorPad = &FPI;
3211 // This unwind edge exits FPI. Make sure it agrees with other
3214 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet "
3215 "pad must have the same unwind "
3217 &FPI, U, FirstUser);
3220 FirstUnwindPad = UnwindPad;
3221 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
3222 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
3223 getParentPad(UnwindPad) == getParentPad(&FPI))
3224 SiblingFuncletInfo[&FPI] = cast<TerminatorInst>(U);
3227 // Make sure we visit all uses of FPI, but for nested pads stop as
3228 // soon as we know where they unwind to.
3229 if (CurrentPad != &FPI)
3232 if (UnresolvedAncestorPad) {
3233 if (CurrentPad == UnresolvedAncestorPad) {
3234 // When CurrentPad is FPI itself, we don't mark it as resolved even if
3235 // we've found an unwind edge that exits it, because we need to verify
3236 // all direct uses of FPI.
3237 assert(CurrentPad == &FPI);
3240 // Pop off the worklist any nested pads that we've found an unwind
3241 // destination for. The pads on the worklist are the uncles,
3242 // great-uncles, etc. of CurrentPad. We've found an unwind destination
3243 // for all ancestors of CurrentPad up to but not including
3244 // UnresolvedAncestorPad.
3245 Value *ResolvedPad = CurrentPad;
3246 while (!Worklist.empty()) {
3247 Value *UnclePad = Worklist.back();
3248 Value *AncestorPad = getParentPad(UnclePad);
3249 // Walk ResolvedPad up the ancestor list until we either find the
3250 // uncle's parent or the last resolved ancestor.
3251 while (ResolvedPad != AncestorPad) {
3252 Value *ResolvedParent = getParentPad(ResolvedPad);
3253 if (ResolvedParent == UnresolvedAncestorPad) {
3256 ResolvedPad = ResolvedParent;
3258 // If the resolved ancestor search didn't find the uncle's parent,
3259 // then the uncle is not yet resolved.
3260 if (ResolvedPad != AncestorPad)
3262 // This uncle is resolved, so pop it from the worklist.
3263 Worklist.pop_back();
3268 if (FirstUnwindPad) {
3269 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) {
3270 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
3271 Value *SwitchUnwindPad;
3272 if (SwitchUnwindDest)
3273 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI();
3275 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext());
3276 Assert(SwitchUnwindPad == FirstUnwindPad,
3277 "Unwind edges out of a catch must have the same unwind dest as "
3278 "the parent catchswitch",
3279 &FPI, FirstUser, CatchSwitch);
3283 visitInstruction(FPI);
3286 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
3287 visitEHPadPredecessors(CatchSwitch);
3289 BasicBlock *BB = CatchSwitch.getParent();
3291 Function *F = BB->getParent();
3292 Assert(F->hasPersonalityFn(),
3293 "CatchSwitchInst needs to be in a function with a personality.",
3296 // The catchswitch instruction must be the first non-PHI instruction in the
3298 Assert(BB->getFirstNonPHI() == &CatchSwitch,
3299 "CatchSwitchInst not the first non-PHI instruction in the block.",
3302 auto *ParentPad = CatchSwitch.getParentPad();
3303 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3304 "CatchSwitchInst has an invalid parent.", ParentPad);
3306 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) {
3307 Instruction *I = UnwindDest->getFirstNonPHI();
3308 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3309 "CatchSwitchInst must unwind to an EH block which is not a "
3313 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
3314 if (getParentPad(I) == ParentPad)
3315 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
3318 Assert(CatchSwitch.getNumHandlers() != 0,
3319 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
3321 for (BasicBlock *Handler : CatchSwitch.handlers()) {
3322 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
3323 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
3326 visitTerminatorInst(CatchSwitch);
3329 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
3330 Assert(isa<CleanupPadInst>(CRI.getOperand(0)),
3331 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
3334 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3335 Instruction *I = UnwindDest->getFirstNonPHI();
3336 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3337 "CleanupReturnInst must unwind to an EH block which is not a "
3342 visitTerminatorInst(CRI);
3345 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3346 Instruction *Op = cast<Instruction>(I.getOperand(i));
3347 // If the we have an invalid invoke, don't try to compute the dominance.
3348 // We already reject it in the invoke specific checks and the dominance
3349 // computation doesn't handle multiple edges.
3350 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3351 if (II->getNormalDest() == II->getUnwindDest())
3355 const Use &U = I.getOperandUse(i);
3356 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
3357 "Instruction does not dominate all uses!", Op, &I);
3360 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3361 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3362 "apply only to pointer types", &I);
3363 Assert(isa<LoadInst>(I),
3364 "dereferenceable, dereferenceable_or_null apply only to load"
3365 " instructions, use attributes for calls or invokes", &I);
3366 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3367 "take one operand!", &I);
3368 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3369 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3370 "dereferenceable_or_null metadata value must be an i64!", &I);
3373 /// verifyInstruction - Verify that an instruction is well formed.
3375 void Verifier::visitInstruction(Instruction &I) {
3376 BasicBlock *BB = I.getParent();
3377 Assert(BB, "Instruction not embedded in basic block!", &I);
3379 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
3380 for (User *U : I.users()) {
3381 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3382 "Only PHI nodes may reference their own value!", &I);
3386 // Check that void typed values don't have names
3387 Assert(!I.getType()->isVoidTy() || !I.hasName(),
3388 "Instruction has a name, but provides a void value!", &I);
3390 // Check that the return value of the instruction is either void or a legal
3392 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3393 "Instruction returns a non-scalar type!", &I);
3395 // Check that the instruction doesn't produce metadata. Calls are already
3396 // checked against the callee type.
3397 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3398 "Invalid use of metadata!", &I);
3400 // Check that all uses of the instruction, if they are instructions
3401 // themselves, actually have parent basic blocks. If the use is not an
3402 // instruction, it is an error!
3403 for (Use &U : I.uses()) {
3404 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
3405 Assert(Used->getParent() != nullptr,
3406 "Instruction referencing"
3407 " instruction not embedded in a basic block!",
3410 CheckFailed("Use of instruction is not an instruction!", U);
3415 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
3416 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
3418 // Check to make sure that only first-class-values are operands to
3420 if (!I.getOperand(i)->getType()->isFirstClassType()) {
3421 Assert(0, "Instruction operands must be first-class values!", &I);
3424 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
3425 // Check to make sure that the "address of" an intrinsic function is never
3428 !F->isIntrinsic() ||
3429 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3430 "Cannot take the address of an intrinsic!", &I);
3432 !F->isIntrinsic() || isa<CallInst>(I) ||
3433 F->getIntrinsicID() == Intrinsic::donothing ||
3434 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
3435 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3436 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
3437 "Cannot invoke an intrinsinc other than"
3438 " donothing or patchpoint",
3440 Assert(F->getParent() == M, "Referencing function in another module!",
3441 &I, M, F, F->getParent());
3442 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
3443 Assert(OpBB->getParent() == BB->getParent(),
3444 "Referring to a basic block in another function!", &I);
3445 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
3446 Assert(OpArg->getParent() == BB->getParent(),
3447 "Referring to an argument in another function!", &I);
3448 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
3449 Assert(GV->getParent() == M, "Referencing global in another module!", &I, M, GV, GV->getParent());
3450 } else if (isa<Instruction>(I.getOperand(i))) {
3451 verifyDominatesUse(I, i);
3452 } else if (isa<InlineAsm>(I.getOperand(i))) {
3453 Assert((i + 1 == e && isa<CallInst>(I)) ||
3454 (i + 3 == e && isa<InvokeInst>(I)),
3455 "Cannot take the address of an inline asm!", &I);
3456 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
3457 if (CE->getType()->isPtrOrPtrVectorTy()) {
3458 // If we have a ConstantExpr pointer, we need to see if it came from an
3459 // illegal bitcast (inttoptr <constant int> )
3460 visitConstantExprsRecursively(CE);
3465 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
3466 Assert(I.getType()->isFPOrFPVectorTy(),
3467 "fpmath requires a floating point result!", &I);
3468 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
3469 if (ConstantFP *CFP0 =
3470 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
3471 APFloat Accuracy = CFP0->getValueAPF();
3472 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
3473 "fpmath accuracy not a positive number!", &I);
3475 Assert(false, "invalid fpmath accuracy!", &I);
3479 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
3480 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
3481 "Ranges are only for loads, calls and invokes!", &I);
3482 visitRangeMetadata(I, Range, I.getType());
3485 if (I.getMetadata(LLVMContext::MD_nonnull)) {
3486 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
3488 Assert(isa<LoadInst>(I),
3489 "nonnull applies only to load instructions, use attributes"
3490 " for calls or invokes",
3494 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
3495 visitDereferenceableMetadata(I, MD);
3497 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
3498 visitDereferenceableMetadata(I, MD);
3500 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
3501 Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
3503 Assert(isa<LoadInst>(I), "align applies only to load instructions, "
3504 "use attributes for calls or invokes", &I);
3505 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
3506 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
3507 Assert(CI && CI->getType()->isIntegerTy(64),
3508 "align metadata value must be an i64!", &I);
3509 uint64_t Align = CI->getZExtValue();
3510 Assert(isPowerOf2_64(Align),
3511 "align metadata value must be a power of 2!", &I);
3512 Assert(Align <= Value::MaximumAlignment,
3513 "alignment is larger that implementation defined limit", &I);
3516 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
3517 Assert(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
3521 InstsInThisBlock.insert(&I);
3524 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
3525 /// intrinsic argument or return value) matches the type constraints specified
3526 /// by the .td file (e.g. an "any integer" argument really is an integer).
3528 /// This return true on error but does not print a message.
3529 bool Verifier::VerifyIntrinsicType(Type *Ty,
3530 ArrayRef<Intrinsic::IITDescriptor> &Infos,
3531 SmallVectorImpl<Type*> &ArgTys) {
3532 using namespace Intrinsic;
3534 // If we ran out of descriptors, there are too many arguments.
3535 if (Infos.empty()) return true;
3536 IITDescriptor D = Infos.front();
3537 Infos = Infos.slice(1);
3540 case IITDescriptor::Void: return !Ty->isVoidTy();
3541 case IITDescriptor::VarArg: return true;
3542 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
3543 case IITDescriptor::Token: return !Ty->isTokenTy();
3544 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
3545 case IITDescriptor::Half: return !Ty->isHalfTy();
3546 case IITDescriptor::Float: return !Ty->isFloatTy();
3547 case IITDescriptor::Double: return !Ty->isDoubleTy();
3548 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
3549 case IITDescriptor::Vector: {
3550 VectorType *VT = dyn_cast<VectorType>(Ty);
3551 return !VT || VT->getNumElements() != D.Vector_Width ||
3552 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
3554 case IITDescriptor::Pointer: {
3555 PointerType *PT = dyn_cast<PointerType>(Ty);
3556 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
3557 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
3560 case IITDescriptor::Struct: {
3561 StructType *ST = dyn_cast<StructType>(Ty);
3562 if (!ST || ST->getNumElements() != D.Struct_NumElements)
3565 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
3566 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
3571 case IITDescriptor::Argument:
3572 // Two cases here - If this is the second occurrence of an argument, verify
3573 // that the later instance matches the previous instance.
3574 if (D.getArgumentNumber() < ArgTys.size())
3575 return Ty != ArgTys[D.getArgumentNumber()];
3577 // Otherwise, if this is the first instance of an argument, record it and
3578 // verify the "Any" kind.
3579 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
3580 ArgTys.push_back(Ty);
3582 switch (D.getArgumentKind()) {
3583 case IITDescriptor::AK_Any: return false; // Success
3584 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
3585 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
3586 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
3587 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
3589 llvm_unreachable("all argument kinds not covered");
3591 case IITDescriptor::ExtendArgument: {
3592 // This may only be used when referring to a previous vector argument.
3593 if (D.getArgumentNumber() >= ArgTys.size())
3596 Type *NewTy = ArgTys[D.getArgumentNumber()];
3597 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3598 NewTy = VectorType::getExtendedElementVectorType(VTy);
3599 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3600 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
3606 case IITDescriptor::TruncArgument: {
3607 // This may only be used when referring to a previous vector argument.
3608 if (D.getArgumentNumber() >= ArgTys.size())
3611 Type *NewTy = ArgTys[D.getArgumentNumber()];
3612 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3613 NewTy = VectorType::getTruncatedElementVectorType(VTy);
3614 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3615 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3621 case IITDescriptor::HalfVecArgument:
3622 // This may only be used when referring to a previous vector argument.
3623 return D.getArgumentNumber() >= ArgTys.size() ||
3624 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3625 VectorType::getHalfElementsVectorType(
3626 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3627 case IITDescriptor::SameVecWidthArgument: {
3628 if (D.getArgumentNumber() >= ArgTys.size())
3630 VectorType * ReferenceType =
3631 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3632 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3633 if (!ThisArgType || !ReferenceType ||
3634 (ReferenceType->getVectorNumElements() !=
3635 ThisArgType->getVectorNumElements()))
3637 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3640 case IITDescriptor::PtrToArgument: {
3641 if (D.getArgumentNumber() >= ArgTys.size())
3643 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3644 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3645 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3647 case IITDescriptor::VecOfPtrsToElt: {
3648 if (D.getArgumentNumber() >= ArgTys.size())
3650 VectorType * ReferenceType =
3651 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3652 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3653 if (!ThisArgVecTy || !ReferenceType ||
3654 (ReferenceType->getVectorNumElements() !=
3655 ThisArgVecTy->getVectorNumElements()))
3657 PointerType *ThisArgEltTy =
3658 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3661 return ThisArgEltTy->getElementType() !=
3662 ReferenceType->getVectorElementType();
3665 llvm_unreachable("unhandled");
3668 /// \brief Verify if the intrinsic has variable arguments.
3669 /// This method is intended to be called after all the fixed arguments have been
3672 /// This method returns true on error and does not print an error message.
3674 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3675 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3676 using namespace Intrinsic;
3678 // If there are no descriptors left, then it can't be a vararg.
3682 // There should be only one descriptor remaining at this point.
3683 if (Infos.size() != 1)
3686 // Check and verify the descriptor.
3687 IITDescriptor D = Infos.front();
3688 Infos = Infos.slice(1);
3689 if (D.Kind == IITDescriptor::VarArg)
3695 /// Allow intrinsics to be verified in different ways.
3696 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
3697 Function *IF = CS.getCalledFunction();
3698 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3701 // Verify that the intrinsic prototype lines up with what the .td files
3703 FunctionType *IFTy = IF->getFunctionType();
3704 bool IsVarArg = IFTy->isVarArg();
3706 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3707 getIntrinsicInfoTableEntries(ID, Table);
3708 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3710 SmallVector<Type *, 4> ArgTys;
3711 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3712 "Intrinsic has incorrect return type!", IF);
3713 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3714 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3715 "Intrinsic has incorrect argument type!", IF);
3717 // Verify if the intrinsic call matches the vararg property.
3719 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3720 "Intrinsic was not defined with variable arguments!", IF);
3722 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3723 "Callsite was not defined with variable arguments!", IF);
3725 // All descriptors should be absorbed by now.
3726 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3728 // Now that we have the intrinsic ID and the actual argument types (and we
3729 // know they are legal for the intrinsic!) get the intrinsic name through the
3730 // usual means. This allows us to verify the mangling of argument types into
3732 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3733 Assert(ExpectedName == IF->getName(),
3734 "Intrinsic name not mangled correctly for type arguments! "
3739 // If the intrinsic takes MDNode arguments, verify that they are either global
3740 // or are local to *this* function.
3741 for (Value *V : CS.args())
3742 if (auto *MD = dyn_cast<MetadataAsValue>(V))
3743 visitMetadataAsValue(*MD, CS.getCaller());
3748 case Intrinsic::ctlz: // llvm.ctlz
3749 case Intrinsic::cttz: // llvm.cttz
3750 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3751 "is_zero_undef argument of bit counting intrinsics must be a "
3755 case Intrinsic::dbg_declare: // llvm.dbg.declare
3756 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
3757 "invalid llvm.dbg.declare intrinsic call 1", CS);
3758 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction()));
3760 case Intrinsic::dbg_value: // llvm.dbg.value
3761 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction()));
3763 case Intrinsic::memcpy:
3764 case Intrinsic::memmove:
3765 case Intrinsic::memset: {
3766 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
3768 "alignment argument of memory intrinsics must be a constant int",
3770 const APInt &AlignVal = AlignCI->getValue();
3771 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3772 "alignment argument of memory intrinsics must be a power of 2", CS);
3773 Assert(isa<ConstantInt>(CS.getArgOperand(4)),
3774 "isvolatile argument of memory intrinsics must be a constant int",
3778 case Intrinsic::gcroot:
3779 case Intrinsic::gcwrite:
3780 case Intrinsic::gcread:
3781 if (ID == Intrinsic::gcroot) {
3783 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts());
3784 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
3785 Assert(isa<Constant>(CS.getArgOperand(1)),
3786 "llvm.gcroot parameter #2 must be a constant.", CS);
3787 if (!AI->getAllocatedType()->isPointerTy()) {
3788 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
3789 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3790 "or argument #2 must be a non-null constant.",
3795 Assert(CS.getParent()->getParent()->hasGC(),
3796 "Enclosing function does not use GC.", CS);
3798 case Intrinsic::init_trampoline:
3799 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
3800 "llvm.init_trampoline parameter #2 must resolve to a function.",
3803 case Intrinsic::prefetch:
3804 Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
3805 isa<ConstantInt>(CS.getArgOperand(2)) &&
3806 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
3807 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
3808 "invalid arguments to llvm.prefetch", CS);
3810 case Intrinsic::stackprotector:
3811 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
3812 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
3814 case Intrinsic::lifetime_start:
3815 case Intrinsic::lifetime_end:
3816 case Intrinsic::invariant_start:
3817 Assert(isa<ConstantInt>(CS.getArgOperand(0)),
3818 "size argument of memory use markers must be a constant integer",
3821 case Intrinsic::invariant_end:
3822 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3823 "llvm.invariant.end parameter #2 must be a constant integer", CS);
3826 case Intrinsic::localescape: {
3827 BasicBlock *BB = CS.getParent();
3828 Assert(BB == &BB->getParent()->front(),
3829 "llvm.localescape used outside of entry block", CS);
3830 Assert(!SawFrameEscape,
3831 "multiple calls to llvm.localescape in one function", CS);
3832 for (Value *Arg : CS.args()) {
3833 if (isa<ConstantPointerNull>(Arg))
3834 continue; // Null values are allowed as placeholders.
3835 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3836 Assert(AI && AI->isStaticAlloca(),
3837 "llvm.localescape only accepts static allocas", CS);
3839 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
3840 SawFrameEscape = true;
3843 case Intrinsic::localrecover: {
3844 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
3845 Function *Fn = dyn_cast<Function>(FnArg);
3846 Assert(Fn && !Fn->isDeclaration(),
3847 "llvm.localrecover first "
3848 "argument must be function defined in this module",
3850 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
3851 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
3853 auto &Entry = FrameEscapeInfo[Fn];
3854 Entry.second = unsigned(
3855 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3859 case Intrinsic::experimental_gc_statepoint:
3860 Assert(!CS.isInlineAsm(),
3861 "gc.statepoint support for inline assembly unimplemented", CS);
3862 Assert(CS.getParent()->getParent()->hasGC(),
3863 "Enclosing function does not use GC.", CS);
3865 VerifyStatepoint(CS);
3867 case Intrinsic::experimental_gc_result: {
3868 Assert(CS.getParent()->getParent()->hasGC(),
3869 "Enclosing function does not use GC.", CS);
3870 // Are we tied to a statepoint properly?
3871 CallSite StatepointCS(CS.getArgOperand(0));
3872 const Function *StatepointFn =
3873 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3874 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3875 StatepointFn->getIntrinsicID() ==
3876 Intrinsic::experimental_gc_statepoint,
3877 "gc.result operand #1 must be from a statepoint", CS,
3878 CS.getArgOperand(0));
3880 // Assert that result type matches wrapped callee.
3881 const Value *Target = StatepointCS.getArgument(2);
3882 auto *PT = cast<PointerType>(Target->getType());
3883 auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
3884 Assert(CS.getType() == TargetFuncType->getReturnType(),
3885 "gc.result result type does not match wrapped callee", CS);
3888 case Intrinsic::experimental_gc_relocate: {
3889 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
3891 Assert(isa<PointerType>(CS.getType()->getScalarType()),
3892 "gc.relocate must return a pointer or a vector of pointers", CS);
3894 // Check that this relocate is correctly tied to the statepoint
3896 // This is case for relocate on the unwinding path of an invoke statepoint
3897 if (LandingPadInst *LandingPad =
3898 dyn_cast<LandingPadInst>(CS.getArgOperand(0))) {
3900 const BasicBlock *InvokeBB =
3901 LandingPad->getParent()->getUniquePredecessor();
3903 // Landingpad relocates should have only one predecessor with invoke
3904 // statepoint terminator
3905 Assert(InvokeBB, "safepoints should have unique landingpads",
3906 LandingPad->getParent());
3907 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
3909 Assert(isStatepoint(InvokeBB->getTerminator()),
3910 "gc relocate should be linked to a statepoint", InvokeBB);
3913 // In all other cases relocate should be tied to the statepoint directly.
3914 // This covers relocates on a normal return path of invoke statepoint and
3915 // relocates of a call statepoint
3916 auto Token = CS.getArgOperand(0);
3917 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3918 "gc relocate is incorrectly tied to the statepoint", CS, Token);
3921 // Verify rest of the relocate arguments
3923 ImmutableCallSite StatepointCS(
3924 cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint());
3926 // Both the base and derived must be piped through the safepoint
3927 Value* Base = CS.getArgOperand(1);
3928 Assert(isa<ConstantInt>(Base),
3929 "gc.relocate operand #2 must be integer offset", CS);
3931 Value* Derived = CS.getArgOperand(2);
3932 Assert(isa<ConstantInt>(Derived),
3933 "gc.relocate operand #3 must be integer offset", CS);
3935 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3936 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3938 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3939 "gc.relocate: statepoint base index out of bounds", CS);
3940 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3941 "gc.relocate: statepoint derived index out of bounds", CS);
3943 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3944 // section of the statepoint's argument
3945 Assert(StatepointCS.arg_size() > 0,
3946 "gc.statepoint: insufficient arguments");
3947 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
3948 "gc.statement: number of call arguments must be constant integer");
3949 const unsigned NumCallArgs =
3950 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
3951 Assert(StatepointCS.arg_size() > NumCallArgs + 5,
3952 "gc.statepoint: mismatch in number of call arguments");
3953 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
3954 "gc.statepoint: number of transition arguments must be "
3955 "a constant integer");
3956 const int NumTransitionArgs =
3957 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
3959 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
3960 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
3961 "gc.statepoint: number of deoptimization arguments must be "
3962 "a constant integer");
3963 const int NumDeoptArgs =
3964 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))->getZExtValue();
3965 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
3966 const int GCParamArgsEnd = StatepointCS.arg_size();
3967 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3968 "gc.relocate: statepoint base index doesn't fall within the "
3969 "'gc parameters' section of the statepoint call",
3971 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3972 "gc.relocate: statepoint derived index doesn't fall within the "
3973 "'gc parameters' section of the statepoint call",
3976 // Relocated value must be either a pointer type or vector-of-pointer type,
3977 // but gc_relocate does not need to return the same pointer type as the
3978 // relocated pointer. It can be casted to the correct type later if it's
3979 // desired. However, they must have the same address space and 'vectorness'
3980 GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction());
3981 Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(),
3982 "gc.relocate: relocated value must be a gc pointer", CS);
3984 auto ResultType = CS.getType();
3985 auto DerivedType = Relocate.getDerivedPtr()->getType();
3986 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
3987 "gc.relocate: vector relocates to vector and pointer to pointer", CS);
3988 Assert(ResultType->getPointerAddressSpace() ==
3989 DerivedType->getPointerAddressSpace(),
3990 "gc.relocate: relocating a pointer shouldn't change its address space", CS);
3993 case Intrinsic::eh_exceptioncode:
3994 case Intrinsic::eh_exceptionpointer: {
3995 Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
3996 "eh.exceptionpointer argument must be a catchpad", CS);
4002 /// \brief Carefully grab the subprogram from a local scope.
4004 /// This carefully grabs the subprogram from a local scope, avoiding the
4005 /// built-in assertions that would typically fire.
4006 static DISubprogram *getSubprogram(Metadata *LocalScope) {
4010 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
4013 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
4014 return getSubprogram(LB->getRawScope());
4016 // Just return null; broken scope chains are checked elsewhere.
4017 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
4021 template <class DbgIntrinsicTy>
4022 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
4023 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
4024 Assert(isa<ValueAsMetadata>(MD) ||
4025 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
4026 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
4027 Assert(isa<DILocalVariable>(DII.getRawVariable()),
4028 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
4029 DII.getRawVariable());
4030 Assert(isa<DIExpression>(DII.getRawExpression()),
4031 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
4032 DII.getRawExpression());
4034 // Ignore broken !dbg attachments; they're checked elsewhere.
4035 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
4036 if (!isa<DILocation>(N))
4039 BasicBlock *BB = DII.getParent();
4040 Function *F = BB ? BB->getParent() : nullptr;
4042 // The scopes for variables and !dbg attachments must agree.
4043 DILocalVariable *Var = DII.getVariable();
4044 DILocation *Loc = DII.getDebugLoc();
4045 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
4048 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
4049 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
4050 if (!VarSP || !LocSP)
4051 return; // Broken scope chains are checked elsewhere.
4053 Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
4054 " variable and !dbg attachment",
4055 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
4056 Loc->getScope()->getSubprogram());
4059 template <class MapTy>
4060 static uint64_t getVariableSize(const DILocalVariable &V, const MapTy &Map) {
4061 // Be careful of broken types (checked elsewhere).
4062 const Metadata *RawType = V.getRawType();
4064 // Try to get the size directly.
4065 if (auto *T = dyn_cast<DIType>(RawType))
4066 if (uint64_t Size = T->getSizeInBits())
4069 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
4070 // Look at the base type.
4071 RawType = DT->getRawBaseType();
4075 if (auto *S = dyn_cast<MDString>(RawType)) {
4076 // Don't error on missing types (checked elsewhere).
4077 RawType = Map.lookup(S);
4081 // Missing type or size.
4089 template <class MapTy>
4090 void Verifier::verifyDIExpression(const DbgInfoIntrinsic &I,
4091 const MapTy &TypeRefs) {
4095 uint64_t ArgumentTypeSizeInBits = 0;
4096 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
4097 Arg = DVI->getValue();
4099 ArgumentTypeSizeInBits =
4100 M->getDataLayout().getTypeAllocSizeInBits(Arg->getType());
4101 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
4102 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
4104 auto *DDI = cast<DbgDeclareInst>(&I);
4105 // For declare intrinsics, get the total size of the alloca, to allow
4106 // case where the variable may span more than one element.
4107 Arg = DDI->getAddress();
4109 Arg = Arg->stripPointerCasts();
4110 const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(Arg);
4112 // We can only say something about constant size allocations
4113 if (const ConstantInt *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
4114 ArgumentTypeSizeInBits =
4115 CI->getLimitedValue() *
4116 M->getDataLayout().getTypeAllocSizeInBits(AI->getAllocatedType());
4118 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
4119 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
4122 // We don't know whether this intrinsic verified correctly.
4123 if (!V || !E || !E->isValid())
4126 // The frontend helps out GDB by emitting the members of local anonymous
4127 // unions as artificial local variables with shared storage. When SROA splits
4128 // the storage for artificial local variables that are smaller than the entire
4129 // union, the overhang piece will be outside of the allotted space for the
4130 // variable and this check fails.
4131 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
4132 if (V->isArtificial())
4135 // If there's no size, the type is broken, but that should be checked
4137 uint64_t VarSize = getVariableSize(*V, TypeRefs);
4141 if (E->isBitPiece()) {
4142 unsigned PieceSize = E->getBitPieceSize();
4143 unsigned PieceOffset = E->getBitPieceOffset();
4144 Assert(PieceSize + PieceOffset <= VarSize,
4145 "piece is larger than or outside of variable", &I, V, E);
4146 Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
4150 if (!ArgumentTypeSizeInBits)
4151 return; // We were unable to determine the size of the argument
4153 if (E->getNumElements() == 0) {
4154 // In the case where the expression is empty, verify the size of the
4155 // argument. Doing this in the general case would require looking through
4156 // any dereferences that may be in the expression.
4157 Assert(ArgumentTypeSizeInBits == VarSize,
4158 "size of passed value (" + std::to_string(ArgumentTypeSizeInBits) +
4159 ") does not match size of declared variable (" +
4160 std::to_string(VarSize) + ")",
4161 &I, Arg, V, V->getType(), E);
4162 } else if (E->getElement(0) == dwarf::DW_OP_deref) {
4163 Assert(ArgumentTypeSizeInBits == M->getDataLayout().getPointerSizeInBits(),
4164 "the operation of the expression is a deref, but the passed value "
4165 "is not pointer sized",
4166 &I, Arg, V, V->getType(), E);
4170 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
4171 // This is in its own function so we get an error for each bad type ref (not
4173 Assert(false, "unresolved type ref", S, N);
4176 void Verifier::verifyTypeRefs() {
4177 auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
4181 // Visit all the compile units again to map the type references.
4182 SmallDenseMap<const MDString *, const DIType *, 32> TypeRefs;
4183 for (auto *CU : CUs->operands())
4184 if (auto Ts = cast<DICompileUnit>(CU)->getRetainedTypes())
4185 for (DIType *Op : Ts)
4186 if (auto *T = dyn_cast_or_null<DICompositeType>(Op))
4187 if (auto *S = T->getRawIdentifier()) {
4188 UnresolvedTypeRefs.erase(S);
4189 TypeRefs.insert(std::make_pair(S, T));
4192 // Verify debug info intrinsic bit piece expressions. This needs a second
4193 // pass through the intructions, since we haven't built TypeRefs yet when
4194 // verifying functions, and simply queuing the DbgInfoIntrinsics to evaluate
4195 // later/now would queue up some that could be later deleted.
4196 for (const Function &F : *M)
4197 for (const BasicBlock &BB : F)
4198 for (const Instruction &I : BB)
4199 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
4200 verifyDIExpression(*DII, TypeRefs);
4202 // Return early if all typerefs were resolved.
4203 if (UnresolvedTypeRefs.empty())
4206 // Sort the unresolved references by name so the output is deterministic.
4207 typedef std::pair<const MDString *, const MDNode *> TypeRef;
4208 SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
4209 UnresolvedTypeRefs.end());
4210 std::sort(Unresolved.begin(), Unresolved.end(),
4211 [](const TypeRef &LHS, const TypeRef &RHS) {
4212 return LHS.first->getString() < RHS.first->getString();
4215 // Visit the unresolved refs (printing out the errors).
4216 for (const TypeRef &TR : Unresolved)
4217 visitUnresolvedTypeRef(TR.first, TR.second);
4220 //===----------------------------------------------------------------------===//
4221 // Implement the public interfaces to this file...
4222 //===----------------------------------------------------------------------===//
4224 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
4225 Function &F = const_cast<Function &>(f);
4226 assert(!F.isDeclaration() && "Cannot verify external functions");
4228 raw_null_ostream NullStr;
4229 Verifier V(OS ? *OS : NullStr);
4231 // Note that this function's return value is inverted from what you would
4232 // expect of a function called "verify".
4233 return !V.verify(F);
4236 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
4237 raw_null_ostream NullStr;
4238 Verifier V(OS ? *OS : NullStr);