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/STLExtras.h"
49 #include "llvm/ADT/SetVector.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/IR/CFG.h"
54 #include "llvm/IR/CallSite.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/ConstantRange.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DataLayout.h"
59 #include "llvm/IR/DebugInfo.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/Dominators.h"
62 #include "llvm/IR/InlineAsm.h"
63 #include "llvm/IR/InstIterator.h"
64 #include "llvm/IR/InstVisitor.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/IR/Metadata.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/PassManager.h"
70 #include "llvm/IR/Statepoint.h"
71 #include "llvm/Pass.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
80 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
83 struct VerifierSupport {
87 /// \brief Track the brokenness of the module while recursively visiting.
90 explicit VerifierSupport(raw_ostream &OS)
91 : OS(OS), M(nullptr), Broken(false) {}
94 template <class NodeTy> void Write(const ilist_iterator<NodeTy> &I) {
98 void Write(const Value *V) {
101 if (isa<Instruction>(V)) {
104 V->printAsOperand(OS, true, M);
108 void Write(ImmutableCallSite CS) {
109 Write(CS.getInstruction());
112 void Write(const Metadata *MD) {
119 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) {
123 void Write(const NamedMDNode *NMD) {
130 void Write(Type *T) {
136 void Write(const Comdat *C) {
142 template <typename T1, typename... Ts>
143 void WriteTs(const T1 &V1, const Ts &... Vs) {
148 template <typename... Ts> void WriteTs() {}
151 /// \brief A check failed, so printout out the condition and the message.
153 /// This provides a nice place to put a breakpoint if you want to see why
154 /// something is not correct.
155 void CheckFailed(const Twine &Message) {
156 OS << Message << '\n';
160 /// \brief A check failed (with values to print).
162 /// This calls the Message-only version so that the above is easier to set a
164 template <typename T1, typename... Ts>
165 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
166 CheckFailed(Message);
171 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
172 friend class InstVisitor<Verifier>;
174 LLVMContext *Context;
177 /// \brief When verifying a basic block, keep track of all of the
178 /// instructions we have seen so far.
180 /// This allows us to do efficient dominance checks for the case when an
181 /// instruction has an operand that is an instruction in the same block.
182 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
184 /// \brief Keep track of the metadata nodes that have been checked already.
185 SmallPtrSet<const Metadata *, 32> MDNodes;
187 /// \brief Track unresolved string-based type references.
188 SmallDenseMap<const MDString *, const MDNode *, 32> UnresolvedTypeRefs;
190 /// \brief The result type for a landingpad.
191 Type *LandingPadResultTy;
193 /// \brief Whether we've seen a call to @llvm.localescape in this function
197 /// Stores the count of how many objects were passed to llvm.localescape for a
198 /// given function and the largest index passed to llvm.localrecover.
199 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
202 explicit Verifier(raw_ostream &OS)
203 : VerifierSupport(OS), Context(nullptr), LandingPadResultTy(nullptr),
204 SawFrameEscape(false) {}
206 bool verify(const Function &F) {
208 Context = &M->getContext();
210 // First ensure the function is well-enough formed to compute dominance
213 OS << "Function '" << F.getName()
214 << "' does not contain an entry block!\n";
217 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
218 if (I->empty() || !I->back().isTerminator()) {
219 OS << "Basic Block in function '" << F.getName()
220 << "' does not have terminator!\n";
221 I->printAsOperand(OS, true);
227 // Now directly compute a dominance tree. We don't rely on the pass
228 // manager to provide this as it isolates us from a potentially
229 // out-of-date dominator tree and makes it significantly more complex to
230 // run this code outside of a pass manager.
231 // FIXME: It's really gross that we have to cast away constness here.
232 DT.recalculate(const_cast<Function &>(F));
235 // FIXME: We strip const here because the inst visitor strips const.
236 visit(const_cast<Function &>(F));
237 InstsInThisBlock.clear();
238 LandingPadResultTy = nullptr;
239 SawFrameEscape = false;
244 bool verify(const Module &M) {
246 Context = &M.getContext();
249 // Scan through, checking all of the external function's linkage now...
250 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
251 visitGlobalValue(*I);
253 // Check to make sure function prototypes are okay.
254 if (I->isDeclaration())
258 // Now that we've visited every function, verify that we never asked to
259 // recover a frame index that wasn't escaped.
260 verifyFrameRecoverIndices();
262 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
264 visitGlobalVariable(*I);
266 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
268 visitGlobalAlias(*I);
270 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
271 E = M.named_metadata_end();
273 visitNamedMDNode(*I);
275 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
276 visitComdat(SMEC.getValue());
279 visitModuleIdents(M);
281 // Verify type referneces last.
288 // Verification methods...
289 void visitGlobalValue(const GlobalValue &GV);
290 void visitGlobalVariable(const GlobalVariable &GV);
291 void visitGlobalAlias(const GlobalAlias &GA);
292 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
293 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
294 const GlobalAlias &A, const Constant &C);
295 void visitNamedMDNode(const NamedMDNode &NMD);
296 void visitMDNode(const MDNode &MD);
297 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
298 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
299 void visitComdat(const Comdat &C);
300 void visitModuleIdents(const Module &M);
301 void visitModuleFlags(const Module &M);
302 void visitModuleFlag(const MDNode *Op,
303 DenseMap<const MDString *, const MDNode *> &SeenIDs,
304 SmallVectorImpl<const MDNode *> &Requirements);
305 void visitFunction(const Function &F);
306 void visitBasicBlock(BasicBlock &BB);
307 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
308 void visitDereferenceableMetadata(Instruction& I, MDNode* MD);
310 template <class Ty> bool isValidMetadataArray(const MDTuple &N);
311 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
312 #include "llvm/IR/Metadata.def"
313 void visitDIScope(const DIScope &N);
314 void visitDIVariable(const DIVariable &N);
315 void visitDILexicalBlockBase(const DILexicalBlockBase &N);
316 void visitDITemplateParameter(const DITemplateParameter &N);
318 void visitTemplateParams(const MDNode &N, const Metadata &RawParams);
320 /// \brief Check for a valid string-based type reference.
322 /// Checks if \c MD is a string-based type reference. If it is, keeps track
323 /// of it (and its user, \c N) for error messages later.
324 bool isValidUUID(const MDNode &N, const Metadata *MD);
326 /// \brief Check for a valid type reference.
328 /// Checks for subclasses of \a DIType, or \a isValidUUID().
329 bool isTypeRef(const MDNode &N, const Metadata *MD);
331 /// \brief Check for a valid scope reference.
333 /// Checks for subclasses of \a DIScope, or \a isValidUUID().
334 bool isScopeRef(const MDNode &N, const Metadata *MD);
336 /// \brief Check for a valid debug info reference.
338 /// Checks for subclasses of \a DINode, or \a isValidUUID().
339 bool isDIRef(const MDNode &N, const Metadata *MD);
341 // InstVisitor overrides...
342 using InstVisitor<Verifier>::visit;
343 void visit(Instruction &I);
345 void visitTruncInst(TruncInst &I);
346 void visitZExtInst(ZExtInst &I);
347 void visitSExtInst(SExtInst &I);
348 void visitFPTruncInst(FPTruncInst &I);
349 void visitFPExtInst(FPExtInst &I);
350 void visitFPToUIInst(FPToUIInst &I);
351 void visitFPToSIInst(FPToSIInst &I);
352 void visitUIToFPInst(UIToFPInst &I);
353 void visitSIToFPInst(SIToFPInst &I);
354 void visitIntToPtrInst(IntToPtrInst &I);
355 void visitPtrToIntInst(PtrToIntInst &I);
356 void visitBitCastInst(BitCastInst &I);
357 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
358 void visitPHINode(PHINode &PN);
359 void visitBinaryOperator(BinaryOperator &B);
360 void visitICmpInst(ICmpInst &IC);
361 void visitFCmpInst(FCmpInst &FC);
362 void visitExtractElementInst(ExtractElementInst &EI);
363 void visitInsertElementInst(InsertElementInst &EI);
364 void visitShuffleVectorInst(ShuffleVectorInst &EI);
365 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
366 void visitCallInst(CallInst &CI);
367 void visitInvokeInst(InvokeInst &II);
368 void visitGetElementPtrInst(GetElementPtrInst &GEP);
369 void visitLoadInst(LoadInst &LI);
370 void visitStoreInst(StoreInst &SI);
371 void verifyDominatesUse(Instruction &I, unsigned i);
372 void visitInstruction(Instruction &I);
373 void visitTerminatorInst(TerminatorInst &I);
374 void visitBranchInst(BranchInst &BI);
375 void visitReturnInst(ReturnInst &RI);
376 void visitSwitchInst(SwitchInst &SI);
377 void visitIndirectBrInst(IndirectBrInst &BI);
378 void visitSelectInst(SelectInst &SI);
379 void visitUserOp1(Instruction &I);
380 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
381 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS);
382 template <class DbgIntrinsicTy>
383 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
384 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
385 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
386 void visitFenceInst(FenceInst &FI);
387 void visitAllocaInst(AllocaInst &AI);
388 void visitExtractValueInst(ExtractValueInst &EVI);
389 void visitInsertValueInst(InsertValueInst &IVI);
390 void visitEHPadPredecessors(Instruction &I);
391 void visitLandingPadInst(LandingPadInst &LPI);
392 void visitCatchPadInst(CatchPadInst &CPI);
393 void visitCatchEndPadInst(CatchEndPadInst &CEPI);
394 void visitCleanupPadInst(CleanupPadInst &CPI);
395 void visitCleanupEndPadInst(CleanupEndPadInst &CEPI);
396 void visitCleanupReturnInst(CleanupReturnInst &CRI);
397 void visitTerminatePadInst(TerminatePadInst &TPI);
399 void VerifyCallSite(CallSite CS);
400 void verifyMustTailCall(CallInst &CI);
401 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
402 unsigned ArgNo, std::string &Suffix);
403 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
404 SmallVectorImpl<Type *> &ArgTys);
405 bool VerifyIntrinsicIsVarArg(bool isVarArg,
406 ArrayRef<Intrinsic::IITDescriptor> &Infos);
407 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
408 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
410 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
411 bool isReturnValue, const Value *V);
412 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
414 void VerifyFunctionMetadata(
415 const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs);
417 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
418 void VerifyStatepoint(ImmutableCallSite CS);
419 void verifyFrameRecoverIndices();
421 // Module-level debug info verification...
422 void verifyTypeRefs();
423 template <class MapTy>
424 void verifyBitPieceExpression(const DbgInfoIntrinsic &I,
425 const MapTy &TypeRefs);
426 void visitUnresolvedTypeRef(const MDString *S, const MDNode *N);
428 } // End anonymous namespace
430 // Assert - We know that cond should be true, if not print an error message.
431 #define Assert(C, ...) \
432 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
434 void Verifier::visit(Instruction &I) {
435 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
436 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
437 InstVisitor<Verifier>::visit(I);
441 void Verifier::visitGlobalValue(const GlobalValue &GV) {
442 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
443 GV.hasExternalWeakLinkage(),
444 "Global is external, but doesn't have external or weak linkage!", &GV);
446 Assert(GV.getAlignment() <= Value::MaximumAlignment,
447 "huge alignment values are unsupported", &GV);
448 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
449 "Only global variables can have appending linkage!", &GV);
451 if (GV.hasAppendingLinkage()) {
452 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
453 Assert(GVar && GVar->getValueType()->isArrayTy(),
454 "Only global arrays can have appending linkage!", GVar);
457 if (GV.isDeclarationForLinker())
458 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV);
461 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
462 if (GV.hasInitializer()) {
463 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
464 "Global variable initializer type does not match global "
468 // If the global has common linkage, it must have a zero initializer and
469 // cannot be constant.
470 if (GV.hasCommonLinkage()) {
471 Assert(GV.getInitializer()->isNullValue(),
472 "'common' global must have a zero initializer!", &GV);
473 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
475 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
478 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
479 "invalid linkage type for global declaration", &GV);
482 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
483 GV.getName() == "llvm.global_dtors")) {
484 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
485 "invalid linkage for intrinsic global variable", &GV);
486 // Don't worry about emitting an error for it not being an array,
487 // visitGlobalValue will complain on appending non-array.
488 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) {
489 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
490 PointerType *FuncPtrTy =
491 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
492 // FIXME: Reject the 2-field form in LLVM 4.0.
494 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
495 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
496 STy->getTypeAtIndex(1) == FuncPtrTy,
497 "wrong type for intrinsic global variable", &GV);
498 if (STy->getNumElements() == 3) {
499 Type *ETy = STy->getTypeAtIndex(2);
500 Assert(ETy->isPointerTy() &&
501 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
502 "wrong type for intrinsic global variable", &GV);
507 if (GV.hasName() && (GV.getName() == "llvm.used" ||
508 GV.getName() == "llvm.compiler.used")) {
509 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
510 "invalid linkage for intrinsic global variable", &GV);
511 Type *GVType = GV.getValueType();
512 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
513 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
514 Assert(PTy, "wrong type for intrinsic global variable", &GV);
515 if (GV.hasInitializer()) {
516 const Constant *Init = GV.getInitializer();
517 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
518 Assert(InitArray, "wrong initalizer for intrinsic global variable",
520 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
521 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
522 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
524 "invalid llvm.used member", V);
525 Assert(V->hasName(), "members of llvm.used must be named", V);
531 Assert(!GV.hasDLLImportStorageClass() ||
532 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
533 GV.hasAvailableExternallyLinkage(),
534 "Global is marked as dllimport, but not external", &GV);
536 if (!GV.hasInitializer()) {
537 visitGlobalValue(GV);
541 // Walk any aggregate initializers looking for bitcasts between address spaces
542 SmallPtrSet<const Value *, 4> Visited;
543 SmallVector<const Value *, 4> WorkStack;
544 WorkStack.push_back(cast<Value>(GV.getInitializer()));
546 while (!WorkStack.empty()) {
547 const Value *V = WorkStack.pop_back_val();
548 if (!Visited.insert(V).second)
551 if (const User *U = dyn_cast<User>(V)) {
552 WorkStack.append(U->op_begin(), U->op_end());
555 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
556 VerifyConstantExprBitcastType(CE);
562 visitGlobalValue(GV);
565 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
566 SmallPtrSet<const GlobalAlias*, 4> Visited;
568 visitAliaseeSubExpr(Visited, GA, C);
571 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
572 const GlobalAlias &GA, const Constant &C) {
573 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
574 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition",
577 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
578 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
580 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
583 // Only continue verifying subexpressions of GlobalAliases.
584 // Do not recurse into global initializers.
589 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
590 VerifyConstantExprBitcastType(CE);
592 for (const Use &U : C.operands()) {
594 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
595 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
596 else if (const auto *C2 = dyn_cast<Constant>(V))
597 visitAliaseeSubExpr(Visited, GA, *C2);
601 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
602 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
603 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
604 "weak_odr, or external linkage!",
606 const Constant *Aliasee = GA.getAliasee();
607 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
608 Assert(GA.getType() == Aliasee->getType(),
609 "Alias and aliasee types should match!", &GA);
611 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
612 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
614 visitAliaseeSubExpr(GA, *Aliasee);
616 visitGlobalValue(GA);
619 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
620 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
621 MDNode *MD = NMD.getOperand(i);
623 if (NMD.getName() == "llvm.dbg.cu") {
624 Assert(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD);
634 void Verifier::visitMDNode(const MDNode &MD) {
635 // Only visit each node once. Metadata can be mutually recursive, so this
636 // avoids infinite recursion here, as well as being an optimization.
637 if (!MDNodes.insert(&MD).second)
640 switch (MD.getMetadataID()) {
642 llvm_unreachable("Invalid MDNode subclass");
643 case Metadata::MDTupleKind:
645 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
646 case Metadata::CLASS##Kind: \
647 visit##CLASS(cast<CLASS>(MD)); \
649 #include "llvm/IR/Metadata.def"
652 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
653 Metadata *Op = MD.getOperand(i);
656 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
658 if (auto *N = dyn_cast<MDNode>(Op)) {
662 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
663 visitValueAsMetadata(*V, nullptr);
668 // Check these last, so we diagnose problems in operands first.
669 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
670 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
673 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
674 Assert(MD.getValue(), "Expected valid value", &MD);
675 Assert(!MD.getValue()->getType()->isMetadataTy(),
676 "Unexpected metadata round-trip through values", &MD, MD.getValue());
678 auto *L = dyn_cast<LocalAsMetadata>(&MD);
682 Assert(F, "function-local metadata used outside a function", L);
684 // If this was an instruction, bb, or argument, verify that it is in the
685 // function that we expect.
686 Function *ActualF = nullptr;
687 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
688 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
689 ActualF = I->getParent()->getParent();
690 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
691 ActualF = BB->getParent();
692 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
693 ActualF = A->getParent();
694 assert(ActualF && "Unimplemented function local metadata case!");
696 Assert(ActualF == F, "function-local metadata used in wrong function", L);
699 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
700 Metadata *MD = MDV.getMetadata();
701 if (auto *N = dyn_cast<MDNode>(MD)) {
706 // Only visit each node once. Metadata can be mutually recursive, so this
707 // avoids infinite recursion here, as well as being an optimization.
708 if (!MDNodes.insert(MD).second)
711 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
712 visitValueAsMetadata(*V, F);
715 bool Verifier::isValidUUID(const MDNode &N, const Metadata *MD) {
716 auto *S = dyn_cast<MDString>(MD);
719 if (S->getString().empty())
722 // Keep track of names of types referenced via UUID so we can check that they
724 UnresolvedTypeRefs.insert(std::make_pair(S, &N));
728 /// \brief Check if a value can be a reference to a type.
729 bool Verifier::isTypeRef(const MDNode &N, const Metadata *MD) {
730 return !MD || isValidUUID(N, MD) || isa<DIType>(MD);
733 /// \brief Check if a value can be a ScopeRef.
734 bool Verifier::isScopeRef(const MDNode &N, const Metadata *MD) {
735 return !MD || isValidUUID(N, MD) || isa<DIScope>(MD);
738 /// \brief Check if a value can be a debug info ref.
739 bool Verifier::isDIRef(const MDNode &N, const Metadata *MD) {
740 return !MD || isValidUUID(N, MD) || isa<DINode>(MD);
744 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) {
745 for (Metadata *MD : N.operands()) {
758 bool isValidMetadataArray(const MDTuple &N) {
759 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false);
763 bool isValidMetadataNullArray(const MDTuple &N) {
764 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true);
767 void Verifier::visitDILocation(const DILocation &N) {
768 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
769 "location requires a valid scope", &N, N.getRawScope());
770 if (auto *IA = N.getRawInlinedAt())
771 Assert(isa<DILocation>(IA), "inlined-at should be a location", &N, IA);
774 void Verifier::visitGenericDINode(const GenericDINode &N) {
775 Assert(N.getTag(), "invalid tag", &N);
778 void Verifier::visitDIScope(const DIScope &N) {
779 if (auto *F = N.getRawFile())
780 Assert(isa<DIFile>(F), "invalid file", &N, F);
783 void Verifier::visitDISubrange(const DISubrange &N) {
784 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
785 Assert(N.getCount() >= -1, "invalid subrange count", &N);
788 void Verifier::visitDIEnumerator(const DIEnumerator &N) {
789 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
792 void Verifier::visitDIBasicType(const DIBasicType &N) {
793 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
794 N.getTag() == dwarf::DW_TAG_unspecified_type,
798 void Verifier::visitDIDerivedType(const DIDerivedType &N) {
799 // Common scope checks.
802 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
803 N.getTag() == dwarf::DW_TAG_pointer_type ||
804 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
805 N.getTag() == dwarf::DW_TAG_reference_type ||
806 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
807 N.getTag() == dwarf::DW_TAG_const_type ||
808 N.getTag() == dwarf::DW_TAG_volatile_type ||
809 N.getTag() == dwarf::DW_TAG_restrict_type ||
810 N.getTag() == dwarf::DW_TAG_member ||
811 N.getTag() == dwarf::DW_TAG_inheritance ||
812 N.getTag() == dwarf::DW_TAG_friend,
814 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
815 Assert(isTypeRef(N, N.getExtraData()), "invalid pointer to member type", &N,
819 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
820 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
824 static bool hasConflictingReferenceFlags(unsigned Flags) {
825 return (Flags & DINode::FlagLValueReference) &&
826 (Flags & DINode::FlagRValueReference);
829 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) {
830 auto *Params = dyn_cast<MDTuple>(&RawParams);
831 Assert(Params, "invalid template params", &N, &RawParams);
832 for (Metadata *Op : Params->operands()) {
833 Assert(Op && isa<DITemplateParameter>(Op), "invalid template parameter", &N,
838 void Verifier::visitDICompositeType(const DICompositeType &N) {
839 // Common scope checks.
842 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
843 N.getTag() == dwarf::DW_TAG_structure_type ||
844 N.getTag() == dwarf::DW_TAG_union_type ||
845 N.getTag() == dwarf::DW_TAG_enumeration_type ||
846 N.getTag() == dwarf::DW_TAG_class_type,
849 Assert(isScopeRef(N, N.getScope()), "invalid scope", &N, N.getScope());
850 Assert(isTypeRef(N, N.getBaseType()), "invalid base type", &N,
853 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
854 "invalid composite elements", &N, N.getRawElements());
855 Assert(isTypeRef(N, N.getRawVTableHolder()), "invalid vtable holder", &N,
856 N.getRawVTableHolder());
857 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
858 "invalid composite elements", &N, N.getRawElements());
859 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
861 if (auto *Params = N.getRawTemplateParams())
862 visitTemplateParams(N, *Params);
864 if (N.getTag() == dwarf::DW_TAG_class_type ||
865 N.getTag() == dwarf::DW_TAG_union_type) {
866 Assert(N.getFile() && !N.getFile()->getFilename().empty(),
867 "class/union requires a filename", &N, N.getFile());
871 void Verifier::visitDISubroutineType(const DISubroutineType &N) {
872 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
873 if (auto *Types = N.getRawTypeArray()) {
874 Assert(isa<MDTuple>(Types), "invalid composite elements", &N, Types);
875 for (Metadata *Ty : N.getTypeArray()->operands()) {
876 Assert(isTypeRef(N, Ty), "invalid subroutine type ref", &N, Types, Ty);
879 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
883 void Verifier::visitDIFile(const DIFile &N) {
884 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
887 void Verifier::visitDICompileUnit(const DICompileUnit &N) {
888 Assert(N.isDistinct(), "compile units must be distinct", &N);
889 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
891 // Don't bother verifying the compilation directory or producer string
892 // as those could be empty.
893 Assert(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N,
895 Assert(!N.getFile()->getFilename().empty(), "invalid filename", &N,
898 if (auto *Array = N.getRawEnumTypes()) {
899 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
900 for (Metadata *Op : N.getEnumTypes()->operands()) {
901 auto *Enum = dyn_cast_or_null<DICompositeType>(Op);
902 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
903 "invalid enum type", &N, N.getEnumTypes(), Op);
906 if (auto *Array = N.getRawRetainedTypes()) {
907 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
908 for (Metadata *Op : N.getRetainedTypes()->operands()) {
909 Assert(Op && isa<DIType>(Op), "invalid retained type", &N, Op);
912 if (auto *Array = N.getRawSubprograms()) {
913 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
914 for (Metadata *Op : N.getSubprograms()->operands()) {
915 Assert(Op && isa<DISubprogram>(Op), "invalid subprogram ref", &N, Op);
918 if (auto *Array = N.getRawGlobalVariables()) {
919 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
920 for (Metadata *Op : N.getGlobalVariables()->operands()) {
921 Assert(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", &N,
925 if (auto *Array = N.getRawImportedEntities()) {
926 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
927 for (Metadata *Op : N.getImportedEntities()->operands()) {
928 Assert(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", &N,
934 void Verifier::visitDISubprogram(const DISubprogram &N) {
935 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
936 Assert(isScopeRef(N, N.getRawScope()), "invalid scope", &N, N.getRawScope());
937 if (auto *T = N.getRawType())
938 Assert(isa<DISubroutineType>(T), "invalid subroutine type", &N, T);
939 Assert(isTypeRef(N, N.getRawContainingType()), "invalid containing type", &N,
940 N.getRawContainingType());
941 if (auto *Params = N.getRawTemplateParams())
942 visitTemplateParams(N, *Params);
943 if (auto *S = N.getRawDeclaration()) {
944 Assert(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
945 "invalid subprogram declaration", &N, S);
947 if (auto *RawVars = N.getRawVariables()) {
948 auto *Vars = dyn_cast<MDTuple>(RawVars);
949 Assert(Vars, "invalid variable list", &N, RawVars);
950 for (Metadata *Op : Vars->operands()) {
951 Assert(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, Vars,
955 Assert(!hasConflictingReferenceFlags(N.getFlags()), "invalid reference flags",
958 if (N.isDefinition())
959 Assert(N.isDistinct(), "subprogram definitions must be distinct", &N);
962 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) {
963 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
964 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
965 "invalid local scope", &N, N.getRawScope());
968 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) {
969 visitDILexicalBlockBase(N);
971 Assert(N.getLine() || !N.getColumn(),
972 "cannot have column info without line info", &N);
975 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) {
976 visitDILexicalBlockBase(N);
979 void Verifier::visitDINamespace(const DINamespace &N) {
980 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
981 if (auto *S = N.getRawScope())
982 Assert(isa<DIScope>(S), "invalid scope ref", &N, S);
985 void Verifier::visitDIModule(const DIModule &N) {
986 Assert(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N);
987 Assert(!N.getName().empty(), "anonymous module", &N);
990 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) {
991 Assert(isTypeRef(N, N.getType()), "invalid type ref", &N, N.getType());
994 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) {
995 visitDITemplateParameter(N);
997 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
1001 void Verifier::visitDITemplateValueParameter(
1002 const DITemplateValueParameter &N) {
1003 visitDITemplateParameter(N);
1005 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1006 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1007 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1011 void Verifier::visitDIVariable(const DIVariable &N) {
1012 if (auto *S = N.getRawScope())
1013 Assert(isa<DIScope>(S), "invalid scope", &N, S);
1014 Assert(isTypeRef(N, N.getRawType()), "invalid type ref", &N, N.getRawType());
1015 if (auto *F = N.getRawFile())
1016 Assert(isa<DIFile>(F), "invalid file", &N, F);
1019 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) {
1020 // Checks common to all variables.
1023 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1024 Assert(!N.getName().empty(), "missing global variable name", &N);
1025 if (auto *V = N.getRawVariable()) {
1026 Assert(isa<ConstantAsMetadata>(V) &&
1027 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
1028 "invalid global varaible ref", &N, V);
1030 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
1031 Assert(isa<DIDerivedType>(Member), "invalid static data member declaration",
1036 void Verifier::visitDILocalVariable(const DILocalVariable &N) {
1037 // Checks common to all variables.
1040 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
1041 Assert(N.getRawScope() && isa<DILocalScope>(N.getRawScope()),
1042 "local variable requires a valid scope", &N, N.getRawScope());
1045 void Verifier::visitDIExpression(const DIExpression &N) {
1046 Assert(N.isValid(), "invalid expression", &N);
1049 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) {
1050 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
1051 if (auto *T = N.getRawType())
1052 Assert(isTypeRef(N, T), "invalid type ref", &N, T);
1053 if (auto *F = N.getRawFile())
1054 Assert(isa<DIFile>(F), "invalid file", &N, F);
1057 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) {
1058 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
1059 N.getTag() == dwarf::DW_TAG_imported_declaration,
1061 if (auto *S = N.getRawScope())
1062 Assert(isa<DIScope>(S), "invalid scope for imported entity", &N, S);
1063 Assert(isDIRef(N, N.getEntity()), "invalid imported entity", &N,
1067 void Verifier::visitComdat(const Comdat &C) {
1068 // The Module is invalid if the GlobalValue has private linkage. Entities
1069 // with private linkage don't have entries in the symbol table.
1070 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
1071 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
1075 void Verifier::visitModuleIdents(const Module &M) {
1076 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
1080 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1081 // Scan each llvm.ident entry and make sure that this requirement is met.
1082 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
1083 const MDNode *N = Idents->getOperand(i);
1084 Assert(N->getNumOperands() == 1,
1085 "incorrect number of operands in llvm.ident metadata", N);
1086 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
1087 ("invalid value for llvm.ident metadata entry operand"
1088 "(the operand should be a string)"),
1093 void Verifier::visitModuleFlags(const Module &M) {
1094 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
1097 // Scan each flag, and track the flags and requirements.
1098 DenseMap<const MDString*, const MDNode*> SeenIDs;
1099 SmallVector<const MDNode*, 16> Requirements;
1100 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
1101 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
1104 // Validate that the requirements in the module are valid.
1105 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1106 const MDNode *Requirement = Requirements[I];
1107 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1108 const Metadata *ReqValue = Requirement->getOperand(1);
1110 const MDNode *Op = SeenIDs.lookup(Flag);
1112 CheckFailed("invalid requirement on flag, flag is not present in module",
1117 if (Op->getOperand(2) != ReqValue) {
1118 CheckFailed(("invalid requirement on flag, "
1119 "flag does not have the required value"),
1127 Verifier::visitModuleFlag(const MDNode *Op,
1128 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1129 SmallVectorImpl<const MDNode *> &Requirements) {
1130 // Each module flag should have three arguments, the merge behavior (a
1131 // constant int), the flag ID (an MDString), and the value.
1132 Assert(Op->getNumOperands() == 3,
1133 "incorrect number of operands in module flag", Op);
1134 Module::ModFlagBehavior MFB;
1135 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
1137 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
1138 "invalid behavior operand in module flag (expected constant integer)",
1141 "invalid behavior operand in module flag (unexpected constant)",
1144 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
1145 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
1148 // Sanity check the values for behaviors with additional requirements.
1151 case Module::Warning:
1152 case Module::Override:
1153 // These behavior types accept any value.
1156 case Module::Require: {
1157 // The value should itself be an MDNode with two operands, a flag ID (an
1158 // MDString), and a value.
1159 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
1160 Assert(Value && Value->getNumOperands() == 2,
1161 "invalid value for 'require' module flag (expected metadata pair)",
1163 Assert(isa<MDString>(Value->getOperand(0)),
1164 ("invalid value for 'require' module flag "
1165 "(first value operand should be a string)"),
1166 Value->getOperand(0));
1168 // Append it to the list of requirements, to check once all module flags are
1170 Requirements.push_back(Value);
1174 case Module::Append:
1175 case Module::AppendUnique: {
1176 // These behavior types require the operand be an MDNode.
1177 Assert(isa<MDNode>(Op->getOperand(2)),
1178 "invalid value for 'append'-type module flag "
1179 "(expected a metadata node)",
1185 // Unless this is a "requires" flag, check the ID is unique.
1186 if (MFB != Module::Require) {
1187 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1189 "module flag identifiers must be unique (or of 'require' type)", ID);
1193 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1194 bool isFunction, const Value *V) {
1195 unsigned Slot = ~0U;
1196 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1197 if (Attrs.getSlotIndex(I) == Idx) {
1202 assert(Slot != ~0U && "Attribute set inconsistency!");
1204 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1206 if (I->isStringAttribute())
1209 if (I->getKindAsEnum() == Attribute::NoReturn ||
1210 I->getKindAsEnum() == Attribute::NoUnwind ||
1211 I->getKindAsEnum() == Attribute::NoInline ||
1212 I->getKindAsEnum() == Attribute::AlwaysInline ||
1213 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1214 I->getKindAsEnum() == Attribute::StackProtect ||
1215 I->getKindAsEnum() == Attribute::StackProtectReq ||
1216 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1217 I->getKindAsEnum() == Attribute::SafeStack ||
1218 I->getKindAsEnum() == Attribute::NoRedZone ||
1219 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1220 I->getKindAsEnum() == Attribute::Naked ||
1221 I->getKindAsEnum() == Attribute::InlineHint ||
1222 I->getKindAsEnum() == Attribute::StackAlignment ||
1223 I->getKindAsEnum() == Attribute::UWTable ||
1224 I->getKindAsEnum() == Attribute::NonLazyBind ||
1225 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1226 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1227 I->getKindAsEnum() == Attribute::SanitizeThread ||
1228 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1229 I->getKindAsEnum() == Attribute::MinSize ||
1230 I->getKindAsEnum() == Attribute::NoDuplicate ||
1231 I->getKindAsEnum() == Attribute::Builtin ||
1232 I->getKindAsEnum() == Attribute::NoBuiltin ||
1233 I->getKindAsEnum() == Attribute::Cold ||
1234 I->getKindAsEnum() == Attribute::OptimizeNone ||
1235 I->getKindAsEnum() == Attribute::JumpTable ||
1236 I->getKindAsEnum() == Attribute::Convergent ||
1237 I->getKindAsEnum() == Attribute::ArgMemOnly ||
1238 I->getKindAsEnum() == Attribute::NoRecurse) {
1240 CheckFailed("Attribute '" + I->getAsString() +
1241 "' only applies to functions!", V);
1244 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1245 I->getKindAsEnum() == Attribute::ReadNone) {
1247 CheckFailed("Attribute '" + I->getAsString() +
1248 "' does not apply to function returns");
1251 } else if (isFunction) {
1252 CheckFailed("Attribute '" + I->getAsString() +
1253 "' does not apply to functions!", V);
1259 // VerifyParameterAttrs - Check the given attributes for an argument or return
1260 // value of the specified type. The value V is printed in error messages.
1261 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1262 bool isReturnValue, const Value *V) {
1263 if (!Attrs.hasAttributes(Idx))
1266 VerifyAttributeTypes(Attrs, Idx, false, V);
1269 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1270 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1271 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1272 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1273 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1274 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1275 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1276 "'returned' do not apply to return values!",
1279 // Check for mutually incompatible attributes. Only inreg is compatible with
1281 unsigned AttrCount = 0;
1282 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1283 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1284 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1285 Attrs.hasAttribute(Idx, Attribute::InReg);
1286 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1287 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1288 "and 'sret' are incompatible!",
1291 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1292 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1294 "'inalloca and readonly' are incompatible!",
1297 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1298 Attrs.hasAttribute(Idx, Attribute::Returned)),
1300 "'sret and returned' are incompatible!",
1303 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1304 Attrs.hasAttribute(Idx, Attribute::SExt)),
1306 "'zeroext and signext' are incompatible!",
1309 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1310 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1312 "'readnone and readonly' are incompatible!",
1315 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1316 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1318 "'noinline and alwaysinline' are incompatible!",
1321 Assert(!AttrBuilder(Attrs, Idx)
1322 .overlaps(AttributeFuncs::typeIncompatible(Ty)),
1323 "Wrong types for attribute: " +
1324 AttributeSet::get(*Context, Idx,
1325 AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx),
1328 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1329 SmallPtrSet<Type*, 4> Visited;
1330 if (!PTy->getElementType()->isSized(&Visited)) {
1331 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1332 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1333 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1337 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1338 "Attribute 'byval' only applies to parameters with pointer type!",
1343 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1344 // The value V is printed in error messages.
1345 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1347 if (Attrs.isEmpty())
1350 bool SawNest = false;
1351 bool SawReturned = false;
1352 bool SawSRet = false;
1354 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1355 unsigned Idx = Attrs.getSlotIndex(i);
1359 Ty = FT->getReturnType();
1360 else if (Idx-1 < FT->getNumParams())
1361 Ty = FT->getParamType(Idx-1);
1363 break; // VarArgs attributes, verified elsewhere.
1365 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1370 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1371 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1375 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1376 Assert(!SawReturned, "More than one parameter has attribute returned!",
1378 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1380 "argument and return types for 'returned' attribute",
1385 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1386 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1387 Assert(Idx == 1 || Idx == 2,
1388 "Attribute 'sret' is not on first or second parameter!", V);
1392 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1393 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1398 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1401 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1404 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1405 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1406 "Attributes 'readnone and readonly' are incompatible!", V);
1409 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1410 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1411 Attribute::AlwaysInline)),
1412 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1414 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1415 Attribute::OptimizeNone)) {
1416 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1417 "Attribute 'optnone' requires 'noinline'!", V);
1419 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1420 Attribute::OptimizeForSize),
1421 "Attributes 'optsize and optnone' are incompatible!", V);
1423 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1424 "Attributes 'minsize and optnone' are incompatible!", V);
1427 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1428 Attribute::JumpTable)) {
1429 const GlobalValue *GV = cast<GlobalValue>(V);
1430 Assert(GV->hasUnnamedAddr(),
1431 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1435 void Verifier::VerifyFunctionMetadata(
1436 const SmallVector<std::pair<unsigned, MDNode *>, 4> MDs) {
1440 for (unsigned i = 0; i < MDs.size(); i++) {
1441 if (MDs[i].first == LLVMContext::MD_prof) {
1442 MDNode *MD = MDs[i].second;
1443 Assert(MD->getNumOperands() == 2,
1444 "!prof annotations should have exactly 2 operands", MD);
1446 // Check first operand.
1447 Assert(MD->getOperand(0) != nullptr, "first operand should not be null",
1449 Assert(isa<MDString>(MD->getOperand(0)),
1450 "expected string with name of the !prof annotation", MD);
1451 MDString *MDS = cast<MDString>(MD->getOperand(0));
1452 StringRef ProfName = MDS->getString();
1453 Assert(ProfName.equals("function_entry_count"),
1454 "first operand should be 'function_entry_count'", MD);
1456 // Check second operand.
1457 Assert(MD->getOperand(1) != nullptr, "second operand should not be null",
1459 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)),
1460 "expected integer argument to function_entry_count", MD);
1465 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1466 if (CE->getOpcode() != Instruction::BitCast)
1469 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1471 "Invalid bitcast", CE);
1474 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1475 if (Attrs.getNumSlots() == 0)
1478 unsigned LastSlot = Attrs.getNumSlots() - 1;
1479 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1480 if (LastIndex <= Params
1481 || (LastIndex == AttributeSet::FunctionIndex
1482 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1488 /// \brief Verify that statepoint intrinsic is well formed.
1489 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1490 assert(CS.getCalledFunction() &&
1491 CS.getCalledFunction()->getIntrinsicID() ==
1492 Intrinsic::experimental_gc_statepoint);
1494 const Instruction &CI = *CS.getInstruction();
1496 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() &&
1497 !CS.onlyAccessesArgMemory(),
1498 "gc.statepoint must read and write all memory to preserve "
1499 "reordering restrictions required by safepoint semantics",
1502 const Value *IDV = CS.getArgument(0);
1503 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer",
1506 const Value *NumPatchBytesV = CS.getArgument(1);
1507 Assert(isa<ConstantInt>(NumPatchBytesV),
1508 "gc.statepoint number of patchable bytes must be a constant integer",
1510 const int64_t NumPatchBytes =
1511 cast<ConstantInt>(NumPatchBytesV)->getSExtValue();
1512 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!");
1513 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be "
1517 const Value *Target = CS.getArgument(2);
1518 auto *PT = dyn_cast<PointerType>(Target->getType());
1519 Assert(PT && PT->getElementType()->isFunctionTy(),
1520 "gc.statepoint callee must be of function pointer type", &CI, Target);
1521 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1523 const Value *NumCallArgsV = CS.getArgument(3);
1524 Assert(isa<ConstantInt>(NumCallArgsV),
1525 "gc.statepoint number of arguments to underlying call "
1526 "must be constant integer",
1528 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1529 Assert(NumCallArgs >= 0,
1530 "gc.statepoint number of arguments to underlying call "
1533 const int NumParams = (int)TargetFuncType->getNumParams();
1534 if (TargetFuncType->isVarArg()) {
1535 Assert(NumCallArgs >= NumParams,
1536 "gc.statepoint mismatch in number of vararg call args", &CI);
1538 // TODO: Remove this limitation
1539 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1540 "gc.statepoint doesn't support wrapping non-void "
1541 "vararg functions yet",
1544 Assert(NumCallArgs == NumParams,
1545 "gc.statepoint mismatch in number of call args", &CI);
1547 const Value *FlagsV = CS.getArgument(4);
1548 Assert(isa<ConstantInt>(FlagsV),
1549 "gc.statepoint flags must be constant integer", &CI);
1550 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue();
1551 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
1552 "unknown flag used in gc.statepoint flags argument", &CI);
1554 // Verify that the types of the call parameter arguments match
1555 // the type of the wrapped callee.
1556 for (int i = 0; i < NumParams; i++) {
1557 Type *ParamType = TargetFuncType->getParamType(i);
1558 Type *ArgType = CS.getArgument(5 + i)->getType();
1559 Assert(ArgType == ParamType,
1560 "gc.statepoint call argument does not match wrapped "
1565 const int EndCallArgsInx = 4 + NumCallArgs;
1567 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1);
1568 Assert(isa<ConstantInt>(NumTransitionArgsV),
1569 "gc.statepoint number of transition arguments "
1570 "must be constant integer",
1572 const int NumTransitionArgs =
1573 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
1574 Assert(NumTransitionArgs >= 0,
1575 "gc.statepoint number of transition arguments must be positive", &CI);
1576 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
1578 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1);
1579 Assert(isa<ConstantInt>(NumDeoptArgsV),
1580 "gc.statepoint number of deoptimization arguments "
1581 "must be constant integer",
1583 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1584 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1588 const int ExpectedNumArgs =
1589 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
1590 Assert(ExpectedNumArgs <= (int)CS.arg_size(),
1591 "gc.statepoint too few arguments according to length fields", &CI);
1593 // Check that the only uses of this gc.statepoint are gc.result or
1594 // gc.relocate calls which are tied to this statepoint and thus part
1595 // of the same statepoint sequence
1596 for (const User *U : CI.users()) {
1597 const CallInst *Call = dyn_cast<const CallInst>(U);
1598 Assert(Call, "illegal use of statepoint token", &CI, U);
1599 if (!Call) continue;
1600 Assert(isGCRelocate(Call) || isGCResult(Call),
1601 "gc.result or gc.relocate are the only value uses"
1602 "of a gc.statepoint",
1604 if (isGCResult(Call)) {
1605 Assert(Call->getArgOperand(0) == &CI,
1606 "gc.result connected to wrong gc.statepoint", &CI, Call);
1607 } else if (isGCRelocate(Call)) {
1608 Assert(Call->getArgOperand(0) == &CI,
1609 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1613 // Note: It is legal for a single derived pointer to be listed multiple
1614 // times. It's non-optimal, but it is legal. It can also happen after
1615 // insertion if we strip a bitcast away.
1616 // Note: It is really tempting to check that each base is relocated and
1617 // that a derived pointer is never reused as a base pointer. This turns
1618 // out to be problematic since optimizations run after safepoint insertion
1619 // can recognize equality properties that the insertion logic doesn't know
1620 // about. See example statepoint.ll in the verifier subdirectory
1623 void Verifier::verifyFrameRecoverIndices() {
1624 for (auto &Counts : FrameEscapeInfo) {
1625 Function *F = Counts.first;
1626 unsigned EscapedObjectCount = Counts.second.first;
1627 unsigned MaxRecoveredIndex = Counts.second.second;
1628 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1629 "all indices passed to llvm.localrecover must be less than the "
1630 "number of arguments passed ot llvm.localescape in the parent "
1636 // visitFunction - Verify that a function is ok.
1638 void Verifier::visitFunction(const Function &F) {
1639 // Check function arguments.
1640 FunctionType *FT = F.getFunctionType();
1641 unsigned NumArgs = F.arg_size();
1643 Assert(Context == &F.getContext(),
1644 "Function context does not match Module context!", &F);
1646 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1647 Assert(FT->getNumParams() == NumArgs,
1648 "# formal arguments must match # of arguments for function type!", &F,
1650 Assert(F.getReturnType()->isFirstClassType() ||
1651 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1652 "Functions cannot return aggregate values!", &F);
1654 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1655 "Invalid struct return type!", &F);
1657 AttributeSet Attrs = F.getAttributes();
1659 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1660 "Attribute after last parameter!", &F);
1662 // Check function attributes.
1663 VerifyFunctionAttrs(FT, Attrs, &F);
1665 // On function declarations/definitions, we do not support the builtin
1666 // attribute. We do not check this in VerifyFunctionAttrs since that is
1667 // checking for Attributes that can/can not ever be on functions.
1668 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1669 "Attribute 'builtin' can only be applied to a callsite.", &F);
1671 // Check that this function meets the restrictions on this calling convention.
1672 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1673 // restrictions can be lifted.
1674 switch (F.getCallingConv()) {
1676 case CallingConv::C:
1678 case CallingConv::Fast:
1679 case CallingConv::Cold:
1680 case CallingConv::Intel_OCL_BI:
1681 case CallingConv::PTX_Kernel:
1682 case CallingConv::PTX_Device:
1683 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1684 "perfect forwarding!",
1689 bool isLLVMdotName = F.getName().size() >= 5 &&
1690 F.getName().substr(0, 5) == "llvm.";
1692 // Check that the argument values match the function type for this function...
1694 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1696 Assert(I->getType() == FT->getParamType(i),
1697 "Argument value does not match function argument type!", I,
1698 FT->getParamType(i));
1699 Assert(I->getType()->isFirstClassType(),
1700 "Function arguments must have first-class types!", I);
1701 if (!isLLVMdotName) {
1702 Assert(!I->getType()->isMetadataTy(),
1703 "Function takes metadata but isn't an intrinsic", I, &F);
1704 Assert(!I->getType()->isTokenTy(),
1705 "Function takes token but isn't an intrinsic", I, &F);
1710 Assert(!F.getReturnType()->isTokenTy(),
1711 "Functions returns a token but isn't an intrinsic", &F);
1713 // Get the function metadata attachments.
1714 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1715 F.getAllMetadata(MDs);
1716 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync");
1717 VerifyFunctionMetadata(MDs);
1719 // Check validity of the personality function
1720 if (F.hasPersonalityFn()) {
1721 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
1723 Assert(Per->getParent() == F.getParent(),
1724 "Referencing personality function in another module!", &F, Per);
1727 if (F.isMaterializable()) {
1728 // Function has a body somewhere we can't see.
1729 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F,
1730 MDs.empty() ? nullptr : MDs.front().second);
1731 } else if (F.isDeclaration()) {
1732 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1733 "invalid linkage type for function declaration", &F);
1734 Assert(MDs.empty(), "function without a body cannot have metadata", &F,
1735 MDs.empty() ? nullptr : MDs.front().second);
1736 Assert(!F.hasPersonalityFn(),
1737 "Function declaration shouldn't have a personality routine", &F);
1739 // Verify that this function (which has a body) is not named "llvm.*". It
1740 // is not legal to define intrinsics.
1741 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1743 // Check the entry node
1744 const BasicBlock *Entry = &F.getEntryBlock();
1745 Assert(pred_empty(Entry),
1746 "Entry block to function must not have predecessors!", Entry);
1748 // The address of the entry block cannot be taken, unless it is dead.
1749 if (Entry->hasAddressTaken()) {
1750 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1751 "blockaddress may not be used with the entry block!", Entry);
1754 // Visit metadata attachments.
1755 for (const auto &I : MDs) {
1756 // Verify that the attachment is legal.
1760 case LLVMContext::MD_dbg:
1761 Assert(isa<DISubprogram>(I.second),
1762 "function !dbg attachment must be a subprogram", &F, I.second);
1766 // Verify the metadata itself.
1767 visitMDNode(*I.second);
1771 // If this function is actually an intrinsic, verify that it is only used in
1772 // direct call/invokes, never having its "address taken".
1773 if (F.getIntrinsicID()) {
1775 if (F.hasAddressTaken(&U))
1776 Assert(0, "Invalid user of intrinsic instruction!", U);
1779 Assert(!F.hasDLLImportStorageClass() ||
1780 (F.isDeclaration() && F.hasExternalLinkage()) ||
1781 F.hasAvailableExternallyLinkage(),
1782 "Function is marked as dllimport, but not external.", &F);
1784 auto *N = F.getSubprogram();
1788 // Check that all !dbg attachments lead to back to N (or, at least, another
1789 // subprogram that describes the same function).
1791 // FIXME: Check this incrementally while visiting !dbg attachments.
1792 // FIXME: Only check when N is the canonical subprogram for F.
1793 SmallPtrSet<const MDNode *, 32> Seen;
1795 for (auto &I : BB) {
1796 // Be careful about using DILocation here since we might be dealing with
1797 // broken code (this is the Verifier after all).
1799 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode());
1802 if (!Seen.insert(DL).second)
1805 DILocalScope *Scope = DL->getInlinedAtScope();
1806 if (Scope && !Seen.insert(Scope).second)
1809 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr;
1810 if (SP && !Seen.insert(SP).second)
1813 // FIXME: Once N is canonical, check "SP == &N".
1814 Assert(SP->describes(&F),
1815 "!dbg attachment points at wrong subprogram for function", N, &F,
1820 // verifyBasicBlock - Verify that a basic block is well formed...
1822 void Verifier::visitBasicBlock(BasicBlock &BB) {
1823 InstsInThisBlock.clear();
1825 // Ensure that basic blocks have terminators!
1826 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1828 // Check constraints that this basic block imposes on all of the PHI nodes in
1830 if (isa<PHINode>(BB.front())) {
1831 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1832 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1833 std::sort(Preds.begin(), Preds.end());
1835 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1836 // Ensure that PHI nodes have at least one entry!
1837 Assert(PN->getNumIncomingValues() != 0,
1838 "PHI nodes must have at least one entry. If the block is dead, "
1839 "the PHI should be removed!",
1841 Assert(PN->getNumIncomingValues() == Preds.size(),
1842 "PHINode should have one entry for each predecessor of its "
1843 "parent basic block!",
1846 // Get and sort all incoming values in the PHI node...
1848 Values.reserve(PN->getNumIncomingValues());
1849 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1850 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1851 PN->getIncomingValue(i)));
1852 std::sort(Values.begin(), Values.end());
1854 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1855 // Check to make sure that if there is more than one entry for a
1856 // particular basic block in this PHI node, that the incoming values are
1859 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1860 Values[i].second == Values[i - 1].second,
1861 "PHI node has multiple entries for the same basic block with "
1862 "different incoming values!",
1863 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1865 // Check to make sure that the predecessors and PHI node entries are
1867 Assert(Values[i].first == Preds[i],
1868 "PHI node entries do not match predecessors!", PN,
1869 Values[i].first, Preds[i]);
1874 // Check that all instructions have their parent pointers set up correctly.
1877 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1881 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1882 // Ensure that terminators only exist at the end of the basic block.
1883 Assert(&I == I.getParent()->getTerminator(),
1884 "Terminator found in the middle of a basic block!", I.getParent());
1885 visitInstruction(I);
1888 void Verifier::visitBranchInst(BranchInst &BI) {
1889 if (BI.isConditional()) {
1890 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1891 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1893 visitTerminatorInst(BI);
1896 void Verifier::visitReturnInst(ReturnInst &RI) {
1897 Function *F = RI.getParent()->getParent();
1898 unsigned N = RI.getNumOperands();
1899 if (F->getReturnType()->isVoidTy())
1901 "Found return instr that returns non-void in Function of void "
1903 &RI, F->getReturnType());
1905 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1906 "Function return type does not match operand "
1907 "type of return inst!",
1908 &RI, F->getReturnType());
1910 // Check to make sure that the return value has necessary properties for
1912 visitTerminatorInst(RI);
1915 void Verifier::visitSwitchInst(SwitchInst &SI) {
1916 // Check to make sure that all of the constants in the switch instruction
1917 // have the same type as the switched-on value.
1918 Type *SwitchTy = SI.getCondition()->getType();
1919 SmallPtrSet<ConstantInt*, 32> Constants;
1920 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1921 Assert(i.getCaseValue()->getType() == SwitchTy,
1922 "Switch constants must all be same type as switch value!", &SI);
1923 Assert(Constants.insert(i.getCaseValue()).second,
1924 "Duplicate integer as switch case", &SI, i.getCaseValue());
1927 visitTerminatorInst(SI);
1930 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1931 Assert(BI.getAddress()->getType()->isPointerTy(),
1932 "Indirectbr operand must have pointer type!", &BI);
1933 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1934 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1935 "Indirectbr destinations must all have pointer type!", &BI);
1937 visitTerminatorInst(BI);
1940 void Verifier::visitSelectInst(SelectInst &SI) {
1941 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1943 "Invalid operands for select instruction!", &SI);
1945 Assert(SI.getTrueValue()->getType() == SI.getType(),
1946 "Select values must have same type as select instruction!", &SI);
1947 visitInstruction(SI);
1950 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1951 /// a pass, if any exist, it's an error.
1953 void Verifier::visitUserOp1(Instruction &I) {
1954 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1957 void Verifier::visitTruncInst(TruncInst &I) {
1958 // Get the source and destination types
1959 Type *SrcTy = I.getOperand(0)->getType();
1960 Type *DestTy = I.getType();
1962 // Get the size of the types in bits, we'll need this later
1963 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1964 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1966 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1967 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1968 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1969 "trunc source and destination must both be a vector or neither", &I);
1970 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1972 visitInstruction(I);
1975 void Verifier::visitZExtInst(ZExtInst &I) {
1976 // Get the source and destination types
1977 Type *SrcTy = I.getOperand(0)->getType();
1978 Type *DestTy = I.getType();
1980 // Get the size of the types in bits, we'll need this later
1981 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1982 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1983 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1984 "zext source and destination must both be a vector or neither", &I);
1985 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1986 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1988 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1990 visitInstruction(I);
1993 void Verifier::visitSExtInst(SExtInst &I) {
1994 // Get the source and destination types
1995 Type *SrcTy = I.getOperand(0)->getType();
1996 Type *DestTy = I.getType();
1998 // Get the size of the types in bits, we'll need this later
1999 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2000 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2002 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
2003 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
2004 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2005 "sext source and destination must both be a vector or neither", &I);
2006 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
2008 visitInstruction(I);
2011 void Verifier::visitFPTruncInst(FPTruncInst &I) {
2012 // Get the source and destination types
2013 Type *SrcTy = I.getOperand(0)->getType();
2014 Type *DestTy = I.getType();
2015 // Get the size of the types in bits, we'll need this later
2016 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2017 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2019 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
2020 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
2021 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2022 "fptrunc source and destination must both be a vector or neither", &I);
2023 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
2025 visitInstruction(I);
2028 void Verifier::visitFPExtInst(FPExtInst &I) {
2029 // Get the source and destination types
2030 Type *SrcTy = I.getOperand(0)->getType();
2031 Type *DestTy = I.getType();
2033 // Get the size of the types in bits, we'll need this later
2034 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2035 unsigned DestBitSize = DestTy->getScalarSizeInBits();
2037 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
2038 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
2039 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
2040 "fpext source and destination must both be a vector or neither", &I);
2041 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
2043 visitInstruction(I);
2046 void Verifier::visitUIToFPInst(UIToFPInst &I) {
2047 // Get the source and destination types
2048 Type *SrcTy = I.getOperand(0)->getType();
2049 Type *DestTy = I.getType();
2051 bool SrcVec = SrcTy->isVectorTy();
2052 bool DstVec = DestTy->isVectorTy();
2054 Assert(SrcVec == DstVec,
2055 "UIToFP source and dest must both be vector or scalar", &I);
2056 Assert(SrcTy->isIntOrIntVectorTy(),
2057 "UIToFP source must be integer or integer vector", &I);
2058 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2061 if (SrcVec && DstVec)
2062 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2063 cast<VectorType>(DestTy)->getNumElements(),
2064 "UIToFP source and dest vector length mismatch", &I);
2066 visitInstruction(I);
2069 void Verifier::visitSIToFPInst(SIToFPInst &I) {
2070 // Get the source and destination types
2071 Type *SrcTy = I.getOperand(0)->getType();
2072 Type *DestTy = I.getType();
2074 bool SrcVec = SrcTy->isVectorTy();
2075 bool DstVec = DestTy->isVectorTy();
2077 Assert(SrcVec == DstVec,
2078 "SIToFP source and dest must both be vector or scalar", &I);
2079 Assert(SrcTy->isIntOrIntVectorTy(),
2080 "SIToFP source must be integer or integer vector", &I);
2081 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2084 if (SrcVec && DstVec)
2085 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2086 cast<VectorType>(DestTy)->getNumElements(),
2087 "SIToFP source and dest vector length mismatch", &I);
2089 visitInstruction(I);
2092 void Verifier::visitFPToUIInst(FPToUIInst &I) {
2093 // Get the source and destination types
2094 Type *SrcTy = I.getOperand(0)->getType();
2095 Type *DestTy = I.getType();
2097 bool SrcVec = SrcTy->isVectorTy();
2098 bool DstVec = DestTy->isVectorTy();
2100 Assert(SrcVec == DstVec,
2101 "FPToUI source and dest must both be vector or scalar", &I);
2102 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2104 Assert(DestTy->isIntOrIntVectorTy(),
2105 "FPToUI result must be integer or integer vector", &I);
2107 if (SrcVec && DstVec)
2108 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2109 cast<VectorType>(DestTy)->getNumElements(),
2110 "FPToUI source and dest vector length mismatch", &I);
2112 visitInstruction(I);
2115 void Verifier::visitFPToSIInst(FPToSIInst &I) {
2116 // Get the source and destination types
2117 Type *SrcTy = I.getOperand(0)->getType();
2118 Type *DestTy = I.getType();
2120 bool SrcVec = SrcTy->isVectorTy();
2121 bool DstVec = DestTy->isVectorTy();
2123 Assert(SrcVec == DstVec,
2124 "FPToSI source and dest must both be vector or scalar", &I);
2125 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2127 Assert(DestTy->isIntOrIntVectorTy(),
2128 "FPToSI result must be integer or integer vector", &I);
2130 if (SrcVec && DstVec)
2131 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2132 cast<VectorType>(DestTy)->getNumElements(),
2133 "FPToSI source and dest vector length mismatch", &I);
2135 visitInstruction(I);
2138 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
2139 // Get the source and destination types
2140 Type *SrcTy = I.getOperand(0)->getType();
2141 Type *DestTy = I.getType();
2143 Assert(SrcTy->getScalarType()->isPointerTy(),
2144 "PtrToInt source must be pointer", &I);
2145 Assert(DestTy->getScalarType()->isIntegerTy(),
2146 "PtrToInt result must be integral", &I);
2147 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
2150 if (SrcTy->isVectorTy()) {
2151 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2152 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2153 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2154 "PtrToInt Vector width mismatch", &I);
2157 visitInstruction(I);
2160 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
2161 // Get the source and destination types
2162 Type *SrcTy = I.getOperand(0)->getType();
2163 Type *DestTy = I.getType();
2165 Assert(SrcTy->getScalarType()->isIntegerTy(),
2166 "IntToPtr source must be an integral", &I);
2167 Assert(DestTy->getScalarType()->isPointerTy(),
2168 "IntToPtr result must be a pointer", &I);
2169 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
2171 if (SrcTy->isVectorTy()) {
2172 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
2173 VectorType *VDest = dyn_cast<VectorType>(DestTy);
2174 Assert(VSrc->getNumElements() == VDest->getNumElements(),
2175 "IntToPtr Vector width mismatch", &I);
2177 visitInstruction(I);
2180 void Verifier::visitBitCastInst(BitCastInst &I) {
2182 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
2183 "Invalid bitcast", &I);
2184 visitInstruction(I);
2187 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
2188 Type *SrcTy = I.getOperand(0)->getType();
2189 Type *DestTy = I.getType();
2191 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2193 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2195 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
2196 "AddrSpaceCast must be between different address spaces", &I);
2197 if (SrcTy->isVectorTy())
2198 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
2199 "AddrSpaceCast vector pointer number of elements mismatch", &I);
2200 visitInstruction(I);
2203 /// visitPHINode - Ensure that a PHI node is well formed.
2205 void Verifier::visitPHINode(PHINode &PN) {
2206 // Ensure that the PHI nodes are all grouped together at the top of the block.
2207 // This can be tested by checking whether the instruction before this is
2208 // either nonexistent (because this is begin()) or is a PHI node. If not,
2209 // then there is some other instruction before a PHI.
2210 Assert(&PN == &PN.getParent()->front() ||
2211 isa<PHINode>(--BasicBlock::iterator(&PN)),
2212 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
2214 // Check that a PHI doesn't yield a Token.
2215 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2217 // Check that all of the values of the PHI node have the same type as the
2218 // result, and that the incoming blocks are really basic blocks.
2219 for (Value *IncValue : PN.incoming_values()) {
2220 Assert(PN.getType() == IncValue->getType(),
2221 "PHI node operands are not the same type as the result!", &PN);
2224 // All other PHI node constraints are checked in the visitBasicBlock method.
2226 visitInstruction(PN);
2229 void Verifier::VerifyCallSite(CallSite CS) {
2230 Instruction *I = CS.getInstruction();
2232 Assert(CS.getCalledValue()->getType()->isPointerTy(),
2233 "Called function must be a pointer!", I);
2234 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
2236 Assert(FPTy->getElementType()->isFunctionTy(),
2237 "Called function is not pointer to function type!", I);
2239 Assert(FPTy->getElementType() == CS.getFunctionType(),
2240 "Called function is not the same type as the call!", I);
2242 FunctionType *FTy = CS.getFunctionType();
2244 // Verify that the correct number of arguments are being passed
2245 if (FTy->isVarArg())
2246 Assert(CS.arg_size() >= FTy->getNumParams(),
2247 "Called function requires more parameters than were provided!", I);
2249 Assert(CS.arg_size() == FTy->getNumParams(),
2250 "Incorrect number of arguments passed to called function!", I);
2252 // Verify that all arguments to the call match the function type.
2253 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2254 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
2255 "Call parameter type does not match function signature!",
2256 CS.getArgument(i), FTy->getParamType(i), I);
2258 AttributeSet Attrs = CS.getAttributes();
2260 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
2261 "Attribute after last parameter!", I);
2263 // Verify call attributes.
2264 VerifyFunctionAttrs(FTy, Attrs, I);
2266 // Conservatively check the inalloca argument.
2267 // We have a bug if we can find that there is an underlying alloca without
2269 if (CS.hasInAllocaArgument()) {
2270 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
2271 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
2272 Assert(AI->isUsedWithInAlloca(),
2273 "inalloca argument for call has mismatched alloca", AI, I);
2276 if (FTy->isVarArg()) {
2277 // FIXME? is 'nest' even legal here?
2278 bool SawNest = false;
2279 bool SawReturned = false;
2281 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
2282 if (Attrs.hasAttribute(Idx, Attribute::Nest))
2284 if (Attrs.hasAttribute(Idx, Attribute::Returned))
2288 // Check attributes on the varargs part.
2289 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
2290 Type *Ty = CS.getArgument(Idx-1)->getType();
2291 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
2293 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
2294 Assert(!SawNest, "More than one parameter has attribute nest!", I);
2298 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
2299 Assert(!SawReturned, "More than one parameter has attribute returned!",
2301 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
2302 "Incompatible argument and return types for 'returned' "
2308 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
2309 "Attribute 'sret' cannot be used for vararg call arguments!", I);
2311 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
2312 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
2316 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2317 if (CS.getCalledFunction() == nullptr ||
2318 !CS.getCalledFunction()->getName().startswith("llvm.")) {
2319 for (Type *ParamTy : FTy->params()) {
2320 Assert(!ParamTy->isMetadataTy(),
2321 "Function has metadata parameter but isn't an intrinsic", I);
2322 Assert(!ParamTy->isTokenTy(),
2323 "Function has token parameter but isn't an intrinsic", I);
2327 // Verify that indirect calls don't return tokens.
2328 if (CS.getCalledFunction() == nullptr)
2329 Assert(!FTy->getReturnType()->isTokenTy(),
2330 "Return type cannot be token for indirect call!");
2332 if (Function *F = CS.getCalledFunction())
2333 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2334 visitIntrinsicCallSite(ID, CS);
2336 // Verify that a callsite has at most one "deopt" operand bundle.
2337 bool FoundDeoptBundle = false;
2338 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) {
2339 if (CS.getOperandBundleAt(i).getTagID() == LLVMContext::OB_deopt) {
2340 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I);
2341 FoundDeoptBundle = true;
2345 visitInstruction(*I);
2348 /// Two types are "congruent" if they are identical, or if they are both pointer
2349 /// types with different pointee types and the same address space.
2350 static bool isTypeCongruent(Type *L, Type *R) {
2353 PointerType *PL = dyn_cast<PointerType>(L);
2354 PointerType *PR = dyn_cast<PointerType>(R);
2357 return PL->getAddressSpace() == PR->getAddressSpace();
2360 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2361 static const Attribute::AttrKind ABIAttrs[] = {
2362 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2363 Attribute::InReg, Attribute::Returned};
2365 for (auto AK : ABIAttrs) {
2366 if (Attrs.hasAttribute(I + 1, AK))
2367 Copy.addAttribute(AK);
2369 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2370 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2374 void Verifier::verifyMustTailCall(CallInst &CI) {
2375 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2377 // - The caller and callee prototypes must match. Pointer types of
2378 // parameters or return types may differ in pointee type, but not
2380 Function *F = CI.getParent()->getParent();
2381 FunctionType *CallerTy = F->getFunctionType();
2382 FunctionType *CalleeTy = CI.getFunctionType();
2383 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2384 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2385 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2386 "cannot guarantee tail call due to mismatched varargs", &CI);
2387 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2388 "cannot guarantee tail call due to mismatched return types", &CI);
2389 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2391 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2392 "cannot guarantee tail call due to mismatched parameter types", &CI);
2395 // - The calling conventions of the caller and callee must match.
2396 Assert(F->getCallingConv() == CI.getCallingConv(),
2397 "cannot guarantee tail call due to mismatched calling conv", &CI);
2399 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2400 // returned, and inalloca, must match.
2401 AttributeSet CallerAttrs = F->getAttributes();
2402 AttributeSet CalleeAttrs = CI.getAttributes();
2403 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2404 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2405 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2406 Assert(CallerABIAttrs == CalleeABIAttrs,
2407 "cannot guarantee tail call due to mismatched ABI impacting "
2408 "function attributes",
2409 &CI, CI.getOperand(I));
2412 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2413 // or a pointer bitcast followed by a ret instruction.
2414 // - The ret instruction must return the (possibly bitcasted) value
2415 // produced by the call or void.
2416 Value *RetVal = &CI;
2417 Instruction *Next = CI.getNextNode();
2419 // Handle the optional bitcast.
2420 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2421 Assert(BI->getOperand(0) == RetVal,
2422 "bitcast following musttail call must use the call", BI);
2424 Next = BI->getNextNode();
2427 // Check the return.
2428 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2429 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2431 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2432 "musttail call result must be returned", Ret);
2435 void Verifier::visitCallInst(CallInst &CI) {
2436 VerifyCallSite(&CI);
2438 if (CI.isMustTailCall())
2439 verifyMustTailCall(CI);
2442 void Verifier::visitInvokeInst(InvokeInst &II) {
2443 VerifyCallSite(&II);
2445 // Verify that the first non-PHI instruction of the unwind destination is an
2446 // exception handling instruction.
2448 II.getUnwindDest()->isEHPad(),
2449 "The unwind destination does not have an exception handling instruction!",
2452 visitTerminatorInst(II);
2455 /// visitBinaryOperator - Check that both arguments to the binary operator are
2456 /// of the same type!
2458 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2459 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2460 "Both operands to a binary operator are not of the same type!", &B);
2462 switch (B.getOpcode()) {
2463 // Check that integer arithmetic operators are only used with
2464 // integral operands.
2465 case Instruction::Add:
2466 case Instruction::Sub:
2467 case Instruction::Mul:
2468 case Instruction::SDiv:
2469 case Instruction::UDiv:
2470 case Instruction::SRem:
2471 case Instruction::URem:
2472 Assert(B.getType()->isIntOrIntVectorTy(),
2473 "Integer arithmetic operators only work with integral types!", &B);
2474 Assert(B.getType() == B.getOperand(0)->getType(),
2475 "Integer arithmetic operators must have same type "
2476 "for operands and result!",
2479 // Check that floating-point arithmetic operators are only used with
2480 // floating-point operands.
2481 case Instruction::FAdd:
2482 case Instruction::FSub:
2483 case Instruction::FMul:
2484 case Instruction::FDiv:
2485 case Instruction::FRem:
2486 Assert(B.getType()->isFPOrFPVectorTy(),
2487 "Floating-point arithmetic operators only work with "
2488 "floating-point types!",
2490 Assert(B.getType() == B.getOperand(0)->getType(),
2491 "Floating-point arithmetic operators must have same type "
2492 "for operands and result!",
2495 // Check that logical operators are only used with integral operands.
2496 case Instruction::And:
2497 case Instruction::Or:
2498 case Instruction::Xor:
2499 Assert(B.getType()->isIntOrIntVectorTy(),
2500 "Logical operators only work with integral types!", &B);
2501 Assert(B.getType() == B.getOperand(0)->getType(),
2502 "Logical operators must have same type for operands and result!",
2505 case Instruction::Shl:
2506 case Instruction::LShr:
2507 case Instruction::AShr:
2508 Assert(B.getType()->isIntOrIntVectorTy(),
2509 "Shifts only work with integral types!", &B);
2510 Assert(B.getType() == B.getOperand(0)->getType(),
2511 "Shift return type must be same as operands!", &B);
2514 llvm_unreachable("Unknown BinaryOperator opcode!");
2517 visitInstruction(B);
2520 void Verifier::visitICmpInst(ICmpInst &IC) {
2521 // Check that the operands are the same type
2522 Type *Op0Ty = IC.getOperand(0)->getType();
2523 Type *Op1Ty = IC.getOperand(1)->getType();
2524 Assert(Op0Ty == Op1Ty,
2525 "Both operands to ICmp instruction are not of the same type!", &IC);
2526 // Check that the operands are the right type
2527 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2528 "Invalid operand types for ICmp instruction", &IC);
2529 // Check that the predicate is valid.
2530 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2531 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2532 "Invalid predicate in ICmp instruction!", &IC);
2534 visitInstruction(IC);
2537 void Verifier::visitFCmpInst(FCmpInst &FC) {
2538 // Check that the operands are the same type
2539 Type *Op0Ty = FC.getOperand(0)->getType();
2540 Type *Op1Ty = FC.getOperand(1)->getType();
2541 Assert(Op0Ty == Op1Ty,
2542 "Both operands to FCmp instruction are not of the same type!", &FC);
2543 // Check that the operands are the right type
2544 Assert(Op0Ty->isFPOrFPVectorTy(),
2545 "Invalid operand types for FCmp instruction", &FC);
2546 // Check that the predicate is valid.
2547 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2548 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2549 "Invalid predicate in FCmp instruction!", &FC);
2551 visitInstruction(FC);
2554 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2556 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2557 "Invalid extractelement operands!", &EI);
2558 visitInstruction(EI);
2561 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2562 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2564 "Invalid insertelement operands!", &IE);
2565 visitInstruction(IE);
2568 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2569 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2571 "Invalid shufflevector operands!", &SV);
2572 visitInstruction(SV);
2575 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2576 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2578 Assert(isa<PointerType>(TargetTy),
2579 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2580 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP);
2581 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2583 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs);
2584 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2586 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2587 GEP.getResultElementType() == ElTy,
2588 "GEP is not of right type for indices!", &GEP, ElTy);
2590 if (GEP.getType()->isVectorTy()) {
2591 // Additional checks for vector GEPs.
2592 unsigned GEPWidth = GEP.getType()->getVectorNumElements();
2593 if (GEP.getPointerOperandType()->isVectorTy())
2594 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
2595 "Vector GEP result width doesn't match operand's", &GEP);
2596 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2597 Type *IndexTy = Idxs[i]->getType();
2598 if (IndexTy->isVectorTy()) {
2599 unsigned IndexWidth = IndexTy->getVectorNumElements();
2600 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP);
2602 Assert(IndexTy->getScalarType()->isIntegerTy(),
2603 "All GEP indices should be of integer type");
2606 visitInstruction(GEP);
2609 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2610 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2613 void Verifier::visitRangeMetadata(Instruction& I,
2614 MDNode* Range, Type* Ty) {
2616 Range == I.getMetadata(LLVMContext::MD_range) &&
2617 "precondition violation");
2619 unsigned NumOperands = Range->getNumOperands();
2620 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2621 unsigned NumRanges = NumOperands / 2;
2622 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2624 ConstantRange LastRange(1); // Dummy initial value
2625 for (unsigned i = 0; i < NumRanges; ++i) {
2627 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2628 Assert(Low, "The lower limit must be an integer!", Low);
2630 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2631 Assert(High, "The upper limit must be an integer!", High);
2632 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2633 "Range types must match instruction type!", &I);
2635 APInt HighV = High->getValue();
2636 APInt LowV = Low->getValue();
2637 ConstantRange CurRange(LowV, HighV);
2638 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2639 "Range must not be empty!", Range);
2641 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2642 "Intervals are overlapping", Range);
2643 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2645 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2648 LastRange = ConstantRange(LowV, HighV);
2650 if (NumRanges > 2) {
2652 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2654 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2655 ConstantRange FirstRange(FirstLow, FirstHigh);
2656 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2657 "Intervals are overlapping", Range);
2658 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2663 void Verifier::visitLoadInst(LoadInst &LI) {
2664 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2665 Assert(PTy, "Load operand must be a pointer.", &LI);
2666 Type *ElTy = LI.getType();
2667 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2668 "huge alignment values are unsupported", &LI);
2669 if (LI.isAtomic()) {
2670 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2671 "Load cannot have Release ordering", &LI);
2672 Assert(LI.getAlignment() != 0,
2673 "Atomic load must specify explicit alignment", &LI);
2674 if (!ElTy->isPointerTy()) {
2675 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2677 unsigned Size = ElTy->getPrimitiveSizeInBits();
2678 Assert(Size >= 8 && !(Size & (Size - 1)),
2679 "atomic load operand must be power-of-two byte-sized integer", &LI,
2683 Assert(LI.getSynchScope() == CrossThread,
2684 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2687 visitInstruction(LI);
2690 void Verifier::visitStoreInst(StoreInst &SI) {
2691 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2692 Assert(PTy, "Store operand must be a pointer.", &SI);
2693 Type *ElTy = PTy->getElementType();
2694 Assert(ElTy == SI.getOperand(0)->getType(),
2695 "Stored value type does not match pointer operand type!", &SI, ElTy);
2696 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2697 "huge alignment values are unsupported", &SI);
2698 if (SI.isAtomic()) {
2699 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2700 "Store cannot have Acquire ordering", &SI);
2701 Assert(SI.getAlignment() != 0,
2702 "Atomic store must specify explicit alignment", &SI);
2703 if (!ElTy->isPointerTy()) {
2704 Assert(ElTy->isIntegerTy(),
2705 "atomic store operand must have integer type!", &SI, ElTy);
2706 unsigned Size = ElTy->getPrimitiveSizeInBits();
2707 Assert(Size >= 8 && !(Size & (Size - 1)),
2708 "atomic store operand must be power-of-two byte-sized integer",
2712 Assert(SI.getSynchScope() == CrossThread,
2713 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2715 visitInstruction(SI);
2718 void Verifier::visitAllocaInst(AllocaInst &AI) {
2719 SmallPtrSet<Type*, 4> Visited;
2720 PointerType *PTy = AI.getType();
2721 Assert(PTy->getAddressSpace() == 0,
2722 "Allocation instruction pointer not in the generic address space!",
2724 Assert(AI.getAllocatedType()->isSized(&Visited),
2725 "Cannot allocate unsized type", &AI);
2726 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2727 "Alloca array size must have integer type", &AI);
2728 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2729 "huge alignment values are unsupported", &AI);
2731 visitInstruction(AI);
2734 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2736 // FIXME: more conditions???
2737 Assert(CXI.getSuccessOrdering() != NotAtomic,
2738 "cmpxchg instructions must be atomic.", &CXI);
2739 Assert(CXI.getFailureOrdering() != NotAtomic,
2740 "cmpxchg instructions must be atomic.", &CXI);
2741 Assert(CXI.getSuccessOrdering() != Unordered,
2742 "cmpxchg instructions cannot be unordered.", &CXI);
2743 Assert(CXI.getFailureOrdering() != Unordered,
2744 "cmpxchg instructions cannot be unordered.", &CXI);
2745 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2746 "cmpxchg instructions be at least as constrained on success as fail",
2748 Assert(CXI.getFailureOrdering() != Release &&
2749 CXI.getFailureOrdering() != AcquireRelease,
2750 "cmpxchg failure ordering cannot include release semantics", &CXI);
2752 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2753 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2754 Type *ElTy = PTy->getElementType();
2755 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2757 unsigned Size = ElTy->getPrimitiveSizeInBits();
2758 Assert(Size >= 8 && !(Size & (Size - 1)),
2759 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2760 Assert(ElTy == CXI.getOperand(1)->getType(),
2761 "Expected value type does not match pointer operand type!", &CXI,
2763 Assert(ElTy == CXI.getOperand(2)->getType(),
2764 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2765 visitInstruction(CXI);
2768 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2769 Assert(RMWI.getOrdering() != NotAtomic,
2770 "atomicrmw instructions must be atomic.", &RMWI);
2771 Assert(RMWI.getOrdering() != Unordered,
2772 "atomicrmw instructions cannot be unordered.", &RMWI);
2773 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2774 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2775 Type *ElTy = PTy->getElementType();
2776 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2778 unsigned Size = ElTy->getPrimitiveSizeInBits();
2779 Assert(Size >= 8 && !(Size & (Size - 1)),
2780 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2782 Assert(ElTy == RMWI.getOperand(1)->getType(),
2783 "Argument value type does not match pointer operand type!", &RMWI,
2785 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2786 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2787 "Invalid binary operation!", &RMWI);
2788 visitInstruction(RMWI);
2791 void Verifier::visitFenceInst(FenceInst &FI) {
2792 const AtomicOrdering Ordering = FI.getOrdering();
2793 Assert(Ordering == Acquire || Ordering == Release ||
2794 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2795 "fence instructions may only have "
2796 "acquire, release, acq_rel, or seq_cst ordering.",
2798 visitInstruction(FI);
2801 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2802 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2803 EVI.getIndices()) == EVI.getType(),
2804 "Invalid ExtractValueInst operands!", &EVI);
2806 visitInstruction(EVI);
2809 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2810 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2811 IVI.getIndices()) ==
2812 IVI.getOperand(1)->getType(),
2813 "Invalid InsertValueInst operands!", &IVI);
2815 visitInstruction(IVI);
2818 void Verifier::visitEHPadPredecessors(Instruction &I) {
2819 assert(I.isEHPad());
2821 BasicBlock *BB = I.getParent();
2822 Function *F = BB->getParent();
2824 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I);
2826 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) {
2827 // The landingpad instruction defines its parent as a landing pad block. The
2828 // landing pad block may be branched to only by the unwind edge of an
2830 for (BasicBlock *PredBB : predecessors(BB)) {
2831 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
2832 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2833 "Block containing LandingPadInst must be jumped to "
2834 "only by the unwind edge of an invoke.",
2840 for (BasicBlock *PredBB : predecessors(BB)) {
2841 TerminatorInst *TI = PredBB->getTerminator();
2842 if (auto *II = dyn_cast<InvokeInst>(TI))
2843 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB,
2844 "EH pad must be jumped to via an unwind edge", &I, II);
2845 else if (auto *CPI = dyn_cast<CatchPadInst>(TI))
2846 Assert(CPI->getUnwindDest() == BB && CPI->getNormalDest() != BB,
2847 "EH pad must be jumped to via an unwind edge", &I, CPI);
2848 else if (isa<CatchEndPadInst>(TI))
2850 else if (isa<CleanupReturnInst>(TI))
2852 else if (isa<CleanupEndPadInst>(TI))
2854 else if (isa<TerminatePadInst>(TI))
2857 Assert(false, "EH pad must be jumped to via an unwind edge", &I, TI);
2861 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2862 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2864 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2865 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2867 visitEHPadPredecessors(LPI);
2869 if (!LandingPadResultTy)
2870 LandingPadResultTy = LPI.getType();
2872 Assert(LandingPadResultTy == LPI.getType(),
2873 "The landingpad instruction should have a consistent result type "
2874 "inside a function.",
2877 Function *F = LPI.getParent()->getParent();
2878 Assert(F->hasPersonalityFn(),
2879 "LandingPadInst needs to be in a function with a personality.", &LPI);
2881 // The landingpad instruction must be the first non-PHI instruction in the
2883 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2884 "LandingPadInst not the first non-PHI instruction in the block.",
2887 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2888 Constant *Clause = LPI.getClause(i);
2889 if (LPI.isCatch(i)) {
2890 Assert(isa<PointerType>(Clause->getType()),
2891 "Catch operand does not have pointer type!", &LPI);
2893 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2894 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2895 "Filter operand is not an array of constants!", &LPI);
2899 visitInstruction(LPI);
2902 void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
2903 visitEHPadPredecessors(CPI);
2905 BasicBlock *BB = CPI.getParent();
2906 Function *F = BB->getParent();
2907 Assert(F->hasPersonalityFn(),
2908 "CatchPadInst needs to be in a function with a personality.", &CPI);
2910 // The catchpad instruction must be the first non-PHI instruction in the
2912 Assert(BB->getFirstNonPHI() == &CPI,
2913 "CatchPadInst not the first non-PHI instruction in the block.",
2916 if (!BB->getSinglePredecessor())
2917 for (BasicBlock *PredBB : predecessors(BB)) {
2918 Assert(!isa<CatchPadInst>(PredBB->getTerminator()),
2919 "CatchPadInst with CatchPadInst predecessor cannot have any other "
2924 BasicBlock *UnwindDest = CPI.getUnwindDest();
2925 Instruction *I = UnwindDest->getFirstNonPHI();
2927 isa<CatchPadInst>(I) || isa<CatchEndPadInst>(I),
2928 "CatchPadInst must unwind to a CatchPadInst or a CatchEndPadInst.",
2931 visitTerminatorInst(CPI);
2934 void Verifier::visitCatchEndPadInst(CatchEndPadInst &CEPI) {
2935 visitEHPadPredecessors(CEPI);
2937 BasicBlock *BB = CEPI.getParent();
2938 Function *F = BB->getParent();
2939 Assert(F->hasPersonalityFn(),
2940 "CatchEndPadInst needs to be in a function with a personality.",
2943 // The catchendpad instruction must be the first non-PHI instruction in the
2945 Assert(BB->getFirstNonPHI() == &CEPI,
2946 "CatchEndPadInst not the first non-PHI instruction in the block.",
2949 unsigned CatchPadsSeen = 0;
2950 for (BasicBlock *PredBB : predecessors(BB))
2951 if (isa<CatchPadInst>(PredBB->getTerminator()))
2954 Assert(CatchPadsSeen <= 1, "CatchEndPadInst must have no more than one "
2955 "CatchPadInst predecessor.",
2958 if (BasicBlock *UnwindDest = CEPI.getUnwindDest()) {
2959 Instruction *I = UnwindDest->getFirstNonPHI();
2961 I->isEHPad() && !isa<LandingPadInst>(I),
2962 "CatchEndPad must unwind to an EH block which is not a landingpad.",
2966 visitTerminatorInst(CEPI);
2969 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
2970 visitEHPadPredecessors(CPI);
2972 BasicBlock *BB = CPI.getParent();
2974 Function *F = BB->getParent();
2975 Assert(F->hasPersonalityFn(),
2976 "CleanupPadInst needs to be in a function with a personality.", &CPI);
2978 // The cleanuppad instruction must be the first non-PHI instruction in the
2980 Assert(BB->getFirstNonPHI() == &CPI,
2981 "CleanupPadInst not the first non-PHI instruction in the block.",
2984 User *FirstUser = nullptr;
2985 BasicBlock *FirstUnwindDest = nullptr;
2986 for (User *U : CPI.users()) {
2987 BasicBlock *UnwindDest;
2988 if (CleanupReturnInst *CRI = dyn_cast<CleanupReturnInst>(U)) {
2989 UnwindDest = CRI->getUnwindDest();
2991 UnwindDest = cast<CleanupEndPadInst>(U)->getUnwindDest();
2996 FirstUnwindDest = UnwindDest;
2998 Assert(UnwindDest == FirstUnwindDest,
2999 "Cleanuprets/cleanupendpads from the same cleanuppad must "
3000 "have the same unwind destination",
3005 visitInstruction(CPI);
3008 void Verifier::visitCleanupEndPadInst(CleanupEndPadInst &CEPI) {
3009 visitEHPadPredecessors(CEPI);
3011 BasicBlock *BB = CEPI.getParent();
3012 Function *F = BB->getParent();
3013 Assert(F->hasPersonalityFn(),
3014 "CleanupEndPadInst needs to be in a function with a personality.",
3017 // The cleanupendpad instruction must be the first non-PHI instruction in the
3019 Assert(BB->getFirstNonPHI() == &CEPI,
3020 "CleanupEndPadInst not the first non-PHI instruction in the block.",
3023 if (BasicBlock *UnwindDest = CEPI.getUnwindDest()) {
3024 Instruction *I = UnwindDest->getFirstNonPHI();
3026 I->isEHPad() && !isa<LandingPadInst>(I),
3027 "CleanupEndPad must unwind to an EH block which is not a landingpad.",
3031 visitTerminatorInst(CEPI);
3034 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
3035 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) {
3036 Instruction *I = UnwindDest->getFirstNonPHI();
3037 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3038 "CleanupReturnInst must unwind to an EH block which is not a "
3043 visitTerminatorInst(CRI);
3046 void Verifier::visitTerminatePadInst(TerminatePadInst &TPI) {
3047 visitEHPadPredecessors(TPI);
3049 BasicBlock *BB = TPI.getParent();
3050 Function *F = BB->getParent();
3051 Assert(F->hasPersonalityFn(),
3052 "TerminatePadInst needs to be in a function with a personality.",
3055 // The terminatepad instruction must be the first non-PHI instruction in the
3057 Assert(BB->getFirstNonPHI() == &TPI,
3058 "TerminatePadInst not the first non-PHI instruction in the block.",
3061 if (BasicBlock *UnwindDest = TPI.getUnwindDest()) {
3062 Instruction *I = UnwindDest->getFirstNonPHI();
3063 Assert(I->isEHPad() && !isa<LandingPadInst>(I),
3064 "TerminatePadInst must unwind to an EH block which is not a "
3069 visitTerminatorInst(TPI);
3072 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
3073 Instruction *Op = cast<Instruction>(I.getOperand(i));
3074 // If the we have an invalid invoke, don't try to compute the dominance.
3075 // We already reject it in the invoke specific checks and the dominance
3076 // computation doesn't handle multiple edges.
3077 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
3078 if (II->getNormalDest() == II->getUnwindDest())
3082 const Use &U = I.getOperandUse(i);
3083 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
3084 "Instruction does not dominate all uses!", Op, &I);
3087 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) {
3088 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3089 "apply only to pointer types", &I);
3090 Assert(isa<LoadInst>(I),
3091 "dereferenceable, dereferenceable_or_null apply only to load"
3092 " instructions, use attributes for calls or invokes", &I);
3093 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3094 "take one operand!", &I);
3095 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
3096 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, "
3097 "dereferenceable_or_null metadata value must be an i64!", &I);
3100 /// verifyInstruction - Verify that an instruction is well formed.
3102 void Verifier::visitInstruction(Instruction &I) {
3103 BasicBlock *BB = I.getParent();
3104 Assert(BB, "Instruction not embedded in basic block!", &I);
3106 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
3107 for (User *U : I.users()) {
3108 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
3109 "Only PHI nodes may reference their own value!", &I);
3113 // Check that void typed values don't have names
3114 Assert(!I.getType()->isVoidTy() || !I.hasName(),
3115 "Instruction has a name, but provides a void value!", &I);
3117 // Check that the return value of the instruction is either void or a legal
3119 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
3120 "Instruction returns a non-scalar type!", &I);
3122 // Check that the instruction doesn't produce metadata. Calls are already
3123 // checked against the callee type.
3124 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
3125 "Invalid use of metadata!", &I);
3127 // Check that all uses of the instruction, if they are instructions
3128 // themselves, actually have parent basic blocks. If the use is not an
3129 // instruction, it is an error!
3130 for (Use &U : I.uses()) {
3131 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
3132 Assert(Used->getParent() != nullptr,
3133 "Instruction referencing"
3134 " instruction not embedded in a basic block!",
3137 CheckFailed("Use of instruction is not an instruction!", U);
3142 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
3143 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
3145 // Check to make sure that only first-class-values are operands to
3147 if (!I.getOperand(i)->getType()->isFirstClassType()) {
3148 Assert(0, "Instruction operands must be first-class values!", &I);
3151 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
3152 // Check to make sure that the "address of" an intrinsic function is never
3155 !F->isIntrinsic() ||
3156 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
3157 "Cannot take the address of an intrinsic!", &I);
3159 !F->isIntrinsic() || isa<CallInst>(I) ||
3160 F->getIntrinsicID() == Intrinsic::donothing ||
3161 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
3162 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
3163 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
3164 "Cannot invoke an intrinsinc other than"
3165 " donothing or patchpoint",
3167 Assert(F->getParent() == M, "Referencing function in another module!",
3169 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
3170 Assert(OpBB->getParent() == BB->getParent(),
3171 "Referring to a basic block in another function!", &I);
3172 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
3173 Assert(OpArg->getParent() == BB->getParent(),
3174 "Referring to an argument in another function!", &I);
3175 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
3176 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
3177 } else if (isa<Instruction>(I.getOperand(i))) {
3178 verifyDominatesUse(I, i);
3179 } else if (isa<InlineAsm>(I.getOperand(i))) {
3180 Assert((i + 1 == e && isa<CallInst>(I)) ||
3181 (i + 3 == e && isa<InvokeInst>(I)),
3182 "Cannot take the address of an inline asm!", &I);
3183 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
3184 if (CE->getType()->isPtrOrPtrVectorTy()) {
3185 // If we have a ConstantExpr pointer, we need to see if it came from an
3186 // illegal bitcast (inttoptr <constant int> )
3187 SmallVector<const ConstantExpr *, 4> Stack;
3188 SmallPtrSet<const ConstantExpr *, 4> Visited;
3189 Stack.push_back(CE);
3191 while (!Stack.empty()) {
3192 const ConstantExpr *V = Stack.pop_back_val();
3193 if (!Visited.insert(V).second)
3196 VerifyConstantExprBitcastType(V);
3198 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
3199 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
3200 Stack.push_back(Op);
3207 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
3208 Assert(I.getType()->isFPOrFPVectorTy(),
3209 "fpmath requires a floating point result!", &I);
3210 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
3211 if (ConstantFP *CFP0 =
3212 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
3213 APFloat Accuracy = CFP0->getValueAPF();
3214 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
3215 "fpmath accuracy not a positive number!", &I);
3217 Assert(false, "invalid fpmath accuracy!", &I);
3221 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
3222 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
3223 "Ranges are only for loads, calls and invokes!", &I);
3224 visitRangeMetadata(I, Range, I.getType());
3227 if (I.getMetadata(LLVMContext::MD_nonnull)) {
3228 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
3230 Assert(isa<LoadInst>(I),
3231 "nonnull applies only to load instructions, use attributes"
3232 " for calls or invokes",
3236 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable))
3237 visitDereferenceableMetadata(I, MD);
3239 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
3240 visitDereferenceableMetadata(I, MD);
3242 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) {
3243 Assert(I.getType()->isPointerTy(), "align applies only to pointer types",
3245 Assert(isa<LoadInst>(I), "align applies only to load instructions, "
3246 "use attributes for calls or invokes", &I);
3247 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I);
3248 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
3249 Assert(CI && CI->getType()->isIntegerTy(64),
3250 "align metadata value must be an i64!", &I);
3251 uint64_t Align = CI->getZExtValue();
3252 Assert(isPowerOf2_64(Align),
3253 "align metadata value must be a power of 2!", &I);
3254 Assert(Align <= Value::MaximumAlignment,
3255 "alignment is larger that implementation defined limit", &I);
3258 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
3259 Assert(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N);
3263 InstsInThisBlock.insert(&I);
3266 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
3267 /// intrinsic argument or return value) matches the type constraints specified
3268 /// by the .td file (e.g. an "any integer" argument really is an integer).
3270 /// This return true on error but does not print a message.
3271 bool Verifier::VerifyIntrinsicType(Type *Ty,
3272 ArrayRef<Intrinsic::IITDescriptor> &Infos,
3273 SmallVectorImpl<Type*> &ArgTys) {
3274 using namespace Intrinsic;
3276 // If we ran out of descriptors, there are too many arguments.
3277 if (Infos.empty()) return true;
3278 IITDescriptor D = Infos.front();
3279 Infos = Infos.slice(1);
3282 case IITDescriptor::Void: return !Ty->isVoidTy();
3283 case IITDescriptor::VarArg: return true;
3284 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
3285 case IITDescriptor::Token: return !Ty->isTokenTy();
3286 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
3287 case IITDescriptor::Half: return !Ty->isHalfTy();
3288 case IITDescriptor::Float: return !Ty->isFloatTy();
3289 case IITDescriptor::Double: return !Ty->isDoubleTy();
3290 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
3291 case IITDescriptor::Vector: {
3292 VectorType *VT = dyn_cast<VectorType>(Ty);
3293 return !VT || VT->getNumElements() != D.Vector_Width ||
3294 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
3296 case IITDescriptor::Pointer: {
3297 PointerType *PT = dyn_cast<PointerType>(Ty);
3298 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
3299 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
3302 case IITDescriptor::Struct: {
3303 StructType *ST = dyn_cast<StructType>(Ty);
3304 if (!ST || ST->getNumElements() != D.Struct_NumElements)
3307 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
3308 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
3313 case IITDescriptor::Argument:
3314 // Two cases here - If this is the second occurrence of an argument, verify
3315 // that the later instance matches the previous instance.
3316 if (D.getArgumentNumber() < ArgTys.size())
3317 return Ty != ArgTys[D.getArgumentNumber()];
3319 // Otherwise, if this is the first instance of an argument, record it and
3320 // verify the "Any" kind.
3321 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
3322 ArgTys.push_back(Ty);
3324 switch (D.getArgumentKind()) {
3325 case IITDescriptor::AK_Any: return false; // Success
3326 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
3327 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
3328 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
3329 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
3331 llvm_unreachable("all argument kinds not covered");
3333 case IITDescriptor::ExtendArgument: {
3334 // This may only be used when referring to a previous vector argument.
3335 if (D.getArgumentNumber() >= ArgTys.size())
3338 Type *NewTy = ArgTys[D.getArgumentNumber()];
3339 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3340 NewTy = VectorType::getExtendedElementVectorType(VTy);
3341 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3342 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
3348 case IITDescriptor::TruncArgument: {
3349 // This may only be used when referring to a previous vector argument.
3350 if (D.getArgumentNumber() >= ArgTys.size())
3353 Type *NewTy = ArgTys[D.getArgumentNumber()];
3354 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
3355 NewTy = VectorType::getTruncatedElementVectorType(VTy);
3356 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
3357 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
3363 case IITDescriptor::HalfVecArgument:
3364 // This may only be used when referring to a previous vector argument.
3365 return D.getArgumentNumber() >= ArgTys.size() ||
3366 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
3367 VectorType::getHalfElementsVectorType(
3368 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
3369 case IITDescriptor::SameVecWidthArgument: {
3370 if (D.getArgumentNumber() >= ArgTys.size())
3372 VectorType * ReferenceType =
3373 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
3374 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
3375 if (!ThisArgType || !ReferenceType ||
3376 (ReferenceType->getVectorNumElements() !=
3377 ThisArgType->getVectorNumElements()))
3379 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
3382 case IITDescriptor::PtrToArgument: {
3383 if (D.getArgumentNumber() >= ArgTys.size())
3385 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
3386 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
3387 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
3389 case IITDescriptor::VecOfPtrsToElt: {
3390 if (D.getArgumentNumber() >= ArgTys.size())
3392 VectorType * ReferenceType =
3393 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
3394 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
3395 if (!ThisArgVecTy || !ReferenceType ||
3396 (ReferenceType->getVectorNumElements() !=
3397 ThisArgVecTy->getVectorNumElements()))
3399 PointerType *ThisArgEltTy =
3400 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
3403 return ThisArgEltTy->getElementType() !=
3404 ReferenceType->getVectorElementType();
3407 llvm_unreachable("unhandled");
3410 /// \brief Verify if the intrinsic has variable arguments.
3411 /// This method is intended to be called after all the fixed arguments have been
3414 /// This method returns true on error and does not print an error message.
3416 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
3417 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
3418 using namespace Intrinsic;
3420 // If there are no descriptors left, then it can't be a vararg.
3424 // There should be only one descriptor remaining at this point.
3425 if (Infos.size() != 1)
3428 // Check and verify the descriptor.
3429 IITDescriptor D = Infos.front();
3430 Infos = Infos.slice(1);
3431 if (D.Kind == IITDescriptor::VarArg)
3437 /// Allow intrinsics to be verified in different ways.
3438 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) {
3439 Function *IF = CS.getCalledFunction();
3440 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
3443 // Verify that the intrinsic prototype lines up with what the .td files
3445 FunctionType *IFTy = IF->getFunctionType();
3446 bool IsVarArg = IFTy->isVarArg();
3448 SmallVector<Intrinsic::IITDescriptor, 8> Table;
3449 getIntrinsicInfoTableEntries(ID, Table);
3450 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
3452 SmallVector<Type *, 4> ArgTys;
3453 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
3454 "Intrinsic has incorrect return type!", IF);
3455 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
3456 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
3457 "Intrinsic has incorrect argument type!", IF);
3459 // Verify if the intrinsic call matches the vararg property.
3461 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3462 "Intrinsic was not defined with variable arguments!", IF);
3464 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
3465 "Callsite was not defined with variable arguments!", IF);
3467 // All descriptors should be absorbed by now.
3468 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
3470 // Now that we have the intrinsic ID and the actual argument types (and we
3471 // know they are legal for the intrinsic!) get the intrinsic name through the
3472 // usual means. This allows us to verify the mangling of argument types into
3474 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
3475 Assert(ExpectedName == IF->getName(),
3476 "Intrinsic name not mangled correctly for type arguments! "
3481 // If the intrinsic takes MDNode arguments, verify that they are either global
3482 // or are local to *this* function.
3483 for (Value *V : CS.args())
3484 if (auto *MD = dyn_cast<MetadataAsValue>(V))
3485 visitMetadataAsValue(*MD, CS.getCaller());
3490 case Intrinsic::ctlz: // llvm.ctlz
3491 case Intrinsic::cttz: // llvm.cttz
3492 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3493 "is_zero_undef argument of bit counting intrinsics must be a "
3497 case Intrinsic::dbg_declare: // llvm.dbg.declare
3498 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)),
3499 "invalid llvm.dbg.declare intrinsic call 1", CS);
3500 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction()));
3502 case Intrinsic::dbg_value: // llvm.dbg.value
3503 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction()));
3505 case Intrinsic::memcpy:
3506 case Intrinsic::memmove:
3507 case Intrinsic::memset: {
3508 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3));
3510 "alignment argument of memory intrinsics must be a constant int",
3512 const APInt &AlignVal = AlignCI->getValue();
3513 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
3514 "alignment argument of memory intrinsics must be a power of 2", CS);
3515 Assert(isa<ConstantInt>(CS.getArgOperand(4)),
3516 "isvolatile argument of memory intrinsics must be a constant int",
3520 case Intrinsic::gcroot:
3521 case Intrinsic::gcwrite:
3522 case Intrinsic::gcread:
3523 if (ID == Intrinsic::gcroot) {
3525 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts());
3526 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS);
3527 Assert(isa<Constant>(CS.getArgOperand(1)),
3528 "llvm.gcroot parameter #2 must be a constant.", CS);
3529 if (!AI->getAllocatedType()->isPointerTy()) {
3530 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)),
3531 "llvm.gcroot parameter #1 must either be a pointer alloca, "
3532 "or argument #2 must be a non-null constant.",
3537 Assert(CS.getParent()->getParent()->hasGC(),
3538 "Enclosing function does not use GC.", CS);
3540 case Intrinsic::init_trampoline:
3541 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()),
3542 "llvm.init_trampoline parameter #2 must resolve to a function.",
3545 case Intrinsic::prefetch:
3546 Assert(isa<ConstantInt>(CS.getArgOperand(1)) &&
3547 isa<ConstantInt>(CS.getArgOperand(2)) &&
3548 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 &&
3549 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4,
3550 "invalid arguments to llvm.prefetch", CS);
3552 case Intrinsic::stackprotector:
3553 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()),
3554 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS);
3556 case Intrinsic::lifetime_start:
3557 case Intrinsic::lifetime_end:
3558 case Intrinsic::invariant_start:
3559 Assert(isa<ConstantInt>(CS.getArgOperand(0)),
3560 "size argument of memory use markers must be a constant integer",
3563 case Intrinsic::invariant_end:
3564 Assert(isa<ConstantInt>(CS.getArgOperand(1)),
3565 "llvm.invariant.end parameter #2 must be a constant integer", CS);
3568 case Intrinsic::localescape: {
3569 BasicBlock *BB = CS.getParent();
3570 Assert(BB == &BB->getParent()->front(),
3571 "llvm.localescape used outside of entry block", CS);
3572 Assert(!SawFrameEscape,
3573 "multiple calls to llvm.localescape in one function", CS);
3574 for (Value *Arg : CS.args()) {
3575 if (isa<ConstantPointerNull>(Arg))
3576 continue; // Null values are allowed as placeholders.
3577 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3578 Assert(AI && AI->isStaticAlloca(),
3579 "llvm.localescape only accepts static allocas", CS);
3581 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands();
3582 SawFrameEscape = true;
3585 case Intrinsic::localrecover: {
3586 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts();
3587 Function *Fn = dyn_cast<Function>(FnArg);
3588 Assert(Fn && !Fn->isDeclaration(),
3589 "llvm.localrecover first "
3590 "argument must be function defined in this module",
3592 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2));
3593 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int",
3595 auto &Entry = FrameEscapeInfo[Fn];
3596 Entry.second = unsigned(
3597 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3601 case Intrinsic::experimental_gc_statepoint:
3602 Assert(!CS.isInlineAsm(),
3603 "gc.statepoint support for inline assembly unimplemented", CS);
3604 Assert(CS.getParent()->getParent()->hasGC(),
3605 "Enclosing function does not use GC.", CS);
3607 VerifyStatepoint(CS);
3609 case Intrinsic::experimental_gc_result_int:
3610 case Intrinsic::experimental_gc_result_float:
3611 case Intrinsic::experimental_gc_result_ptr:
3612 case Intrinsic::experimental_gc_result: {
3613 Assert(CS.getParent()->getParent()->hasGC(),
3614 "Enclosing function does not use GC.", CS);
3615 // Are we tied to a statepoint properly?
3616 CallSite StatepointCS(CS.getArgOperand(0));
3617 const Function *StatepointFn =
3618 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3619 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3620 StatepointFn->getIntrinsicID() ==
3621 Intrinsic::experimental_gc_statepoint,
3622 "gc.result operand #1 must be from a statepoint", CS,
3623 CS.getArgOperand(0));
3625 // Assert that result type matches wrapped callee.
3626 const Value *Target = StatepointCS.getArgument(2);
3627 auto *PT = cast<PointerType>(Target->getType());
3628 auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
3629 Assert(CS.getType() == TargetFuncType->getReturnType(),
3630 "gc.result result type does not match wrapped callee", CS);
3633 case Intrinsic::experimental_gc_relocate: {
3634 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS);
3636 // Check that this relocate is correctly tied to the statepoint
3638 // This is case for relocate on the unwinding path of an invoke statepoint
3639 if (ExtractValueInst *ExtractValue =
3640 dyn_cast<ExtractValueInst>(CS.getArgOperand(0))) {
3641 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3642 "gc relocate on unwind path incorrectly linked to the statepoint",
3645 const BasicBlock *InvokeBB =
3646 ExtractValue->getParent()->getUniquePredecessor();
3648 // Landingpad relocates should have only one predecessor with invoke
3649 // statepoint terminator
3650 Assert(InvokeBB, "safepoints should have unique landingpads",
3651 ExtractValue->getParent());
3652 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed",
3654 Assert(isStatepoint(InvokeBB->getTerminator()),
3655 "gc relocate should be linked to a statepoint", InvokeBB);
3658 // In all other cases relocate should be tied to the statepoint directly.
3659 // This covers relocates on a normal return path of invoke statepoint and
3660 // relocates of a call statepoint
3661 auto Token = CS.getArgOperand(0);
3662 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3663 "gc relocate is incorrectly tied to the statepoint", CS, Token);
3666 // Verify rest of the relocate arguments
3668 GCRelocateOperands Ops(CS);
3669 ImmutableCallSite StatepointCS(Ops.getStatepoint());
3671 // Both the base and derived must be piped through the safepoint
3672 Value* Base = CS.getArgOperand(1);
3673 Assert(isa<ConstantInt>(Base),
3674 "gc.relocate operand #2 must be integer offset", CS);
3676 Value* Derived = CS.getArgOperand(2);
3677 Assert(isa<ConstantInt>(Derived),
3678 "gc.relocate operand #3 must be integer offset", CS);
3680 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3681 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3683 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3684 "gc.relocate: statepoint base index out of bounds", CS);
3685 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3686 "gc.relocate: statepoint derived index out of bounds", CS);
3688 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3689 // section of the statepoint's argument
3690 Assert(StatepointCS.arg_size() > 0,
3691 "gc.statepoint: insufficient arguments");
3692 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)),
3693 "gc.statement: number of call arguments must be constant integer");
3694 const unsigned NumCallArgs =
3695 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue();
3696 Assert(StatepointCS.arg_size() > NumCallArgs + 5,
3697 "gc.statepoint: mismatch in number of call arguments");
3698 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)),
3699 "gc.statepoint: number of transition arguments must be "
3700 "a constant integer");
3701 const int NumTransitionArgs =
3702 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5))
3704 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
3705 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)),
3706 "gc.statepoint: number of deoptimization arguments must be "
3707 "a constant integer");
3708 const int NumDeoptArgs =
3709 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart))->getZExtValue();
3710 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
3711 const int GCParamArgsEnd = StatepointCS.arg_size();
3712 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3713 "gc.relocate: statepoint base index doesn't fall within the "
3714 "'gc parameters' section of the statepoint call",
3716 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3717 "gc.relocate: statepoint derived index doesn't fall within the "
3718 "'gc parameters' section of the statepoint call",
3721 // Relocated value must be a pointer type, but gc_relocate does not need to return the
3722 // same pointer type as the relocated pointer. It can be casted to the correct type later
3723 // if it's desired. However, they must have the same address space.
3724 GCRelocateOperands Operands(CS);
3725 Assert(Operands.getDerivedPtr()->getType()->isPointerTy(),
3726 "gc.relocate: relocated value must be a gc pointer", CS);
3728 // gc_relocate return type must be a pointer type, and is verified earlier in
3729 // VerifyIntrinsicType().
3730 Assert(cast<PointerType>(CS.getType())->getAddressSpace() ==
3731 cast<PointerType>(Operands.getDerivedPtr()->getType())->getAddressSpace(),
3732 "gc.relocate: relocating a pointer shouldn't change its address space", CS);
3735 case Intrinsic::eh_exceptioncode:
3736 case Intrinsic::eh_exceptionpointer: {
3737 Assert(isa<CatchPadInst>(CS.getArgOperand(0)),
3738 "eh.exceptionpointer argument must be a catchpad", CS);
3744 /// \brief Carefully grab the subprogram from a local scope.
3746 /// This carefully grabs the subprogram from a local scope, avoiding the
3747 /// built-in assertions that would typically fire.
3748 static DISubprogram *getSubprogram(Metadata *LocalScope) {
3752 if (auto *SP = dyn_cast<DISubprogram>(LocalScope))
3755 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
3756 return getSubprogram(LB->getRawScope());
3758 // Just return null; broken scope chains are checked elsewhere.
3759 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope");
3763 template <class DbgIntrinsicTy>
3764 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3765 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3766 Assert(isa<ValueAsMetadata>(MD) ||
3767 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3768 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3769 Assert(isa<DILocalVariable>(DII.getRawVariable()),
3770 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3771 DII.getRawVariable());
3772 Assert(isa<DIExpression>(DII.getRawExpression()),
3773 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3774 DII.getRawExpression());
3776 // Ignore broken !dbg attachments; they're checked elsewhere.
3777 if (MDNode *N = DII.getDebugLoc().getAsMDNode())
3778 if (!isa<DILocation>(N))
3781 BasicBlock *BB = DII.getParent();
3782 Function *F = BB ? BB->getParent() : nullptr;
3784 // The scopes for variables and !dbg attachments must agree.
3785 DILocalVariable *Var = DII.getVariable();
3786 DILocation *Loc = DII.getDebugLoc();
3787 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment",
3790 DISubprogram *VarSP = getSubprogram(Var->getRawScope());
3791 DISubprogram *LocSP = getSubprogram(Loc->getRawScope());
3792 if (!VarSP || !LocSP)
3793 return; // Broken scope chains are checked elsewhere.
3795 Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind +
3796 " variable and !dbg attachment",
3797 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc,
3798 Loc->getScope()->getSubprogram());
3801 template <class MapTy>
3802 static uint64_t getVariableSize(const DILocalVariable &V, const MapTy &Map) {
3803 // Be careful of broken types (checked elsewhere).
3804 const Metadata *RawType = V.getRawType();
3806 // Try to get the size directly.
3807 if (auto *T = dyn_cast<DIType>(RawType))
3808 if (uint64_t Size = T->getSizeInBits())
3811 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
3812 // Look at the base type.
3813 RawType = DT->getRawBaseType();
3817 if (auto *S = dyn_cast<MDString>(RawType)) {
3818 // Don't error on missing types (checked elsewhere).
3819 RawType = Map.lookup(S);
3823 // Missing type or size.
3831 template <class MapTy>
3832 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I,
3833 const MapTy &TypeRefs) {
3836 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) {
3837 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable());
3838 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression());
3840 auto *DDI = cast<DbgDeclareInst>(&I);
3841 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable());
3842 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression());
3845 // We don't know whether this intrinsic verified correctly.
3846 if (!V || !E || !E->isValid())
3849 // Nothing to do if this isn't a bit piece expression.
3850 if (!E->isBitPiece())
3853 // The frontend helps out GDB by emitting the members of local anonymous
3854 // unions as artificial local variables with shared storage. When SROA splits
3855 // the storage for artificial local variables that are smaller than the entire
3856 // union, the overhang piece will be outside of the allotted space for the
3857 // variable and this check fails.
3858 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
3859 if (V->isArtificial())
3862 // If there's no size, the type is broken, but that should be checked
3864 uint64_t VarSize = getVariableSize(*V, TypeRefs);
3868 unsigned PieceSize = E->getBitPieceSize();
3869 unsigned PieceOffset = E->getBitPieceOffset();
3870 Assert(PieceSize + PieceOffset <= VarSize,
3871 "piece is larger than or outside of variable", &I, V, E);
3872 Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E);
3875 void Verifier::visitUnresolvedTypeRef(const MDString *S, const MDNode *N) {
3876 // This is in its own function so we get an error for each bad type ref (not
3878 Assert(false, "unresolved type ref", S, N);
3881 void Verifier::verifyTypeRefs() {
3882 auto *CUs = M->getNamedMetadata("llvm.dbg.cu");
3886 // Visit all the compile units again to map the type references.
3887 SmallDenseMap<const MDString *, const DIType *, 32> TypeRefs;
3888 for (auto *CU : CUs->operands())
3889 if (auto Ts = cast<DICompileUnit>(CU)->getRetainedTypes())
3890 for (DIType *Op : Ts)
3891 if (auto *T = dyn_cast_or_null<DICompositeType>(Op))
3892 if (auto *S = T->getRawIdentifier()) {
3893 UnresolvedTypeRefs.erase(S);
3894 TypeRefs.insert(std::make_pair(S, T));
3897 // Verify debug info intrinsic bit piece expressions. This needs a second
3898 // pass through the intructions, since we haven't built TypeRefs yet when
3899 // verifying functions, and simply queuing the DbgInfoIntrinsics to evaluate
3900 // later/now would queue up some that could be later deleted.
3901 for (const Function &F : *M)
3902 for (const BasicBlock &BB : F)
3903 for (const Instruction &I : BB)
3904 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I))
3905 verifyBitPieceExpression(*DII, TypeRefs);
3907 // Return early if all typerefs were resolved.
3908 if (UnresolvedTypeRefs.empty())
3911 // Sort the unresolved references by name so the output is deterministic.
3912 typedef std::pair<const MDString *, const MDNode *> TypeRef;
3913 SmallVector<TypeRef, 32> Unresolved(UnresolvedTypeRefs.begin(),
3914 UnresolvedTypeRefs.end());
3915 std::sort(Unresolved.begin(), Unresolved.end(),
3916 [](const TypeRef &LHS, const TypeRef &RHS) {
3917 return LHS.first->getString() < RHS.first->getString();
3920 // Visit the unresolved refs (printing out the errors).
3921 for (const TypeRef &TR : Unresolved)
3922 visitUnresolvedTypeRef(TR.first, TR.second);
3925 //===----------------------------------------------------------------------===//
3926 // Implement the public interfaces to this file...
3927 //===----------------------------------------------------------------------===//
3929 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3930 Function &F = const_cast<Function &>(f);
3931 assert(!F.isDeclaration() && "Cannot verify external functions");
3933 raw_null_ostream NullStr;
3934 Verifier V(OS ? *OS : NullStr);
3936 // Note that this function's return value is inverted from what you would
3937 // expect of a function called "verify".
3938 return !V.verify(F);
3941 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3942 raw_null_ostream NullStr;
3943 Verifier V(OS ? *OS : NullStr);
3945 bool Broken = false;
3946 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3947 if (!I->isDeclaration() && !I->isMaterializable())
3948 Broken |= !V.verify(*I);
3950 // Note that this function's return value is inverted from what you would
3951 // expect of a function called "verify".
3952 return !V.verify(M) || Broken;
3956 struct VerifierLegacyPass : public FunctionPass {
3962 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3963 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3965 explicit VerifierLegacyPass(bool FatalErrors)
3966 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3967 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3970 bool runOnFunction(Function &F) override {
3971 if (!V.verify(F) && FatalErrors)
3972 report_fatal_error("Broken function found, compilation aborted!");
3977 bool doFinalization(Module &M) override {
3978 if (!V.verify(M) && FatalErrors)
3979 report_fatal_error("Broken module found, compilation aborted!");
3984 void getAnalysisUsage(AnalysisUsage &AU) const override {
3985 AU.setPreservesAll();
3990 char VerifierLegacyPass::ID = 0;
3991 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3993 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3994 return new VerifierLegacyPass(FatalErrors);
3997 PreservedAnalyses VerifierPass::run(Module &M) {
3998 if (verifyModule(M, &dbgs()) && FatalErrors)
3999 report_fatal_error("Broken module found, compilation aborted!");
4001 return PreservedAnalyses::all();
4004 PreservedAnalyses VerifierPass::run(Function &F) {
4005 if (verifyFunction(F, &dbgs()) && FatalErrors)
4006 report_fatal_error("Broken function found, compilation aborted!");
4008 return PreservedAnalyses::all();