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.
92 explicit VerifierSupport(raw_ostream &OS)
93 : OS(OS), M(nullptr), Broken(false), EverBroken(false) {}
96 void Write(const Value *V) {
99 if (isa<Instruction>(V)) {
102 V->printAsOperand(OS, true, M);
107 void Write(const Metadata *MD) {
114 void Write(const NamedMDNode *NMD) {
121 void Write(Type *T) {
127 void Write(const Comdat *C) {
133 template <typename T1, typename... Ts>
134 void WriteTs(const T1 &V1, const Ts &... Vs) {
139 template <typename... Ts> void WriteTs() {}
142 /// \brief A check failed, so printout out the condition and the message.
144 /// This provides a nice place to put a breakpoint if you want to see why
145 /// something is not correct.
146 void CheckFailed(const Twine &Message) {
147 OS << Message << '\n';
148 EverBroken = Broken = true;
151 /// \brief A check failed (with values to print).
153 /// This calls the Message-only version so that the above is easier to set a
155 template <typename T1, typename... Ts>
156 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
157 CheckFailed(Message);
162 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
163 friend class InstVisitor<Verifier>;
165 LLVMContext *Context;
168 /// \brief When verifying a basic block, keep track of all of the
169 /// instructions we have seen so far.
171 /// This allows us to do efficient dominance checks for the case when an
172 /// instruction has an operand that is an instruction in the same block.
173 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
175 /// \brief Keep track of the metadata nodes that have been checked already.
176 SmallPtrSet<const Metadata *, 32> MDNodes;
178 /// \brief The personality function referenced by the LandingPadInsts.
179 /// All LandingPadInsts within the same function must use the same
180 /// personality function.
181 const Value *PersonalityFn;
183 /// \brief Whether we've seen a call to @llvm.frameescape in this function
187 /// Stores the count of how many objects were passed to llvm.frameescape for a
188 /// given function and the largest index passed to llvm.framerecover.
189 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
192 explicit Verifier(raw_ostream &OS)
193 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
194 SawFrameEscape(false) {}
196 bool verify(const Function &F) {
198 Context = &M->getContext();
200 // First ensure the function is well-enough formed to compute dominance
203 OS << "Function '" << F.getName()
204 << "' does not contain an entry block!\n";
207 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
208 if (I->empty() || !I->back().isTerminator()) {
209 OS << "Basic Block in function '" << F.getName()
210 << "' does not have terminator!\n";
211 I->printAsOperand(OS, true);
217 // Now directly compute a dominance tree. We don't rely on the pass
218 // manager to provide this as it isolates us from a potentially
219 // out-of-date dominator tree and makes it significantly more complex to
220 // run this code outside of a pass manager.
221 // FIXME: It's really gross that we have to cast away constness here.
222 DT.recalculate(const_cast<Function &>(F));
225 // FIXME: We strip const here because the inst visitor strips const.
226 visit(const_cast<Function &>(F));
227 InstsInThisBlock.clear();
228 PersonalityFn = nullptr;
229 SawFrameEscape = false;
234 bool verify(const Module &M) {
236 Context = &M.getContext();
239 // Scan through, checking all of the external function's linkage now...
240 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
241 visitGlobalValue(*I);
243 // Check to make sure function prototypes are okay.
244 if (I->isDeclaration())
248 // Now that we've visited every function, verify that we never asked to
249 // recover a frame index that wasn't escaped.
250 verifyFrameRecoverIndices();
252 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
254 visitGlobalVariable(*I);
256 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
258 visitGlobalAlias(*I);
260 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
261 E = M.named_metadata_end();
263 visitNamedMDNode(*I);
265 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
266 visitComdat(SMEC.getValue());
269 visitModuleIdents(M);
271 // Verify debug info last.
278 // Verification methods...
279 void visitGlobalValue(const GlobalValue &GV);
280 void visitGlobalVariable(const GlobalVariable &GV);
281 void visitGlobalAlias(const GlobalAlias &GA);
282 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
283 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
284 const GlobalAlias &A, const Constant &C);
285 void visitNamedMDNode(const NamedMDNode &NMD);
286 void visitMDNode(const MDNode &MD);
287 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
288 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
289 void visitComdat(const Comdat &C);
290 void visitModuleIdents(const Module &M);
291 void visitModuleFlags(const Module &M);
292 void visitModuleFlag(const MDNode *Op,
293 DenseMap<const MDString *, const MDNode *> &SeenIDs,
294 SmallVectorImpl<const MDNode *> &Requirements);
295 void visitFunction(const Function &F);
296 void visitBasicBlock(BasicBlock &BB);
297 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
299 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
300 #include "llvm/IR/Metadata.def"
301 void visitMDScope(const MDScope &N);
302 void visitMDDerivedTypeBase(const MDDerivedTypeBase &N);
303 void visitMDVariable(const MDVariable &N);
305 // InstVisitor overrides...
306 using InstVisitor<Verifier>::visit;
307 void visit(Instruction &I);
309 void visitTruncInst(TruncInst &I);
310 void visitZExtInst(ZExtInst &I);
311 void visitSExtInst(SExtInst &I);
312 void visitFPTruncInst(FPTruncInst &I);
313 void visitFPExtInst(FPExtInst &I);
314 void visitFPToUIInst(FPToUIInst &I);
315 void visitFPToSIInst(FPToSIInst &I);
316 void visitUIToFPInst(UIToFPInst &I);
317 void visitSIToFPInst(SIToFPInst &I);
318 void visitIntToPtrInst(IntToPtrInst &I);
319 void visitPtrToIntInst(PtrToIntInst &I);
320 void visitBitCastInst(BitCastInst &I);
321 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
322 void visitPHINode(PHINode &PN);
323 void visitBinaryOperator(BinaryOperator &B);
324 void visitICmpInst(ICmpInst &IC);
325 void visitFCmpInst(FCmpInst &FC);
326 void visitExtractElementInst(ExtractElementInst &EI);
327 void visitInsertElementInst(InsertElementInst &EI);
328 void visitShuffleVectorInst(ShuffleVectorInst &EI);
329 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
330 void visitCallInst(CallInst &CI);
331 void visitInvokeInst(InvokeInst &II);
332 void visitGetElementPtrInst(GetElementPtrInst &GEP);
333 void visitLoadInst(LoadInst &LI);
334 void visitStoreInst(StoreInst &SI);
335 void verifyDominatesUse(Instruction &I, unsigned i);
336 void visitInstruction(Instruction &I);
337 void visitTerminatorInst(TerminatorInst &I);
338 void visitBranchInst(BranchInst &BI);
339 void visitReturnInst(ReturnInst &RI);
340 void visitSwitchInst(SwitchInst &SI);
341 void visitIndirectBrInst(IndirectBrInst &BI);
342 void visitSelectInst(SelectInst &SI);
343 void visitUserOp1(Instruction &I);
344 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
345 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
346 template <class DbgIntrinsicTy>
347 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
348 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
349 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
350 void visitFenceInst(FenceInst &FI);
351 void visitAllocaInst(AllocaInst &AI);
352 void visitExtractValueInst(ExtractValueInst &EVI);
353 void visitInsertValueInst(InsertValueInst &IVI);
354 void visitLandingPadInst(LandingPadInst &LPI);
356 void VerifyCallSite(CallSite CS);
357 void verifyMustTailCall(CallInst &CI);
358 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
359 unsigned ArgNo, std::string &Suffix);
360 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
361 SmallVectorImpl<Type *> &ArgTys);
362 bool VerifyIntrinsicIsVarArg(bool isVarArg,
363 ArrayRef<Intrinsic::IITDescriptor> &Infos);
364 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
365 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
367 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
368 bool isReturnValue, const Value *V);
369 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
372 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
373 void VerifyStatepoint(ImmutableCallSite CS);
374 void verifyFrameRecoverIndices();
376 // Module-level debug info verification...
377 void verifyDebugInfo();
378 void processInstructions(DebugInfoFinder &Finder);
379 void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
381 } // End anonymous namespace
383 // Assert - We know that cond should be true, if not print an error message.
384 #define Assert(C, ...) \
385 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
387 void Verifier::visit(Instruction &I) {
388 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
389 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
390 InstVisitor<Verifier>::visit(I);
394 void Verifier::visitGlobalValue(const GlobalValue &GV) {
395 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
396 GV.hasExternalWeakLinkage(),
397 "Global is external, but doesn't have external or weak linkage!", &GV);
399 Assert(GV.getAlignment() <= Value::MaximumAlignment,
400 "huge alignment values are unsupported", &GV);
401 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
402 "Only global variables can have appending linkage!", &GV);
404 if (GV.hasAppendingLinkage()) {
405 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
406 Assert(GVar && GVar->getType()->getElementType()->isArrayTy(),
407 "Only global arrays can have appending linkage!", GVar);
411 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
412 if (GV.hasInitializer()) {
413 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
414 "Global variable initializer type does not match global "
418 // If the global has common linkage, it must have a zero initializer and
419 // cannot be constant.
420 if (GV.hasCommonLinkage()) {
421 Assert(GV.getInitializer()->isNullValue(),
422 "'common' global must have a zero initializer!", &GV);
423 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
425 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
428 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
429 "invalid linkage type for global declaration", &GV);
432 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
433 GV.getName() == "llvm.global_dtors")) {
434 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
435 "invalid linkage for intrinsic global variable", &GV);
436 // Don't worry about emitting an error for it not being an array,
437 // visitGlobalValue will complain on appending non-array.
438 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
439 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
440 PointerType *FuncPtrTy =
441 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
442 // FIXME: Reject the 2-field form in LLVM 4.0.
444 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
445 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
446 STy->getTypeAtIndex(1) == FuncPtrTy,
447 "wrong type for intrinsic global variable", &GV);
448 if (STy->getNumElements() == 3) {
449 Type *ETy = STy->getTypeAtIndex(2);
450 Assert(ETy->isPointerTy() &&
451 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
452 "wrong type for intrinsic global variable", &GV);
457 if (GV.hasName() && (GV.getName() == "llvm.used" ||
458 GV.getName() == "llvm.compiler.used")) {
459 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
460 "invalid linkage for intrinsic global variable", &GV);
461 Type *GVType = GV.getType()->getElementType();
462 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
463 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
464 Assert(PTy, "wrong type for intrinsic global variable", &GV);
465 if (GV.hasInitializer()) {
466 const Constant *Init = GV.getInitializer();
467 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
468 Assert(InitArray, "wrong initalizer for intrinsic global variable",
470 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
471 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
472 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
474 "invalid llvm.used member", V);
475 Assert(V->hasName(), "members of llvm.used must be named", V);
481 Assert(!GV.hasDLLImportStorageClass() ||
482 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
483 GV.hasAvailableExternallyLinkage(),
484 "Global is marked as dllimport, but not external", &GV);
486 if (!GV.hasInitializer()) {
487 visitGlobalValue(GV);
491 // Walk any aggregate initializers looking for bitcasts between address spaces
492 SmallPtrSet<const Value *, 4> Visited;
493 SmallVector<const Value *, 4> WorkStack;
494 WorkStack.push_back(cast<Value>(GV.getInitializer()));
496 while (!WorkStack.empty()) {
497 const Value *V = WorkStack.pop_back_val();
498 if (!Visited.insert(V).second)
501 if (const User *U = dyn_cast<User>(V)) {
502 WorkStack.append(U->op_begin(), U->op_end());
505 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
506 VerifyConstantExprBitcastType(CE);
512 visitGlobalValue(GV);
515 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
516 SmallPtrSet<const GlobalAlias*, 4> Visited;
518 visitAliaseeSubExpr(Visited, GA, C);
521 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
522 const GlobalAlias &GA, const Constant &C) {
523 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
524 Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
526 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
527 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
529 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
532 // Only continue verifying subexpressions of GlobalAliases.
533 // Do not recurse into global initializers.
538 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
539 VerifyConstantExprBitcastType(CE);
541 for (const Use &U : C.operands()) {
543 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
544 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
545 else if (const auto *C2 = dyn_cast<Constant>(V))
546 visitAliaseeSubExpr(Visited, GA, *C2);
550 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
551 Assert(!GA.getName().empty(), "Alias name cannot be empty!", &GA);
552 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
553 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
554 "weak_odr, or external linkage!",
556 const Constant *Aliasee = GA.getAliasee();
557 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
558 Assert(GA.getType() == Aliasee->getType(),
559 "Alias and aliasee types should match!", &GA);
561 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
562 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
564 visitAliaseeSubExpr(GA, *Aliasee);
566 visitGlobalValue(GA);
569 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
570 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
571 MDNode *MD = NMD.getOperand(i);
575 if (NMD.getName() == "llvm.dbg.cu") {
576 Assert(isa<MDCompileUnit>(MD), "invalid compile unit", &NMD, MD);
583 void Verifier::visitMDNode(const MDNode &MD) {
584 // Only visit each node once. Metadata can be mutually recursive, so this
585 // avoids infinite recursion here, as well as being an optimization.
586 if (!MDNodes.insert(&MD).second)
589 switch (MD.getMetadataID()) {
591 llvm_unreachable("Invalid MDNode subclass");
592 case Metadata::MDTupleKind:
594 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
595 case Metadata::CLASS##Kind: \
596 visit##CLASS(cast<CLASS>(MD)); \
598 #include "llvm/IR/Metadata.def"
601 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
602 Metadata *Op = MD.getOperand(i);
605 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
607 if (auto *N = dyn_cast<MDNode>(Op)) {
611 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
612 visitValueAsMetadata(*V, nullptr);
617 // Check these last, so we diagnose problems in operands first.
618 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
619 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
622 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
623 Assert(MD.getValue(), "Expected valid value", &MD);
624 Assert(!MD.getValue()->getType()->isMetadataTy(),
625 "Unexpected metadata round-trip through values", &MD, MD.getValue());
627 auto *L = dyn_cast<LocalAsMetadata>(&MD);
631 Assert(F, "function-local metadata used outside a function", L);
633 // If this was an instruction, bb, or argument, verify that it is in the
634 // function that we expect.
635 Function *ActualF = nullptr;
636 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
637 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
638 ActualF = I->getParent()->getParent();
639 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
640 ActualF = BB->getParent();
641 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
642 ActualF = A->getParent();
643 assert(ActualF && "Unimplemented function local metadata case!");
645 Assert(ActualF == F, "function-local metadata used in wrong function", L);
648 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
649 Metadata *MD = MDV.getMetadata();
650 if (auto *N = dyn_cast<MDNode>(MD)) {
655 // Only visit each node once. Metadata can be mutually recursive, so this
656 // avoids infinite recursion here, as well as being an optimization.
657 if (!MDNodes.insert(MD).second)
660 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
661 visitValueAsMetadata(*V, F);
664 /// \brief Check if a value can be a reference to a type.
665 static bool isTypeRef(const Metadata *MD) {
668 if (auto *S = dyn_cast<MDString>(MD))
669 return !S->getString().empty();
670 return isa<MDType>(MD);
673 /// \brief Check if a value can be a ScopeRef.
674 static bool isScopeRef(const Metadata *MD) {
677 if (auto *S = dyn_cast<MDString>(MD))
678 return !S->getString().empty();
679 return isa<MDScope>(MD);
682 void Verifier::visitMDLocation(const MDLocation &N) {
683 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
684 "location requires a valid scope", &N, N.getRawScope());
685 if (auto *IA = N.getRawInlinedAt())
686 Assert(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
689 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
690 Assert(N.getTag(), "invalid tag", &N);
693 void Verifier::visitMDScope(const MDScope &N) {
694 if (auto *F = N.getRawFile())
695 Assert(isa<MDFile>(F), "invalid file", &N, F);
698 void Verifier::visitMDSubrange(const MDSubrange &N) {
699 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
700 Assert(N.getCount() >= -1, "invalid subrange count", &N);
703 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
704 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
707 void Verifier::visitMDBasicType(const MDBasicType &N) {
708 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
709 N.getTag() == dwarf::DW_TAG_unspecified_type,
713 void Verifier::visitMDDerivedTypeBase(const MDDerivedTypeBase &N) {
714 // Common scope checks.
717 Assert(isScopeRef(N.getScope()), "invalid scope", &N, N.getScope());
718 Assert(isTypeRef(N.getBaseType()), "invalid base type", &N, N.getBaseType());
721 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
722 // Common derived type checks.
723 visitMDDerivedTypeBase(N);
725 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
726 N.getTag() == dwarf::DW_TAG_pointer_type ||
727 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
728 N.getTag() == dwarf::DW_TAG_reference_type ||
729 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
730 N.getTag() == dwarf::DW_TAG_const_type ||
731 N.getTag() == dwarf::DW_TAG_volatile_type ||
732 N.getTag() == dwarf::DW_TAG_restrict_type ||
733 N.getTag() == dwarf::DW_TAG_member ||
734 N.getTag() == dwarf::DW_TAG_inheritance ||
735 N.getTag() == dwarf::DW_TAG_friend,
739 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
740 // Common derived type checks.
741 visitMDDerivedTypeBase(N);
743 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
744 N.getTag() == dwarf::DW_TAG_structure_type ||
745 N.getTag() == dwarf::DW_TAG_union_type ||
746 N.getTag() == dwarf::DW_TAG_enumeration_type ||
747 N.getTag() == dwarf::DW_TAG_subroutine_type ||
748 N.getTag() == dwarf::DW_TAG_class_type,
751 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
752 "invalid composite elements", &N, N.getRawElements());
753 Assert(isTypeRef(N.getRawVTableHolder()), "invalid vtable holder", &N,
754 N.getRawVTableHolder());
755 Assert(!N.getRawElements() || isa<MDTuple>(N.getRawElements()),
756 "invalid composite elements", &N, N.getRawElements());
759 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
760 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
761 Assert(N.getRawElements() && isa<MDTuple>(N.getRawElements()),
762 "invalid composite elements", &N, N.getRawElements());
764 for (Metadata *Ty : N.getTypeArray()->operands()) {
765 Assert(isTypeRef(Ty), "invalid subroutine type ref", &N, N.getTypeArray(),
770 void Verifier::visitMDFile(const MDFile &N) {
771 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
774 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
775 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
777 if (auto *Array = N.getRawEnumTypes()) {
778 Assert(isa<MDTuple>(Array), "invalid enum list", &N, Array);
779 for (Metadata *Op : N.getEnumTypes()->operands()) {
780 auto *Enum = dyn_cast_or_null<MDCompositeType>(Op);
781 Assert(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
782 "invalid enum type", &N, N.getEnumTypes(), Op);
785 if (auto *Array = N.getRawRetainedTypes()) {
786 Assert(isa<MDTuple>(Array), "invalid retained type list", &N, Array);
787 for (Metadata *Op : N.getRetainedTypes()->operands()) {
788 Assert(Op && isa<MDType>(Op), "invalid retained type", &N, Op);
791 if (auto *Array = N.getRawSubprograms()) {
792 Assert(isa<MDTuple>(Array), "invalid subprogram list", &N, Array);
793 for (Metadata *Op : N.getSubprograms()->operands()) {
794 Assert(Op && isa<MDSubprogram>(Op), "invalid subprogram ref", &N, Op);
797 if (auto *Array = N.getRawGlobalVariables()) {
798 Assert(isa<MDTuple>(Array), "invalid global variable list", &N, Array);
799 for (Metadata *Op : N.getGlobalVariables()->operands()) {
800 Assert(Op && isa<MDGlobalVariable>(Op), "invalid global variable ref", &N,
804 if (auto *Array = N.getRawImportedEntities()) {
805 Assert(isa<MDTuple>(Array), "invalid imported entity list", &N, Array);
806 for (Metadata *Op : N.getImportedEntities()->operands()) {
807 Assert(Op && isa<MDImportedEntity>(Op), "invalid imported entity ref", &N,
813 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
814 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
817 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
818 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
821 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
822 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
825 void Verifier::visitMDNamespace(const MDNamespace &N) {
826 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
829 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
830 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
834 void Verifier::visitMDTemplateValueParameter(
835 const MDTemplateValueParameter &N) {
836 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
837 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
838 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
842 void Verifier::visitMDVariable(const MDVariable &N) {
843 if (auto *S = N.getRawScope())
844 Assert(isa<MDScope>(S), "invalid scope", &N, S);
845 Assert(isTypeRef(N.getRawType()), "invalid type ref", &N, N.getRawType());
846 if (auto *F = N.getRawFile())
847 Assert(isa<MDFile>(F), "invalid file", &N, F);
850 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
851 // Checks common to all variables.
854 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
855 if (auto *V = N.getRawVariable()) {
856 Assert(isa<ConstantAsMetadata>(V) &&
857 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()),
858 "invalid global varaible ref", &N, V);
860 if (auto *Member = N.getRawStaticDataMemberDeclaration()) {
861 Assert(isa<MDDerivedType>(Member), "invalid static data member declaration",
866 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
867 // Checks common to all variables.
870 Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
871 N.getTag() == dwarf::DW_TAG_arg_variable,
873 Assert(N.getRawScope() && isa<MDLocalScope>(N.getRawScope()),
874 "local variable requires a valid scope", &N, N.getRawScope());
875 if (auto *IA = N.getRawInlinedAt())
876 Assert(isa<MDLocation>(IA), "local variable requires a valid scope", &N,
880 void Verifier::visitMDExpression(const MDExpression &N) {
881 Assert(N.isValid(), "invalid expression", &N);
884 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
885 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
888 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
889 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
890 N.getTag() == dwarf::DW_TAG_imported_declaration,
894 void Verifier::visitComdat(const Comdat &C) {
895 // The Module is invalid if the GlobalValue has private linkage. Entities
896 // with private linkage don't have entries in the symbol table.
897 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
898 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
902 void Verifier::visitModuleIdents(const Module &M) {
903 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
907 // llvm.ident takes a list of metadata entry. Each entry has only one string.
908 // Scan each llvm.ident entry and make sure that this requirement is met.
909 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
910 const MDNode *N = Idents->getOperand(i);
911 Assert(N->getNumOperands() == 1,
912 "incorrect number of operands in llvm.ident metadata", N);
913 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
914 ("invalid value for llvm.ident metadata entry operand"
915 "(the operand should be a string)"),
920 void Verifier::visitModuleFlags(const Module &M) {
921 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
924 // Scan each flag, and track the flags and requirements.
925 DenseMap<const MDString*, const MDNode*> SeenIDs;
926 SmallVector<const MDNode*, 16> Requirements;
927 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
928 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
931 // Validate that the requirements in the module are valid.
932 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
933 const MDNode *Requirement = Requirements[I];
934 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
935 const Metadata *ReqValue = Requirement->getOperand(1);
937 const MDNode *Op = SeenIDs.lookup(Flag);
939 CheckFailed("invalid requirement on flag, flag is not present in module",
944 if (Op->getOperand(2) != ReqValue) {
945 CheckFailed(("invalid requirement on flag, "
946 "flag does not have the required value"),
954 Verifier::visitModuleFlag(const MDNode *Op,
955 DenseMap<const MDString *, const MDNode *> &SeenIDs,
956 SmallVectorImpl<const MDNode *> &Requirements) {
957 // Each module flag should have three arguments, the merge behavior (a
958 // constant int), the flag ID (an MDString), and the value.
959 Assert(Op->getNumOperands() == 3,
960 "incorrect number of operands in module flag", Op);
961 Module::ModFlagBehavior MFB;
962 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
964 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
965 "invalid behavior operand in module flag (expected constant integer)",
968 "invalid behavior operand in module flag (unexpected constant)",
971 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
972 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
975 // Sanity check the values for behaviors with additional requirements.
978 case Module::Warning:
979 case Module::Override:
980 // These behavior types accept any value.
983 case Module::Require: {
984 // The value should itself be an MDNode with two operands, a flag ID (an
985 // MDString), and a value.
986 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
987 Assert(Value && Value->getNumOperands() == 2,
988 "invalid value for 'require' module flag (expected metadata pair)",
990 Assert(isa<MDString>(Value->getOperand(0)),
991 ("invalid value for 'require' module flag "
992 "(first value operand should be a string)"),
993 Value->getOperand(0));
995 // Append it to the list of requirements, to check once all module flags are
997 Requirements.push_back(Value);
1001 case Module::Append:
1002 case Module::AppendUnique: {
1003 // These behavior types require the operand be an MDNode.
1004 Assert(isa<MDNode>(Op->getOperand(2)),
1005 "invalid value for 'append'-type module flag "
1006 "(expected a metadata node)",
1012 // Unless this is a "requires" flag, check the ID is unique.
1013 if (MFB != Module::Require) {
1014 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
1016 "module flag identifiers must be unique (or of 'require' type)", ID);
1020 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
1021 bool isFunction, const Value *V) {
1022 unsigned Slot = ~0U;
1023 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
1024 if (Attrs.getSlotIndex(I) == Idx) {
1029 assert(Slot != ~0U && "Attribute set inconsistency!");
1031 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
1033 if (I->isStringAttribute())
1036 if (I->getKindAsEnum() == Attribute::NoReturn ||
1037 I->getKindAsEnum() == Attribute::NoUnwind ||
1038 I->getKindAsEnum() == Attribute::NoInline ||
1039 I->getKindAsEnum() == Attribute::AlwaysInline ||
1040 I->getKindAsEnum() == Attribute::OptimizeForSize ||
1041 I->getKindAsEnum() == Attribute::StackProtect ||
1042 I->getKindAsEnum() == Attribute::StackProtectReq ||
1043 I->getKindAsEnum() == Attribute::StackProtectStrong ||
1044 I->getKindAsEnum() == Attribute::NoRedZone ||
1045 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
1046 I->getKindAsEnum() == Attribute::Naked ||
1047 I->getKindAsEnum() == Attribute::InlineHint ||
1048 I->getKindAsEnum() == Attribute::StackAlignment ||
1049 I->getKindAsEnum() == Attribute::UWTable ||
1050 I->getKindAsEnum() == Attribute::NonLazyBind ||
1051 I->getKindAsEnum() == Attribute::ReturnsTwice ||
1052 I->getKindAsEnum() == Attribute::SanitizeAddress ||
1053 I->getKindAsEnum() == Attribute::SanitizeThread ||
1054 I->getKindAsEnum() == Attribute::SanitizeMemory ||
1055 I->getKindAsEnum() == Attribute::MinSize ||
1056 I->getKindAsEnum() == Attribute::NoDuplicate ||
1057 I->getKindAsEnum() == Attribute::Builtin ||
1058 I->getKindAsEnum() == Attribute::NoBuiltin ||
1059 I->getKindAsEnum() == Attribute::Cold ||
1060 I->getKindAsEnum() == Attribute::OptimizeNone ||
1061 I->getKindAsEnum() == Attribute::JumpTable) {
1063 CheckFailed("Attribute '" + I->getAsString() +
1064 "' only applies to functions!", V);
1067 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
1068 I->getKindAsEnum() == Attribute::ReadNone) {
1070 CheckFailed("Attribute '" + I->getAsString() +
1071 "' does not apply to function returns");
1074 } else if (isFunction) {
1075 CheckFailed("Attribute '" + I->getAsString() +
1076 "' does not apply to functions!", V);
1082 // VerifyParameterAttrs - Check the given attributes for an argument or return
1083 // value of the specified type. The value V is printed in error messages.
1084 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
1085 bool isReturnValue, const Value *V) {
1086 if (!Attrs.hasAttributes(Idx))
1089 VerifyAttributeTypes(Attrs, Idx, false, V);
1092 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1093 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1094 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1095 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1096 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1097 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1098 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1099 "'returned' do not apply to return values!",
1102 // Check for mutually incompatible attributes. Only inreg is compatible with
1104 unsigned AttrCount = 0;
1105 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1106 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1107 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1108 Attrs.hasAttribute(Idx, Attribute::InReg);
1109 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1110 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1111 "and 'sret' are incompatible!",
1114 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1115 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1117 "'inalloca and readonly' are incompatible!",
1120 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1121 Attrs.hasAttribute(Idx, Attribute::Returned)),
1123 "'sret and returned' are incompatible!",
1126 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1127 Attrs.hasAttribute(Idx, Attribute::SExt)),
1129 "'zeroext and signext' are incompatible!",
1132 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1133 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1135 "'readnone and readonly' are incompatible!",
1138 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1139 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1141 "'noinline and alwaysinline' are incompatible!",
1144 Assert(!AttrBuilder(Attrs, Idx)
1145 .hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1146 "Wrong types for attribute: " +
1147 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx),
1150 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1151 SmallPtrSet<const Type*, 4> Visited;
1152 if (!PTy->getElementType()->isSized(&Visited)) {
1153 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1154 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1155 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1159 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1160 "Attribute 'byval' only applies to parameters with pointer type!",
1165 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1166 // The value V is printed in error messages.
1167 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1169 if (Attrs.isEmpty())
1172 bool SawNest = false;
1173 bool SawReturned = false;
1174 bool SawSRet = false;
1176 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1177 unsigned Idx = Attrs.getSlotIndex(i);
1181 Ty = FT->getReturnType();
1182 else if (Idx-1 < FT->getNumParams())
1183 Ty = FT->getParamType(Idx-1);
1185 break; // VarArgs attributes, verified elsewhere.
1187 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1192 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1193 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1197 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1198 Assert(!SawReturned, "More than one parameter has attribute returned!",
1200 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1202 "argument and return types for 'returned' attribute",
1207 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1208 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1209 Assert(Idx == 1 || Idx == 2,
1210 "Attribute 'sret' is not on first or second parameter!", V);
1214 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1215 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1220 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1223 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1226 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1227 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1228 "Attributes 'readnone and readonly' are incompatible!", V);
1231 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1232 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1233 Attribute::AlwaysInline)),
1234 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1236 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1237 Attribute::OptimizeNone)) {
1238 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1239 "Attribute 'optnone' requires 'noinline'!", V);
1241 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1242 Attribute::OptimizeForSize),
1243 "Attributes 'optsize and optnone' are incompatible!", V);
1245 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1246 "Attributes 'minsize and optnone' are incompatible!", V);
1249 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1250 Attribute::JumpTable)) {
1251 const GlobalValue *GV = cast<GlobalValue>(V);
1252 Assert(GV->hasUnnamedAddr(),
1253 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1257 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1258 if (CE->getOpcode() != Instruction::BitCast)
1261 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1263 "Invalid bitcast", CE);
1266 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1267 if (Attrs.getNumSlots() == 0)
1270 unsigned LastSlot = Attrs.getNumSlots() - 1;
1271 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1272 if (LastIndex <= Params
1273 || (LastIndex == AttributeSet::FunctionIndex
1274 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1280 /// \brief Verify that statepoint intrinsic is well formed.
1281 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1282 assert(CS.getCalledFunction() &&
1283 CS.getCalledFunction()->getIntrinsicID() ==
1284 Intrinsic::experimental_gc_statepoint);
1286 const Instruction &CI = *CS.getInstruction();
1288 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory(),
1289 "gc.statepoint must read and write memory to preserve "
1290 "reordering restrictions required by safepoint semantics",
1293 const Value *Target = CS.getArgument(0);
1294 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1295 Assert(PT && PT->getElementType()->isFunctionTy(),
1296 "gc.statepoint callee must be of function pointer type", &CI, Target);
1297 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1299 const Value *NumCallArgsV = CS.getArgument(1);
1300 Assert(isa<ConstantInt>(NumCallArgsV),
1301 "gc.statepoint number of arguments to underlying call "
1302 "must be constant integer",
1304 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1305 Assert(NumCallArgs >= 0,
1306 "gc.statepoint number of arguments to underlying call "
1309 const int NumParams = (int)TargetFuncType->getNumParams();
1310 if (TargetFuncType->isVarArg()) {
1311 Assert(NumCallArgs >= NumParams,
1312 "gc.statepoint mismatch in number of vararg call args", &CI);
1314 // TODO: Remove this limitation
1315 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1316 "gc.statepoint doesn't support wrapping non-void "
1317 "vararg functions yet",
1320 Assert(NumCallArgs == NumParams,
1321 "gc.statepoint mismatch in number of call args", &CI);
1323 const Value *Unused = CS.getArgument(2);
1324 Assert(isa<ConstantInt>(Unused) && cast<ConstantInt>(Unused)->isNullValue(),
1325 "gc.statepoint parameter #3 must be zero", &CI);
1327 // Verify that the types of the call parameter arguments match
1328 // the type of the wrapped callee.
1329 for (int i = 0; i < NumParams; i++) {
1330 Type *ParamType = TargetFuncType->getParamType(i);
1331 Type *ArgType = CS.getArgument(3+i)->getType();
1332 Assert(ArgType == ParamType,
1333 "gc.statepoint call argument does not match wrapped "
1337 const int EndCallArgsInx = 2+NumCallArgs;
1338 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1339 Assert(isa<ConstantInt>(NumDeoptArgsV),
1340 "gc.statepoint number of deoptimization arguments "
1341 "must be constant integer",
1343 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1344 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1348 Assert(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1349 "gc.statepoint too few arguments according to length fields", &CI);
1351 // Check that the only uses of this gc.statepoint are gc.result or
1352 // gc.relocate calls which are tied to this statepoint and thus part
1353 // of the same statepoint sequence
1354 for (const User *U : CI.users()) {
1355 const CallInst *Call = dyn_cast<const CallInst>(U);
1356 Assert(Call, "illegal use of statepoint token", &CI, U);
1357 if (!Call) continue;
1358 Assert(isGCRelocate(Call) || isGCResult(Call),
1359 "gc.result or gc.relocate are the only value uses"
1360 "of a gc.statepoint",
1362 if (isGCResult(Call)) {
1363 Assert(Call->getArgOperand(0) == &CI,
1364 "gc.result connected to wrong gc.statepoint", &CI, Call);
1365 } else if (isGCRelocate(Call)) {
1366 Assert(Call->getArgOperand(0) == &CI,
1367 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1371 // Note: It is legal for a single derived pointer to be listed multiple
1372 // times. It's non-optimal, but it is legal. It can also happen after
1373 // insertion if we strip a bitcast away.
1374 // Note: It is really tempting to check that each base is relocated and
1375 // that a derived pointer is never reused as a base pointer. This turns
1376 // out to be problematic since optimizations run after safepoint insertion
1377 // can recognize equality properties that the insertion logic doesn't know
1378 // about. See example statepoint.ll in the verifier subdirectory
1381 void Verifier::verifyFrameRecoverIndices() {
1382 for (auto &Counts : FrameEscapeInfo) {
1383 Function *F = Counts.first;
1384 unsigned EscapedObjectCount = Counts.second.first;
1385 unsigned MaxRecoveredIndex = Counts.second.second;
1386 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1387 "all indices passed to llvm.framerecover must be less than the "
1388 "number of arguments passed ot llvm.frameescape in the parent "
1394 // visitFunction - Verify that a function is ok.
1396 void Verifier::visitFunction(const Function &F) {
1397 // Check function arguments.
1398 FunctionType *FT = F.getFunctionType();
1399 unsigned NumArgs = F.arg_size();
1401 Assert(Context == &F.getContext(),
1402 "Function context does not match Module context!", &F);
1404 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1405 Assert(FT->getNumParams() == NumArgs,
1406 "# formal arguments must match # of arguments for function type!", &F,
1408 Assert(F.getReturnType()->isFirstClassType() ||
1409 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1410 "Functions cannot return aggregate values!", &F);
1412 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1413 "Invalid struct return type!", &F);
1415 AttributeSet Attrs = F.getAttributes();
1417 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1418 "Attribute after last parameter!", &F);
1420 // Check function attributes.
1421 VerifyFunctionAttrs(FT, Attrs, &F);
1423 // On function declarations/definitions, we do not support the builtin
1424 // attribute. We do not check this in VerifyFunctionAttrs since that is
1425 // checking for Attributes that can/can not ever be on functions.
1426 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1427 "Attribute 'builtin' can only be applied to a callsite.", &F);
1429 // Check that this function meets the restrictions on this calling convention.
1430 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1431 // restrictions can be lifted.
1432 switch (F.getCallingConv()) {
1434 case CallingConv::C:
1436 case CallingConv::Fast:
1437 case CallingConv::Cold:
1438 case CallingConv::Intel_OCL_BI:
1439 case CallingConv::PTX_Kernel:
1440 case CallingConv::PTX_Device:
1441 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1442 "perfect forwarding!",
1447 bool isLLVMdotName = F.getName().size() >= 5 &&
1448 F.getName().substr(0, 5) == "llvm.";
1450 // Check that the argument values match the function type for this function...
1452 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1454 Assert(I->getType() == FT->getParamType(i),
1455 "Argument value does not match function argument type!", I,
1456 FT->getParamType(i));
1457 Assert(I->getType()->isFirstClassType(),
1458 "Function arguments must have first-class types!", I);
1460 Assert(!I->getType()->isMetadataTy(),
1461 "Function takes metadata but isn't an intrinsic", I, &F);
1464 if (F.isMaterializable()) {
1465 // Function has a body somewhere we can't see.
1466 } else if (F.isDeclaration()) {
1467 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1468 "invalid linkage type for function declaration", &F);
1470 // Verify that this function (which has a body) is not named "llvm.*". It
1471 // is not legal to define intrinsics.
1472 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1474 // Check the entry node
1475 const BasicBlock *Entry = &F.getEntryBlock();
1476 Assert(pred_empty(Entry),
1477 "Entry block to function must not have predecessors!", Entry);
1479 // The address of the entry block cannot be taken, unless it is dead.
1480 if (Entry->hasAddressTaken()) {
1481 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1482 "blockaddress may not be used with the entry block!", Entry);
1486 // If this function is actually an intrinsic, verify that it is only used in
1487 // direct call/invokes, never having its "address taken".
1488 if (F.getIntrinsicID()) {
1490 if (F.hasAddressTaken(&U))
1491 Assert(0, "Invalid user of intrinsic instruction!", U);
1494 Assert(!F.hasDLLImportStorageClass() ||
1495 (F.isDeclaration() && F.hasExternalLinkage()) ||
1496 F.hasAvailableExternallyLinkage(),
1497 "Function is marked as dllimport, but not external.", &F);
1500 // verifyBasicBlock - Verify that a basic block is well formed...
1502 void Verifier::visitBasicBlock(BasicBlock &BB) {
1503 InstsInThisBlock.clear();
1505 // Ensure that basic blocks have terminators!
1506 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1508 // Check constraints that this basic block imposes on all of the PHI nodes in
1510 if (isa<PHINode>(BB.front())) {
1511 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1512 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1513 std::sort(Preds.begin(), Preds.end());
1515 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1516 // Ensure that PHI nodes have at least one entry!
1517 Assert(PN->getNumIncomingValues() != 0,
1518 "PHI nodes must have at least one entry. If the block is dead, "
1519 "the PHI should be removed!",
1521 Assert(PN->getNumIncomingValues() == Preds.size(),
1522 "PHINode should have one entry for each predecessor of its "
1523 "parent basic block!",
1526 // Get and sort all incoming values in the PHI node...
1528 Values.reserve(PN->getNumIncomingValues());
1529 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1530 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1531 PN->getIncomingValue(i)));
1532 std::sort(Values.begin(), Values.end());
1534 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1535 // Check to make sure that if there is more than one entry for a
1536 // particular basic block in this PHI node, that the incoming values are
1539 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1540 Values[i].second == Values[i - 1].second,
1541 "PHI node has multiple entries for the same basic block with "
1542 "different incoming values!",
1543 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1545 // Check to make sure that the predecessors and PHI node entries are
1547 Assert(Values[i].first == Preds[i],
1548 "PHI node entries do not match predecessors!", PN,
1549 Values[i].first, Preds[i]);
1554 // Check that all instructions have their parent pointers set up correctly.
1557 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1561 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1562 // Ensure that terminators only exist at the end of the basic block.
1563 Assert(&I == I.getParent()->getTerminator(),
1564 "Terminator found in the middle of a basic block!", I.getParent());
1565 visitInstruction(I);
1568 void Verifier::visitBranchInst(BranchInst &BI) {
1569 if (BI.isConditional()) {
1570 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1571 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1573 visitTerminatorInst(BI);
1576 void Verifier::visitReturnInst(ReturnInst &RI) {
1577 Function *F = RI.getParent()->getParent();
1578 unsigned N = RI.getNumOperands();
1579 if (F->getReturnType()->isVoidTy())
1581 "Found return instr that returns non-void in Function of void "
1583 &RI, F->getReturnType());
1585 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1586 "Function return type does not match operand "
1587 "type of return inst!",
1588 &RI, F->getReturnType());
1590 // Check to make sure that the return value has necessary properties for
1592 visitTerminatorInst(RI);
1595 void Verifier::visitSwitchInst(SwitchInst &SI) {
1596 // Check to make sure that all of the constants in the switch instruction
1597 // have the same type as the switched-on value.
1598 Type *SwitchTy = SI.getCondition()->getType();
1599 SmallPtrSet<ConstantInt*, 32> Constants;
1600 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1601 Assert(i.getCaseValue()->getType() == SwitchTy,
1602 "Switch constants must all be same type as switch value!", &SI);
1603 Assert(Constants.insert(i.getCaseValue()).second,
1604 "Duplicate integer as switch case", &SI, i.getCaseValue());
1607 visitTerminatorInst(SI);
1610 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1611 Assert(BI.getAddress()->getType()->isPointerTy(),
1612 "Indirectbr operand must have pointer type!", &BI);
1613 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1614 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1615 "Indirectbr destinations must all have pointer type!", &BI);
1617 visitTerminatorInst(BI);
1620 void Verifier::visitSelectInst(SelectInst &SI) {
1621 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1623 "Invalid operands for select instruction!", &SI);
1625 Assert(SI.getTrueValue()->getType() == SI.getType(),
1626 "Select values must have same type as select instruction!", &SI);
1627 visitInstruction(SI);
1630 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1631 /// a pass, if any exist, it's an error.
1633 void Verifier::visitUserOp1(Instruction &I) {
1634 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1637 void Verifier::visitTruncInst(TruncInst &I) {
1638 // Get the source and destination types
1639 Type *SrcTy = I.getOperand(0)->getType();
1640 Type *DestTy = I.getType();
1642 // Get the size of the types in bits, we'll need this later
1643 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1644 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1646 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1647 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1648 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1649 "trunc source and destination must both be a vector or neither", &I);
1650 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1652 visitInstruction(I);
1655 void Verifier::visitZExtInst(ZExtInst &I) {
1656 // Get the source and destination types
1657 Type *SrcTy = I.getOperand(0)->getType();
1658 Type *DestTy = I.getType();
1660 // Get the size of the types in bits, we'll need this later
1661 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1662 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1663 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1664 "zext source and destination must both be a vector or neither", &I);
1665 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1666 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1668 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1670 visitInstruction(I);
1673 void Verifier::visitSExtInst(SExtInst &I) {
1674 // Get the source and destination types
1675 Type *SrcTy = I.getOperand(0)->getType();
1676 Type *DestTy = I.getType();
1678 // Get the size of the types in bits, we'll need this later
1679 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1680 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1682 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1683 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1684 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1685 "sext source and destination must both be a vector or neither", &I);
1686 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1688 visitInstruction(I);
1691 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1692 // Get the source and destination types
1693 Type *SrcTy = I.getOperand(0)->getType();
1694 Type *DestTy = I.getType();
1695 // Get the size of the types in bits, we'll need this later
1696 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1697 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1699 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1700 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1701 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1702 "fptrunc source and destination must both be a vector or neither", &I);
1703 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1705 visitInstruction(I);
1708 void Verifier::visitFPExtInst(FPExtInst &I) {
1709 // Get the source and destination types
1710 Type *SrcTy = I.getOperand(0)->getType();
1711 Type *DestTy = I.getType();
1713 // Get the size of the types in bits, we'll need this later
1714 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1715 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1717 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
1718 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
1719 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1720 "fpext source and destination must both be a vector or neither", &I);
1721 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
1723 visitInstruction(I);
1726 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1727 // Get the source and destination types
1728 Type *SrcTy = I.getOperand(0)->getType();
1729 Type *DestTy = I.getType();
1731 bool SrcVec = SrcTy->isVectorTy();
1732 bool DstVec = DestTy->isVectorTy();
1734 Assert(SrcVec == DstVec,
1735 "UIToFP source and dest must both be vector or scalar", &I);
1736 Assert(SrcTy->isIntOrIntVectorTy(),
1737 "UIToFP source must be integer or integer vector", &I);
1738 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
1741 if (SrcVec && DstVec)
1742 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1743 cast<VectorType>(DestTy)->getNumElements(),
1744 "UIToFP source and dest vector length mismatch", &I);
1746 visitInstruction(I);
1749 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1750 // Get the source and destination types
1751 Type *SrcTy = I.getOperand(0)->getType();
1752 Type *DestTy = I.getType();
1754 bool SrcVec = SrcTy->isVectorTy();
1755 bool DstVec = DestTy->isVectorTy();
1757 Assert(SrcVec == DstVec,
1758 "SIToFP source and dest must both be vector or scalar", &I);
1759 Assert(SrcTy->isIntOrIntVectorTy(),
1760 "SIToFP source must be integer or integer vector", &I);
1761 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
1764 if (SrcVec && DstVec)
1765 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1766 cast<VectorType>(DestTy)->getNumElements(),
1767 "SIToFP source and dest vector length mismatch", &I);
1769 visitInstruction(I);
1772 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1773 // Get the source and destination types
1774 Type *SrcTy = I.getOperand(0)->getType();
1775 Type *DestTy = I.getType();
1777 bool SrcVec = SrcTy->isVectorTy();
1778 bool DstVec = DestTy->isVectorTy();
1780 Assert(SrcVec == DstVec,
1781 "FPToUI source and dest must both be vector or scalar", &I);
1782 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1784 Assert(DestTy->isIntOrIntVectorTy(),
1785 "FPToUI result must be integer or integer vector", &I);
1787 if (SrcVec && DstVec)
1788 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1789 cast<VectorType>(DestTy)->getNumElements(),
1790 "FPToUI source and dest vector length mismatch", &I);
1792 visitInstruction(I);
1795 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1796 // Get the source and destination types
1797 Type *SrcTy = I.getOperand(0)->getType();
1798 Type *DestTy = I.getType();
1800 bool SrcVec = SrcTy->isVectorTy();
1801 bool DstVec = DestTy->isVectorTy();
1803 Assert(SrcVec == DstVec,
1804 "FPToSI source and dest must both be vector or scalar", &I);
1805 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
1807 Assert(DestTy->isIntOrIntVectorTy(),
1808 "FPToSI result must be integer or integer vector", &I);
1810 if (SrcVec && DstVec)
1811 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1812 cast<VectorType>(DestTy)->getNumElements(),
1813 "FPToSI source and dest vector length mismatch", &I);
1815 visitInstruction(I);
1818 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1819 // Get the source and destination types
1820 Type *SrcTy = I.getOperand(0)->getType();
1821 Type *DestTy = I.getType();
1823 Assert(SrcTy->getScalarType()->isPointerTy(),
1824 "PtrToInt source must be pointer", &I);
1825 Assert(DestTy->getScalarType()->isIntegerTy(),
1826 "PtrToInt result must be integral", &I);
1827 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
1830 if (SrcTy->isVectorTy()) {
1831 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1832 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1833 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1834 "PtrToInt Vector width mismatch", &I);
1837 visitInstruction(I);
1840 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1841 // Get the source and destination types
1842 Type *SrcTy = I.getOperand(0)->getType();
1843 Type *DestTy = I.getType();
1845 Assert(SrcTy->getScalarType()->isIntegerTy(),
1846 "IntToPtr source must be an integral", &I);
1847 Assert(DestTy->getScalarType()->isPointerTy(),
1848 "IntToPtr result must be a pointer", &I);
1849 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
1851 if (SrcTy->isVectorTy()) {
1852 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1853 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1854 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1855 "IntToPtr Vector width mismatch", &I);
1857 visitInstruction(I);
1860 void Verifier::visitBitCastInst(BitCastInst &I) {
1862 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
1863 "Invalid bitcast", &I);
1864 visitInstruction(I);
1867 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1868 Type *SrcTy = I.getOperand(0)->getType();
1869 Type *DestTy = I.getType();
1871 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
1873 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
1875 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1876 "AddrSpaceCast must be between different address spaces", &I);
1877 if (SrcTy->isVectorTy())
1878 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1879 "AddrSpaceCast vector pointer number of elements mismatch", &I);
1880 visitInstruction(I);
1883 /// visitPHINode - Ensure that a PHI node is well formed.
1885 void Verifier::visitPHINode(PHINode &PN) {
1886 // Ensure that the PHI nodes are all grouped together at the top of the block.
1887 // This can be tested by checking whether the instruction before this is
1888 // either nonexistent (because this is begin()) or is a PHI node. If not,
1889 // then there is some other instruction before a PHI.
1890 Assert(&PN == &PN.getParent()->front() ||
1891 isa<PHINode>(--BasicBlock::iterator(&PN)),
1892 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
1894 // Check that all of the values of the PHI node have the same type as the
1895 // result, and that the incoming blocks are really basic blocks.
1896 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1897 Assert(PN.getType() == PN.getIncomingValue(i)->getType(),
1898 "PHI node operands are not the same type as the result!", &PN);
1901 // All other PHI node constraints are checked in the visitBasicBlock method.
1903 visitInstruction(PN);
1906 void Verifier::VerifyCallSite(CallSite CS) {
1907 Instruction *I = CS.getInstruction();
1909 Assert(CS.getCalledValue()->getType()->isPointerTy(),
1910 "Called function must be a pointer!", I);
1911 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1913 Assert(FPTy->getElementType()->isFunctionTy(),
1914 "Called function is not pointer to function type!", I);
1915 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1917 // Verify that the correct number of arguments are being passed
1918 if (FTy->isVarArg())
1919 Assert(CS.arg_size() >= FTy->getNumParams(),
1920 "Called function requires more parameters than were provided!", I);
1922 Assert(CS.arg_size() == FTy->getNumParams(),
1923 "Incorrect number of arguments passed to called function!", I);
1925 // Verify that all arguments to the call match the function type.
1926 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1927 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
1928 "Call parameter type does not match function signature!",
1929 CS.getArgument(i), FTy->getParamType(i), I);
1931 AttributeSet Attrs = CS.getAttributes();
1933 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
1934 "Attribute after last parameter!", I);
1936 // Verify call attributes.
1937 VerifyFunctionAttrs(FTy, Attrs, I);
1939 // Conservatively check the inalloca argument.
1940 // We have a bug if we can find that there is an underlying alloca without
1942 if (CS.hasInAllocaArgument()) {
1943 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
1944 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
1945 Assert(AI->isUsedWithInAlloca(),
1946 "inalloca argument for call has mismatched alloca", AI, I);
1949 if (FTy->isVarArg()) {
1950 // FIXME? is 'nest' even legal here?
1951 bool SawNest = false;
1952 bool SawReturned = false;
1954 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1955 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1957 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1961 // Check attributes on the varargs part.
1962 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1963 Type *Ty = CS.getArgument(Idx-1)->getType();
1964 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1966 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1967 Assert(!SawNest, "More than one parameter has attribute nest!", I);
1971 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1972 Assert(!SawReturned, "More than one parameter has attribute returned!",
1974 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1975 "Incompatible argument and return types for 'returned' "
1981 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1982 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1984 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1985 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
1989 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1990 if (CS.getCalledFunction() == nullptr ||
1991 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1992 for (FunctionType::param_iterator PI = FTy->param_begin(),
1993 PE = FTy->param_end(); PI != PE; ++PI)
1994 Assert(!(*PI)->isMetadataTy(),
1995 "Function has metadata parameter but isn't an intrinsic", I);
1998 visitInstruction(*I);
2001 /// Two types are "congruent" if they are identical, or if they are both pointer
2002 /// types with different pointee types and the same address space.
2003 static bool isTypeCongruent(Type *L, Type *R) {
2006 PointerType *PL = dyn_cast<PointerType>(L);
2007 PointerType *PR = dyn_cast<PointerType>(R);
2010 return PL->getAddressSpace() == PR->getAddressSpace();
2013 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
2014 static const Attribute::AttrKind ABIAttrs[] = {
2015 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
2016 Attribute::InReg, Attribute::Returned};
2018 for (auto AK : ABIAttrs) {
2019 if (Attrs.hasAttribute(I + 1, AK))
2020 Copy.addAttribute(AK);
2022 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
2023 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
2027 void Verifier::verifyMustTailCall(CallInst &CI) {
2028 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
2030 // - The caller and callee prototypes must match. Pointer types of
2031 // parameters or return types may differ in pointee type, but not
2033 Function *F = CI.getParent()->getParent();
2034 auto GetFnTy = [](Value *V) {
2035 return cast<FunctionType>(
2036 cast<PointerType>(V->getType())->getElementType());
2038 FunctionType *CallerTy = GetFnTy(F);
2039 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
2040 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
2041 "cannot guarantee tail call due to mismatched parameter counts", &CI);
2042 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
2043 "cannot guarantee tail call due to mismatched varargs", &CI);
2044 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
2045 "cannot guarantee tail call due to mismatched return types", &CI);
2046 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2048 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
2049 "cannot guarantee tail call due to mismatched parameter types", &CI);
2052 // - The calling conventions of the caller and callee must match.
2053 Assert(F->getCallingConv() == CI.getCallingConv(),
2054 "cannot guarantee tail call due to mismatched calling conv", &CI);
2056 // - All ABI-impacting function attributes, such as sret, byval, inreg,
2057 // returned, and inalloca, must match.
2058 AttributeSet CallerAttrs = F->getAttributes();
2059 AttributeSet CalleeAttrs = CI.getAttributes();
2060 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
2061 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
2062 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
2063 Assert(CallerABIAttrs == CalleeABIAttrs,
2064 "cannot guarantee tail call due to mismatched ABI impacting "
2065 "function attributes",
2066 &CI, CI.getOperand(I));
2069 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
2070 // or a pointer bitcast followed by a ret instruction.
2071 // - The ret instruction must return the (possibly bitcasted) value
2072 // produced by the call or void.
2073 Value *RetVal = &CI;
2074 Instruction *Next = CI.getNextNode();
2076 // Handle the optional bitcast.
2077 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
2078 Assert(BI->getOperand(0) == RetVal,
2079 "bitcast following musttail call must use the call", BI);
2081 Next = BI->getNextNode();
2084 // Check the return.
2085 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
2086 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
2088 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
2089 "musttail call result must be returned", Ret);
2092 void Verifier::visitCallInst(CallInst &CI) {
2093 VerifyCallSite(&CI);
2095 if (CI.isMustTailCall())
2096 verifyMustTailCall(CI);
2098 if (Function *F = CI.getCalledFunction())
2099 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
2100 visitIntrinsicFunctionCall(ID, CI);
2103 void Verifier::visitInvokeInst(InvokeInst &II) {
2104 VerifyCallSite(&II);
2106 // Verify that there is a landingpad instruction as the first non-PHI
2107 // instruction of the 'unwind' destination.
2108 Assert(II.getUnwindDest()->isLandingPad(),
2109 "The unwind destination does not have a landingpad instruction!", &II);
2111 if (Function *F = II.getCalledFunction())
2112 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
2113 // CallInst as an input parameter. It not woth updating this whole
2114 // function only to support statepoint verification.
2115 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
2116 VerifyStatepoint(ImmutableCallSite(&II));
2118 visitTerminatorInst(II);
2121 /// visitBinaryOperator - Check that both arguments to the binary operator are
2122 /// of the same type!
2124 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2125 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2126 "Both operands to a binary operator are not of the same type!", &B);
2128 switch (B.getOpcode()) {
2129 // Check that integer arithmetic operators are only used with
2130 // integral operands.
2131 case Instruction::Add:
2132 case Instruction::Sub:
2133 case Instruction::Mul:
2134 case Instruction::SDiv:
2135 case Instruction::UDiv:
2136 case Instruction::SRem:
2137 case Instruction::URem:
2138 Assert(B.getType()->isIntOrIntVectorTy(),
2139 "Integer arithmetic operators only work with integral types!", &B);
2140 Assert(B.getType() == B.getOperand(0)->getType(),
2141 "Integer arithmetic operators must have same type "
2142 "for operands and result!",
2145 // Check that floating-point arithmetic operators are only used with
2146 // floating-point operands.
2147 case Instruction::FAdd:
2148 case Instruction::FSub:
2149 case Instruction::FMul:
2150 case Instruction::FDiv:
2151 case Instruction::FRem:
2152 Assert(B.getType()->isFPOrFPVectorTy(),
2153 "Floating-point arithmetic operators only work with "
2154 "floating-point types!",
2156 Assert(B.getType() == B.getOperand(0)->getType(),
2157 "Floating-point arithmetic operators must have same type "
2158 "for operands and result!",
2161 // Check that logical operators are only used with integral operands.
2162 case Instruction::And:
2163 case Instruction::Or:
2164 case Instruction::Xor:
2165 Assert(B.getType()->isIntOrIntVectorTy(),
2166 "Logical operators only work with integral types!", &B);
2167 Assert(B.getType() == B.getOperand(0)->getType(),
2168 "Logical operators must have same type for operands and result!",
2171 case Instruction::Shl:
2172 case Instruction::LShr:
2173 case Instruction::AShr:
2174 Assert(B.getType()->isIntOrIntVectorTy(),
2175 "Shifts only work with integral types!", &B);
2176 Assert(B.getType() == B.getOperand(0)->getType(),
2177 "Shift return type must be same as operands!", &B);
2180 llvm_unreachable("Unknown BinaryOperator opcode!");
2183 visitInstruction(B);
2186 void Verifier::visitICmpInst(ICmpInst &IC) {
2187 // Check that the operands are the same type
2188 Type *Op0Ty = IC.getOperand(0)->getType();
2189 Type *Op1Ty = IC.getOperand(1)->getType();
2190 Assert(Op0Ty == Op1Ty,
2191 "Both operands to ICmp instruction are not of the same type!", &IC);
2192 // Check that the operands are the right type
2193 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2194 "Invalid operand types for ICmp instruction", &IC);
2195 // Check that the predicate is valid.
2196 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2197 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2198 "Invalid predicate in ICmp instruction!", &IC);
2200 visitInstruction(IC);
2203 void Verifier::visitFCmpInst(FCmpInst &FC) {
2204 // Check that the operands are the same type
2205 Type *Op0Ty = FC.getOperand(0)->getType();
2206 Type *Op1Ty = FC.getOperand(1)->getType();
2207 Assert(Op0Ty == Op1Ty,
2208 "Both operands to FCmp instruction are not of the same type!", &FC);
2209 // Check that the operands are the right type
2210 Assert(Op0Ty->isFPOrFPVectorTy(),
2211 "Invalid operand types for FCmp instruction", &FC);
2212 // Check that the predicate is valid.
2213 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2214 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2215 "Invalid predicate in FCmp instruction!", &FC);
2217 visitInstruction(FC);
2220 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2222 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2223 "Invalid extractelement operands!", &EI);
2224 visitInstruction(EI);
2227 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2228 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2230 "Invalid insertelement operands!", &IE);
2231 visitInstruction(IE);
2234 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2235 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2237 "Invalid shufflevector operands!", &SV);
2238 visitInstruction(SV);
2241 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2242 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2244 Assert(isa<PointerType>(TargetTy),
2245 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2246 Assert(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2247 "GEP into unsized type!", &GEP);
2248 Assert(GEP.getPointerOperandType()->isVectorTy() ==
2249 GEP.getType()->isVectorTy(),
2250 "Vector GEP must return a vector value", &GEP);
2252 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2254 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
2255 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2257 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2258 cast<PointerType>(GEP.getType()->getScalarType())
2259 ->getElementType() == ElTy,
2260 "GEP is not of right type for indices!", &GEP, ElTy);
2262 if (GEP.getPointerOperandType()->isVectorTy()) {
2263 // Additional checks for vector GEPs.
2264 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2265 Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2266 "Vector GEP result width doesn't match operand's", &GEP);
2267 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2268 Type *IndexTy = Idxs[i]->getType();
2269 Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2271 unsigned IndexWidth = IndexTy->getVectorNumElements();
2272 Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2275 visitInstruction(GEP);
2278 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2279 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2282 void Verifier::visitRangeMetadata(Instruction& I,
2283 MDNode* Range, Type* Ty) {
2285 Range == I.getMetadata(LLVMContext::MD_range) &&
2286 "precondition violation");
2288 unsigned NumOperands = Range->getNumOperands();
2289 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2290 unsigned NumRanges = NumOperands / 2;
2291 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2293 ConstantRange LastRange(1); // Dummy initial value
2294 for (unsigned i = 0; i < NumRanges; ++i) {
2296 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2297 Assert(Low, "The lower limit must be an integer!", Low);
2299 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2300 Assert(High, "The upper limit must be an integer!", High);
2301 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2302 "Range types must match instruction type!", &I);
2304 APInt HighV = High->getValue();
2305 APInt LowV = Low->getValue();
2306 ConstantRange CurRange(LowV, HighV);
2307 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2308 "Range must not be empty!", Range);
2310 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2311 "Intervals are overlapping", Range);
2312 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2314 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2317 LastRange = ConstantRange(LowV, HighV);
2319 if (NumRanges > 2) {
2321 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2323 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2324 ConstantRange FirstRange(FirstLow, FirstHigh);
2325 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2326 "Intervals are overlapping", Range);
2327 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2332 void Verifier::visitLoadInst(LoadInst &LI) {
2333 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2334 Assert(PTy, "Load operand must be a pointer.", &LI);
2335 Type *ElTy = PTy->getElementType();
2336 Assert(ElTy == LI.getType(),
2337 "Load result type does not match pointer operand type!", &LI, ElTy);
2338 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2339 "huge alignment values are unsupported", &LI);
2340 if (LI.isAtomic()) {
2341 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2342 "Load cannot have Release ordering", &LI);
2343 Assert(LI.getAlignment() != 0,
2344 "Atomic load must specify explicit alignment", &LI);
2345 if (!ElTy->isPointerTy()) {
2346 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2348 unsigned Size = ElTy->getPrimitiveSizeInBits();
2349 Assert(Size >= 8 && !(Size & (Size - 1)),
2350 "atomic load operand must be power-of-two byte-sized integer", &LI,
2354 Assert(LI.getSynchScope() == CrossThread,
2355 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2358 visitInstruction(LI);
2361 void Verifier::visitStoreInst(StoreInst &SI) {
2362 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2363 Assert(PTy, "Store operand must be a pointer.", &SI);
2364 Type *ElTy = PTy->getElementType();
2365 Assert(ElTy == SI.getOperand(0)->getType(),
2366 "Stored value type does not match pointer operand type!", &SI, ElTy);
2367 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2368 "huge alignment values are unsupported", &SI);
2369 if (SI.isAtomic()) {
2370 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2371 "Store cannot have Acquire ordering", &SI);
2372 Assert(SI.getAlignment() != 0,
2373 "Atomic store must specify explicit alignment", &SI);
2374 if (!ElTy->isPointerTy()) {
2375 Assert(ElTy->isIntegerTy(),
2376 "atomic store operand must have integer type!", &SI, ElTy);
2377 unsigned Size = ElTy->getPrimitiveSizeInBits();
2378 Assert(Size >= 8 && !(Size & (Size - 1)),
2379 "atomic store operand must be power-of-two byte-sized integer",
2383 Assert(SI.getSynchScope() == CrossThread,
2384 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2386 visitInstruction(SI);
2389 void Verifier::visitAllocaInst(AllocaInst &AI) {
2390 SmallPtrSet<const Type*, 4> Visited;
2391 PointerType *PTy = AI.getType();
2392 Assert(PTy->getAddressSpace() == 0,
2393 "Allocation instruction pointer not in the generic address space!",
2395 Assert(PTy->getElementType()->isSized(&Visited),
2396 "Cannot allocate unsized type", &AI);
2397 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2398 "Alloca array size must have integer type", &AI);
2399 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2400 "huge alignment values are unsupported", &AI);
2402 visitInstruction(AI);
2405 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2407 // FIXME: more conditions???
2408 Assert(CXI.getSuccessOrdering() != NotAtomic,
2409 "cmpxchg instructions must be atomic.", &CXI);
2410 Assert(CXI.getFailureOrdering() != NotAtomic,
2411 "cmpxchg instructions must be atomic.", &CXI);
2412 Assert(CXI.getSuccessOrdering() != Unordered,
2413 "cmpxchg instructions cannot be unordered.", &CXI);
2414 Assert(CXI.getFailureOrdering() != Unordered,
2415 "cmpxchg instructions cannot be unordered.", &CXI);
2416 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2417 "cmpxchg instructions be at least as constrained on success as fail",
2419 Assert(CXI.getFailureOrdering() != Release &&
2420 CXI.getFailureOrdering() != AcquireRelease,
2421 "cmpxchg failure ordering cannot include release semantics", &CXI);
2423 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2424 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2425 Type *ElTy = PTy->getElementType();
2426 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2428 unsigned Size = ElTy->getPrimitiveSizeInBits();
2429 Assert(Size >= 8 && !(Size & (Size - 1)),
2430 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2431 Assert(ElTy == CXI.getOperand(1)->getType(),
2432 "Expected value type does not match pointer operand type!", &CXI,
2434 Assert(ElTy == CXI.getOperand(2)->getType(),
2435 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2436 visitInstruction(CXI);
2439 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2440 Assert(RMWI.getOrdering() != NotAtomic,
2441 "atomicrmw instructions must be atomic.", &RMWI);
2442 Assert(RMWI.getOrdering() != Unordered,
2443 "atomicrmw instructions cannot be unordered.", &RMWI);
2444 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2445 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2446 Type *ElTy = PTy->getElementType();
2447 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2449 unsigned Size = ElTy->getPrimitiveSizeInBits();
2450 Assert(Size >= 8 && !(Size & (Size - 1)),
2451 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2453 Assert(ElTy == RMWI.getOperand(1)->getType(),
2454 "Argument value type does not match pointer operand type!", &RMWI,
2456 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2457 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2458 "Invalid binary operation!", &RMWI);
2459 visitInstruction(RMWI);
2462 void Verifier::visitFenceInst(FenceInst &FI) {
2463 const AtomicOrdering Ordering = FI.getOrdering();
2464 Assert(Ordering == Acquire || Ordering == Release ||
2465 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2466 "fence instructions may only have "
2467 "acquire, release, acq_rel, or seq_cst ordering.",
2469 visitInstruction(FI);
2472 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2473 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2474 EVI.getIndices()) == EVI.getType(),
2475 "Invalid ExtractValueInst operands!", &EVI);
2477 visitInstruction(EVI);
2480 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2481 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2482 IVI.getIndices()) ==
2483 IVI.getOperand(1)->getType(),
2484 "Invalid InsertValueInst operands!", &IVI);
2486 visitInstruction(IVI);
2489 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2490 BasicBlock *BB = LPI.getParent();
2492 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2494 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2495 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2497 // The landingpad instruction defines its parent as a landing pad block. The
2498 // landing pad block may be branched to only by the unwind edge of an invoke.
2499 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2500 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2501 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2502 "Block containing LandingPadInst must be jumped to "
2503 "only by the unwind edge of an invoke.",
2507 // The landingpad instruction must be the first non-PHI instruction in the
2509 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2510 "LandingPadInst not the first non-PHI instruction in the block.",
2513 // The personality functions for all landingpad instructions within the same
2514 // function should match.
2516 Assert(LPI.getPersonalityFn() == PersonalityFn,
2517 "Personality function doesn't match others in function", &LPI);
2518 PersonalityFn = LPI.getPersonalityFn();
2520 // All operands must be constants.
2521 Assert(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2523 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2524 Constant *Clause = LPI.getClause(i);
2525 if (LPI.isCatch(i)) {
2526 Assert(isa<PointerType>(Clause->getType()),
2527 "Catch operand does not have pointer type!", &LPI);
2529 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2530 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2531 "Filter operand is not an array of constants!", &LPI);
2535 visitInstruction(LPI);
2538 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2539 Instruction *Op = cast<Instruction>(I.getOperand(i));
2540 // If the we have an invalid invoke, don't try to compute the dominance.
2541 // We already reject it in the invoke specific checks and the dominance
2542 // computation doesn't handle multiple edges.
2543 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2544 if (II->getNormalDest() == II->getUnwindDest())
2548 const Use &U = I.getOperandUse(i);
2549 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2550 "Instruction does not dominate all uses!", Op, &I);
2553 /// verifyInstruction - Verify that an instruction is well formed.
2555 void Verifier::visitInstruction(Instruction &I) {
2556 BasicBlock *BB = I.getParent();
2557 Assert(BB, "Instruction not embedded in basic block!", &I);
2559 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2560 for (User *U : I.users()) {
2561 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2562 "Only PHI nodes may reference their own value!", &I);
2566 // Check that void typed values don't have names
2567 Assert(!I.getType()->isVoidTy() || !I.hasName(),
2568 "Instruction has a name, but provides a void value!", &I);
2570 // Check that the return value of the instruction is either void or a legal
2572 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2573 "Instruction returns a non-scalar type!", &I);
2575 // Check that the instruction doesn't produce metadata. Calls are already
2576 // checked against the callee type.
2577 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2578 "Invalid use of metadata!", &I);
2580 // Check that all uses of the instruction, if they are instructions
2581 // themselves, actually have parent basic blocks. If the use is not an
2582 // instruction, it is an error!
2583 for (Use &U : I.uses()) {
2584 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2585 Assert(Used->getParent() != nullptr,
2586 "Instruction referencing"
2587 " instruction not embedded in a basic block!",
2590 CheckFailed("Use of instruction is not an instruction!", U);
2595 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2596 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2598 // Check to make sure that only first-class-values are operands to
2600 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2601 Assert(0, "Instruction operands must be first-class values!", &I);
2604 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2605 // Check to make sure that the "address of" an intrinsic function is never
2608 !F->isIntrinsic() ||
2609 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2610 "Cannot take the address of an intrinsic!", &I);
2612 !F->isIntrinsic() || isa<CallInst>(I) ||
2613 F->getIntrinsicID() == Intrinsic::donothing ||
2614 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2615 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2616 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2617 "Cannot invoke an intrinsinc other than"
2618 " donothing or patchpoint",
2620 Assert(F->getParent() == M, "Referencing function in another module!",
2622 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2623 Assert(OpBB->getParent() == BB->getParent(),
2624 "Referring to a basic block in another function!", &I);
2625 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2626 Assert(OpArg->getParent() == BB->getParent(),
2627 "Referring to an argument in another function!", &I);
2628 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2629 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2630 } else if (isa<Instruction>(I.getOperand(i))) {
2631 verifyDominatesUse(I, i);
2632 } else if (isa<InlineAsm>(I.getOperand(i))) {
2633 Assert((i + 1 == e && isa<CallInst>(I)) ||
2634 (i + 3 == e && isa<InvokeInst>(I)),
2635 "Cannot take the address of an inline asm!", &I);
2636 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2637 if (CE->getType()->isPtrOrPtrVectorTy()) {
2638 // If we have a ConstantExpr pointer, we need to see if it came from an
2639 // illegal bitcast (inttoptr <constant int> )
2640 SmallVector<const ConstantExpr *, 4> Stack;
2641 SmallPtrSet<const ConstantExpr *, 4> Visited;
2642 Stack.push_back(CE);
2644 while (!Stack.empty()) {
2645 const ConstantExpr *V = Stack.pop_back_val();
2646 if (!Visited.insert(V).second)
2649 VerifyConstantExprBitcastType(V);
2651 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2652 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2653 Stack.push_back(Op);
2660 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2661 Assert(I.getType()->isFPOrFPVectorTy(),
2662 "fpmath requires a floating point result!", &I);
2663 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2664 if (ConstantFP *CFP0 =
2665 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2666 APFloat Accuracy = CFP0->getValueAPF();
2667 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2668 "fpmath accuracy not a positive number!", &I);
2670 Assert(false, "invalid fpmath accuracy!", &I);
2674 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2675 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2676 "Ranges are only for loads, calls and invokes!", &I);
2677 visitRangeMetadata(I, Range, I.getType());
2680 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2681 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2683 Assert(isa<LoadInst>(I),
2684 "nonnull applies only to load instructions, use attributes"
2685 " for calls or invokes",
2689 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
2690 Assert(isa<MDLocation>(N), "invalid !dbg metadata attachment", &I, N);
2694 InstsInThisBlock.insert(&I);
2697 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2698 /// intrinsic argument or return value) matches the type constraints specified
2699 /// by the .td file (e.g. an "any integer" argument really is an integer).
2701 /// This return true on error but does not print a message.
2702 bool Verifier::VerifyIntrinsicType(Type *Ty,
2703 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2704 SmallVectorImpl<Type*> &ArgTys) {
2705 using namespace Intrinsic;
2707 // If we ran out of descriptors, there are too many arguments.
2708 if (Infos.empty()) return true;
2709 IITDescriptor D = Infos.front();
2710 Infos = Infos.slice(1);
2713 case IITDescriptor::Void: return !Ty->isVoidTy();
2714 case IITDescriptor::VarArg: return true;
2715 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2716 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2717 case IITDescriptor::Half: return !Ty->isHalfTy();
2718 case IITDescriptor::Float: return !Ty->isFloatTy();
2719 case IITDescriptor::Double: return !Ty->isDoubleTy();
2720 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2721 case IITDescriptor::Vector: {
2722 VectorType *VT = dyn_cast<VectorType>(Ty);
2723 return !VT || VT->getNumElements() != D.Vector_Width ||
2724 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2726 case IITDescriptor::Pointer: {
2727 PointerType *PT = dyn_cast<PointerType>(Ty);
2728 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2729 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2732 case IITDescriptor::Struct: {
2733 StructType *ST = dyn_cast<StructType>(Ty);
2734 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2737 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2738 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2743 case IITDescriptor::Argument:
2744 // Two cases here - If this is the second occurrence of an argument, verify
2745 // that the later instance matches the previous instance.
2746 if (D.getArgumentNumber() < ArgTys.size())
2747 return Ty != ArgTys[D.getArgumentNumber()];
2749 // Otherwise, if this is the first instance of an argument, record it and
2750 // verify the "Any" kind.
2751 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2752 ArgTys.push_back(Ty);
2754 switch (D.getArgumentKind()) {
2755 case IITDescriptor::AK_Any: return false; // Success
2756 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2757 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2758 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2759 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2761 llvm_unreachable("all argument kinds not covered");
2763 case IITDescriptor::ExtendArgument: {
2764 // This may only be used when referring to a previous vector argument.
2765 if (D.getArgumentNumber() >= ArgTys.size())
2768 Type *NewTy = ArgTys[D.getArgumentNumber()];
2769 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2770 NewTy = VectorType::getExtendedElementVectorType(VTy);
2771 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2772 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2778 case IITDescriptor::TruncArgument: {
2779 // This may only be used when referring to a previous vector argument.
2780 if (D.getArgumentNumber() >= ArgTys.size())
2783 Type *NewTy = ArgTys[D.getArgumentNumber()];
2784 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2785 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2786 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2787 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2793 case IITDescriptor::HalfVecArgument:
2794 // This may only be used when referring to a previous vector argument.
2795 return D.getArgumentNumber() >= ArgTys.size() ||
2796 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2797 VectorType::getHalfElementsVectorType(
2798 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2799 case IITDescriptor::SameVecWidthArgument: {
2800 if (D.getArgumentNumber() >= ArgTys.size())
2802 VectorType * ReferenceType =
2803 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
2804 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
2805 if (!ThisArgType || !ReferenceType ||
2806 (ReferenceType->getVectorNumElements() !=
2807 ThisArgType->getVectorNumElements()))
2809 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
2812 case IITDescriptor::PtrToArgument: {
2813 if (D.getArgumentNumber() >= ArgTys.size())
2815 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
2816 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
2817 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
2819 case IITDescriptor::VecOfPtrsToElt: {
2820 if (D.getArgumentNumber() >= ArgTys.size())
2822 VectorType * ReferenceType =
2823 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
2824 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
2825 if (!ThisArgVecTy || !ReferenceType ||
2826 (ReferenceType->getVectorNumElements() !=
2827 ThisArgVecTy->getVectorNumElements()))
2829 PointerType *ThisArgEltTy =
2830 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
2833 return (!(ThisArgEltTy->getElementType() ==
2834 ReferenceType->getVectorElementType()));
2837 llvm_unreachable("unhandled");
2840 /// \brief Verify if the intrinsic has variable arguments.
2841 /// This method is intended to be called after all the fixed arguments have been
2844 /// This method returns true on error and does not print an error message.
2846 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2847 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2848 using namespace Intrinsic;
2850 // If there are no descriptors left, then it can't be a vararg.
2854 // There should be only one descriptor remaining at this point.
2855 if (Infos.size() != 1)
2858 // Check and verify the descriptor.
2859 IITDescriptor D = Infos.front();
2860 Infos = Infos.slice(1);
2861 if (D.Kind == IITDescriptor::VarArg)
2867 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2869 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2870 Function *IF = CI.getCalledFunction();
2871 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2874 // Verify that the intrinsic prototype lines up with what the .td files
2876 FunctionType *IFTy = IF->getFunctionType();
2877 bool IsVarArg = IFTy->isVarArg();
2879 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2880 getIntrinsicInfoTableEntries(ID, Table);
2881 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2883 SmallVector<Type *, 4> ArgTys;
2884 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2885 "Intrinsic has incorrect return type!", IF);
2886 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2887 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2888 "Intrinsic has incorrect argument type!", IF);
2890 // Verify if the intrinsic call matches the vararg property.
2892 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2893 "Intrinsic was not defined with variable arguments!", IF);
2895 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2896 "Callsite was not defined with variable arguments!", IF);
2898 // All descriptors should be absorbed by now.
2899 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2901 // Now that we have the intrinsic ID and the actual argument types (and we
2902 // know they are legal for the intrinsic!) get the intrinsic name through the
2903 // usual means. This allows us to verify the mangling of argument types into
2905 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2906 Assert(ExpectedName == IF->getName(),
2907 "Intrinsic name not mangled correctly for type arguments! "
2912 // If the intrinsic takes MDNode arguments, verify that they are either global
2913 // or are local to *this* function.
2914 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2915 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
2916 visitMetadataAsValue(*MD, CI.getParent()->getParent());
2921 case Intrinsic::ctlz: // llvm.ctlz
2922 case Intrinsic::cttz: // llvm.cttz
2923 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
2924 "is_zero_undef argument of bit counting intrinsics must be a "
2928 case Intrinsic::dbg_declare: // llvm.dbg.declare
2929 Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
2930 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2931 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(CI));
2933 case Intrinsic::dbg_value: // llvm.dbg.value
2934 visitDbgIntrinsic("value", cast<DbgValueInst>(CI));
2936 case Intrinsic::memcpy:
2937 case Intrinsic::memmove:
2938 case Intrinsic::memset: {
2939 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
2941 "alignment argument of memory intrinsics must be a constant int",
2943 const APInt &AlignVal = AlignCI->getValue();
2944 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
2945 "alignment argument of memory intrinsics must be a power of 2", &CI);
2946 Assert(isa<ConstantInt>(CI.getArgOperand(4)),
2947 "isvolatile argument of memory intrinsics must be a constant int",
2951 case Intrinsic::gcroot:
2952 case Intrinsic::gcwrite:
2953 case Intrinsic::gcread:
2954 if (ID == Intrinsic::gcroot) {
2956 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2957 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2958 Assert(isa<Constant>(CI.getArgOperand(1)),
2959 "llvm.gcroot parameter #2 must be a constant.", &CI);
2960 if (!AI->getType()->getElementType()->isPointerTy()) {
2961 Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2962 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2963 "or argument #2 must be a non-null constant.",
2968 Assert(CI.getParent()->getParent()->hasGC(),
2969 "Enclosing function does not use GC.", &CI);
2971 case Intrinsic::init_trampoline:
2972 Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2973 "llvm.init_trampoline parameter #2 must resolve to a function.",
2976 case Intrinsic::prefetch:
2977 Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
2978 isa<ConstantInt>(CI.getArgOperand(2)) &&
2979 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2980 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2981 "invalid arguments to llvm.prefetch", &CI);
2983 case Intrinsic::stackprotector:
2984 Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2985 "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
2987 case Intrinsic::lifetime_start:
2988 case Intrinsic::lifetime_end:
2989 case Intrinsic::invariant_start:
2990 Assert(isa<ConstantInt>(CI.getArgOperand(0)),
2991 "size argument of memory use markers must be a constant integer",
2994 case Intrinsic::invariant_end:
2995 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
2996 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2999 case Intrinsic::frameescape: {
3000 BasicBlock *BB = CI.getParent();
3001 Assert(BB == &BB->getParent()->front(),
3002 "llvm.frameescape used outside of entry block", &CI);
3003 Assert(!SawFrameEscape,
3004 "multiple calls to llvm.frameescape in one function", &CI);
3005 for (Value *Arg : CI.arg_operands()) {
3006 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
3007 Assert(AI && AI->isStaticAlloca(),
3008 "llvm.frameescape only accepts static allocas", &CI);
3010 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
3011 SawFrameEscape = true;
3014 case Intrinsic::framerecover: {
3015 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
3016 Function *Fn = dyn_cast<Function>(FnArg);
3017 Assert(Fn && !Fn->isDeclaration(),
3018 "llvm.framerecover first "
3019 "argument must be function defined in this module",
3021 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
3022 Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
3024 auto &Entry = FrameEscapeInfo[Fn];
3025 Entry.second = unsigned(
3026 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
3030 case Intrinsic::eh_parentframe: {
3031 auto *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3032 Assert(AI && AI->isStaticAlloca(),
3033 "llvm.eh.parentframe requires a static alloca", &CI);
3037 case Intrinsic::eh_unwindhelp: {
3038 auto *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
3039 Assert(AI && AI->isStaticAlloca(),
3040 "llvm.eh.unwindhelp requires a static alloca", &CI);
3044 case Intrinsic::experimental_gc_statepoint:
3045 Assert(!CI.isInlineAsm(),
3046 "gc.statepoint support for inline assembly unimplemented", &CI);
3047 Assert(CI.getParent()->getParent()->hasGC(),
3048 "Enclosing function does not use GC.", &CI);
3050 VerifyStatepoint(ImmutableCallSite(&CI));
3052 case Intrinsic::experimental_gc_result_int:
3053 case Intrinsic::experimental_gc_result_float:
3054 case Intrinsic::experimental_gc_result_ptr:
3055 case Intrinsic::experimental_gc_result: {
3056 Assert(CI.getParent()->getParent()->hasGC(),
3057 "Enclosing function does not use GC.", &CI);
3058 // Are we tied to a statepoint properly?
3059 CallSite StatepointCS(CI.getArgOperand(0));
3060 const Function *StatepointFn =
3061 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
3062 Assert(StatepointFn && StatepointFn->isDeclaration() &&
3063 StatepointFn->getIntrinsicID() ==
3064 Intrinsic::experimental_gc_statepoint,
3065 "gc.result operand #1 must be from a statepoint", &CI,
3066 CI.getArgOperand(0));
3068 // Assert that result type matches wrapped callee.
3069 const Value *Target = StatepointCS.getArgument(0);
3070 const PointerType *PT = cast<PointerType>(Target->getType());
3071 const FunctionType *TargetFuncType =
3072 cast<FunctionType>(PT->getElementType());
3073 Assert(CI.getType() == TargetFuncType->getReturnType(),
3074 "gc.result result type does not match wrapped callee", &CI);
3077 case Intrinsic::experimental_gc_relocate: {
3078 Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
3080 // Check that this relocate is correctly tied to the statepoint
3082 // This is case for relocate on the unwinding path of an invoke statepoint
3083 if (ExtractValueInst *ExtractValue =
3084 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
3085 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
3086 "gc relocate on unwind path incorrectly linked to the statepoint",
3089 const BasicBlock *invokeBB =
3090 ExtractValue->getParent()->getUniquePredecessor();
3092 // Landingpad relocates should have only one predecessor with invoke
3093 // statepoint terminator
3094 Assert(invokeBB, "safepoints should have unique landingpads",
3095 ExtractValue->getParent());
3096 Assert(invokeBB->getTerminator(), "safepoint block should be well formed",
3098 Assert(isStatepoint(invokeBB->getTerminator()),
3099 "gc relocate should be linked to a statepoint", invokeBB);
3102 // In all other cases relocate should be tied to the statepoint directly.
3103 // This covers relocates on a normal return path of invoke statepoint and
3104 // relocates of a call statepoint
3105 auto Token = CI.getArgOperand(0);
3106 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
3107 "gc relocate is incorrectly tied to the statepoint", &CI, Token);
3110 // Verify rest of the relocate arguments
3112 GCRelocateOperands ops(&CI);
3113 ImmutableCallSite StatepointCS(ops.statepoint());
3115 // Both the base and derived must be piped through the safepoint
3116 Value* Base = CI.getArgOperand(1);
3117 Assert(isa<ConstantInt>(Base),
3118 "gc.relocate operand #2 must be integer offset", &CI);
3120 Value* Derived = CI.getArgOperand(2);
3121 Assert(isa<ConstantInt>(Derived),
3122 "gc.relocate operand #3 must be integer offset", &CI);
3124 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
3125 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
3127 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
3128 "gc.relocate: statepoint base index out of bounds", &CI);
3129 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
3130 "gc.relocate: statepoint derived index out of bounds", &CI);
3132 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3133 // section of the statepoint's argument
3134 Assert(StatepointCS.arg_size() > 0,
3135 "gc.statepoint: insufficient arguments");
3136 Assert(isa<ConstantInt>(StatepointCS.getArgument(1)),
3137 "gc.statement: number of call arguments must be constant integer");
3138 const unsigned NumCallArgs =
3139 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
3140 Assert(StatepointCS.arg_size() > NumCallArgs+3,
3141 "gc.statepoint: mismatch in number of call arguments");
3142 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs+3)),
3143 "gc.statepoint: number of deoptimization arguments must be "
3144 "a constant integer");
3145 const int NumDeoptArgs =
3146 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3147 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3148 const int GCParamArgsEnd = StatepointCS.arg_size();
3149 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3150 "gc.relocate: statepoint base index doesn't fall within the "
3151 "'gc parameters' section of the statepoint call",
3153 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3154 "gc.relocate: statepoint derived index doesn't fall within the "
3155 "'gc parameters' section of the statepoint call",
3158 // Assert that the result type matches the type of the relocated pointer
3159 GCRelocateOperands Operands(&CI);
3160 Assert(Operands.derivedPtr()->getType() == CI.getType(),
3161 "gc.relocate: relocating a pointer shouldn't change its type", &CI);
3167 template <class DbgIntrinsicTy>
3168 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3169 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3170 Assert(isa<ValueAsMetadata>(MD) ||
3171 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3172 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3173 Assert(isa<MDLocalVariable>(DII.getRawVariable()),
3174 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3175 DII.getRawVariable());
3176 Assert(isa<MDExpression>(DII.getRawExpression()),
3177 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3178 DII.getRawExpression());
3181 void Verifier::verifyDebugInfo() {
3182 // Run the debug info verifier only if the regular verifier succeeds, since
3183 // sometimes checks that have already failed will cause crashes here.
3184 if (EverBroken || !VerifyDebugInfo)
3187 DebugInfoFinder Finder;
3188 Finder.processModule(*M);
3189 processInstructions(Finder);
3191 // Verify Debug Info.
3193 // NOTE: The loud braces are necessary for MSVC compatibility.
3194 for (DICompileUnit CU : Finder.compile_units()) {
3195 Assert(CU.Verify(), "DICompileUnit does not Verify!", CU);
3197 for (DISubprogram S : Finder.subprograms()) {
3198 Assert(S.Verify(), "DISubprogram does not Verify!", S);
3200 for (DIGlobalVariable GV : Finder.global_variables()) {
3201 Assert(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
3203 for (DIType T : Finder.types()) {
3204 Assert(T.Verify(), "DIType does not Verify!", T);
3206 for (DIScope S : Finder.scopes()) {
3207 Assert(S.Verify(), "DIScope does not Verify!", S);
3211 void Verifier::processInstructions(DebugInfoFinder &Finder) {
3212 for (const Function &F : *M)
3213 for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
3214 if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
3215 Finder.processLocation(*M, DILocation(MD));
3216 if (const CallInst *CI = dyn_cast<CallInst>(&*I))
3217 processCallInst(Finder, *CI);
3221 void Verifier::processCallInst(DebugInfoFinder &Finder, const CallInst &CI) {
3222 if (Function *F = CI.getCalledFunction())
3223 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3225 case Intrinsic::dbg_declare:
3226 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
3228 case Intrinsic::dbg_value:
3229 Finder.processValue(*M, cast<DbgValueInst>(&CI));
3236 //===----------------------------------------------------------------------===//
3237 // Implement the public interfaces to this file...
3238 //===----------------------------------------------------------------------===//
3240 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3241 Function &F = const_cast<Function &>(f);
3242 assert(!F.isDeclaration() && "Cannot verify external functions");
3244 raw_null_ostream NullStr;
3245 Verifier V(OS ? *OS : NullStr);
3247 // Note that this function's return value is inverted from what you would
3248 // expect of a function called "verify".
3249 return !V.verify(F);
3252 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3253 raw_null_ostream NullStr;
3254 Verifier V(OS ? *OS : NullStr);
3256 bool Broken = false;
3257 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3258 if (!I->isDeclaration() && !I->isMaterializable())
3259 Broken |= !V.verify(*I);
3261 // Note that this function's return value is inverted from what you would
3262 // expect of a function called "verify".
3263 return !V.verify(M) || Broken;
3267 struct VerifierLegacyPass : public FunctionPass {
3273 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3274 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3276 explicit VerifierLegacyPass(bool FatalErrors)
3277 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3278 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3281 bool runOnFunction(Function &F) override {
3282 if (!V.verify(F) && FatalErrors)
3283 report_fatal_error("Broken function found, compilation aborted!");
3288 bool doFinalization(Module &M) override {
3289 if (!V.verify(M) && FatalErrors)
3290 report_fatal_error("Broken module found, compilation aborted!");
3295 void getAnalysisUsage(AnalysisUsage &AU) const override {
3296 AU.setPreservesAll();
3301 char VerifierLegacyPass::ID = 0;
3302 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3304 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3305 return new VerifierLegacyPass(FatalErrors);
3308 PreservedAnalyses VerifierPass::run(Module &M) {
3309 if (verifyModule(M, &dbgs()) && FatalErrors)
3310 report_fatal_error("Broken module found, compilation aborted!");
3312 return PreservedAnalyses::all();
3315 PreservedAnalyses VerifierPass::run(Function &F) {
3316 if (verifyFunction(F, &dbgs()) && FatalErrors)
3317 report_fatal_error("Broken function found, compilation aborted!");
3319 return PreservedAnalyses::all();