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 // * All landingpad instructions must use the same personality function with
44 // * All other things that are tested by asserts spread about the code...
46 //===----------------------------------------------------------------------===//
48 #include "llvm/IR/Verifier.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/ConstantRange.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugInfo.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Dominators.h"
63 #include "llvm/IR/InlineAsm.h"
64 #include "llvm/IR/InstIterator.h"
65 #include "llvm/IR/InstVisitor.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/IR/Metadata.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PassManager.h"
71 #include "llvm/IR/Statepoint.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/raw_ostream.h"
81 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
84 struct VerifierSupport {
88 /// \brief Track the brokenness of the module while recursively visiting.
91 explicit VerifierSupport(raw_ostream &OS)
92 : OS(OS), M(nullptr), Broken(false) {}
95 void Write(const Value *V) {
98 if (isa<Instruction>(V)) {
101 V->printAsOperand(OS, true, M);
106 void Write(const Metadata *MD) {
113 void Write(Type *T) {
119 void Write(const Comdat *C) {
125 template <typename T1, typename... Ts>
126 void WriteTs(const T1 &V1, const Ts &... Vs) {
131 template <typename... Ts> void WriteTs() {}
134 /// \brief A check failed, so printout out the condition and the message.
136 /// This provides a nice place to put a breakpoint if you want to see why
137 /// something is not correct.
138 void CheckFailed(const Twine &Message) {
139 OS << Message << '\n';
143 /// \brief A check failed (with values to print).
145 /// This calls the Message-only version so that the above is easier to set a
147 template <typename T1, typename... Ts>
148 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
149 CheckFailed(Message);
154 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
155 friend class InstVisitor<Verifier>;
157 LLVMContext *Context;
160 /// \brief When verifying a basic block, keep track of all of the
161 /// instructions we have seen so far.
163 /// This allows us to do efficient dominance checks for the case when an
164 /// instruction has an operand that is an instruction in the same block.
165 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
167 /// \brief Keep track of the metadata nodes that have been checked already.
168 SmallPtrSet<const Metadata *, 32> MDNodes;
170 /// \brief The personality function referenced by the LandingPadInsts.
171 /// All LandingPadInsts within the same function must use the same
172 /// personality function.
173 const Value *PersonalityFn;
175 /// \brief Whether we've seen a call to @llvm.frameescape in this function
179 /// Stores the count of how many objects were passed to llvm.frameescape for a
180 /// given function and the largest index passed to llvm.framerecover.
181 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
184 explicit Verifier(raw_ostream &OS)
185 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
186 SawFrameEscape(false) {}
188 bool verify(const Function &F) {
190 Context = &M->getContext();
192 // First ensure the function is well-enough formed to compute dominance
195 OS << "Function '" << F.getName()
196 << "' does not contain an entry block!\n";
199 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
200 if (I->empty() || !I->back().isTerminator()) {
201 OS << "Basic Block in function '" << F.getName()
202 << "' does not have terminator!\n";
203 I->printAsOperand(OS, true);
209 // Now directly compute a dominance tree. We don't rely on the pass
210 // manager to provide this as it isolates us from a potentially
211 // out-of-date dominator tree and makes it significantly more complex to
212 // run this code outside of a pass manager.
213 // FIXME: It's really gross that we have to cast away constness here.
214 DT.recalculate(const_cast<Function &>(F));
217 // FIXME: We strip const here because the inst visitor strips const.
218 visit(const_cast<Function &>(F));
219 InstsInThisBlock.clear();
220 PersonalityFn = nullptr;
221 SawFrameEscape = false;
226 bool verify(const Module &M) {
228 Context = &M.getContext();
231 // Scan through, checking all of the external function's linkage now...
232 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
233 visitGlobalValue(*I);
235 // Check to make sure function prototypes are okay.
236 if (I->isDeclaration())
240 // Now that we've visited every function, verify that we never asked to
241 // recover a frame index that wasn't escaped.
242 verifyFrameRecoverIndices();
244 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
246 visitGlobalVariable(*I);
248 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
250 visitGlobalAlias(*I);
252 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
253 E = M.named_metadata_end();
255 visitNamedMDNode(*I);
257 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
258 visitComdat(SMEC.getValue());
261 visitModuleIdents(M);
267 // Verification methods...
268 void visitGlobalValue(const GlobalValue &GV);
269 void visitGlobalVariable(const GlobalVariable &GV);
270 void visitGlobalAlias(const GlobalAlias &GA);
271 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
272 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
273 const GlobalAlias &A, const Constant &C);
274 void visitNamedMDNode(const NamedMDNode &NMD);
275 void visitMDNode(const MDNode &MD);
276 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
277 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
278 void visitComdat(const Comdat &C);
279 void visitModuleIdents(const Module &M);
280 void visitModuleFlags(const Module &M);
281 void visitModuleFlag(const MDNode *Op,
282 DenseMap<const MDString *, const MDNode *> &SeenIDs,
283 SmallVectorImpl<const MDNode *> &Requirements);
284 void visitFunction(const Function &F);
285 void visitBasicBlock(BasicBlock &BB);
286 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
288 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
289 #include "llvm/IR/Metadata.def"
291 // InstVisitor overrides...
292 using InstVisitor<Verifier>::visit;
293 void visit(Instruction &I);
295 void visitTruncInst(TruncInst &I);
296 void visitZExtInst(ZExtInst &I);
297 void visitSExtInst(SExtInst &I);
298 void visitFPTruncInst(FPTruncInst &I);
299 void visitFPExtInst(FPExtInst &I);
300 void visitFPToUIInst(FPToUIInst &I);
301 void visitFPToSIInst(FPToSIInst &I);
302 void visitUIToFPInst(UIToFPInst &I);
303 void visitSIToFPInst(SIToFPInst &I);
304 void visitIntToPtrInst(IntToPtrInst &I);
305 void visitPtrToIntInst(PtrToIntInst &I);
306 void visitBitCastInst(BitCastInst &I);
307 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
308 void visitPHINode(PHINode &PN);
309 void visitBinaryOperator(BinaryOperator &B);
310 void visitICmpInst(ICmpInst &IC);
311 void visitFCmpInst(FCmpInst &FC);
312 void visitExtractElementInst(ExtractElementInst &EI);
313 void visitInsertElementInst(InsertElementInst &EI);
314 void visitShuffleVectorInst(ShuffleVectorInst &EI);
315 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
316 void visitCallInst(CallInst &CI);
317 void visitInvokeInst(InvokeInst &II);
318 void visitGetElementPtrInst(GetElementPtrInst &GEP);
319 void visitLoadInst(LoadInst &LI);
320 void visitStoreInst(StoreInst &SI);
321 void verifyDominatesUse(Instruction &I, unsigned i);
322 void visitInstruction(Instruction &I);
323 void visitTerminatorInst(TerminatorInst &I);
324 void visitBranchInst(BranchInst &BI);
325 void visitReturnInst(ReturnInst &RI);
326 void visitSwitchInst(SwitchInst &SI);
327 void visitIndirectBrInst(IndirectBrInst &BI);
328 void visitSelectInst(SelectInst &SI);
329 void visitUserOp1(Instruction &I);
330 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
331 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
332 template <class DbgIntrinsicTy>
333 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
334 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
335 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
336 void visitFenceInst(FenceInst &FI);
337 void visitAllocaInst(AllocaInst &AI);
338 void visitExtractValueInst(ExtractValueInst &EVI);
339 void visitInsertValueInst(InsertValueInst &IVI);
340 void visitLandingPadInst(LandingPadInst &LPI);
342 void VerifyCallSite(CallSite CS);
343 void verifyMustTailCall(CallInst &CI);
344 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
345 unsigned ArgNo, std::string &Suffix);
346 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
347 SmallVectorImpl<Type *> &ArgTys);
348 bool VerifyIntrinsicIsVarArg(bool isVarArg,
349 ArrayRef<Intrinsic::IITDescriptor> &Infos);
350 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
351 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
353 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
354 bool isReturnValue, const Value *V);
355 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
358 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
359 void VerifyStatepoint(ImmutableCallSite CS);
360 void verifyFrameRecoverIndices();
362 class DebugInfoVerifier : public VerifierSupport {
364 explicit DebugInfoVerifier(raw_ostream &OS = dbgs()) : VerifierSupport(OS) {}
366 bool verify(const Module &M) {
373 void verifyDebugInfo();
374 void processInstructions(DebugInfoFinder &Finder);
375 void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
377 } // End anonymous namespace
379 // Assert - We know that cond should be true, if not print an error message.
380 #define Assert(C, ...) \
381 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
383 void Verifier::visit(Instruction &I) {
384 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
385 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
386 InstVisitor<Verifier>::visit(I);
390 void Verifier::visitGlobalValue(const GlobalValue &GV) {
391 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
392 GV.hasExternalWeakLinkage(),
393 "Global is external, but doesn't have external or weak linkage!", &GV);
395 Assert(GV.getAlignment() <= Value::MaximumAlignment,
396 "huge alignment values are unsupported", &GV);
397 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
398 "Only global variables can have appending linkage!", &GV);
400 if (GV.hasAppendingLinkage()) {
401 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
402 Assert(GVar && GVar->getType()->getElementType()->isArrayTy(),
403 "Only global arrays can have appending linkage!", GVar);
407 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
408 if (GV.hasInitializer()) {
409 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
410 "Global variable initializer type does not match global "
414 // If the global has common linkage, it must have a zero initializer and
415 // cannot be constant.
416 if (GV.hasCommonLinkage()) {
417 Assert(GV.getInitializer()->isNullValue(),
418 "'common' global must have a zero initializer!", &GV);
419 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
421 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
424 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
425 "invalid linkage type for global declaration", &GV);
428 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
429 GV.getName() == "llvm.global_dtors")) {
430 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
431 "invalid linkage for intrinsic global variable", &GV);
432 // Don't worry about emitting an error for it not being an array,
433 // visitGlobalValue will complain on appending non-array.
434 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
435 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
436 PointerType *FuncPtrTy =
437 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
438 // FIXME: Reject the 2-field form in LLVM 4.0.
440 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
441 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
442 STy->getTypeAtIndex(1) == FuncPtrTy,
443 "wrong type for intrinsic global variable", &GV);
444 if (STy->getNumElements() == 3) {
445 Type *ETy = STy->getTypeAtIndex(2);
446 Assert(ETy->isPointerTy() &&
447 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
448 "wrong type for intrinsic global variable", &GV);
453 if (GV.hasName() && (GV.getName() == "llvm.used" ||
454 GV.getName() == "llvm.compiler.used")) {
455 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
456 "invalid linkage for intrinsic global variable", &GV);
457 Type *GVType = GV.getType()->getElementType();
458 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
459 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
460 Assert(PTy, "wrong type for intrinsic global variable", &GV);
461 if (GV.hasInitializer()) {
462 const Constant *Init = GV.getInitializer();
463 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
464 Assert(InitArray, "wrong initalizer for intrinsic global variable",
466 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
467 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
468 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
470 "invalid llvm.used member", V);
471 Assert(V->hasName(), "members of llvm.used must be named", V);
477 Assert(!GV.hasDLLImportStorageClass() ||
478 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
479 GV.hasAvailableExternallyLinkage(),
480 "Global is marked as dllimport, but not external", &GV);
482 if (!GV.hasInitializer()) {
483 visitGlobalValue(GV);
487 // Walk any aggregate initializers looking for bitcasts between address spaces
488 SmallPtrSet<const Value *, 4> Visited;
489 SmallVector<const Value *, 4> WorkStack;
490 WorkStack.push_back(cast<Value>(GV.getInitializer()));
492 while (!WorkStack.empty()) {
493 const Value *V = WorkStack.pop_back_val();
494 if (!Visited.insert(V).second)
497 if (const User *U = dyn_cast<User>(V)) {
498 WorkStack.append(U->op_begin(), U->op_end());
501 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
502 VerifyConstantExprBitcastType(CE);
508 visitGlobalValue(GV);
511 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
512 SmallPtrSet<const GlobalAlias*, 4> Visited;
514 visitAliaseeSubExpr(Visited, GA, C);
517 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
518 const GlobalAlias &GA, const Constant &C) {
519 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
520 Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
522 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
523 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
525 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
528 // Only continue verifying subexpressions of GlobalAliases.
529 // Do not recurse into global initializers.
534 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
535 VerifyConstantExprBitcastType(CE);
537 for (const Use &U : C.operands()) {
539 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
540 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
541 else if (const auto *C2 = dyn_cast<Constant>(V))
542 visitAliaseeSubExpr(Visited, GA, *C2);
546 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
547 Assert(!GA.getName().empty(), "Alias name cannot be empty!", &GA);
548 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
549 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
550 "weak_odr, or external linkage!",
552 const Constant *Aliasee = GA.getAliasee();
553 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
554 Assert(GA.getType() == Aliasee->getType(),
555 "Alias and aliasee types should match!", &GA);
557 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
558 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
560 visitAliaseeSubExpr(GA, *Aliasee);
562 visitGlobalValue(GA);
565 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
566 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
567 MDNode *MD = NMD.getOperand(i);
575 void Verifier::visitMDNode(const MDNode &MD) {
576 // Only visit each node once. Metadata can be mutually recursive, so this
577 // avoids infinite recursion here, as well as being an optimization.
578 if (!MDNodes.insert(&MD).second)
581 switch (MD.getMetadataID()) {
583 llvm_unreachable("Invalid MDNode subclass");
584 case Metadata::MDTupleKind:
586 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
587 case Metadata::CLASS##Kind: \
588 visit##CLASS(cast<CLASS>(MD)); \
590 #include "llvm/IR/Metadata.def"
593 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
594 Metadata *Op = MD.getOperand(i);
597 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
599 if (auto *N = dyn_cast<MDNode>(Op)) {
603 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
604 visitValueAsMetadata(*V, nullptr);
609 // Check these last, so we diagnose problems in operands first.
610 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
611 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
614 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
615 Assert(MD.getValue(), "Expected valid value", &MD);
616 Assert(!MD.getValue()->getType()->isMetadataTy(),
617 "Unexpected metadata round-trip through values", &MD, MD.getValue());
619 auto *L = dyn_cast<LocalAsMetadata>(&MD);
623 Assert(F, "function-local metadata used outside a function", L);
625 // If this was an instruction, bb, or argument, verify that it is in the
626 // function that we expect.
627 Function *ActualF = nullptr;
628 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
629 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
630 ActualF = I->getParent()->getParent();
631 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
632 ActualF = BB->getParent();
633 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
634 ActualF = A->getParent();
635 assert(ActualF && "Unimplemented function local metadata case!");
637 Assert(ActualF == F, "function-local metadata used in wrong function", L);
640 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
641 Metadata *MD = MDV.getMetadata();
642 if (auto *N = dyn_cast<MDNode>(MD)) {
647 // Only visit each node once. Metadata can be mutually recursive, so this
648 // avoids infinite recursion here, as well as being an optimization.
649 if (!MDNodes.insert(MD).second)
652 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
653 visitValueAsMetadata(*V, F);
656 void Verifier::visitMDLocation(const MDLocation &N) {
657 Assert(N.getScope(), "location requires a valid scope", &N);
658 if (auto *IA = N.getInlinedAt())
659 Assert(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
662 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
663 Assert(N.getTag(), "invalid tag", &N);
666 void Verifier::visitMDSubrange(const MDSubrange &N) {
667 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
670 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
671 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
674 void Verifier::visitMDBasicType(const MDBasicType &N) {
675 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
676 N.getTag() == dwarf::DW_TAG_unspecified_type,
680 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
681 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
682 N.getTag() == dwarf::DW_TAG_pointer_type ||
683 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
684 N.getTag() == dwarf::DW_TAG_reference_type ||
685 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
686 N.getTag() == dwarf::DW_TAG_const_type ||
687 N.getTag() == dwarf::DW_TAG_volatile_type ||
688 N.getTag() == dwarf::DW_TAG_restrict_type ||
689 N.getTag() == dwarf::DW_TAG_member ||
690 N.getTag() == dwarf::DW_TAG_inheritance ||
691 N.getTag() == dwarf::DW_TAG_friend,
695 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
696 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
697 N.getTag() == dwarf::DW_TAG_structure_type ||
698 N.getTag() == dwarf::DW_TAG_union_type ||
699 N.getTag() == dwarf::DW_TAG_enumeration_type ||
700 N.getTag() == dwarf::DW_TAG_subroutine_type ||
701 N.getTag() == dwarf::DW_TAG_class_type,
705 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
706 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
709 void Verifier::visitMDFile(const MDFile &N) {
710 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
713 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
714 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
717 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
718 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
721 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
722 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
725 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
726 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
729 void Verifier::visitMDNamespace(const MDNamespace &N) {
730 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
733 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
734 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
738 void Verifier::visitMDTemplateValueParameter(
739 const MDTemplateValueParameter &N) {
740 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
741 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
742 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
746 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
747 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
750 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
751 Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
752 N.getTag() == dwarf::DW_TAG_arg_variable,
756 void Verifier::visitMDExpression(const MDExpression &N) {
757 Assert(N.isValid(), "invalid expression", &N);
760 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
761 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
764 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
765 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
766 N.getTag() == dwarf::DW_TAG_imported_declaration,
770 void Verifier::visitComdat(const Comdat &C) {
771 // The Module is invalid if the GlobalValue has private linkage. Entities
772 // with private linkage don't have entries in the symbol table.
773 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
774 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
778 void Verifier::visitModuleIdents(const Module &M) {
779 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
783 // llvm.ident takes a list of metadata entry. Each entry has only one string.
784 // Scan each llvm.ident entry and make sure that this requirement is met.
785 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
786 const MDNode *N = Idents->getOperand(i);
787 Assert(N->getNumOperands() == 1,
788 "incorrect number of operands in llvm.ident metadata", N);
789 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
790 ("invalid value for llvm.ident metadata entry operand"
791 "(the operand should be a string)"),
796 void Verifier::visitModuleFlags(const Module &M) {
797 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
800 // Scan each flag, and track the flags and requirements.
801 DenseMap<const MDString*, const MDNode*> SeenIDs;
802 SmallVector<const MDNode*, 16> Requirements;
803 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
804 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
807 // Validate that the requirements in the module are valid.
808 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
809 const MDNode *Requirement = Requirements[I];
810 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
811 const Metadata *ReqValue = Requirement->getOperand(1);
813 const MDNode *Op = SeenIDs.lookup(Flag);
815 CheckFailed("invalid requirement on flag, flag is not present in module",
820 if (Op->getOperand(2) != ReqValue) {
821 CheckFailed(("invalid requirement on flag, "
822 "flag does not have the required value"),
830 Verifier::visitModuleFlag(const MDNode *Op,
831 DenseMap<const MDString *, const MDNode *> &SeenIDs,
832 SmallVectorImpl<const MDNode *> &Requirements) {
833 // Each module flag should have three arguments, the merge behavior (a
834 // constant int), the flag ID (an MDString), and the value.
835 Assert(Op->getNumOperands() == 3,
836 "incorrect number of operands in module flag", Op);
837 Module::ModFlagBehavior MFB;
838 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
840 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
841 "invalid behavior operand in module flag (expected constant integer)",
844 "invalid behavior operand in module flag (unexpected constant)",
847 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
848 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
851 // Sanity check the values for behaviors with additional requirements.
854 case Module::Warning:
855 case Module::Override:
856 // These behavior types accept any value.
859 case Module::Require: {
860 // The value should itself be an MDNode with two operands, a flag ID (an
861 // MDString), and a value.
862 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
863 Assert(Value && Value->getNumOperands() == 2,
864 "invalid value for 'require' module flag (expected metadata pair)",
866 Assert(isa<MDString>(Value->getOperand(0)),
867 ("invalid value for 'require' module flag "
868 "(first value operand should be a string)"),
869 Value->getOperand(0));
871 // Append it to the list of requirements, to check once all module flags are
873 Requirements.push_back(Value);
878 case Module::AppendUnique: {
879 // These behavior types require the operand be an MDNode.
880 Assert(isa<MDNode>(Op->getOperand(2)),
881 "invalid value for 'append'-type module flag "
882 "(expected a metadata node)",
888 // Unless this is a "requires" flag, check the ID is unique.
889 if (MFB != Module::Require) {
890 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
892 "module flag identifiers must be unique (or of 'require' type)", ID);
896 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
897 bool isFunction, const Value *V) {
899 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
900 if (Attrs.getSlotIndex(I) == Idx) {
905 assert(Slot != ~0U && "Attribute set inconsistency!");
907 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
909 if (I->isStringAttribute())
912 if (I->getKindAsEnum() == Attribute::NoReturn ||
913 I->getKindAsEnum() == Attribute::NoUnwind ||
914 I->getKindAsEnum() == Attribute::NoInline ||
915 I->getKindAsEnum() == Attribute::AlwaysInline ||
916 I->getKindAsEnum() == Attribute::OptimizeForSize ||
917 I->getKindAsEnum() == Attribute::StackProtect ||
918 I->getKindAsEnum() == Attribute::StackProtectReq ||
919 I->getKindAsEnum() == Attribute::StackProtectStrong ||
920 I->getKindAsEnum() == Attribute::NoRedZone ||
921 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
922 I->getKindAsEnum() == Attribute::Naked ||
923 I->getKindAsEnum() == Attribute::InlineHint ||
924 I->getKindAsEnum() == Attribute::StackAlignment ||
925 I->getKindAsEnum() == Attribute::UWTable ||
926 I->getKindAsEnum() == Attribute::NonLazyBind ||
927 I->getKindAsEnum() == Attribute::ReturnsTwice ||
928 I->getKindAsEnum() == Attribute::SanitizeAddress ||
929 I->getKindAsEnum() == Attribute::SanitizeThread ||
930 I->getKindAsEnum() == Attribute::SanitizeMemory ||
931 I->getKindAsEnum() == Attribute::MinSize ||
932 I->getKindAsEnum() == Attribute::NoDuplicate ||
933 I->getKindAsEnum() == Attribute::Builtin ||
934 I->getKindAsEnum() == Attribute::NoBuiltin ||
935 I->getKindAsEnum() == Attribute::Cold ||
936 I->getKindAsEnum() == Attribute::OptimizeNone ||
937 I->getKindAsEnum() == Attribute::JumpTable) {
939 CheckFailed("Attribute '" + I->getAsString() +
940 "' only applies to functions!", V);
943 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
944 I->getKindAsEnum() == Attribute::ReadNone) {
946 CheckFailed("Attribute '" + I->getAsString() +
947 "' does not apply to function returns");
950 } else if (isFunction) {
951 CheckFailed("Attribute '" + I->getAsString() +
952 "' does not apply to functions!", V);
958 // VerifyParameterAttrs - Check the given attributes for an argument or return
959 // value of the specified type. The value V is printed in error messages.
960 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
961 bool isReturnValue, const Value *V) {
962 if (!Attrs.hasAttributes(Idx))
965 VerifyAttributeTypes(Attrs, Idx, false, V);
968 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
969 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
970 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
971 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
972 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
973 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
974 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
975 "'returned' do not apply to return values!",
978 // Check for mutually incompatible attributes. Only inreg is compatible with
980 unsigned AttrCount = 0;
981 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
982 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
983 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
984 Attrs.hasAttribute(Idx, Attribute::InReg);
985 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
986 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
987 "and 'sret' are incompatible!",
990 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
991 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
993 "'inalloca and readonly' are incompatible!",
996 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
997 Attrs.hasAttribute(Idx, Attribute::Returned)),
999 "'sret and returned' are incompatible!",
1002 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1003 Attrs.hasAttribute(Idx, Attribute::SExt)),
1005 "'zeroext and signext' are incompatible!",
1008 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1009 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1011 "'readnone and readonly' are incompatible!",
1014 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1015 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1017 "'noinline and alwaysinline' are incompatible!",
1020 Assert(!AttrBuilder(Attrs, Idx)
1021 .hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1022 "Wrong types for attribute: " +
1023 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx),
1026 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1027 SmallPtrSet<const Type*, 4> Visited;
1028 if (!PTy->getElementType()->isSized(&Visited)) {
1029 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1030 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1031 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1035 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1036 "Attribute 'byval' only applies to parameters with pointer type!",
1041 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1042 // The value V is printed in error messages.
1043 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1045 if (Attrs.isEmpty())
1048 bool SawNest = false;
1049 bool SawReturned = false;
1050 bool SawSRet = false;
1052 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1053 unsigned Idx = Attrs.getSlotIndex(i);
1057 Ty = FT->getReturnType();
1058 else if (Idx-1 < FT->getNumParams())
1059 Ty = FT->getParamType(Idx-1);
1061 break; // VarArgs attributes, verified elsewhere.
1063 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1068 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1069 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1073 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1074 Assert(!SawReturned, "More than one parameter has attribute returned!",
1076 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1078 "argument and return types for 'returned' attribute",
1083 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1084 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1085 Assert(Idx == 1 || Idx == 2,
1086 "Attribute 'sret' is not on first or second parameter!", V);
1090 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1091 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1096 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1099 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1102 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1103 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1104 "Attributes 'readnone and readonly' are incompatible!", V);
1107 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1108 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1109 Attribute::AlwaysInline)),
1110 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1112 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1113 Attribute::OptimizeNone)) {
1114 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1115 "Attribute 'optnone' requires 'noinline'!", V);
1117 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1118 Attribute::OptimizeForSize),
1119 "Attributes 'optsize and optnone' are incompatible!", V);
1121 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1122 "Attributes 'minsize and optnone' are incompatible!", V);
1125 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1126 Attribute::JumpTable)) {
1127 const GlobalValue *GV = cast<GlobalValue>(V);
1128 Assert(GV->hasUnnamedAddr(),
1129 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1133 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1134 if (CE->getOpcode() != Instruction::BitCast)
1137 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1139 "Invalid bitcast", CE);
1142 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1143 if (Attrs.getNumSlots() == 0)
1146 unsigned LastSlot = Attrs.getNumSlots() - 1;
1147 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1148 if (LastIndex <= Params
1149 || (LastIndex == AttributeSet::FunctionIndex
1150 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1156 /// \brief Verify that statepoint intrinsic is well formed.
1157 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1158 assert(CS.getCalledFunction() &&
1159 CS.getCalledFunction()->getIntrinsicID() ==
1160 Intrinsic::experimental_gc_statepoint);
1162 const Instruction &CI = *CS.getInstruction();
1164 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory(),
1165 "gc.statepoint must read and write memory to preserve "
1166 "reordering restrictions required by safepoint semantics",
1169 const Value *Target = CS.getArgument(0);
1170 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1171 Assert(PT && PT->getElementType()->isFunctionTy(),
1172 "gc.statepoint callee must be of function pointer type", &CI, Target);
1173 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1175 const Value *NumCallArgsV = CS.getArgument(1);
1176 Assert(isa<ConstantInt>(NumCallArgsV),
1177 "gc.statepoint number of arguments to underlying call "
1178 "must be constant integer",
1180 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1181 Assert(NumCallArgs >= 0,
1182 "gc.statepoint number of arguments to underlying call "
1185 const int NumParams = (int)TargetFuncType->getNumParams();
1186 if (TargetFuncType->isVarArg()) {
1187 Assert(NumCallArgs >= NumParams,
1188 "gc.statepoint mismatch in number of vararg call args", &CI);
1190 // TODO: Remove this limitation
1191 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1192 "gc.statepoint doesn't support wrapping non-void "
1193 "vararg functions yet",
1196 Assert(NumCallArgs == NumParams,
1197 "gc.statepoint mismatch in number of call args", &CI);
1199 const Value *Unused = CS.getArgument(2);
1200 Assert(isa<ConstantInt>(Unused) && cast<ConstantInt>(Unused)->isNullValue(),
1201 "gc.statepoint parameter #3 must be zero", &CI);
1203 // Verify that the types of the call parameter arguments match
1204 // the type of the wrapped callee.
1205 for (int i = 0; i < NumParams; i++) {
1206 Type *ParamType = TargetFuncType->getParamType(i);
1207 Type *ArgType = CS.getArgument(3+i)->getType();
1208 Assert(ArgType == ParamType,
1209 "gc.statepoint call argument does not match wrapped "
1213 const int EndCallArgsInx = 2+NumCallArgs;
1214 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1215 Assert(isa<ConstantInt>(NumDeoptArgsV),
1216 "gc.statepoint number of deoptimization arguments "
1217 "must be constant integer",
1219 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1220 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1224 Assert(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1225 "gc.statepoint too few arguments according to length fields", &CI);
1227 // Check that the only uses of this gc.statepoint are gc.result or
1228 // gc.relocate calls which are tied to this statepoint and thus part
1229 // of the same statepoint sequence
1230 for (const User *U : CI.users()) {
1231 const CallInst *Call = dyn_cast<const CallInst>(U);
1232 Assert(Call, "illegal use of statepoint token", &CI, U);
1233 if (!Call) continue;
1234 Assert(isGCRelocate(Call) || isGCResult(Call),
1235 "gc.result or gc.relocate are the only value uses"
1236 "of a gc.statepoint",
1238 if (isGCResult(Call)) {
1239 Assert(Call->getArgOperand(0) == &CI,
1240 "gc.result connected to wrong gc.statepoint", &CI, Call);
1241 } else if (isGCRelocate(Call)) {
1242 Assert(Call->getArgOperand(0) == &CI,
1243 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1247 // Note: It is legal for a single derived pointer to be listed multiple
1248 // times. It's non-optimal, but it is legal. It can also happen after
1249 // insertion if we strip a bitcast away.
1250 // Note: It is really tempting to check that each base is relocated and
1251 // that a derived pointer is never reused as a base pointer. This turns
1252 // out to be problematic since optimizations run after safepoint insertion
1253 // can recognize equality properties that the insertion logic doesn't know
1254 // about. See example statepoint.ll in the verifier subdirectory
1257 void Verifier::verifyFrameRecoverIndices() {
1258 for (auto &Counts : FrameEscapeInfo) {
1259 Function *F = Counts.first;
1260 unsigned EscapedObjectCount = Counts.second.first;
1261 unsigned MaxRecoveredIndex = Counts.second.second;
1262 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1263 "all indices passed to llvm.framerecover must be less than the "
1264 "number of arguments passed ot llvm.frameescape in the parent "
1270 // visitFunction - Verify that a function is ok.
1272 void Verifier::visitFunction(const Function &F) {
1273 // Check function arguments.
1274 FunctionType *FT = F.getFunctionType();
1275 unsigned NumArgs = F.arg_size();
1277 Assert(Context == &F.getContext(),
1278 "Function context does not match Module context!", &F);
1280 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1281 Assert(FT->getNumParams() == NumArgs,
1282 "# formal arguments must match # of arguments for function type!", &F,
1284 Assert(F.getReturnType()->isFirstClassType() ||
1285 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1286 "Functions cannot return aggregate values!", &F);
1288 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1289 "Invalid struct return type!", &F);
1291 AttributeSet Attrs = F.getAttributes();
1293 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1294 "Attribute after last parameter!", &F);
1296 // Check function attributes.
1297 VerifyFunctionAttrs(FT, Attrs, &F);
1299 // On function declarations/definitions, we do not support the builtin
1300 // attribute. We do not check this in VerifyFunctionAttrs since that is
1301 // checking for Attributes that can/can not ever be on functions.
1302 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1303 "Attribute 'builtin' can only be applied to a callsite.", &F);
1305 // Check that this function meets the restrictions on this calling convention.
1306 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1307 // restrictions can be lifted.
1308 switch (F.getCallingConv()) {
1310 case CallingConv::C:
1312 case CallingConv::Fast:
1313 case CallingConv::Cold:
1314 case CallingConv::Intel_OCL_BI:
1315 case CallingConv::PTX_Kernel:
1316 case CallingConv::PTX_Device:
1317 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1318 "perfect forwarding!",
1323 bool isLLVMdotName = F.getName().size() >= 5 &&
1324 F.getName().substr(0, 5) == "llvm.";
1326 // Check that the argument values match the function type for this function...
1328 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1330 Assert(I->getType() == FT->getParamType(i),
1331 "Argument value does not match function argument type!", I,
1332 FT->getParamType(i));
1333 Assert(I->getType()->isFirstClassType(),
1334 "Function arguments must have first-class types!", I);
1336 Assert(!I->getType()->isMetadataTy(),
1337 "Function takes metadata but isn't an intrinsic", I, &F);
1340 if (F.isMaterializable()) {
1341 // Function has a body somewhere we can't see.
1342 } else if (F.isDeclaration()) {
1343 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1344 "invalid linkage type for function declaration", &F);
1346 // Verify that this function (which has a body) is not named "llvm.*". It
1347 // is not legal to define intrinsics.
1348 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1350 // Check the entry node
1351 const BasicBlock *Entry = &F.getEntryBlock();
1352 Assert(pred_empty(Entry),
1353 "Entry block to function must not have predecessors!", Entry);
1355 // The address of the entry block cannot be taken, unless it is dead.
1356 if (Entry->hasAddressTaken()) {
1357 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1358 "blockaddress may not be used with the entry block!", Entry);
1362 // If this function is actually an intrinsic, verify that it is only used in
1363 // direct call/invokes, never having its "address taken".
1364 if (F.getIntrinsicID()) {
1366 if (F.hasAddressTaken(&U))
1367 Assert(0, "Invalid user of intrinsic instruction!", U);
1370 Assert(!F.hasDLLImportStorageClass() ||
1371 (F.isDeclaration() && F.hasExternalLinkage()) ||
1372 F.hasAvailableExternallyLinkage(),
1373 "Function is marked as dllimport, but not external.", &F);
1376 // verifyBasicBlock - Verify that a basic block is well formed...
1378 void Verifier::visitBasicBlock(BasicBlock &BB) {
1379 InstsInThisBlock.clear();
1381 // Ensure that basic blocks have terminators!
1382 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1384 // Check constraints that this basic block imposes on all of the PHI nodes in
1386 if (isa<PHINode>(BB.front())) {
1387 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1388 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1389 std::sort(Preds.begin(), Preds.end());
1391 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1392 // Ensure that PHI nodes have at least one entry!
1393 Assert(PN->getNumIncomingValues() != 0,
1394 "PHI nodes must have at least one entry. If the block is dead, "
1395 "the PHI should be removed!",
1397 Assert(PN->getNumIncomingValues() == Preds.size(),
1398 "PHINode should have one entry for each predecessor of its "
1399 "parent basic block!",
1402 // Get and sort all incoming values in the PHI node...
1404 Values.reserve(PN->getNumIncomingValues());
1405 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1406 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1407 PN->getIncomingValue(i)));
1408 std::sort(Values.begin(), Values.end());
1410 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1411 // Check to make sure that if there is more than one entry for a
1412 // particular basic block in this PHI node, that the incoming values are
1415 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1416 Values[i].second == Values[i - 1].second,
1417 "PHI node has multiple entries for the same basic block with "
1418 "different incoming values!",
1419 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1421 // Check to make sure that the predecessors and PHI node entries are
1423 Assert(Values[i].first == Preds[i],
1424 "PHI node entries do not match predecessors!", PN,
1425 Values[i].first, Preds[i]);
1430 // Check that all instructions have their parent pointers set up correctly.
1433 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1437 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1438 // Ensure that terminators only exist at the end of the basic block.
1439 Assert(&I == I.getParent()->getTerminator(),
1440 "Terminator found in the middle of a basic block!", I.getParent());
1441 visitInstruction(I);
1444 void Verifier::visitBranchInst(BranchInst &BI) {
1445 if (BI.isConditional()) {
1446 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1447 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1449 visitTerminatorInst(BI);
1452 void Verifier::visitReturnInst(ReturnInst &RI) {
1453 Function *F = RI.getParent()->getParent();
1454 unsigned N = RI.getNumOperands();
1455 if (F->getReturnType()->isVoidTy())
1457 "Found return instr that returns non-void in Function of void "
1459 &RI, F->getReturnType());
1461 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1462 "Function return type does not match operand "
1463 "type of return inst!",
1464 &RI, F->getReturnType());
1466 // Check to make sure that the return value has necessary properties for
1468 visitTerminatorInst(RI);
1471 void Verifier::visitSwitchInst(SwitchInst &SI) {
1472 // Check to make sure that all of the constants in the switch instruction
1473 // have the same type as the switched-on value.
1474 Type *SwitchTy = SI.getCondition()->getType();
1475 SmallPtrSet<ConstantInt*, 32> Constants;
1476 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1477 Assert(i.getCaseValue()->getType() == SwitchTy,
1478 "Switch constants must all be same type as switch value!", &SI);
1479 Assert(Constants.insert(i.getCaseValue()).second,
1480 "Duplicate integer as switch case", &SI, i.getCaseValue());
1483 visitTerminatorInst(SI);
1486 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1487 Assert(BI.getAddress()->getType()->isPointerTy(),
1488 "Indirectbr operand must have pointer type!", &BI);
1489 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1490 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1491 "Indirectbr destinations must all have pointer type!", &BI);
1493 visitTerminatorInst(BI);
1496 void Verifier::visitSelectInst(SelectInst &SI) {
1497 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1499 "Invalid operands for select instruction!", &SI);
1501 Assert(SI.getTrueValue()->getType() == SI.getType(),
1502 "Select values must have same type as select instruction!", &SI);
1503 visitInstruction(SI);
1506 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1507 /// a pass, if any exist, it's an error.
1509 void Verifier::visitUserOp1(Instruction &I) {
1510 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1513 void Verifier::visitTruncInst(TruncInst &I) {
1514 // Get the source and destination types
1515 Type *SrcTy = I.getOperand(0)->getType();
1516 Type *DestTy = I.getType();
1518 // Get the size of the types in bits, we'll need this later
1519 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1520 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1522 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1523 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1524 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1525 "trunc source and destination must both be a vector or neither", &I);
1526 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1528 visitInstruction(I);
1531 void Verifier::visitZExtInst(ZExtInst &I) {
1532 // Get the source and destination types
1533 Type *SrcTy = I.getOperand(0)->getType();
1534 Type *DestTy = I.getType();
1536 // Get the size of the types in bits, we'll need this later
1537 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1538 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1539 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1540 "zext source and destination must both be a vector or neither", &I);
1541 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1542 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1544 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1546 visitInstruction(I);
1549 void Verifier::visitSExtInst(SExtInst &I) {
1550 // Get the source and destination types
1551 Type *SrcTy = I.getOperand(0)->getType();
1552 Type *DestTy = I.getType();
1554 // Get the size of the types in bits, we'll need this later
1555 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1556 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1558 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1559 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1560 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1561 "sext source and destination must both be a vector or neither", &I);
1562 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1564 visitInstruction(I);
1567 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1568 // Get the source and destination types
1569 Type *SrcTy = I.getOperand(0)->getType();
1570 Type *DestTy = I.getType();
1571 // Get the size of the types in bits, we'll need this later
1572 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1573 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1575 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1576 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1577 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1578 "fptrunc source and destination must both be a vector or neither", &I);
1579 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1581 visitInstruction(I);
1584 void Verifier::visitFPExtInst(FPExtInst &I) {
1585 // Get the source and destination types
1586 Type *SrcTy = I.getOperand(0)->getType();
1587 Type *DestTy = I.getType();
1589 // Get the size of the types in bits, we'll need this later
1590 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1591 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1593 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
1594 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
1595 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1596 "fpext source and destination must both be a vector or neither", &I);
1597 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
1599 visitInstruction(I);
1602 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1603 // Get the source and destination types
1604 Type *SrcTy = I.getOperand(0)->getType();
1605 Type *DestTy = I.getType();
1607 bool SrcVec = SrcTy->isVectorTy();
1608 bool DstVec = DestTy->isVectorTy();
1610 Assert(SrcVec == DstVec,
1611 "UIToFP source and dest must both be vector or scalar", &I);
1612 Assert(SrcTy->isIntOrIntVectorTy(),
1613 "UIToFP source must be integer or integer vector", &I);
1614 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
1617 if (SrcVec && DstVec)
1618 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1619 cast<VectorType>(DestTy)->getNumElements(),
1620 "UIToFP source and dest vector length mismatch", &I);
1622 visitInstruction(I);
1625 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1626 // Get the source and destination types
1627 Type *SrcTy = I.getOperand(0)->getType();
1628 Type *DestTy = I.getType();
1630 bool SrcVec = SrcTy->isVectorTy();
1631 bool DstVec = DestTy->isVectorTy();
1633 Assert(SrcVec == DstVec,
1634 "SIToFP source and dest must both be vector or scalar", &I);
1635 Assert(SrcTy->isIntOrIntVectorTy(),
1636 "SIToFP source must be integer or integer vector", &I);
1637 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
1640 if (SrcVec && DstVec)
1641 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1642 cast<VectorType>(DestTy)->getNumElements(),
1643 "SIToFP source and dest vector length mismatch", &I);
1645 visitInstruction(I);
1648 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1649 // Get the source and destination types
1650 Type *SrcTy = I.getOperand(0)->getType();
1651 Type *DestTy = I.getType();
1653 bool SrcVec = SrcTy->isVectorTy();
1654 bool DstVec = DestTy->isVectorTy();
1656 Assert(SrcVec == DstVec,
1657 "FPToUI source and dest must both be vector or scalar", &I);
1658 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1660 Assert(DestTy->isIntOrIntVectorTy(),
1661 "FPToUI result must be integer or integer vector", &I);
1663 if (SrcVec && DstVec)
1664 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1665 cast<VectorType>(DestTy)->getNumElements(),
1666 "FPToUI source and dest vector length mismatch", &I);
1668 visitInstruction(I);
1671 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1672 // Get the source and destination types
1673 Type *SrcTy = I.getOperand(0)->getType();
1674 Type *DestTy = I.getType();
1676 bool SrcVec = SrcTy->isVectorTy();
1677 bool DstVec = DestTy->isVectorTy();
1679 Assert(SrcVec == DstVec,
1680 "FPToSI source and dest must both be vector or scalar", &I);
1681 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
1683 Assert(DestTy->isIntOrIntVectorTy(),
1684 "FPToSI result must be integer or integer vector", &I);
1686 if (SrcVec && DstVec)
1687 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1688 cast<VectorType>(DestTy)->getNumElements(),
1689 "FPToSI source and dest vector length mismatch", &I);
1691 visitInstruction(I);
1694 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1695 // Get the source and destination types
1696 Type *SrcTy = I.getOperand(0)->getType();
1697 Type *DestTy = I.getType();
1699 Assert(SrcTy->getScalarType()->isPointerTy(),
1700 "PtrToInt source must be pointer", &I);
1701 Assert(DestTy->getScalarType()->isIntegerTy(),
1702 "PtrToInt result must be integral", &I);
1703 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
1706 if (SrcTy->isVectorTy()) {
1707 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1708 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1709 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1710 "PtrToInt Vector width mismatch", &I);
1713 visitInstruction(I);
1716 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1717 // Get the source and destination types
1718 Type *SrcTy = I.getOperand(0)->getType();
1719 Type *DestTy = I.getType();
1721 Assert(SrcTy->getScalarType()->isIntegerTy(),
1722 "IntToPtr source must be an integral", &I);
1723 Assert(DestTy->getScalarType()->isPointerTy(),
1724 "IntToPtr result must be a pointer", &I);
1725 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
1727 if (SrcTy->isVectorTy()) {
1728 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1729 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1730 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1731 "IntToPtr Vector width mismatch", &I);
1733 visitInstruction(I);
1736 void Verifier::visitBitCastInst(BitCastInst &I) {
1738 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
1739 "Invalid bitcast", &I);
1740 visitInstruction(I);
1743 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1744 Type *SrcTy = I.getOperand(0)->getType();
1745 Type *DestTy = I.getType();
1747 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
1749 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
1751 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1752 "AddrSpaceCast must be between different address spaces", &I);
1753 if (SrcTy->isVectorTy())
1754 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1755 "AddrSpaceCast vector pointer number of elements mismatch", &I);
1756 visitInstruction(I);
1759 /// visitPHINode - Ensure that a PHI node is well formed.
1761 void Verifier::visitPHINode(PHINode &PN) {
1762 // Ensure that the PHI nodes are all grouped together at the top of the block.
1763 // This can be tested by checking whether the instruction before this is
1764 // either nonexistent (because this is begin()) or is a PHI node. If not,
1765 // then there is some other instruction before a PHI.
1766 Assert(&PN == &PN.getParent()->front() ||
1767 isa<PHINode>(--BasicBlock::iterator(&PN)),
1768 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
1770 // Check that all of the values of the PHI node have the same type as the
1771 // result, and that the incoming blocks are really basic blocks.
1772 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1773 Assert(PN.getType() == PN.getIncomingValue(i)->getType(),
1774 "PHI node operands are not the same type as the result!", &PN);
1777 // All other PHI node constraints are checked in the visitBasicBlock method.
1779 visitInstruction(PN);
1782 void Verifier::VerifyCallSite(CallSite CS) {
1783 Instruction *I = CS.getInstruction();
1785 Assert(CS.getCalledValue()->getType()->isPointerTy(),
1786 "Called function must be a pointer!", I);
1787 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1789 Assert(FPTy->getElementType()->isFunctionTy(),
1790 "Called function is not pointer to function type!", I);
1791 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1793 // Verify that the correct number of arguments are being passed
1794 if (FTy->isVarArg())
1795 Assert(CS.arg_size() >= FTy->getNumParams(),
1796 "Called function requires more parameters than were provided!", I);
1798 Assert(CS.arg_size() == FTy->getNumParams(),
1799 "Incorrect number of arguments passed to called function!", I);
1801 // Verify that all arguments to the call match the function type.
1802 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1803 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
1804 "Call parameter type does not match function signature!",
1805 CS.getArgument(i), FTy->getParamType(i), I);
1807 AttributeSet Attrs = CS.getAttributes();
1809 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
1810 "Attribute after last parameter!", I);
1812 // Verify call attributes.
1813 VerifyFunctionAttrs(FTy, Attrs, I);
1815 // Conservatively check the inalloca argument.
1816 // We have a bug if we can find that there is an underlying alloca without
1818 if (CS.hasInAllocaArgument()) {
1819 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
1820 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
1821 Assert(AI->isUsedWithInAlloca(),
1822 "inalloca argument for call has mismatched alloca", AI, I);
1825 if (FTy->isVarArg()) {
1826 // FIXME? is 'nest' even legal here?
1827 bool SawNest = false;
1828 bool SawReturned = false;
1830 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1831 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1833 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1837 // Check attributes on the varargs part.
1838 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1839 Type *Ty = CS.getArgument(Idx-1)->getType();
1840 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1842 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1843 Assert(!SawNest, "More than one parameter has attribute nest!", I);
1847 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1848 Assert(!SawReturned, "More than one parameter has attribute returned!",
1850 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1851 "Incompatible argument and return types for 'returned' "
1857 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1858 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1860 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1861 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
1865 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1866 if (CS.getCalledFunction() == nullptr ||
1867 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1868 for (FunctionType::param_iterator PI = FTy->param_begin(),
1869 PE = FTy->param_end(); PI != PE; ++PI)
1870 Assert(!(*PI)->isMetadataTy(),
1871 "Function has metadata parameter but isn't an intrinsic", I);
1874 visitInstruction(*I);
1877 /// Two types are "congruent" if they are identical, or if they are both pointer
1878 /// types with different pointee types and the same address space.
1879 static bool isTypeCongruent(Type *L, Type *R) {
1882 PointerType *PL = dyn_cast<PointerType>(L);
1883 PointerType *PR = dyn_cast<PointerType>(R);
1886 return PL->getAddressSpace() == PR->getAddressSpace();
1889 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
1890 static const Attribute::AttrKind ABIAttrs[] = {
1891 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
1892 Attribute::InReg, Attribute::Returned};
1894 for (auto AK : ABIAttrs) {
1895 if (Attrs.hasAttribute(I + 1, AK))
1896 Copy.addAttribute(AK);
1898 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
1899 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
1903 void Verifier::verifyMustTailCall(CallInst &CI) {
1904 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
1906 // - The caller and callee prototypes must match. Pointer types of
1907 // parameters or return types may differ in pointee type, but not
1909 Function *F = CI.getParent()->getParent();
1910 auto GetFnTy = [](Value *V) {
1911 return cast<FunctionType>(
1912 cast<PointerType>(V->getType())->getElementType());
1914 FunctionType *CallerTy = GetFnTy(F);
1915 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
1916 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
1917 "cannot guarantee tail call due to mismatched parameter counts", &CI);
1918 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
1919 "cannot guarantee tail call due to mismatched varargs", &CI);
1920 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
1921 "cannot guarantee tail call due to mismatched return types", &CI);
1922 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1924 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
1925 "cannot guarantee tail call due to mismatched parameter types", &CI);
1928 // - The calling conventions of the caller and callee must match.
1929 Assert(F->getCallingConv() == CI.getCallingConv(),
1930 "cannot guarantee tail call due to mismatched calling conv", &CI);
1932 // - All ABI-impacting function attributes, such as sret, byval, inreg,
1933 // returned, and inalloca, must match.
1934 AttributeSet CallerAttrs = F->getAttributes();
1935 AttributeSet CalleeAttrs = CI.getAttributes();
1936 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1937 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
1938 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
1939 Assert(CallerABIAttrs == CalleeABIAttrs,
1940 "cannot guarantee tail call due to mismatched ABI impacting "
1941 "function attributes",
1942 &CI, CI.getOperand(I));
1945 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
1946 // or a pointer bitcast followed by a ret instruction.
1947 // - The ret instruction must return the (possibly bitcasted) value
1948 // produced by the call or void.
1949 Value *RetVal = &CI;
1950 Instruction *Next = CI.getNextNode();
1952 // Handle the optional bitcast.
1953 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
1954 Assert(BI->getOperand(0) == RetVal,
1955 "bitcast following musttail call must use the call", BI);
1957 Next = BI->getNextNode();
1960 // Check the return.
1961 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
1962 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
1964 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
1965 "musttail call result must be returned", Ret);
1968 void Verifier::visitCallInst(CallInst &CI) {
1969 VerifyCallSite(&CI);
1971 if (CI.isMustTailCall())
1972 verifyMustTailCall(CI);
1974 if (Function *F = CI.getCalledFunction())
1975 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1976 visitIntrinsicFunctionCall(ID, CI);
1979 void Verifier::visitInvokeInst(InvokeInst &II) {
1980 VerifyCallSite(&II);
1982 // Verify that there is a landingpad instruction as the first non-PHI
1983 // instruction of the 'unwind' destination.
1984 Assert(II.getUnwindDest()->isLandingPad(),
1985 "The unwind destination does not have a landingpad instruction!", &II);
1987 if (Function *F = II.getCalledFunction())
1988 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
1989 // CallInst as an input parameter. It not woth updating this whole
1990 // function only to support statepoint verification.
1991 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
1992 VerifyStatepoint(ImmutableCallSite(&II));
1994 visitTerminatorInst(II);
1997 /// visitBinaryOperator - Check that both arguments to the binary operator are
1998 /// of the same type!
2000 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2001 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2002 "Both operands to a binary operator are not of the same type!", &B);
2004 switch (B.getOpcode()) {
2005 // Check that integer arithmetic operators are only used with
2006 // integral operands.
2007 case Instruction::Add:
2008 case Instruction::Sub:
2009 case Instruction::Mul:
2010 case Instruction::SDiv:
2011 case Instruction::UDiv:
2012 case Instruction::SRem:
2013 case Instruction::URem:
2014 Assert(B.getType()->isIntOrIntVectorTy(),
2015 "Integer arithmetic operators only work with integral types!", &B);
2016 Assert(B.getType() == B.getOperand(0)->getType(),
2017 "Integer arithmetic operators must have same type "
2018 "for operands and result!",
2021 // Check that floating-point arithmetic operators are only used with
2022 // floating-point operands.
2023 case Instruction::FAdd:
2024 case Instruction::FSub:
2025 case Instruction::FMul:
2026 case Instruction::FDiv:
2027 case Instruction::FRem:
2028 Assert(B.getType()->isFPOrFPVectorTy(),
2029 "Floating-point arithmetic operators only work with "
2030 "floating-point types!",
2032 Assert(B.getType() == B.getOperand(0)->getType(),
2033 "Floating-point arithmetic operators must have same type "
2034 "for operands and result!",
2037 // Check that logical operators are only used with integral operands.
2038 case Instruction::And:
2039 case Instruction::Or:
2040 case Instruction::Xor:
2041 Assert(B.getType()->isIntOrIntVectorTy(),
2042 "Logical operators only work with integral types!", &B);
2043 Assert(B.getType() == B.getOperand(0)->getType(),
2044 "Logical operators must have same type for operands and result!",
2047 case Instruction::Shl:
2048 case Instruction::LShr:
2049 case Instruction::AShr:
2050 Assert(B.getType()->isIntOrIntVectorTy(),
2051 "Shifts only work with integral types!", &B);
2052 Assert(B.getType() == B.getOperand(0)->getType(),
2053 "Shift return type must be same as operands!", &B);
2056 llvm_unreachable("Unknown BinaryOperator opcode!");
2059 visitInstruction(B);
2062 void Verifier::visitICmpInst(ICmpInst &IC) {
2063 // Check that the operands are the same type
2064 Type *Op0Ty = IC.getOperand(0)->getType();
2065 Type *Op1Ty = IC.getOperand(1)->getType();
2066 Assert(Op0Ty == Op1Ty,
2067 "Both operands to ICmp instruction are not of the same type!", &IC);
2068 // Check that the operands are the right type
2069 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2070 "Invalid operand types for ICmp instruction", &IC);
2071 // Check that the predicate is valid.
2072 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2073 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2074 "Invalid predicate in ICmp instruction!", &IC);
2076 visitInstruction(IC);
2079 void Verifier::visitFCmpInst(FCmpInst &FC) {
2080 // Check that the operands are the same type
2081 Type *Op0Ty = FC.getOperand(0)->getType();
2082 Type *Op1Ty = FC.getOperand(1)->getType();
2083 Assert(Op0Ty == Op1Ty,
2084 "Both operands to FCmp instruction are not of the same type!", &FC);
2085 // Check that the operands are the right type
2086 Assert(Op0Ty->isFPOrFPVectorTy(),
2087 "Invalid operand types for FCmp instruction", &FC);
2088 // Check that the predicate is valid.
2089 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2090 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2091 "Invalid predicate in FCmp instruction!", &FC);
2093 visitInstruction(FC);
2096 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2098 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2099 "Invalid extractelement operands!", &EI);
2100 visitInstruction(EI);
2103 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2104 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2106 "Invalid insertelement operands!", &IE);
2107 visitInstruction(IE);
2110 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2111 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2113 "Invalid shufflevector operands!", &SV);
2114 visitInstruction(SV);
2117 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2118 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2120 Assert(isa<PointerType>(TargetTy),
2121 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2122 Assert(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2123 "GEP into unsized type!", &GEP);
2124 Assert(GEP.getPointerOperandType()->isVectorTy() ==
2125 GEP.getType()->isVectorTy(),
2126 "Vector GEP must return a vector value", &GEP);
2128 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2130 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
2131 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2133 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2134 cast<PointerType>(GEP.getType()->getScalarType())
2135 ->getElementType() == ElTy,
2136 "GEP is not of right type for indices!", &GEP, ElTy);
2138 if (GEP.getPointerOperandType()->isVectorTy()) {
2139 // Additional checks for vector GEPs.
2140 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2141 Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2142 "Vector GEP result width doesn't match operand's", &GEP);
2143 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2144 Type *IndexTy = Idxs[i]->getType();
2145 Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2147 unsigned IndexWidth = IndexTy->getVectorNumElements();
2148 Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2151 visitInstruction(GEP);
2154 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2155 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2158 void Verifier::visitRangeMetadata(Instruction& I,
2159 MDNode* Range, Type* Ty) {
2161 Range == I.getMetadata(LLVMContext::MD_range) &&
2162 "precondition violation");
2164 unsigned NumOperands = Range->getNumOperands();
2165 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2166 unsigned NumRanges = NumOperands / 2;
2167 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2169 ConstantRange LastRange(1); // Dummy initial value
2170 for (unsigned i = 0; i < NumRanges; ++i) {
2172 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2173 Assert(Low, "The lower limit must be an integer!", Low);
2175 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2176 Assert(High, "The upper limit must be an integer!", High);
2177 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2178 "Range types must match instruction type!", &I);
2180 APInt HighV = High->getValue();
2181 APInt LowV = Low->getValue();
2182 ConstantRange CurRange(LowV, HighV);
2183 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2184 "Range must not be empty!", Range);
2186 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2187 "Intervals are overlapping", Range);
2188 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2190 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2193 LastRange = ConstantRange(LowV, HighV);
2195 if (NumRanges > 2) {
2197 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2199 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2200 ConstantRange FirstRange(FirstLow, FirstHigh);
2201 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2202 "Intervals are overlapping", Range);
2203 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2208 void Verifier::visitLoadInst(LoadInst &LI) {
2209 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2210 Assert(PTy, "Load operand must be a pointer.", &LI);
2211 Type *ElTy = PTy->getElementType();
2212 Assert(ElTy == LI.getType(),
2213 "Load result type does not match pointer operand type!", &LI, ElTy);
2214 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2215 "huge alignment values are unsupported", &LI);
2216 if (LI.isAtomic()) {
2217 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2218 "Load cannot have Release ordering", &LI);
2219 Assert(LI.getAlignment() != 0,
2220 "Atomic load must specify explicit alignment", &LI);
2221 if (!ElTy->isPointerTy()) {
2222 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2224 unsigned Size = ElTy->getPrimitiveSizeInBits();
2225 Assert(Size >= 8 && !(Size & (Size - 1)),
2226 "atomic load operand must be power-of-two byte-sized integer", &LI,
2230 Assert(LI.getSynchScope() == CrossThread,
2231 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2234 visitInstruction(LI);
2237 void Verifier::visitStoreInst(StoreInst &SI) {
2238 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2239 Assert(PTy, "Store operand must be a pointer.", &SI);
2240 Type *ElTy = PTy->getElementType();
2241 Assert(ElTy == SI.getOperand(0)->getType(),
2242 "Stored value type does not match pointer operand type!", &SI, ElTy);
2243 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2244 "huge alignment values are unsupported", &SI);
2245 if (SI.isAtomic()) {
2246 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2247 "Store cannot have Acquire ordering", &SI);
2248 Assert(SI.getAlignment() != 0,
2249 "Atomic store must specify explicit alignment", &SI);
2250 if (!ElTy->isPointerTy()) {
2251 Assert(ElTy->isIntegerTy(),
2252 "atomic store operand must have integer type!", &SI, ElTy);
2253 unsigned Size = ElTy->getPrimitiveSizeInBits();
2254 Assert(Size >= 8 && !(Size & (Size - 1)),
2255 "atomic store operand must be power-of-two byte-sized integer",
2259 Assert(SI.getSynchScope() == CrossThread,
2260 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2262 visitInstruction(SI);
2265 void Verifier::visitAllocaInst(AllocaInst &AI) {
2266 SmallPtrSet<const Type*, 4> Visited;
2267 PointerType *PTy = AI.getType();
2268 Assert(PTy->getAddressSpace() == 0,
2269 "Allocation instruction pointer not in the generic address space!",
2271 Assert(PTy->getElementType()->isSized(&Visited),
2272 "Cannot allocate unsized type", &AI);
2273 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2274 "Alloca array size must have integer type", &AI);
2275 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2276 "huge alignment values are unsupported", &AI);
2278 visitInstruction(AI);
2281 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2283 // FIXME: more conditions???
2284 Assert(CXI.getSuccessOrdering() != NotAtomic,
2285 "cmpxchg instructions must be atomic.", &CXI);
2286 Assert(CXI.getFailureOrdering() != NotAtomic,
2287 "cmpxchg instructions must be atomic.", &CXI);
2288 Assert(CXI.getSuccessOrdering() != Unordered,
2289 "cmpxchg instructions cannot be unordered.", &CXI);
2290 Assert(CXI.getFailureOrdering() != Unordered,
2291 "cmpxchg instructions cannot be unordered.", &CXI);
2292 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2293 "cmpxchg instructions be at least as constrained on success as fail",
2295 Assert(CXI.getFailureOrdering() != Release &&
2296 CXI.getFailureOrdering() != AcquireRelease,
2297 "cmpxchg failure ordering cannot include release semantics", &CXI);
2299 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2300 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2301 Type *ElTy = PTy->getElementType();
2302 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2304 unsigned Size = ElTy->getPrimitiveSizeInBits();
2305 Assert(Size >= 8 && !(Size & (Size - 1)),
2306 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2307 Assert(ElTy == CXI.getOperand(1)->getType(),
2308 "Expected value type does not match pointer operand type!", &CXI,
2310 Assert(ElTy == CXI.getOperand(2)->getType(),
2311 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2312 visitInstruction(CXI);
2315 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2316 Assert(RMWI.getOrdering() != NotAtomic,
2317 "atomicrmw instructions must be atomic.", &RMWI);
2318 Assert(RMWI.getOrdering() != Unordered,
2319 "atomicrmw instructions cannot be unordered.", &RMWI);
2320 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2321 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2322 Type *ElTy = PTy->getElementType();
2323 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2325 unsigned Size = ElTy->getPrimitiveSizeInBits();
2326 Assert(Size >= 8 && !(Size & (Size - 1)),
2327 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2329 Assert(ElTy == RMWI.getOperand(1)->getType(),
2330 "Argument value type does not match pointer operand type!", &RMWI,
2332 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2333 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2334 "Invalid binary operation!", &RMWI);
2335 visitInstruction(RMWI);
2338 void Verifier::visitFenceInst(FenceInst &FI) {
2339 const AtomicOrdering Ordering = FI.getOrdering();
2340 Assert(Ordering == Acquire || Ordering == Release ||
2341 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2342 "fence instructions may only have "
2343 "acquire, release, acq_rel, or seq_cst ordering.",
2345 visitInstruction(FI);
2348 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2349 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2350 EVI.getIndices()) == EVI.getType(),
2351 "Invalid ExtractValueInst operands!", &EVI);
2353 visitInstruction(EVI);
2356 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2357 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2358 IVI.getIndices()) ==
2359 IVI.getOperand(1)->getType(),
2360 "Invalid InsertValueInst operands!", &IVI);
2362 visitInstruction(IVI);
2365 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2366 BasicBlock *BB = LPI.getParent();
2368 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2370 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2371 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2373 // The landingpad instruction defines its parent as a landing pad block. The
2374 // landing pad block may be branched to only by the unwind edge of an invoke.
2375 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2376 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2377 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2378 "Block containing LandingPadInst must be jumped to "
2379 "only by the unwind edge of an invoke.",
2383 // The landingpad instruction must be the first non-PHI instruction in the
2385 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2386 "LandingPadInst not the first non-PHI instruction in the block.",
2389 // The personality functions for all landingpad instructions within the same
2390 // function should match.
2392 Assert(LPI.getPersonalityFn() == PersonalityFn,
2393 "Personality function doesn't match others in function", &LPI);
2394 PersonalityFn = LPI.getPersonalityFn();
2396 // All operands must be constants.
2397 Assert(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2399 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2400 Constant *Clause = LPI.getClause(i);
2401 if (LPI.isCatch(i)) {
2402 Assert(isa<PointerType>(Clause->getType()),
2403 "Catch operand does not have pointer type!", &LPI);
2405 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2406 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2407 "Filter operand is not an array of constants!", &LPI);
2411 visitInstruction(LPI);
2414 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2415 Instruction *Op = cast<Instruction>(I.getOperand(i));
2416 // If the we have an invalid invoke, don't try to compute the dominance.
2417 // We already reject it in the invoke specific checks and the dominance
2418 // computation doesn't handle multiple edges.
2419 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2420 if (II->getNormalDest() == II->getUnwindDest())
2424 const Use &U = I.getOperandUse(i);
2425 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2426 "Instruction does not dominate all uses!", Op, &I);
2429 /// verifyInstruction - Verify that an instruction is well formed.
2431 void Verifier::visitInstruction(Instruction &I) {
2432 BasicBlock *BB = I.getParent();
2433 Assert(BB, "Instruction not embedded in basic block!", &I);
2435 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2436 for (User *U : I.users()) {
2437 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2438 "Only PHI nodes may reference their own value!", &I);
2442 // Check that void typed values don't have names
2443 Assert(!I.getType()->isVoidTy() || !I.hasName(),
2444 "Instruction has a name, but provides a void value!", &I);
2446 // Check that the return value of the instruction is either void or a legal
2448 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2449 "Instruction returns a non-scalar type!", &I);
2451 // Check that the instruction doesn't produce metadata. Calls are already
2452 // checked against the callee type.
2453 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2454 "Invalid use of metadata!", &I);
2456 // Check that all uses of the instruction, if they are instructions
2457 // themselves, actually have parent basic blocks. If the use is not an
2458 // instruction, it is an error!
2459 for (Use &U : I.uses()) {
2460 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2461 Assert(Used->getParent() != nullptr,
2462 "Instruction referencing"
2463 " instruction not embedded in a basic block!",
2466 CheckFailed("Use of instruction is not an instruction!", U);
2471 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2472 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2474 // Check to make sure that only first-class-values are operands to
2476 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2477 Assert(0, "Instruction operands must be first-class values!", &I);
2480 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2481 // Check to make sure that the "address of" an intrinsic function is never
2484 !F->isIntrinsic() ||
2485 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2486 "Cannot take the address of an intrinsic!", &I);
2488 !F->isIntrinsic() || isa<CallInst>(I) ||
2489 F->getIntrinsicID() == Intrinsic::donothing ||
2490 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2491 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2492 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2493 "Cannot invoke an intrinsinc other than"
2494 " donothing or patchpoint",
2496 Assert(F->getParent() == M, "Referencing function in another module!",
2498 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2499 Assert(OpBB->getParent() == BB->getParent(),
2500 "Referring to a basic block in another function!", &I);
2501 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2502 Assert(OpArg->getParent() == BB->getParent(),
2503 "Referring to an argument in another function!", &I);
2504 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2505 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2506 } else if (isa<Instruction>(I.getOperand(i))) {
2507 verifyDominatesUse(I, i);
2508 } else if (isa<InlineAsm>(I.getOperand(i))) {
2509 Assert((i + 1 == e && isa<CallInst>(I)) ||
2510 (i + 3 == e && isa<InvokeInst>(I)),
2511 "Cannot take the address of an inline asm!", &I);
2512 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2513 if (CE->getType()->isPtrOrPtrVectorTy()) {
2514 // If we have a ConstantExpr pointer, we need to see if it came from an
2515 // illegal bitcast (inttoptr <constant int> )
2516 SmallVector<const ConstantExpr *, 4> Stack;
2517 SmallPtrSet<const ConstantExpr *, 4> Visited;
2518 Stack.push_back(CE);
2520 while (!Stack.empty()) {
2521 const ConstantExpr *V = Stack.pop_back_val();
2522 if (!Visited.insert(V).second)
2525 VerifyConstantExprBitcastType(V);
2527 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2528 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2529 Stack.push_back(Op);
2536 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2537 Assert(I.getType()->isFPOrFPVectorTy(),
2538 "fpmath requires a floating point result!", &I);
2539 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2540 if (ConstantFP *CFP0 =
2541 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2542 APFloat Accuracy = CFP0->getValueAPF();
2543 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2544 "fpmath accuracy not a positive number!", &I);
2546 Assert(false, "invalid fpmath accuracy!", &I);
2550 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2551 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2552 "Ranges are only for loads, calls and invokes!", &I);
2553 visitRangeMetadata(I, Range, I.getType());
2556 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2557 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2559 Assert(isa<LoadInst>(I),
2560 "nonnull applies only to load instructions, use attributes"
2561 " for calls or invokes",
2565 InstsInThisBlock.insert(&I);
2568 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2569 /// intrinsic argument or return value) matches the type constraints specified
2570 /// by the .td file (e.g. an "any integer" argument really is an integer).
2572 /// This return true on error but does not print a message.
2573 bool Verifier::VerifyIntrinsicType(Type *Ty,
2574 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2575 SmallVectorImpl<Type*> &ArgTys) {
2576 using namespace Intrinsic;
2578 // If we ran out of descriptors, there are too many arguments.
2579 if (Infos.empty()) return true;
2580 IITDescriptor D = Infos.front();
2581 Infos = Infos.slice(1);
2584 case IITDescriptor::Void: return !Ty->isVoidTy();
2585 case IITDescriptor::VarArg: return true;
2586 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2587 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2588 case IITDescriptor::Half: return !Ty->isHalfTy();
2589 case IITDescriptor::Float: return !Ty->isFloatTy();
2590 case IITDescriptor::Double: return !Ty->isDoubleTy();
2591 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2592 case IITDescriptor::Vector: {
2593 VectorType *VT = dyn_cast<VectorType>(Ty);
2594 return !VT || VT->getNumElements() != D.Vector_Width ||
2595 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2597 case IITDescriptor::Pointer: {
2598 PointerType *PT = dyn_cast<PointerType>(Ty);
2599 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2600 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2603 case IITDescriptor::Struct: {
2604 StructType *ST = dyn_cast<StructType>(Ty);
2605 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2608 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2609 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2614 case IITDescriptor::Argument:
2615 // Two cases here - If this is the second occurrence of an argument, verify
2616 // that the later instance matches the previous instance.
2617 if (D.getArgumentNumber() < ArgTys.size())
2618 return Ty != ArgTys[D.getArgumentNumber()];
2620 // Otherwise, if this is the first instance of an argument, record it and
2621 // verify the "Any" kind.
2622 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2623 ArgTys.push_back(Ty);
2625 switch (D.getArgumentKind()) {
2626 case IITDescriptor::AK_Any: return false; // Success
2627 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2628 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2629 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2630 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2632 llvm_unreachable("all argument kinds not covered");
2634 case IITDescriptor::ExtendArgument: {
2635 // This may only be used when referring to a previous vector argument.
2636 if (D.getArgumentNumber() >= ArgTys.size())
2639 Type *NewTy = ArgTys[D.getArgumentNumber()];
2640 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2641 NewTy = VectorType::getExtendedElementVectorType(VTy);
2642 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2643 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2649 case IITDescriptor::TruncArgument: {
2650 // This may only be used when referring to a previous vector argument.
2651 if (D.getArgumentNumber() >= ArgTys.size())
2654 Type *NewTy = ArgTys[D.getArgumentNumber()];
2655 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2656 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2657 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2658 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2664 case IITDescriptor::HalfVecArgument:
2665 // This may only be used when referring to a previous vector argument.
2666 return D.getArgumentNumber() >= ArgTys.size() ||
2667 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2668 VectorType::getHalfElementsVectorType(
2669 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2670 case IITDescriptor::SameVecWidthArgument: {
2671 if (D.getArgumentNumber() >= ArgTys.size())
2673 VectorType * ReferenceType =
2674 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
2675 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
2676 if (!ThisArgType || !ReferenceType ||
2677 (ReferenceType->getVectorNumElements() !=
2678 ThisArgType->getVectorNumElements()))
2680 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
2683 case IITDescriptor::PtrToArgument: {
2684 if (D.getArgumentNumber() >= ArgTys.size())
2686 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
2687 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
2688 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
2690 case IITDescriptor::VecOfPtrsToElt: {
2691 if (D.getArgumentNumber() >= ArgTys.size())
2693 VectorType * ReferenceType =
2694 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
2695 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
2696 if (!ThisArgVecTy || !ReferenceType ||
2697 (ReferenceType->getVectorNumElements() !=
2698 ThisArgVecTy->getVectorNumElements()))
2700 PointerType *ThisArgEltTy =
2701 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
2704 return (!(ThisArgEltTy->getElementType() ==
2705 ReferenceType->getVectorElementType()));
2708 llvm_unreachable("unhandled");
2711 /// \brief Verify if the intrinsic has variable arguments.
2712 /// This method is intended to be called after all the fixed arguments have been
2715 /// This method returns true on error and does not print an error message.
2717 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2718 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2719 using namespace Intrinsic;
2721 // If there are no descriptors left, then it can't be a vararg.
2725 // There should be only one descriptor remaining at this point.
2726 if (Infos.size() != 1)
2729 // Check and verify the descriptor.
2730 IITDescriptor D = Infos.front();
2731 Infos = Infos.slice(1);
2732 if (D.Kind == IITDescriptor::VarArg)
2738 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2740 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2741 Function *IF = CI.getCalledFunction();
2742 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2745 // Verify that the intrinsic prototype lines up with what the .td files
2747 FunctionType *IFTy = IF->getFunctionType();
2748 bool IsVarArg = IFTy->isVarArg();
2750 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2751 getIntrinsicInfoTableEntries(ID, Table);
2752 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2754 SmallVector<Type *, 4> ArgTys;
2755 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2756 "Intrinsic has incorrect return type!", IF);
2757 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2758 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2759 "Intrinsic has incorrect argument type!", IF);
2761 // Verify if the intrinsic call matches the vararg property.
2763 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2764 "Intrinsic was not defined with variable arguments!", IF);
2766 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2767 "Callsite was not defined with variable arguments!", IF);
2769 // All descriptors should be absorbed by now.
2770 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2772 // Now that we have the intrinsic ID and the actual argument types (and we
2773 // know they are legal for the intrinsic!) get the intrinsic name through the
2774 // usual means. This allows us to verify the mangling of argument types into
2776 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2777 Assert(ExpectedName == IF->getName(),
2778 "Intrinsic name not mangled correctly for type arguments! "
2783 // If the intrinsic takes MDNode arguments, verify that they are either global
2784 // or are local to *this* function.
2785 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2786 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
2787 visitMetadataAsValue(*MD, CI.getParent()->getParent());
2792 case Intrinsic::ctlz: // llvm.ctlz
2793 case Intrinsic::cttz: // llvm.cttz
2794 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
2795 "is_zero_undef argument of bit counting intrinsics must be a "
2799 case Intrinsic::dbg_declare: // llvm.dbg.declare
2800 Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
2801 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2802 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(CI));
2804 case Intrinsic::dbg_value: // llvm.dbg.value
2805 visitDbgIntrinsic("value", cast<DbgValueInst>(CI));
2807 case Intrinsic::memcpy:
2808 case Intrinsic::memmove:
2809 case Intrinsic::memset: {
2810 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
2812 "alignment argument of memory intrinsics must be a constant int",
2814 const APInt &AlignVal = AlignCI->getValue();
2815 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
2816 "alignment argument of memory intrinsics must be a power of 2", &CI);
2817 Assert(isa<ConstantInt>(CI.getArgOperand(4)),
2818 "isvolatile argument of memory intrinsics must be a constant int",
2822 case Intrinsic::gcroot:
2823 case Intrinsic::gcwrite:
2824 case Intrinsic::gcread:
2825 if (ID == Intrinsic::gcroot) {
2827 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2828 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2829 Assert(isa<Constant>(CI.getArgOperand(1)),
2830 "llvm.gcroot parameter #2 must be a constant.", &CI);
2831 if (!AI->getType()->getElementType()->isPointerTy()) {
2832 Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2833 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2834 "or argument #2 must be a non-null constant.",
2839 Assert(CI.getParent()->getParent()->hasGC(),
2840 "Enclosing function does not use GC.", &CI);
2842 case Intrinsic::init_trampoline:
2843 Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2844 "llvm.init_trampoline parameter #2 must resolve to a function.",
2847 case Intrinsic::prefetch:
2848 Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
2849 isa<ConstantInt>(CI.getArgOperand(2)) &&
2850 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2851 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2852 "invalid arguments to llvm.prefetch", &CI);
2854 case Intrinsic::stackprotector:
2855 Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2856 "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
2858 case Intrinsic::lifetime_start:
2859 case Intrinsic::lifetime_end:
2860 case Intrinsic::invariant_start:
2861 Assert(isa<ConstantInt>(CI.getArgOperand(0)),
2862 "size argument of memory use markers must be a constant integer",
2865 case Intrinsic::invariant_end:
2866 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
2867 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2870 case Intrinsic::frameescape: {
2871 BasicBlock *BB = CI.getParent();
2872 Assert(BB == &BB->getParent()->front(),
2873 "llvm.frameescape used outside of entry block", &CI);
2874 Assert(!SawFrameEscape,
2875 "multiple calls to llvm.frameescape in one function", &CI);
2876 for (Value *Arg : CI.arg_operands()) {
2877 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2878 Assert(AI && AI->isStaticAlloca(),
2879 "llvm.frameescape only accepts static allocas", &CI);
2881 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
2882 SawFrameEscape = true;
2885 case Intrinsic::framerecover: {
2886 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
2887 Function *Fn = dyn_cast<Function>(FnArg);
2888 Assert(Fn && !Fn->isDeclaration(),
2889 "llvm.framerecover first "
2890 "argument must be function defined in this module",
2892 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
2893 Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
2895 auto &Entry = FrameEscapeInfo[Fn];
2896 Entry.second = unsigned(
2897 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
2901 case Intrinsic::experimental_gc_statepoint:
2902 Assert(!CI.isInlineAsm(),
2903 "gc.statepoint support for inline assembly unimplemented", &CI);
2905 VerifyStatepoint(ImmutableCallSite(&CI));
2907 case Intrinsic::experimental_gc_result_int:
2908 case Intrinsic::experimental_gc_result_float:
2909 case Intrinsic::experimental_gc_result_ptr:
2910 case Intrinsic::experimental_gc_result: {
2911 // Are we tied to a statepoint properly?
2912 CallSite StatepointCS(CI.getArgOperand(0));
2913 const Function *StatepointFn =
2914 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
2915 Assert(StatepointFn && StatepointFn->isDeclaration() &&
2916 StatepointFn->getIntrinsicID() ==
2917 Intrinsic::experimental_gc_statepoint,
2918 "gc.result operand #1 must be from a statepoint", &CI,
2919 CI.getArgOperand(0));
2921 // Assert that result type matches wrapped callee.
2922 const Value *Target = StatepointCS.getArgument(0);
2923 const PointerType *PT = cast<PointerType>(Target->getType());
2924 const FunctionType *TargetFuncType =
2925 cast<FunctionType>(PT->getElementType());
2926 Assert(CI.getType() == TargetFuncType->getReturnType(),
2927 "gc.result result type does not match wrapped callee", &CI);
2930 case Intrinsic::experimental_gc_relocate: {
2931 Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
2933 // Check that this relocate is correctly tied to the statepoint
2935 // This is case for relocate on the unwinding path of an invoke statepoint
2936 if (ExtractValueInst *ExtractValue =
2937 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
2938 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
2939 "gc relocate on unwind path incorrectly linked to the statepoint",
2942 const BasicBlock *invokeBB =
2943 ExtractValue->getParent()->getUniquePredecessor();
2945 // Landingpad relocates should have only one predecessor with invoke
2946 // statepoint terminator
2947 Assert(invokeBB, "safepoints should have unique landingpads",
2948 ExtractValue->getParent());
2949 Assert(invokeBB->getTerminator(), "safepoint block should be well formed",
2951 Assert(isStatepoint(invokeBB->getTerminator()),
2952 "gc relocate should be linked to a statepoint", invokeBB);
2955 // In all other cases relocate should be tied to the statepoint directly.
2956 // This covers relocates on a normal return path of invoke statepoint and
2957 // relocates of a call statepoint
2958 auto Token = CI.getArgOperand(0);
2959 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
2960 "gc relocate is incorrectly tied to the statepoint", &CI, Token);
2963 // Verify rest of the relocate arguments
2965 GCRelocateOperands ops(&CI);
2966 ImmutableCallSite StatepointCS(ops.statepoint());
2968 // Both the base and derived must be piped through the safepoint
2969 Value* Base = CI.getArgOperand(1);
2970 Assert(isa<ConstantInt>(Base),
2971 "gc.relocate operand #2 must be integer offset", &CI);
2973 Value* Derived = CI.getArgOperand(2);
2974 Assert(isa<ConstantInt>(Derived),
2975 "gc.relocate operand #3 must be integer offset", &CI);
2977 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
2978 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
2980 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
2981 "gc.relocate: statepoint base index out of bounds", &CI);
2982 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
2983 "gc.relocate: statepoint derived index out of bounds", &CI);
2985 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
2986 // section of the statepoint's argument
2987 Assert(StatepointCS.arg_size() > 0,
2988 "gc.statepoint: insufficient arguments");
2989 Assert(isa<ConstantInt>(StatepointCS.getArgument(1)),
2990 "gc.statement: number of call arguments must be constant integer");
2991 const unsigned NumCallArgs =
2992 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
2993 Assert(StatepointCS.arg_size() > NumCallArgs+3,
2994 "gc.statepoint: mismatch in number of call arguments");
2995 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs+3)),
2996 "gc.statepoint: number of deoptimization arguments must be "
2997 "a constant integer");
2998 const int NumDeoptArgs =
2999 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3000 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3001 const int GCParamArgsEnd = StatepointCS.arg_size();
3002 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3003 "gc.relocate: statepoint base index doesn't fall within the "
3004 "'gc parameters' section of the statepoint call",
3006 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3007 "gc.relocate: statepoint derived index doesn't fall within the "
3008 "'gc parameters' section of the statepoint call",
3011 // Assert that the result type matches the type of the relocated pointer
3012 GCRelocateOperands Operands(&CI);
3013 Assert(Operands.derivedPtr()->getType() == CI.getType(),
3014 "gc.relocate: relocating a pointer shouldn't change its type", &CI);
3020 template <class DbgIntrinsicTy>
3021 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3022 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3023 Assert(isa<ValueAsMetadata>(MD) ||
3024 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3025 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3026 Assert(isa<MDLocalVariable>(DII.getRawVariable()),
3027 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3028 DII.getRawVariable());
3029 Assert(isa<MDExpression>(DII.getRawExpression()),
3030 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3031 DII.getRawExpression());
3034 void DebugInfoVerifier::verifyDebugInfo() {
3035 if (!VerifyDebugInfo)
3038 DebugInfoFinder Finder;
3039 Finder.processModule(*M);
3040 processInstructions(Finder);
3042 // Verify Debug Info.
3044 // NOTE: The loud braces are necessary for MSVC compatibility.
3045 for (DICompileUnit CU : Finder.compile_units()) {
3046 Assert(CU.Verify(), "DICompileUnit does not Verify!", CU);
3048 for (DISubprogram S : Finder.subprograms()) {
3049 Assert(S.Verify(), "DISubprogram does not Verify!", S);
3051 for (DIGlobalVariable GV : Finder.global_variables()) {
3052 Assert(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
3054 for (DIType T : Finder.types()) {
3055 Assert(T.Verify(), "DIType does not Verify!", T);
3057 for (DIScope S : Finder.scopes()) {
3058 Assert(S.Verify(), "DIScope does not Verify!", S);
3062 void DebugInfoVerifier::processInstructions(DebugInfoFinder &Finder) {
3063 for (const Function &F : *M)
3064 for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
3065 if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
3066 Finder.processLocation(*M, DILocation(MD));
3067 if (const CallInst *CI = dyn_cast<CallInst>(&*I))
3068 processCallInst(Finder, *CI);
3072 void DebugInfoVerifier::processCallInst(DebugInfoFinder &Finder,
3073 const CallInst &CI) {
3074 if (Function *F = CI.getCalledFunction())
3075 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3077 case Intrinsic::dbg_declare:
3078 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
3080 case Intrinsic::dbg_value:
3081 Finder.processValue(*M, cast<DbgValueInst>(&CI));
3088 //===----------------------------------------------------------------------===//
3089 // Implement the public interfaces to this file...
3090 //===----------------------------------------------------------------------===//
3092 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3093 Function &F = const_cast<Function &>(f);
3094 assert(!F.isDeclaration() && "Cannot verify external functions");
3096 raw_null_ostream NullStr;
3097 Verifier V(OS ? *OS : NullStr);
3099 // Note that this function's return value is inverted from what you would
3100 // expect of a function called "verify".
3101 return !V.verify(F);
3104 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3105 raw_null_ostream NullStr;
3106 Verifier V(OS ? *OS : NullStr);
3108 bool Broken = false;
3109 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3110 if (!I->isDeclaration() && !I->isMaterializable())
3111 Broken |= !V.verify(*I);
3113 // Note that this function's return value is inverted from what you would
3114 // expect of a function called "verify".
3115 if (!V.verify(M) || Broken)
3118 // Run the debug info verifier only if the regular verifier succeeds, since
3119 // sometimes checks that have already failed will cause crashes here.
3120 DebugInfoVerifier DIV(OS ? *OS : NullStr);
3121 return !DIV.verify(M);
3125 struct VerifierLegacyPass : public FunctionPass {
3131 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3132 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3134 explicit VerifierLegacyPass(bool FatalErrors)
3135 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3136 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3139 bool runOnFunction(Function &F) override {
3140 if (!V.verify(F) && FatalErrors)
3141 report_fatal_error("Broken function found, compilation aborted!");
3146 bool doFinalization(Module &M) override {
3147 if (!V.verify(M) && FatalErrors)
3148 report_fatal_error("Broken module found, compilation aborted!");
3150 if (!DebugInfoVerifier(dbgs()).verify(M) && FatalErrors)
3151 report_fatal_error("Broken module found, compilation aborted!");
3156 void getAnalysisUsage(AnalysisUsage &AU) const override {
3157 AU.setPreservesAll();
3162 char VerifierLegacyPass::ID = 0;
3163 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3165 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3166 return new VerifierLegacyPass(FatalErrors);
3169 PreservedAnalyses VerifierPass::run(Module &M) {
3170 if (verifyModule(M, &dbgs()) && FatalErrors)
3171 report_fatal_error("Broken module found, compilation aborted!");
3173 return PreservedAnalyses::all();
3176 PreservedAnalyses VerifierPass::run(Function &F) {
3177 if (verifyFunction(F, &dbgs()) && FatalErrors)
3178 report_fatal_error("Broken function found, compilation aborted!");
3180 return PreservedAnalyses::all();