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/InstVisitor.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/LLVMContext.h"
67 #include "llvm/IR/Metadata.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/PassManager.h"
70 #include "llvm/Pass.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/raw_ostream.h"
79 static cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier",
83 class Verifier : public InstVisitor<Verifier> {
84 friend class InstVisitor<Verifier>;
92 /// \brief When verifying a basic block, keep track of all of the
93 /// instructions we have seen so far.
95 /// This allows us to do efficient dominance checks for the case when an
96 /// instruction has an operand that is an instruction in the same block.
97 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
99 /// \brief Keep track of the metadata nodes that have been checked already.
100 SmallPtrSet<MDNode *, 32> MDNodes;
102 /// \brief The personality function referenced by the LandingPadInsts.
103 /// All LandingPadInsts within the same function must use the same
104 /// personality function.
105 const Value *PersonalityFn;
107 /// \brief Finder keeps track of all debug info MDNodes in a Module.
108 DebugInfoFinder Finder;
110 /// \brief Track the brokenness of the module while recursively visiting.
114 explicit Verifier(raw_ostream &OS = dbgs())
115 : OS(OS), M(0), Context(0), DL(0), PersonalityFn(0), Broken(false) {}
117 bool verify(const Function &F) {
119 Context = &M->getContext();
121 // First ensure the function is well-enough formed to compute dominance
124 OS << "Function '" << F.getName()
125 << "' does not contain an entry block!\n";
128 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
129 if (I->empty() || !I->back().isTerminator()) {
130 OS << "Basic Block in function '" << F.getName()
131 << "' does not have terminator!\n";
132 I->printAsOperand(OS, true);
138 // Now directly compute a dominance tree. We don't rely on the pass
139 // manager to provide this as it isolates us from a potentially
140 // out-of-date dominator tree and makes it significantly more complex to
141 // run this code outside of a pass manager.
142 // FIXME: It's really gross that we have to cast away constness here.
143 DT.recalculate(const_cast<Function &>(F));
147 // FIXME: We strip const here because the inst visitor strips const.
148 visit(const_cast<Function &>(F));
149 InstsInThisBlock.clear();
152 if (!DisableDebugInfoVerifier)
153 // Verify Debug Info.
159 bool verify(const Module &M) {
161 Context = &M.getContext();
165 // Scan through, checking all of the external function's linkage now...
166 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
167 visitGlobalValue(*I);
169 // Check to make sure function prototypes are okay.
170 if (I->isDeclaration())
174 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
176 visitGlobalVariable(*I);
178 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
180 visitGlobalAlias(*I);
182 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
183 E = M.named_metadata_end();
185 visitNamedMDNode(*I);
188 visitModuleIdents(M);
190 if (!DisableDebugInfoVerifier) {
192 Finder.processModule(M);
193 // Verify Debug Info.
201 // Verification methods...
202 void visitGlobalValue(const GlobalValue &GV);
203 void visitGlobalVariable(const GlobalVariable &GV);
204 void visitGlobalAlias(const GlobalAlias &GA);
205 void visitNamedMDNode(const NamedMDNode &NMD);
206 void visitMDNode(MDNode &MD, Function *F);
207 void visitModuleIdents(const Module &M);
208 void visitModuleFlags(const Module &M);
209 void visitModuleFlag(const MDNode *Op,
210 DenseMap<const MDString *, const MDNode *> &SeenIDs,
211 SmallVectorImpl<const MDNode *> &Requirements);
212 void visitFunction(const Function &F);
213 void visitBasicBlock(BasicBlock &BB);
215 // InstVisitor overrides...
216 using InstVisitor<Verifier>::visit;
217 void visit(Instruction &I);
219 void visitTruncInst(TruncInst &I);
220 void visitZExtInst(ZExtInst &I);
221 void visitSExtInst(SExtInst &I);
222 void visitFPTruncInst(FPTruncInst &I);
223 void visitFPExtInst(FPExtInst &I);
224 void visitFPToUIInst(FPToUIInst &I);
225 void visitFPToSIInst(FPToSIInst &I);
226 void visitUIToFPInst(UIToFPInst &I);
227 void visitSIToFPInst(SIToFPInst &I);
228 void visitIntToPtrInst(IntToPtrInst &I);
229 void visitPtrToIntInst(PtrToIntInst &I);
230 void visitBitCastInst(BitCastInst &I);
231 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
232 void visitPHINode(PHINode &PN);
233 void visitBinaryOperator(BinaryOperator &B);
234 void visitICmpInst(ICmpInst &IC);
235 void visitFCmpInst(FCmpInst &FC);
236 void visitExtractElementInst(ExtractElementInst &EI);
237 void visitInsertElementInst(InsertElementInst &EI);
238 void visitShuffleVectorInst(ShuffleVectorInst &EI);
239 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
240 void visitCallInst(CallInst &CI);
241 void visitInvokeInst(InvokeInst &II);
242 void visitGetElementPtrInst(GetElementPtrInst &GEP);
243 void visitLoadInst(LoadInst &LI);
244 void visitStoreInst(StoreInst &SI);
245 void verifyDominatesUse(Instruction &I, unsigned i);
246 void visitInstruction(Instruction &I);
247 void visitTerminatorInst(TerminatorInst &I);
248 void visitBranchInst(BranchInst &BI);
249 void visitReturnInst(ReturnInst &RI);
250 void visitSwitchInst(SwitchInst &SI);
251 void visitIndirectBrInst(IndirectBrInst &BI);
252 void visitSelectInst(SelectInst &SI);
253 void visitUserOp1(Instruction &I);
254 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
255 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
256 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
257 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
258 void visitFenceInst(FenceInst &FI);
259 void visitAllocaInst(AllocaInst &AI);
260 void visitExtractValueInst(ExtractValueInst &EVI);
261 void visitInsertValueInst(InsertValueInst &IVI);
262 void visitLandingPadInst(LandingPadInst &LPI);
264 void VerifyCallSite(CallSite CS);
265 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
266 unsigned ArgNo, std::string &Suffix);
267 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
268 SmallVectorImpl<Type *> &ArgTys);
269 bool VerifyIntrinsicIsVarArg(bool isVarArg,
270 ArrayRef<Intrinsic::IITDescriptor> &Infos);
271 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
272 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
274 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
275 bool isReturnValue, const Value *V);
276 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
279 void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
280 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
282 void verifyDebugInfo();
284 void WriteValue(const Value *V) {
287 if (isa<Instruction>(V)) {
290 V->printAsOperand(OS, true, M);
295 void WriteType(Type *T) {
301 // CheckFailed - A check failed, so print out the condition and the message
302 // that failed. This provides a nice place to put a breakpoint if you want
303 // to see why something is not correct.
304 void CheckFailed(const Twine &Message, const Value *V1 = 0,
305 const Value *V2 = 0, const Value *V3 = 0,
306 const Value *V4 = 0) {
307 OS << Message.str() << "\n";
315 void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
316 const Value *V3 = 0) {
317 OS << Message.str() << "\n";
324 void CheckFailed(const Twine &Message, Type *T1, Type *T2 = 0, Type *T3 = 0) {
325 OS << Message.str() << "\n";
332 } // End anonymous namespace
334 // Assert - We know that cond should be true, if not print an error message.
335 #define Assert(C, M) \
336 do { if (!(C)) { CheckFailed(M); return; } } while (0)
337 #define Assert1(C, M, V1) \
338 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
339 #define Assert2(C, M, V1, V2) \
340 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
341 #define Assert3(C, M, V1, V2, V3) \
342 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
343 #define Assert4(C, M, V1, V2, V3, V4) \
344 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
346 void Verifier::visit(Instruction &I) {
347 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
348 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
349 InstVisitor<Verifier>::visit(I);
353 void Verifier::visitGlobalValue(const GlobalValue &GV) {
354 Assert1(!GV.isDeclaration() ||
355 GV.isMaterializable() ||
356 GV.hasExternalLinkage() ||
357 GV.hasExternalWeakLinkage() ||
358 (isa<GlobalAlias>(GV) &&
359 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
360 "Global is external, but doesn't have external or weak linkage!",
363 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
364 "Only global variables can have appending linkage!", &GV);
366 if (GV.hasAppendingLinkage()) {
367 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
368 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
369 "Only global arrays can have appending linkage!", GVar);
373 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
374 if (GV.hasInitializer()) {
375 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
376 "Global variable initializer type does not match global "
377 "variable type!", &GV);
379 // If the global has common linkage, it must have a zero initializer and
380 // cannot be constant.
381 if (GV.hasCommonLinkage()) {
382 Assert1(GV.getInitializer()->isNullValue(),
383 "'common' global must have a zero initializer!", &GV);
384 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
388 Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
389 "invalid linkage type for global declaration", &GV);
392 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
393 GV.getName() == "llvm.global_dtors")) {
394 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
395 "invalid linkage for intrinsic global variable", &GV);
396 // Don't worry about emitting an error for it not being an array,
397 // visitGlobalValue will complain on appending non-array.
398 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
399 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
400 PointerType *FuncPtrTy =
401 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
402 Assert1(STy && STy->getNumElements() == 2 &&
403 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
404 STy->getTypeAtIndex(1) == FuncPtrTy,
405 "wrong type for intrinsic global variable", &GV);
409 if (GV.hasName() && (GV.getName() == "llvm.used" ||
410 GV.getName() == "llvm.compiler.used")) {
411 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
412 "invalid linkage for intrinsic global variable", &GV);
413 Type *GVType = GV.getType()->getElementType();
414 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
415 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
416 Assert1(PTy, "wrong type for intrinsic global variable", &GV);
417 if (GV.hasInitializer()) {
418 const Constant *Init = GV.getInitializer();
419 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
420 Assert1(InitArray, "wrong initalizer for intrinsic global variable",
422 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
423 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
425 isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
426 "invalid llvm.used member", V);
427 Assert1(V->hasName(), "members of llvm.used must be named", V);
433 Assert1(!GV.hasDLLImportStorageClass() ||
434 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
435 GV.hasAvailableExternallyLinkage(),
436 "Global is marked as dllimport, but not external", &GV);
438 if (!GV.hasInitializer()) {
439 visitGlobalValue(GV);
443 // Walk any aggregate initializers looking for bitcasts between address spaces
444 SmallPtrSet<const Value *, 4> Visited;
445 SmallVector<const Value *, 4> WorkStack;
446 WorkStack.push_back(cast<Value>(GV.getInitializer()));
448 while (!WorkStack.empty()) {
449 const Value *V = WorkStack.pop_back_val();
450 if (!Visited.insert(V))
453 if (const User *U = dyn_cast<User>(V)) {
454 for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
455 WorkStack.push_back(U->getOperand(I));
458 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
459 VerifyConstantExprBitcastType(CE);
465 visitGlobalValue(GV);
468 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
469 Assert1(!GA.getName().empty(),
470 "Alias name cannot be empty!", &GA);
471 Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
472 "Alias should have external or external weak linkage!", &GA);
473 Assert1(GA.getAliasee(),
474 "Aliasee cannot be NULL!", &GA);
475 Assert1(GA.getType() == GA.getAliasee()->getType(),
476 "Alias and aliasee types should match!", &GA);
477 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
478 Assert1(!GA.hasSection(), "Alias cannot have a section!", &GA);
479 Assert1(!GA.getAlignment(), "Alias connot have an alignment", &GA);
481 const Constant *Aliasee = GA.getAliasee();
482 const GlobalValue *GV = dyn_cast<GlobalValue>(Aliasee);
485 const ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
486 if (CE && (CE->getOpcode() == Instruction::BitCast ||
487 CE->getOpcode() == Instruction::AddrSpaceCast ||
488 CE->getOpcode() == Instruction::GetElementPtr))
489 GV = dyn_cast<GlobalValue>(CE->getOperand(0));
491 Assert1(GV, "Aliasee should be either GlobalValue, bitcast or "
492 "addrspacecast of GlobalValue",
495 if (CE->getOpcode() == Instruction::BitCast) {
496 unsigned SrcAS = GV->getType()->getPointerAddressSpace();
497 unsigned DstAS = CE->getType()->getPointerAddressSpace();
499 Assert1(SrcAS == DstAS,
500 "Alias bitcasts cannot be between different address spaces",
504 Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
506 const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
508 "Aliasing chain should end with function or global variable", &GA);
510 visitGlobalValue(GA);
513 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
514 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
515 MDNode *MD = NMD.getOperand(i);
519 Assert1(!MD->isFunctionLocal(),
520 "Named metadata operand cannot be function local!", MD);
525 void Verifier::visitMDNode(MDNode &MD, Function *F) {
526 // Only visit each node once. Metadata can be mutually recursive, so this
527 // avoids infinite recursion here, as well as being an optimization.
528 if (!MDNodes.insert(&MD))
531 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
532 Value *Op = MD.getOperand(i);
535 if (isa<Constant>(Op) || isa<MDString>(Op))
537 if (MDNode *N = dyn_cast<MDNode>(Op)) {
538 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
539 "Global metadata operand cannot be function local!", &MD, N);
543 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
545 // If this was an instruction, bb, or argument, verify that it is in the
546 // function that we expect.
547 Function *ActualF = 0;
548 if (Instruction *I = dyn_cast<Instruction>(Op))
549 ActualF = I->getParent()->getParent();
550 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
551 ActualF = BB->getParent();
552 else if (Argument *A = dyn_cast<Argument>(Op))
553 ActualF = A->getParent();
554 assert(ActualF && "Unimplemented function local metadata case!");
556 Assert2(ActualF == F, "function-local metadata used in wrong function",
561 void Verifier::visitModuleIdents(const Module &M) {
562 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
566 // llvm.ident takes a list of metadata entry. Each entry has only one string.
567 // Scan each llvm.ident entry and make sure that this requirement is met.
568 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
569 const MDNode *N = Idents->getOperand(i);
570 Assert1(N->getNumOperands() == 1,
571 "incorrect number of operands in llvm.ident metadata", N);
572 Assert1(isa<MDString>(N->getOperand(0)),
573 ("invalid value for llvm.ident metadata entry operand"
574 "(the operand should be a string)"),
579 void Verifier::visitModuleFlags(const Module &M) {
580 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
583 // Scan each flag, and track the flags and requirements.
584 DenseMap<const MDString*, const MDNode*> SeenIDs;
585 SmallVector<const MDNode*, 16> Requirements;
586 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
587 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
590 // Validate that the requirements in the module are valid.
591 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
592 const MDNode *Requirement = Requirements[I];
593 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
594 const Value *ReqValue = Requirement->getOperand(1);
596 const MDNode *Op = SeenIDs.lookup(Flag);
598 CheckFailed("invalid requirement on flag, flag is not present in module",
603 if (Op->getOperand(2) != ReqValue) {
604 CheckFailed(("invalid requirement on flag, "
605 "flag does not have the required value"),
613 Verifier::visitModuleFlag(const MDNode *Op,
614 DenseMap<const MDString *, const MDNode *> &SeenIDs,
615 SmallVectorImpl<const MDNode *> &Requirements) {
616 // Each module flag should have three arguments, the merge behavior (a
617 // constant int), the flag ID (an MDString), and the value.
618 Assert1(Op->getNumOperands() == 3,
619 "incorrect number of operands in module flag", Op);
620 ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
621 MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
623 "invalid behavior operand in module flag (expected constant integer)",
625 unsigned BehaviorValue = Behavior->getZExtValue();
627 "invalid ID operand in module flag (expected metadata string)",
630 // Sanity check the values for behaviors with additional requirements.
631 switch (BehaviorValue) {
634 "invalid behavior operand in module flag (unexpected constant)",
639 case Module::Warning:
640 case Module::Override:
641 // These behavior types accept any value.
644 case Module::Require: {
645 // The value should itself be an MDNode with two operands, a flag ID (an
646 // MDString), and a value.
647 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
648 Assert1(Value && Value->getNumOperands() == 2,
649 "invalid value for 'require' module flag (expected metadata pair)",
651 Assert1(isa<MDString>(Value->getOperand(0)),
652 ("invalid value for 'require' module flag "
653 "(first value operand should be a string)"),
654 Value->getOperand(0));
656 // Append it to the list of requirements, to check once all module flags are
658 Requirements.push_back(Value);
663 case Module::AppendUnique: {
664 // These behavior types require the operand be an MDNode.
665 Assert1(isa<MDNode>(Op->getOperand(2)),
666 "invalid value for 'append'-type module flag "
667 "(expected a metadata node)", Op->getOperand(2));
672 // Unless this is a "requires" flag, check the ID is unique.
673 if (BehaviorValue != Module::Require) {
674 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
676 "module flag identifiers must be unique (or of 'require' type)",
681 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
682 bool isFunction, const Value *V) {
684 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
685 if (Attrs.getSlotIndex(I) == Idx) {
690 assert(Slot != ~0U && "Attribute set inconsistency!");
692 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
694 if (I->isStringAttribute())
697 if (I->getKindAsEnum() == Attribute::NoReturn ||
698 I->getKindAsEnum() == Attribute::NoUnwind ||
699 I->getKindAsEnum() == Attribute::NoInline ||
700 I->getKindAsEnum() == Attribute::AlwaysInline ||
701 I->getKindAsEnum() == Attribute::OptimizeForSize ||
702 I->getKindAsEnum() == Attribute::StackProtect ||
703 I->getKindAsEnum() == Attribute::StackProtectReq ||
704 I->getKindAsEnum() == Attribute::StackProtectStrong ||
705 I->getKindAsEnum() == Attribute::NoRedZone ||
706 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
707 I->getKindAsEnum() == Attribute::Naked ||
708 I->getKindAsEnum() == Attribute::InlineHint ||
709 I->getKindAsEnum() == Attribute::StackAlignment ||
710 I->getKindAsEnum() == Attribute::UWTable ||
711 I->getKindAsEnum() == Attribute::NonLazyBind ||
712 I->getKindAsEnum() == Attribute::ReturnsTwice ||
713 I->getKindAsEnum() == Attribute::SanitizeAddress ||
714 I->getKindAsEnum() == Attribute::SanitizeThread ||
715 I->getKindAsEnum() == Attribute::SanitizeMemory ||
716 I->getKindAsEnum() == Attribute::MinSize ||
717 I->getKindAsEnum() == Attribute::NoDuplicate ||
718 I->getKindAsEnum() == Attribute::Builtin ||
719 I->getKindAsEnum() == Attribute::NoBuiltin ||
720 I->getKindAsEnum() == Attribute::Cold ||
721 I->getKindAsEnum() == Attribute::OptimizeNone) {
723 CheckFailed("Attribute '" + I->getAsString() +
724 "' only applies to functions!", V);
727 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
728 I->getKindAsEnum() == Attribute::ReadNone) {
730 CheckFailed("Attribute '" + I->getAsString() +
731 "' does not apply to function returns");
734 } else if (isFunction) {
735 CheckFailed("Attribute '" + I->getAsString() +
736 "' does not apply to functions!", V);
742 // VerifyParameterAttrs - Check the given attributes for an argument or return
743 // value of the specified type. The value V is printed in error messages.
744 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
745 bool isReturnValue, const Value *V) {
746 if (!Attrs.hasAttributes(Idx))
749 VerifyAttributeTypes(Attrs, Idx, false, V);
752 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
753 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
754 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
755 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
756 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
757 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
758 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
759 "'returned' do not apply to return values!", V);
761 // Check for mutually incompatible attributes. Only inreg is compatible with
763 unsigned AttrCount = 0;
764 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
765 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
766 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
767 Attrs.hasAttribute(Idx, Attribute::InReg);
768 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
769 Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
770 "and 'sret' are incompatible!", V);
772 Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
773 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
774 "'inalloca and readonly' are incompatible!", V);
776 Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
777 Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
778 "'sret and returned' are incompatible!", V);
780 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
781 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
782 "'zeroext and signext' are incompatible!", V);
784 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
785 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
786 "'readnone and readonly' are incompatible!", V);
788 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
789 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
790 "'noinline and alwaysinline' are incompatible!", V);
792 Assert1(!AttrBuilder(Attrs, Idx).
793 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
794 "Wrong types for attribute: " +
795 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
797 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
798 if (!PTy->getElementType()->isSized()) {
799 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
800 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
801 "Attributes 'byval' and 'inalloca' do not support unsized types!",
805 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
806 "Attribute 'byval' only applies to parameters with pointer type!",
811 // VerifyFunctionAttrs - Check parameter attributes against a function type.
812 // The value V is printed in error messages.
813 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
818 bool SawNest = false;
819 bool SawReturned = false;
821 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
822 unsigned Idx = Attrs.getSlotIndex(i);
826 Ty = FT->getReturnType();
827 else if (Idx-1 < FT->getNumParams())
828 Ty = FT->getParamType(Idx-1);
830 break; // VarArgs attributes, verified elsewhere.
832 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
837 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
838 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
842 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
843 Assert1(!SawReturned, "More than one parameter has attribute returned!",
845 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
846 "argument and return types for 'returned' attribute", V);
850 if (Attrs.hasAttribute(Idx, Attribute::StructRet))
851 Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
853 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
854 Assert1(Idx == FT->getNumParams(),
855 "inalloca isn't on the last parameter!", V);
859 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
862 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
864 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
865 Attribute::ReadNone) &&
866 Attrs.hasAttribute(AttributeSet::FunctionIndex,
867 Attribute::ReadOnly)),
868 "Attributes 'readnone and readonly' are incompatible!", V);
870 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
871 Attribute::NoInline) &&
872 Attrs.hasAttribute(AttributeSet::FunctionIndex,
873 Attribute::AlwaysInline)),
874 "Attributes 'noinline and alwaysinline' are incompatible!", V);
876 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
877 Attribute::OptimizeNone)) {
878 Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
879 Attribute::NoInline),
880 "Attribute 'optnone' requires 'noinline'!", V);
882 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
883 Attribute::OptimizeForSize),
884 "Attributes 'optsize and optnone' are incompatible!", V);
886 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
888 "Attributes 'minsize and optnone' are incompatible!", V);
892 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
893 // Get the size of the types in bits, we'll need this later
894 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
895 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
897 // BitCast implies a no-op cast of type only. No bits change.
898 // However, you can't cast pointers to anything but pointers.
899 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
900 "Bitcast requires both operands to be pointer or neither", V);
901 Assert1(SrcBitSize == DestBitSize,
902 "Bitcast requires types of same width", V);
904 // Disallow aggregates.
905 Assert1(!SrcTy->isAggregateType(),
906 "Bitcast operand must not be aggregate", V);
907 Assert1(!DestTy->isAggregateType(),
908 "Bitcast type must not be aggregate", V);
910 // Without datalayout, assume all address spaces are the same size.
911 // Don't check if both types are not pointers.
912 // Skip casts between scalars and vectors.
914 !SrcTy->isPtrOrPtrVectorTy() ||
915 !DestTy->isPtrOrPtrVectorTy() ||
916 SrcTy->isVectorTy() != DestTy->isVectorTy()) {
920 unsigned SrcAS = SrcTy->getPointerAddressSpace();
921 unsigned DstAS = DestTy->getPointerAddressSpace();
923 Assert1(SrcAS == DstAS,
924 "Bitcasts between pointers of different address spaces is not legal."
925 "Use AddrSpaceCast instead.", V);
928 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
929 if (CE->getOpcode() == Instruction::BitCast) {
930 Type *SrcTy = CE->getOperand(0)->getType();
931 Type *DstTy = CE->getType();
932 VerifyBitcastType(CE, DstTy, SrcTy);
936 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
937 if (Attrs.getNumSlots() == 0)
940 unsigned LastSlot = Attrs.getNumSlots() - 1;
941 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
942 if (LastIndex <= Params
943 || (LastIndex == AttributeSet::FunctionIndex
944 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
950 // visitFunction - Verify that a function is ok.
952 void Verifier::visitFunction(const Function &F) {
953 // Check function arguments.
954 FunctionType *FT = F.getFunctionType();
955 unsigned NumArgs = F.arg_size();
957 Assert1(Context == &F.getContext(),
958 "Function context does not match Module context!", &F);
960 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
961 Assert2(FT->getNumParams() == NumArgs,
962 "# formal arguments must match # of arguments for function type!",
964 Assert1(F.getReturnType()->isFirstClassType() ||
965 F.getReturnType()->isVoidTy() ||
966 F.getReturnType()->isStructTy(),
967 "Functions cannot return aggregate values!", &F);
969 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
970 "Invalid struct return type!", &F);
972 AttributeSet Attrs = F.getAttributes();
974 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
975 "Attribute after last parameter!", &F);
977 // Check function attributes.
978 VerifyFunctionAttrs(FT, Attrs, &F);
980 // On function declarations/definitions, we do not support the builtin
981 // attribute. We do not check this in VerifyFunctionAttrs since that is
982 // checking for Attributes that can/can not ever be on functions.
983 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
985 "Attribute 'builtin' can only be applied to a callsite.", &F);
987 // Check that this function meets the restrictions on this calling convention.
988 switch (F.getCallingConv()) {
993 case CallingConv::Fast:
994 case CallingConv::Cold:
995 case CallingConv::X86_FastCall:
996 case CallingConv::X86_ThisCall:
997 case CallingConv::Intel_OCL_BI:
998 case CallingConv::PTX_Kernel:
999 case CallingConv::PTX_Device:
1000 Assert1(!F.isVarArg(),
1001 "Varargs functions must have C calling conventions!", &F);
1005 bool isLLVMdotName = F.getName().size() >= 5 &&
1006 F.getName().substr(0, 5) == "llvm.";
1008 // Check that the argument values match the function type for this function...
1010 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1012 Assert2(I->getType() == FT->getParamType(i),
1013 "Argument value does not match function argument type!",
1014 I, FT->getParamType(i));
1015 Assert1(I->getType()->isFirstClassType(),
1016 "Function arguments must have first-class types!", I);
1018 Assert2(!I->getType()->isMetadataTy(),
1019 "Function takes metadata but isn't an intrinsic", I, &F);
1022 if (F.isMaterializable()) {
1023 // Function has a body somewhere we can't see.
1024 } else if (F.isDeclaration()) {
1025 Assert1(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1026 "invalid linkage type for function declaration", &F);
1028 // Verify that this function (which has a body) is not named "llvm.*". It
1029 // is not legal to define intrinsics.
1030 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1032 // Check the entry node
1033 const BasicBlock *Entry = &F.getEntryBlock();
1034 Assert1(pred_begin(Entry) == pred_end(Entry),
1035 "Entry block to function must not have predecessors!", Entry);
1037 // The address of the entry block cannot be taken, unless it is dead.
1038 if (Entry->hasAddressTaken()) {
1039 Assert1(!BlockAddress::lookup(Entry)->isConstantUsed(),
1040 "blockaddress may not be used with the entry block!", Entry);
1044 // If this function is actually an intrinsic, verify that it is only used in
1045 // direct call/invokes, never having its "address taken".
1046 if (F.getIntrinsicID()) {
1048 if (F.hasAddressTaken(&U))
1049 Assert1(0, "Invalid user of intrinsic instruction!", U);
1052 Assert1(!F.hasDLLImportStorageClass() ||
1053 (F.isDeclaration() && F.hasExternalLinkage()) ||
1054 F.hasAvailableExternallyLinkage(),
1055 "Function is marked as dllimport, but not external.", &F);
1058 // verifyBasicBlock - Verify that a basic block is well formed...
1060 void Verifier::visitBasicBlock(BasicBlock &BB) {
1061 InstsInThisBlock.clear();
1063 // Ensure that basic blocks have terminators!
1064 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1066 // Check constraints that this basic block imposes on all of the PHI nodes in
1068 if (isa<PHINode>(BB.front())) {
1069 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1070 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1071 std::sort(Preds.begin(), Preds.end());
1073 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1074 // Ensure that PHI nodes have at least one entry!
1075 Assert1(PN->getNumIncomingValues() != 0,
1076 "PHI nodes must have at least one entry. If the block is dead, "
1077 "the PHI should be removed!", PN);
1078 Assert1(PN->getNumIncomingValues() == Preds.size(),
1079 "PHINode should have one entry for each predecessor of its "
1080 "parent basic block!", PN);
1082 // Get and sort all incoming values in the PHI node...
1084 Values.reserve(PN->getNumIncomingValues());
1085 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1086 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1087 PN->getIncomingValue(i)));
1088 std::sort(Values.begin(), Values.end());
1090 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1091 // Check to make sure that if there is more than one entry for a
1092 // particular basic block in this PHI node, that the incoming values are
1095 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
1096 Values[i].second == Values[i-1].second,
1097 "PHI node has multiple entries for the same basic block with "
1098 "different incoming values!", PN, Values[i].first,
1099 Values[i].second, Values[i-1].second);
1101 // Check to make sure that the predecessors and PHI node entries are
1103 Assert3(Values[i].first == Preds[i],
1104 "PHI node entries do not match predecessors!", PN,
1105 Values[i].first, Preds[i]);
1111 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1112 // Ensure that terminators only exist at the end of the basic block.
1113 Assert1(&I == I.getParent()->getTerminator(),
1114 "Terminator found in the middle of a basic block!", I.getParent());
1115 visitInstruction(I);
1118 void Verifier::visitBranchInst(BranchInst &BI) {
1119 if (BI.isConditional()) {
1120 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1121 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1123 visitTerminatorInst(BI);
1126 void Verifier::visitReturnInst(ReturnInst &RI) {
1127 Function *F = RI.getParent()->getParent();
1128 unsigned N = RI.getNumOperands();
1129 if (F->getReturnType()->isVoidTy())
1131 "Found return instr that returns non-void in Function of void "
1132 "return type!", &RI, F->getReturnType());
1134 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1135 "Function return type does not match operand "
1136 "type of return inst!", &RI, F->getReturnType());
1138 // Check to make sure that the return value has necessary properties for
1140 visitTerminatorInst(RI);
1143 void Verifier::visitSwitchInst(SwitchInst &SI) {
1144 // Check to make sure that all of the constants in the switch instruction
1145 // have the same type as the switched-on value.
1146 Type *SwitchTy = SI.getCondition()->getType();
1147 SmallPtrSet<ConstantInt*, 32> Constants;
1148 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1149 Assert1(i.getCaseValue()->getType() == SwitchTy,
1150 "Switch constants must all be same type as switch value!", &SI);
1151 Assert2(Constants.insert(i.getCaseValue()),
1152 "Duplicate integer as switch case", &SI, i.getCaseValue());
1155 visitTerminatorInst(SI);
1158 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1159 Assert1(BI.getAddress()->getType()->isPointerTy(),
1160 "Indirectbr operand must have pointer type!", &BI);
1161 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1162 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1163 "Indirectbr destinations must all have pointer type!", &BI);
1165 visitTerminatorInst(BI);
1168 void Verifier::visitSelectInst(SelectInst &SI) {
1169 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1171 "Invalid operands for select instruction!", &SI);
1173 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1174 "Select values must have same type as select instruction!", &SI);
1175 visitInstruction(SI);
1178 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1179 /// a pass, if any exist, it's an error.
1181 void Verifier::visitUserOp1(Instruction &I) {
1182 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1185 void Verifier::visitTruncInst(TruncInst &I) {
1186 // Get the source and destination types
1187 Type *SrcTy = I.getOperand(0)->getType();
1188 Type *DestTy = I.getType();
1190 // Get the size of the types in bits, we'll need this later
1191 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1192 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1194 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1195 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1196 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1197 "trunc source and destination must both be a vector or neither", &I);
1198 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1200 visitInstruction(I);
1203 void Verifier::visitZExtInst(ZExtInst &I) {
1204 // Get the source and destination types
1205 Type *SrcTy = I.getOperand(0)->getType();
1206 Type *DestTy = I.getType();
1208 // Get the size of the types in bits, we'll need this later
1209 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1210 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1211 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1212 "zext source and destination must both be a vector or neither", &I);
1213 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1214 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1216 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1218 visitInstruction(I);
1221 void Verifier::visitSExtInst(SExtInst &I) {
1222 // Get the source and destination types
1223 Type *SrcTy = I.getOperand(0)->getType();
1224 Type *DestTy = I.getType();
1226 // Get the size of the types in bits, we'll need this later
1227 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1228 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1230 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1231 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1232 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1233 "sext source and destination must both be a vector or neither", &I);
1234 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1236 visitInstruction(I);
1239 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1240 // Get the source and destination types
1241 Type *SrcTy = I.getOperand(0)->getType();
1242 Type *DestTy = I.getType();
1243 // Get the size of the types in bits, we'll need this later
1244 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1245 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1247 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1248 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1249 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1250 "fptrunc source and destination must both be a vector or neither",&I);
1251 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1253 visitInstruction(I);
1256 void Verifier::visitFPExtInst(FPExtInst &I) {
1257 // Get the source and destination types
1258 Type *SrcTy = I.getOperand(0)->getType();
1259 Type *DestTy = I.getType();
1261 // Get the size of the types in bits, we'll need this later
1262 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1263 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1265 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1266 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1267 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1268 "fpext source and destination must both be a vector or neither", &I);
1269 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1271 visitInstruction(I);
1274 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1275 // Get the source and destination types
1276 Type *SrcTy = I.getOperand(0)->getType();
1277 Type *DestTy = I.getType();
1279 bool SrcVec = SrcTy->isVectorTy();
1280 bool DstVec = DestTy->isVectorTy();
1282 Assert1(SrcVec == DstVec,
1283 "UIToFP source and dest must both be vector or scalar", &I);
1284 Assert1(SrcTy->isIntOrIntVectorTy(),
1285 "UIToFP source must be integer or integer vector", &I);
1286 Assert1(DestTy->isFPOrFPVectorTy(),
1287 "UIToFP result must be FP or FP vector", &I);
1289 if (SrcVec && DstVec)
1290 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1291 cast<VectorType>(DestTy)->getNumElements(),
1292 "UIToFP source and dest vector length mismatch", &I);
1294 visitInstruction(I);
1297 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1298 // Get the source and destination types
1299 Type *SrcTy = I.getOperand(0)->getType();
1300 Type *DestTy = I.getType();
1302 bool SrcVec = SrcTy->isVectorTy();
1303 bool DstVec = DestTy->isVectorTy();
1305 Assert1(SrcVec == DstVec,
1306 "SIToFP source and dest must both be vector or scalar", &I);
1307 Assert1(SrcTy->isIntOrIntVectorTy(),
1308 "SIToFP source must be integer or integer vector", &I);
1309 Assert1(DestTy->isFPOrFPVectorTy(),
1310 "SIToFP result must be FP or FP vector", &I);
1312 if (SrcVec && DstVec)
1313 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1314 cast<VectorType>(DestTy)->getNumElements(),
1315 "SIToFP source and dest vector length mismatch", &I);
1317 visitInstruction(I);
1320 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1321 // Get the source and destination types
1322 Type *SrcTy = I.getOperand(0)->getType();
1323 Type *DestTy = I.getType();
1325 bool SrcVec = SrcTy->isVectorTy();
1326 bool DstVec = DestTy->isVectorTy();
1328 Assert1(SrcVec == DstVec,
1329 "FPToUI source and dest must both be vector or scalar", &I);
1330 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1332 Assert1(DestTy->isIntOrIntVectorTy(),
1333 "FPToUI result must be integer or integer vector", &I);
1335 if (SrcVec && DstVec)
1336 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1337 cast<VectorType>(DestTy)->getNumElements(),
1338 "FPToUI source and dest vector length mismatch", &I);
1340 visitInstruction(I);
1343 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1344 // Get the source and destination types
1345 Type *SrcTy = I.getOperand(0)->getType();
1346 Type *DestTy = I.getType();
1348 bool SrcVec = SrcTy->isVectorTy();
1349 bool DstVec = DestTy->isVectorTy();
1351 Assert1(SrcVec == DstVec,
1352 "FPToSI source and dest must both be vector or scalar", &I);
1353 Assert1(SrcTy->isFPOrFPVectorTy(),
1354 "FPToSI source must be FP or FP vector", &I);
1355 Assert1(DestTy->isIntOrIntVectorTy(),
1356 "FPToSI result must be integer or integer vector", &I);
1358 if (SrcVec && DstVec)
1359 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1360 cast<VectorType>(DestTy)->getNumElements(),
1361 "FPToSI source and dest vector length mismatch", &I);
1363 visitInstruction(I);
1366 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1367 // Get the source and destination types
1368 Type *SrcTy = I.getOperand(0)->getType();
1369 Type *DestTy = I.getType();
1371 Assert1(SrcTy->getScalarType()->isPointerTy(),
1372 "PtrToInt source must be pointer", &I);
1373 Assert1(DestTy->getScalarType()->isIntegerTy(),
1374 "PtrToInt result must be integral", &I);
1375 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1376 "PtrToInt type mismatch", &I);
1378 if (SrcTy->isVectorTy()) {
1379 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1380 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1381 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1382 "PtrToInt Vector width mismatch", &I);
1385 visitInstruction(I);
1388 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1389 // Get the source and destination types
1390 Type *SrcTy = I.getOperand(0)->getType();
1391 Type *DestTy = I.getType();
1393 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1394 "IntToPtr source must be an integral", &I);
1395 Assert1(DestTy->getScalarType()->isPointerTy(),
1396 "IntToPtr result must be a pointer",&I);
1397 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1398 "IntToPtr type mismatch", &I);
1399 if (SrcTy->isVectorTy()) {
1400 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1401 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1402 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1403 "IntToPtr Vector width mismatch", &I);
1405 visitInstruction(I);
1408 void Verifier::visitBitCastInst(BitCastInst &I) {
1409 Type *SrcTy = I.getOperand(0)->getType();
1410 Type *DestTy = I.getType();
1411 VerifyBitcastType(&I, DestTy, SrcTy);
1412 visitInstruction(I);
1415 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1416 Type *SrcTy = I.getOperand(0)->getType();
1417 Type *DestTy = I.getType();
1419 Assert1(SrcTy->isPtrOrPtrVectorTy(),
1420 "AddrSpaceCast source must be a pointer", &I);
1421 Assert1(DestTy->isPtrOrPtrVectorTy(),
1422 "AddrSpaceCast result must be a pointer", &I);
1423 Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1424 "AddrSpaceCast must be between different address spaces", &I);
1425 if (SrcTy->isVectorTy())
1426 Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1427 "AddrSpaceCast vector pointer number of elements mismatch", &I);
1428 visitInstruction(I);
1431 /// visitPHINode - Ensure that a PHI node is well formed.
1433 void Verifier::visitPHINode(PHINode &PN) {
1434 // Ensure that the PHI nodes are all grouped together at the top of the block.
1435 // This can be tested by checking whether the instruction before this is
1436 // either nonexistent (because this is begin()) or is a PHI node. If not,
1437 // then there is some other instruction before a PHI.
1438 Assert2(&PN == &PN.getParent()->front() ||
1439 isa<PHINode>(--BasicBlock::iterator(&PN)),
1440 "PHI nodes not grouped at top of basic block!",
1441 &PN, PN.getParent());
1443 // Check that all of the values of the PHI node have the same type as the
1444 // result, and that the incoming blocks are really basic blocks.
1445 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1446 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1447 "PHI node operands are not the same type as the result!", &PN);
1450 // All other PHI node constraints are checked in the visitBasicBlock method.
1452 visitInstruction(PN);
1455 void Verifier::VerifyCallSite(CallSite CS) {
1456 Instruction *I = CS.getInstruction();
1458 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1459 "Called function must be a pointer!", I);
1460 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1462 Assert1(FPTy->getElementType()->isFunctionTy(),
1463 "Called function is not pointer to function type!", I);
1464 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1466 // Verify that the correct number of arguments are being passed
1467 if (FTy->isVarArg())
1468 Assert1(CS.arg_size() >= FTy->getNumParams(),
1469 "Called function requires more parameters than were provided!",I);
1471 Assert1(CS.arg_size() == FTy->getNumParams(),
1472 "Incorrect number of arguments passed to called function!", I);
1474 // Verify that all arguments to the call match the function type.
1475 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1476 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1477 "Call parameter type does not match function signature!",
1478 CS.getArgument(i), FTy->getParamType(i), I);
1480 AttributeSet Attrs = CS.getAttributes();
1482 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1483 "Attribute after last parameter!", I);
1485 // Verify call attributes.
1486 VerifyFunctionAttrs(FTy, Attrs, I);
1488 if (FTy->isVarArg()) {
1489 // FIXME? is 'nest' even legal here?
1490 bool SawNest = false;
1491 bool SawReturned = false;
1493 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1494 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1496 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1500 // Check attributes on the varargs part.
1501 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1502 Type *Ty = CS.getArgument(Idx-1)->getType();
1503 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1505 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1506 Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1510 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1511 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1513 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1514 "Incompatible argument and return types for 'returned' "
1519 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1520 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1522 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1523 Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!",
1528 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1529 if (CS.getCalledFunction() == 0 ||
1530 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1531 for (FunctionType::param_iterator PI = FTy->param_begin(),
1532 PE = FTy->param_end(); PI != PE; ++PI)
1533 Assert1(!(*PI)->isMetadataTy(),
1534 "Function has metadata parameter but isn't an intrinsic", I);
1537 visitInstruction(*I);
1540 void Verifier::visitCallInst(CallInst &CI) {
1541 VerifyCallSite(&CI);
1543 if (Function *F = CI.getCalledFunction())
1544 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1545 visitIntrinsicFunctionCall(ID, CI);
1548 void Verifier::visitInvokeInst(InvokeInst &II) {
1549 VerifyCallSite(&II);
1551 // Verify that there is a landingpad instruction as the first non-PHI
1552 // instruction of the 'unwind' destination.
1553 Assert1(II.getUnwindDest()->isLandingPad(),
1554 "The unwind destination does not have a landingpad instruction!",&II);
1556 visitTerminatorInst(II);
1559 /// visitBinaryOperator - Check that both arguments to the binary operator are
1560 /// of the same type!
1562 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1563 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1564 "Both operands to a binary operator are not of the same type!", &B);
1566 switch (B.getOpcode()) {
1567 // Check that integer arithmetic operators are only used with
1568 // integral operands.
1569 case Instruction::Add:
1570 case Instruction::Sub:
1571 case Instruction::Mul:
1572 case Instruction::SDiv:
1573 case Instruction::UDiv:
1574 case Instruction::SRem:
1575 case Instruction::URem:
1576 Assert1(B.getType()->isIntOrIntVectorTy(),
1577 "Integer arithmetic operators only work with integral types!", &B);
1578 Assert1(B.getType() == B.getOperand(0)->getType(),
1579 "Integer arithmetic operators must have same type "
1580 "for operands and result!", &B);
1582 // Check that floating-point arithmetic operators are only used with
1583 // floating-point operands.
1584 case Instruction::FAdd:
1585 case Instruction::FSub:
1586 case Instruction::FMul:
1587 case Instruction::FDiv:
1588 case Instruction::FRem:
1589 Assert1(B.getType()->isFPOrFPVectorTy(),
1590 "Floating-point arithmetic operators only work with "
1591 "floating-point types!", &B);
1592 Assert1(B.getType() == B.getOperand(0)->getType(),
1593 "Floating-point arithmetic operators must have same type "
1594 "for operands and result!", &B);
1596 // Check that logical operators are only used with integral operands.
1597 case Instruction::And:
1598 case Instruction::Or:
1599 case Instruction::Xor:
1600 Assert1(B.getType()->isIntOrIntVectorTy(),
1601 "Logical operators only work with integral types!", &B);
1602 Assert1(B.getType() == B.getOperand(0)->getType(),
1603 "Logical operators must have same type for operands and result!",
1606 case Instruction::Shl:
1607 case Instruction::LShr:
1608 case Instruction::AShr:
1609 Assert1(B.getType()->isIntOrIntVectorTy(),
1610 "Shifts only work with integral types!", &B);
1611 Assert1(B.getType() == B.getOperand(0)->getType(),
1612 "Shift return type must be same as operands!", &B);
1615 llvm_unreachable("Unknown BinaryOperator opcode!");
1618 visitInstruction(B);
1621 void Verifier::visitICmpInst(ICmpInst &IC) {
1622 // Check that the operands are the same type
1623 Type *Op0Ty = IC.getOperand(0)->getType();
1624 Type *Op1Ty = IC.getOperand(1)->getType();
1625 Assert1(Op0Ty == Op1Ty,
1626 "Both operands to ICmp instruction are not of the same type!", &IC);
1627 // Check that the operands are the right type
1628 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1629 "Invalid operand types for ICmp instruction", &IC);
1630 // Check that the predicate is valid.
1631 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1632 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1633 "Invalid predicate in ICmp instruction!", &IC);
1635 visitInstruction(IC);
1638 void Verifier::visitFCmpInst(FCmpInst &FC) {
1639 // Check that the operands are the same type
1640 Type *Op0Ty = FC.getOperand(0)->getType();
1641 Type *Op1Ty = FC.getOperand(1)->getType();
1642 Assert1(Op0Ty == Op1Ty,
1643 "Both operands to FCmp instruction are not of the same type!", &FC);
1644 // Check that the operands are the right type
1645 Assert1(Op0Ty->isFPOrFPVectorTy(),
1646 "Invalid operand types for FCmp instruction", &FC);
1647 // Check that the predicate is valid.
1648 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1649 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1650 "Invalid predicate in FCmp instruction!", &FC);
1652 visitInstruction(FC);
1655 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1656 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1658 "Invalid extractelement operands!", &EI);
1659 visitInstruction(EI);
1662 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1663 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1666 "Invalid insertelement operands!", &IE);
1667 visitInstruction(IE);
1670 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1671 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1673 "Invalid shufflevector operands!", &SV);
1674 visitInstruction(SV);
1677 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1678 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1680 Assert1(isa<PointerType>(TargetTy),
1681 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1682 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1683 "GEP into unsized type!", &GEP);
1684 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1685 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1688 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1690 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1691 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1693 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1694 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1695 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1697 if (GEP.getPointerOperandType()->isVectorTy()) {
1698 // Additional checks for vector GEPs.
1699 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1700 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1701 "Vector GEP result width doesn't match operand's", &GEP);
1702 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1703 Type *IndexTy = Idxs[i]->getType();
1704 Assert1(IndexTy->isVectorTy(),
1705 "Vector GEP must have vector indices!", &GEP);
1706 unsigned IndexWidth = IndexTy->getVectorNumElements();
1707 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1710 visitInstruction(GEP);
1713 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1714 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1717 void Verifier::visitLoadInst(LoadInst &LI) {
1718 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1719 Assert1(PTy, "Load operand must be a pointer.", &LI);
1720 Type *ElTy = PTy->getElementType();
1721 Assert2(ElTy == LI.getType(),
1722 "Load result type does not match pointer operand type!", &LI, ElTy);
1723 if (LI.isAtomic()) {
1724 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1725 "Load cannot have Release ordering", &LI);
1726 Assert1(LI.getAlignment() != 0,
1727 "Atomic load must specify explicit alignment", &LI);
1728 if (!ElTy->isPointerTy()) {
1729 Assert2(ElTy->isIntegerTy(),
1730 "atomic store operand must have integer type!",
1732 unsigned Size = ElTy->getPrimitiveSizeInBits();
1733 Assert2(Size >= 8 && !(Size & (Size - 1)),
1734 "atomic store operand must be power-of-two byte-sized integer",
1738 Assert1(LI.getSynchScope() == CrossThread,
1739 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1742 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1743 unsigned NumOperands = Range->getNumOperands();
1744 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1745 unsigned NumRanges = NumOperands / 2;
1746 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1748 ConstantRange LastRange(1); // Dummy initial value
1749 for (unsigned i = 0; i < NumRanges; ++i) {
1750 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1751 Assert1(Low, "The lower limit must be an integer!", Low);
1752 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1753 Assert1(High, "The upper limit must be an integer!", High);
1754 Assert1(High->getType() == Low->getType() &&
1755 High->getType() == ElTy, "Range types must match load type!",
1758 APInt HighV = High->getValue();
1759 APInt LowV = Low->getValue();
1760 ConstantRange CurRange(LowV, HighV);
1761 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1762 "Range must not be empty!", Range);
1764 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1765 "Intervals are overlapping", Range);
1766 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1768 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1771 LastRange = ConstantRange(LowV, HighV);
1773 if (NumRanges > 2) {
1775 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1777 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1778 ConstantRange FirstRange(FirstLow, FirstHigh);
1779 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1780 "Intervals are overlapping", Range);
1781 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1788 visitInstruction(LI);
1791 void Verifier::visitStoreInst(StoreInst &SI) {
1792 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1793 Assert1(PTy, "Store operand must be a pointer.", &SI);
1794 Type *ElTy = PTy->getElementType();
1795 Assert2(ElTy == SI.getOperand(0)->getType(),
1796 "Stored value type does not match pointer operand type!",
1798 if (SI.isAtomic()) {
1799 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1800 "Store cannot have Acquire ordering", &SI);
1801 Assert1(SI.getAlignment() != 0,
1802 "Atomic store must specify explicit alignment", &SI);
1803 if (!ElTy->isPointerTy()) {
1804 Assert2(ElTy->isIntegerTy(),
1805 "atomic store operand must have integer type!",
1807 unsigned Size = ElTy->getPrimitiveSizeInBits();
1808 Assert2(Size >= 8 && !(Size & (Size - 1)),
1809 "atomic store operand must be power-of-two byte-sized integer",
1813 Assert1(SI.getSynchScope() == CrossThread,
1814 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1816 visitInstruction(SI);
1819 void Verifier::visitAllocaInst(AllocaInst &AI) {
1820 SmallPtrSet<const Type*, 4> Visited;
1821 PointerType *PTy = AI.getType();
1822 Assert1(PTy->getAddressSpace() == 0,
1823 "Allocation instruction pointer not in the generic address space!",
1825 Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
1827 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1828 "Alloca array size must have integer type", &AI);
1830 visitInstruction(AI);
1833 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1835 // FIXME: more conditions???
1836 Assert1(CXI.getSuccessOrdering() != NotAtomic,
1837 "cmpxchg instructions must be atomic.", &CXI);
1838 Assert1(CXI.getFailureOrdering() != NotAtomic,
1839 "cmpxchg instructions must be atomic.", &CXI);
1840 Assert1(CXI.getSuccessOrdering() != Unordered,
1841 "cmpxchg instructions cannot be unordered.", &CXI);
1842 Assert1(CXI.getFailureOrdering() != Unordered,
1843 "cmpxchg instructions cannot be unordered.", &CXI);
1844 Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
1845 "cmpxchg instructions be at least as constrained on success as fail",
1847 Assert1(CXI.getFailureOrdering() != Release &&
1848 CXI.getFailureOrdering() != AcquireRelease,
1849 "cmpxchg failure ordering cannot include release semantics", &CXI);
1851 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1852 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1853 Type *ElTy = PTy->getElementType();
1854 Assert2(ElTy->isIntegerTy(),
1855 "cmpxchg operand must have integer type!",
1857 unsigned Size = ElTy->getPrimitiveSizeInBits();
1858 Assert2(Size >= 8 && !(Size & (Size - 1)),
1859 "cmpxchg operand must be power-of-two byte-sized integer",
1861 Assert2(ElTy == CXI.getOperand(1)->getType(),
1862 "Expected value type does not match pointer operand type!",
1864 Assert2(ElTy == CXI.getOperand(2)->getType(),
1865 "Stored value type does not match pointer operand type!",
1867 visitInstruction(CXI);
1870 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1871 Assert1(RMWI.getOrdering() != NotAtomic,
1872 "atomicrmw instructions must be atomic.", &RMWI);
1873 Assert1(RMWI.getOrdering() != Unordered,
1874 "atomicrmw instructions cannot be unordered.", &RMWI);
1875 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1876 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1877 Type *ElTy = PTy->getElementType();
1878 Assert2(ElTy->isIntegerTy(),
1879 "atomicrmw operand must have integer type!",
1881 unsigned Size = ElTy->getPrimitiveSizeInBits();
1882 Assert2(Size >= 8 && !(Size & (Size - 1)),
1883 "atomicrmw operand must be power-of-two byte-sized integer",
1885 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1886 "Argument value type does not match pointer operand type!",
1888 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1889 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1890 "Invalid binary operation!", &RMWI);
1891 visitInstruction(RMWI);
1894 void Verifier::visitFenceInst(FenceInst &FI) {
1895 const AtomicOrdering Ordering = FI.getOrdering();
1896 Assert1(Ordering == Acquire || Ordering == Release ||
1897 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1898 "fence instructions may only have "
1899 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1900 visitInstruction(FI);
1903 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1904 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1905 EVI.getIndices()) ==
1907 "Invalid ExtractValueInst operands!", &EVI);
1909 visitInstruction(EVI);
1912 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1913 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1914 IVI.getIndices()) ==
1915 IVI.getOperand(1)->getType(),
1916 "Invalid InsertValueInst operands!", &IVI);
1918 visitInstruction(IVI);
1921 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1922 BasicBlock *BB = LPI.getParent();
1924 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1926 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1927 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1929 // The landingpad instruction defines its parent as a landing pad block. The
1930 // landing pad block may be branched to only by the unwind edge of an invoke.
1931 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1932 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1933 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1934 "Block containing LandingPadInst must be jumped to "
1935 "only by the unwind edge of an invoke.", &LPI);
1938 // The landingpad instruction must be the first non-PHI instruction in the
1940 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1941 "LandingPadInst not the first non-PHI instruction in the block.",
1944 // The personality functions for all landingpad instructions within the same
1945 // function should match.
1947 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1948 "Personality function doesn't match others in function", &LPI);
1949 PersonalityFn = LPI.getPersonalityFn();
1951 // All operands must be constants.
1952 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1954 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1955 Value *Clause = LPI.getClause(i);
1956 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1957 if (LPI.isCatch(i)) {
1958 Assert1(isa<PointerType>(Clause->getType()),
1959 "Catch operand does not have pointer type!", &LPI);
1961 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1962 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1963 "Filter operand is not an array of constants!", &LPI);
1967 visitInstruction(LPI);
1970 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1971 Instruction *Op = cast<Instruction>(I.getOperand(i));
1972 // If the we have an invalid invoke, don't try to compute the dominance.
1973 // We already reject it in the invoke specific checks and the dominance
1974 // computation doesn't handle multiple edges.
1975 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1976 if (II->getNormalDest() == II->getUnwindDest())
1980 const Use &U = I.getOperandUse(i);
1981 Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
1982 "Instruction does not dominate all uses!", Op, &I);
1985 /// verifyInstruction - Verify that an instruction is well formed.
1987 void Verifier::visitInstruction(Instruction &I) {
1988 BasicBlock *BB = I.getParent();
1989 Assert1(BB, "Instruction not embedded in basic block!", &I);
1991 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1992 for (User *U : I.users()) {
1993 Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB),
1994 "Only PHI nodes may reference their own value!", &I);
1998 // Check that void typed values don't have names
1999 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2000 "Instruction has a name, but provides a void value!", &I);
2002 // Check that the return value of the instruction is either void or a legal
2004 Assert1(I.getType()->isVoidTy() ||
2005 I.getType()->isFirstClassType(),
2006 "Instruction returns a non-scalar type!", &I);
2008 // Check that the instruction doesn't produce metadata. Calls are already
2009 // checked against the callee type.
2010 Assert1(!I.getType()->isMetadataTy() ||
2011 isa<CallInst>(I) || isa<InvokeInst>(I),
2012 "Invalid use of metadata!", &I);
2014 // Check that all uses of the instruction, if they are instructions
2015 // themselves, actually have parent basic blocks. If the use is not an
2016 // instruction, it is an error!
2017 for (Use &U : I.uses()) {
2018 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2019 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
2020 " embedded in a basic block!", &I, Used);
2022 CheckFailed("Use of instruction is not an instruction!", U);
2027 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2028 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
2030 // Check to make sure that only first-class-values are operands to
2032 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2033 Assert1(0, "Instruction operands must be first-class values!", &I);
2036 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2037 // Check to make sure that the "address of" an intrinsic function is never
2039 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2040 "Cannot take the address of an intrinsic!", &I);
2041 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2042 F->getIntrinsicID() == Intrinsic::donothing,
2043 "Cannot invoke an intrinsinc other than donothing", &I);
2044 Assert1(F->getParent() == M, "Referencing function in another module!",
2046 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2047 Assert1(OpBB->getParent() == BB->getParent(),
2048 "Referring to a basic block in another function!", &I);
2049 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2050 Assert1(OpArg->getParent() == BB->getParent(),
2051 "Referring to an argument in another function!", &I);
2052 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2053 Assert1(GV->getParent() == M, "Referencing global in another module!",
2055 } else if (isa<Instruction>(I.getOperand(i))) {
2056 verifyDominatesUse(I, i);
2057 } else if (isa<InlineAsm>(I.getOperand(i))) {
2058 Assert1((i + 1 == e && isa<CallInst>(I)) ||
2059 (i + 3 == e && isa<InvokeInst>(I)),
2060 "Cannot take the address of an inline asm!", &I);
2061 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2062 if (CE->getType()->isPtrOrPtrVectorTy()) {
2063 // If we have a ConstantExpr pointer, we need to see if it came from an
2064 // illegal bitcast (inttoptr <constant int> )
2065 SmallVector<const ConstantExpr *, 4> Stack;
2066 SmallPtrSet<const ConstantExpr *, 4> Visited;
2067 Stack.push_back(CE);
2069 while (!Stack.empty()) {
2070 const ConstantExpr *V = Stack.pop_back_val();
2071 if (!Visited.insert(V))
2074 VerifyConstantExprBitcastType(V);
2076 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2077 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2078 Stack.push_back(Op);
2085 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2086 Assert1(I.getType()->isFPOrFPVectorTy(),
2087 "fpmath requires a floating point result!", &I);
2088 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2089 Value *Op0 = MD->getOperand(0);
2090 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2091 APFloat Accuracy = CFP0->getValueAPF();
2092 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2093 "fpmath accuracy not a positive number!", &I);
2095 Assert1(false, "invalid fpmath accuracy!", &I);
2099 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2100 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2102 if (!DisableDebugInfoVerifier) {
2103 MD = I.getMetadata(LLVMContext::MD_dbg);
2104 Finder.processLocation(*M, DILocation(MD));
2107 InstsInThisBlock.insert(&I);
2110 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2111 /// intrinsic argument or return value) matches the type constraints specified
2112 /// by the .td file (e.g. an "any integer" argument really is an integer).
2114 /// This return true on error but does not print a message.
2115 bool Verifier::VerifyIntrinsicType(Type *Ty,
2116 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2117 SmallVectorImpl<Type*> &ArgTys) {
2118 using namespace Intrinsic;
2120 // If we ran out of descriptors, there are too many arguments.
2121 if (Infos.empty()) return true;
2122 IITDescriptor D = Infos.front();
2123 Infos = Infos.slice(1);
2126 case IITDescriptor::Void: return !Ty->isVoidTy();
2127 case IITDescriptor::VarArg: return true;
2128 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2129 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2130 case IITDescriptor::Half: return !Ty->isHalfTy();
2131 case IITDescriptor::Float: return !Ty->isFloatTy();
2132 case IITDescriptor::Double: return !Ty->isDoubleTy();
2133 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2134 case IITDescriptor::Vector: {
2135 VectorType *VT = dyn_cast<VectorType>(Ty);
2136 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
2137 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2139 case IITDescriptor::Pointer: {
2140 PointerType *PT = dyn_cast<PointerType>(Ty);
2141 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2142 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2145 case IITDescriptor::Struct: {
2146 StructType *ST = dyn_cast<StructType>(Ty);
2147 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2150 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2151 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2156 case IITDescriptor::Argument:
2157 // Two cases here - If this is the second occurrence of an argument, verify
2158 // that the later instance matches the previous instance.
2159 if (D.getArgumentNumber() < ArgTys.size())
2160 return Ty != ArgTys[D.getArgumentNumber()];
2162 // Otherwise, if this is the first instance of an argument, record it and
2163 // verify the "Any" kind.
2164 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2165 ArgTys.push_back(Ty);
2167 switch (D.getArgumentKind()) {
2168 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2169 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2170 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2171 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2173 llvm_unreachable("all argument kinds not covered");
2175 case IITDescriptor::ExtendVecArgument:
2176 // This may only be used when referring to a previous vector argument.
2177 return D.getArgumentNumber() >= ArgTys.size() ||
2178 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2179 VectorType::getExtendedElementVectorType(
2180 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2182 case IITDescriptor::TruncVecArgument:
2183 // This may only be used when referring to a previous vector argument.
2184 return D.getArgumentNumber() >= ArgTys.size() ||
2185 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2186 VectorType::getTruncatedElementVectorType(
2187 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2189 llvm_unreachable("unhandled");
2192 /// \brief Verify if the intrinsic has variable arguments.
2193 /// This method is intended to be called after all the fixed arguments have been
2196 /// This method returns true on error and does not print an error message.
2198 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2199 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2200 using namespace Intrinsic;
2202 // If there are no descriptors left, then it can't be a vararg.
2204 return isVarArg ? true : false;
2206 // There should be only one descriptor remaining at this point.
2207 if (Infos.size() != 1)
2210 // Check and verify the descriptor.
2211 IITDescriptor D = Infos.front();
2212 Infos = Infos.slice(1);
2213 if (D.Kind == IITDescriptor::VarArg)
2214 return isVarArg ? false : true;
2219 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2221 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2222 Function *IF = CI.getCalledFunction();
2223 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2226 // Verify that the intrinsic prototype lines up with what the .td files
2228 FunctionType *IFTy = IF->getFunctionType();
2229 bool IsVarArg = IFTy->isVarArg();
2231 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2232 getIntrinsicInfoTableEntries(ID, Table);
2233 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2235 SmallVector<Type *, 4> ArgTys;
2236 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2237 "Intrinsic has incorrect return type!", IF);
2238 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2239 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2240 "Intrinsic has incorrect argument type!", IF);
2242 // Verify if the intrinsic call matches the vararg property.
2244 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2245 "Intrinsic was not defined with variable arguments!", IF);
2247 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2248 "Callsite was not defined with variable arguments!", IF);
2250 // All descriptors should be absorbed by now.
2251 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2253 // Now that we have the intrinsic ID and the actual argument types (and we
2254 // know they are legal for the intrinsic!) get the intrinsic name through the
2255 // usual means. This allows us to verify the mangling of argument types into
2257 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2258 Assert1(ExpectedName == IF->getName(),
2259 "Intrinsic name not mangled correctly for type arguments! "
2260 "Should be: " + ExpectedName, IF);
2262 // If the intrinsic takes MDNode arguments, verify that they are either global
2263 // or are local to *this* function.
2264 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2265 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2266 visitMDNode(*MD, CI.getParent()->getParent());
2271 case Intrinsic::ctlz: // llvm.ctlz
2272 case Intrinsic::cttz: // llvm.cttz
2273 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2274 "is_zero_undef argument of bit counting intrinsics must be a "
2275 "constant int", &CI);
2277 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2278 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2279 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2280 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2281 Assert1(MD->getNumOperands() == 1,
2282 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2283 if (!DisableDebugInfoVerifier)
2284 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
2286 case Intrinsic::dbg_value: { //llvm.dbg.value
2287 if (!DisableDebugInfoVerifier) {
2288 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2289 "invalid llvm.dbg.value intrinsic call 1", &CI);
2290 Finder.processValue(*M, cast<DbgValueInst>(&CI));
2294 case Intrinsic::memcpy:
2295 case Intrinsic::memmove:
2296 case Intrinsic::memset:
2297 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2298 "alignment argument of memory intrinsics must be a constant int",
2300 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2301 "isvolatile argument of memory intrinsics must be a constant int",
2304 case Intrinsic::gcroot:
2305 case Intrinsic::gcwrite:
2306 case Intrinsic::gcread:
2307 if (ID == Intrinsic::gcroot) {
2309 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2310 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2311 Assert1(isa<Constant>(CI.getArgOperand(1)),
2312 "llvm.gcroot parameter #2 must be a constant.", &CI);
2313 if (!AI->getType()->getElementType()->isPointerTy()) {
2314 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2315 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2316 "or argument #2 must be a non-null constant.", &CI);
2320 Assert1(CI.getParent()->getParent()->hasGC(),
2321 "Enclosing function does not use GC.", &CI);
2323 case Intrinsic::init_trampoline:
2324 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2325 "llvm.init_trampoline parameter #2 must resolve to a function.",
2328 case Intrinsic::prefetch:
2329 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2330 isa<ConstantInt>(CI.getArgOperand(2)) &&
2331 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2332 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2333 "invalid arguments to llvm.prefetch",
2336 case Intrinsic::stackprotector:
2337 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2338 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2341 case Intrinsic::lifetime_start:
2342 case Intrinsic::lifetime_end:
2343 case Intrinsic::invariant_start:
2344 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2345 "size argument of memory use markers must be a constant integer",
2348 case Intrinsic::invariant_end:
2349 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2350 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2355 void Verifier::verifyDebugInfo() {
2356 // Verify Debug Info.
2357 if (!DisableDebugInfoVerifier) {
2358 for (DICompileUnit CU : Finder.compile_units()) {
2359 Assert1(CU.Verify(), "DICompileUnit does not Verify!", CU);
2361 for (DISubprogram S : Finder.subprograms()) {
2362 Assert1(S.Verify(), "DISubprogram does not Verify!", S);
2364 for (DIGlobalVariable GV : Finder.global_variables()) {
2365 Assert1(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
2367 for (DIType T : Finder.types()) {
2368 Assert1(T.Verify(), "DIType does not Verify!", T);
2370 for (DIScope S : Finder.scopes()) {
2371 Assert1(S.Verify(), "DIScope does not Verify!", S);
2376 //===----------------------------------------------------------------------===//
2377 // Implement the public interfaces to this file...
2378 //===----------------------------------------------------------------------===//
2380 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
2381 Function &F = const_cast<Function &>(f);
2382 assert(!F.isDeclaration() && "Cannot verify external functions");
2384 raw_null_ostream NullStr;
2385 Verifier V(OS ? *OS : NullStr);
2387 // Note that this function's return value is inverted from what you would
2388 // expect of a function called "verify".
2389 return !V.verify(F);
2392 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
2393 raw_null_ostream NullStr;
2394 Verifier V(OS ? *OS : NullStr);
2396 bool Broken = false;
2397 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
2398 if (!I->isDeclaration())
2399 Broken |= !V.verify(*I);
2401 // Note that this function's return value is inverted from what you would
2402 // expect of a function called "verify".
2403 return !V.verify(M) || Broken;
2407 struct VerifierLegacyPass : public FunctionPass {
2413 VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) {
2414 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2416 explicit VerifierLegacyPass(bool FatalErrors)
2417 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
2418 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
2421 bool runOnFunction(Function &F) override {
2422 if (!V.verify(F) && FatalErrors)
2423 report_fatal_error("Broken function found, compilation aborted!");
2428 bool doFinalization(Module &M) override {
2429 if (!V.verify(M) && FatalErrors)
2430 report_fatal_error("Broken module found, compilation aborted!");
2435 void getAnalysisUsage(AnalysisUsage &AU) const override {
2436 AU.setPreservesAll();
2441 char VerifierLegacyPass::ID = 0;
2442 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
2444 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
2445 return new VerifierLegacyPass(FatalErrors);
2448 PreservedAnalyses VerifierPass::run(Module *M) {
2449 if (verifyModule(*M, &dbgs()) && FatalErrors)
2450 report_fatal_error("Broken module found, compilation aborted!");
2452 return PreservedAnalyses::all();
2455 PreservedAnalyses VerifierPass::run(Function *F) {
2456 if (verifyFunction(*F, &dbgs()) && FatalErrors)
2457 report_fatal_error("Broken function found, compilation aborted!");
2459 return PreservedAnalyses::all();