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/Analysis/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/Analysis/Dominators.h"
55 #include "llvm/Assembly/Writer.h"
56 #include "llvm/DebugInfo.h"
57 #include "llvm/IR/CallingConv.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DerivedTypes.h"
60 #include "llvm/IR/InlineAsm.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/Metadata.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/InstVisitor.h"
66 #include "llvm/Pass.h"
67 #include "llvm/PassManager.h"
68 #include "llvm/Support/CFG.h"
69 #include "llvm/Support/CallSite.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/ConstantRange.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",
82 namespace { // Anonymous namespace for class
83 struct PreVerifier : public FunctionPass {
84 static char ID; // Pass ID, replacement for typeid
86 PreVerifier() : FunctionPass(ID) {
87 initializePreVerifierPass(*PassRegistry::getPassRegistry());
90 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
94 // Check that the prerequisites for successful DominatorTree construction
96 bool runOnFunction(Function &F) {
99 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
100 if (I->empty() || !I->back().isTerminator()) {
101 dbgs() << "Basic Block in function '" << F.getName()
102 << "' does not have terminator!\n";
103 WriteAsOperand(dbgs(), I, true);
110 report_fatal_error("Broken module, no Basic Block terminator!");
117 char PreVerifier::ID = 0;
118 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
120 static char &PreVerifyID = PreVerifier::ID;
123 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
124 static char ID; // Pass ID, replacement for typeid
125 bool Broken; // Is this module found to be broken?
126 VerifierFailureAction action;
127 // What to do if verification fails.
128 Module *Mod; // Module we are verifying right now
129 LLVMContext *Context; // Context within which we are verifying
130 DominatorTree *DT; // Dominator Tree, caution can be null!
132 std::string Messages;
133 raw_string_ostream MessagesStr;
135 /// InstInThisBlock - when verifying a basic block, keep track of all of the
136 /// instructions we have seen so far. This allows us to do efficient
137 /// dominance checks for the case when an instruction has an operand that is
138 /// an instruction in the same block.
139 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
141 /// MDNodes - keep track of the metadata nodes that have been checked
143 SmallPtrSet<MDNode *, 32> MDNodes;
145 /// PersonalityFn - The personality function referenced by the
146 /// LandingPadInsts. All LandingPadInsts within the same function must use
147 /// the same personality function.
148 const Value *PersonalityFn;
150 /// Finder keeps track of all debug info MDNodes in a Module.
151 DebugInfoFinder Finder;
154 : FunctionPass(ID), Broken(false),
155 action(AbortProcessAction), Mod(0), Context(0), DT(0),
156 MessagesStr(Messages), PersonalityFn(0) {
157 initializeVerifierPass(*PassRegistry::getPassRegistry());
159 explicit Verifier(VerifierFailureAction ctn)
160 : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
161 Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
162 initializeVerifierPass(*PassRegistry::getPassRegistry());
165 bool doInitialization(Module &M) {
167 Context = &M.getContext();
170 // We must abort before returning back to the pass manager, or else the
171 // pass manager may try to run other passes on the broken module.
172 return abortIfBroken();
175 bool runOnFunction(Function &F) {
176 // Get dominator information if we are being run by PassManager
177 DT = &getAnalysis<DominatorTree>();
180 if (!Context) Context = &F.getContext();
183 InstsInThisBlock.clear();
186 // We must abort before returning back to the pass manager, or else the
187 // pass manager may try to run other passes on the broken module.
188 return abortIfBroken();
191 bool doFinalization(Module &M) {
192 // Scan through, checking all of the external function's linkage now...
193 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
194 visitGlobalValue(*I);
196 // Check to make sure function prototypes are okay.
197 if (I->isDeclaration()) visitFunction(*I);
200 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
202 visitGlobalVariable(*I);
204 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
206 visitGlobalAlias(*I);
208 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
209 E = M.named_metadata_end(); I != E; ++I)
210 visitNamedMDNode(*I);
214 // Verify Debug Info.
217 // If the module is broken, abort at this time.
218 return abortIfBroken();
221 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
222 AU.setPreservesAll();
223 AU.addRequiredID(PreVerifyID);
224 AU.addRequired<DominatorTree>();
227 /// abortIfBroken - If the module is broken and we are supposed to abort on
228 /// this condition, do so.
230 bool abortIfBroken() {
231 if (!Broken) return false;
232 MessagesStr << "Broken module found, ";
234 case AbortProcessAction:
235 MessagesStr << "compilation aborted!\n";
236 dbgs() << MessagesStr.str();
237 // Client should choose different reaction if abort is not desired
239 case PrintMessageAction:
240 MessagesStr << "verification continues.\n";
241 dbgs() << MessagesStr.str();
243 case ReturnStatusAction:
244 MessagesStr << "compilation terminated.\n";
247 llvm_unreachable("Invalid action");
251 // Verification methods...
252 void visitGlobalValue(GlobalValue &GV);
253 void visitGlobalVariable(GlobalVariable &GV);
254 void visitGlobalAlias(GlobalAlias &GA);
255 void visitNamedMDNode(NamedMDNode &NMD);
256 void visitMDNode(MDNode &MD, Function *F);
257 void visitModuleFlags(Module &M);
258 void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
259 SmallVectorImpl<MDNode*> &Requirements);
260 void visitFunction(Function &F);
261 void visitBasicBlock(BasicBlock &BB);
262 using InstVisitor<Verifier>::visit;
264 void visit(Instruction &I);
266 void visitTruncInst(TruncInst &I);
267 void visitZExtInst(ZExtInst &I);
268 void visitSExtInst(SExtInst &I);
269 void visitFPTruncInst(FPTruncInst &I);
270 void visitFPExtInst(FPExtInst &I);
271 void visitFPToUIInst(FPToUIInst &I);
272 void visitFPToSIInst(FPToSIInst &I);
273 void visitUIToFPInst(UIToFPInst &I);
274 void visitSIToFPInst(SIToFPInst &I);
275 void visitIntToPtrInst(IntToPtrInst &I);
276 void visitPtrToIntInst(PtrToIntInst &I);
277 void visitBitCastInst(BitCastInst &I);
278 void visitPHINode(PHINode &PN);
279 void visitBinaryOperator(BinaryOperator &B);
280 void visitICmpInst(ICmpInst &IC);
281 void visitFCmpInst(FCmpInst &FC);
282 void visitExtractElementInst(ExtractElementInst &EI);
283 void visitInsertElementInst(InsertElementInst &EI);
284 void visitShuffleVectorInst(ShuffleVectorInst &EI);
285 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
286 void visitCallInst(CallInst &CI);
287 void visitInvokeInst(InvokeInst &II);
288 void visitGetElementPtrInst(GetElementPtrInst &GEP);
289 void visitLoadInst(LoadInst &LI);
290 void visitStoreInst(StoreInst &SI);
291 void verifyDominatesUse(Instruction &I, unsigned i);
292 void visitInstruction(Instruction &I);
293 void visitTerminatorInst(TerminatorInst &I);
294 void visitBranchInst(BranchInst &BI);
295 void visitReturnInst(ReturnInst &RI);
296 void visitSwitchInst(SwitchInst &SI);
297 void visitIndirectBrInst(IndirectBrInst &BI);
298 void visitSelectInst(SelectInst &SI);
299 void visitUserOp1(Instruction &I);
300 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
301 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
302 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
303 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
304 void visitFenceInst(FenceInst &FI);
305 void visitAllocaInst(AllocaInst &AI);
306 void visitExtractValueInst(ExtractValueInst &EVI);
307 void visitInsertValueInst(InsertValueInst &IVI);
308 void visitLandingPadInst(LandingPadInst &LPI);
310 void VerifyCallSite(CallSite CS);
311 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
312 int VT, unsigned ArgNo, std::string &Suffix);
313 bool VerifyIntrinsicType(Type *Ty,
314 ArrayRef<Intrinsic::IITDescriptor> &Infos,
315 SmallVectorImpl<Type*> &ArgTys);
316 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
317 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
318 bool isFunction, const Value *V);
319 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
320 bool isReturnValue, const Value *V);
321 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
324 void verifyDebugInfo(Module &M);
326 void WriteValue(const Value *V) {
328 if (isa<Instruction>(V)) {
329 MessagesStr << *V << '\n';
331 WriteAsOperand(MessagesStr, V, true, Mod);
336 void WriteType(Type *T) {
338 MessagesStr << ' ' << *T;
342 // CheckFailed - A check failed, so print out the condition and the message
343 // that failed. This provides a nice place to put a breakpoint if you want
344 // to see why something is not correct.
345 void CheckFailed(const Twine &Message,
346 const Value *V1 = 0, const Value *V2 = 0,
347 const Value *V3 = 0, const Value *V4 = 0) {
348 MessagesStr << Message.str() << "\n";
356 void CheckFailed(const Twine &Message, const Value *V1,
357 Type *T2, const Value *V3 = 0) {
358 MessagesStr << Message.str() << "\n";
365 void CheckFailed(const Twine &Message, Type *T1,
366 Type *T2 = 0, Type *T3 = 0) {
367 MessagesStr << Message.str() << "\n";
374 } // End anonymous namespace
376 char Verifier::ID = 0;
377 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
378 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
379 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
380 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
382 // Assert - We know that cond should be true, if not print an error message.
383 #define Assert(C, M) \
384 do { if (!(C)) { CheckFailed(M); return; } } while (0)
385 #define Assert1(C, M, V1) \
386 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
387 #define Assert2(C, M, V1, V2) \
388 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
389 #define Assert3(C, M, V1, V2, V3) \
390 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
391 #define Assert4(C, M, V1, V2, V3, V4) \
392 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
394 void Verifier::visit(Instruction &I) {
395 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
396 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
397 InstVisitor<Verifier>::visit(I);
401 void Verifier::visitGlobalValue(GlobalValue &GV) {
402 Assert1(!GV.isDeclaration() ||
403 GV.isMaterializable() ||
404 GV.hasExternalLinkage() ||
405 GV.hasDLLImportLinkage() ||
406 GV.hasExternalWeakLinkage() ||
407 (isa<GlobalAlias>(GV) &&
408 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
409 "Global is external, but doesn't have external or dllimport or weak linkage!",
412 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
413 "Global is marked as dllimport, but not external", &GV);
415 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
416 "Only global variables can have appending linkage!", &GV);
418 if (GV.hasAppendingLinkage()) {
419 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
420 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
421 "Only global arrays can have appending linkage!", GVar);
424 Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
425 "linkonce_odr_auto_hide can only have default visibility!",
429 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
430 if (GV.hasInitializer()) {
431 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
432 "Global variable initializer type does not match global "
433 "variable type!", &GV);
435 // If the global has common linkage, it must have a zero initializer and
436 // cannot be constant.
437 if (GV.hasCommonLinkage()) {
438 Assert1(GV.getInitializer()->isNullValue(),
439 "'common' global must have a zero initializer!", &GV);
440 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
444 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
445 GV.hasExternalWeakLinkage(),
446 "invalid linkage type for global declaration", &GV);
449 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
450 GV.getName() == "llvm.global_dtors")) {
451 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
452 "invalid linkage for intrinsic global variable", &GV);
453 // Don't worry about emitting an error for it not being an array,
454 // visitGlobalValue will complain on appending non-array.
455 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
456 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
457 PointerType *FuncPtrTy =
458 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
459 Assert1(STy && STy->getNumElements() == 2 &&
460 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
461 STy->getTypeAtIndex(1) == FuncPtrTy,
462 "wrong type for intrinsic global variable", &GV);
466 if (GV.hasName() && (GV.getName() == "llvm.used" ||
467 GV.getName() == "llvm.compiler.used")) {
468 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
469 "invalid linkage for intrinsic global variable", &GV);
470 Type *GVType = GV.getType()->getElementType();
471 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
472 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
473 Assert1(PTy, "wrong type for intrinsic global variable", &GV);
474 if (GV.hasInitializer()) {
475 Constant *Init = GV.getInitializer();
476 ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
477 Assert1(InitArray, "wrong initalizer for intrinsic global variable",
479 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
480 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
482 isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
483 "invalid llvm.used member", V);
484 Assert1(V->hasName(), "members of llvm.used must be named", V);
490 visitGlobalValue(GV);
493 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
494 Assert1(!GA.getName().empty(),
495 "Alias name cannot be empty!", &GA);
496 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
498 "Alias should have external or external weak linkage!", &GA);
499 Assert1(GA.getAliasee(),
500 "Aliasee cannot be NULL!", &GA);
501 Assert1(GA.getType() == GA.getAliasee()->getType(),
502 "Alias and aliasee types should match!", &GA);
503 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
505 Constant *Aliasee = GA.getAliasee();
507 if (!isa<GlobalValue>(Aliasee)) {
508 ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
510 (CE->getOpcode() == Instruction::BitCast ||
511 CE->getOpcode() == Instruction::GetElementPtr) &&
512 isa<GlobalValue>(CE->getOperand(0)),
513 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
516 if (CE->getOpcode() == Instruction::BitCast) {
517 unsigned SrcAS = CE->getOperand(0)->getType()->getPointerAddressSpace();
518 unsigned DstAS = CE->getType()->getPointerAddressSpace();
520 Assert1(SrcAS == DstAS,
521 "Alias bitcasts cannot be between different address spaces",
526 const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
528 "Aliasing chain should end with function or global variable", &GA);
530 visitGlobalValue(GA);
533 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
534 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
535 MDNode *MD = NMD.getOperand(i);
539 Assert1(!MD->isFunctionLocal(),
540 "Named metadata operand cannot be function local!", MD);
545 void Verifier::visitMDNode(MDNode &MD, Function *F) {
546 // Only visit each node once. Metadata can be mutually recursive, so this
547 // avoids infinite recursion here, as well as being an optimization.
548 if (!MDNodes.insert(&MD))
551 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
552 Value *Op = MD.getOperand(i);
555 if (isa<Constant>(Op) || isa<MDString>(Op))
557 if (MDNode *N = dyn_cast<MDNode>(Op)) {
558 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
559 "Global metadata operand cannot be function local!", &MD, N);
563 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
565 // If this was an instruction, bb, or argument, verify that it is in the
566 // function that we expect.
567 Function *ActualF = 0;
568 if (Instruction *I = dyn_cast<Instruction>(Op))
569 ActualF = I->getParent()->getParent();
570 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
571 ActualF = BB->getParent();
572 else if (Argument *A = dyn_cast<Argument>(Op))
573 ActualF = A->getParent();
574 assert(ActualF && "Unimplemented function local metadata case!");
576 Assert2(ActualF == F, "function-local metadata used in wrong function",
581 void Verifier::visitModuleFlags(Module &M) {
582 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
585 // Scan each flag, and track the flags and requirements.
586 DenseMap<MDString*, MDNode*> SeenIDs;
587 SmallVector<MDNode*, 16> Requirements;
588 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
589 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
592 // Validate that the requirements in the module are valid.
593 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
594 MDNode *Requirement = Requirements[I];
595 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
596 Value *ReqValue = Requirement->getOperand(1);
598 MDNode *Op = SeenIDs.lookup(Flag);
600 CheckFailed("invalid requirement on flag, flag is not present in module",
605 if (Op->getOperand(2) != ReqValue) {
606 CheckFailed(("invalid requirement on flag, "
607 "flag does not have the required value"),
614 void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
615 SmallVectorImpl<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) {
722 CheckFailed("Attribute '" + I->getAsString() +
723 "' only applies to functions!", V);
726 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
727 I->getKindAsEnum() == Attribute::ReadNone) {
729 CheckFailed("Attribute '" + I->getAsString() +
730 "' does not apply to function returns");
733 } else if (isFunction) {
734 CheckFailed("Attribute '" + I->getAsString() +
735 "' does not apply to functions!", V);
741 // VerifyParameterAttrs - Check the given attributes for an argument or return
742 // value of the specified type. The value V is printed in error messages.
743 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
744 bool isReturnValue, const Value *V) {
745 if (!Attrs.hasAttributes(Idx))
748 VerifyAttributeTypes(Attrs, Idx, false, V);
751 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
752 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
753 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
754 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
755 !Attrs.hasAttribute(Idx, Attribute::Returned),
756 "Attribute 'byval', 'nest', 'sret', 'nocapture', and 'returned' "
757 "do not apply to return values!", V);
759 // Check for mutually incompatible attributes.
760 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
761 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
762 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
763 Attrs.hasAttribute(Idx, Attribute::StructRet)) ||
764 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
765 Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes "
766 "'byval, nest, and sret' are incompatible!", V);
768 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
769 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
770 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
771 Attrs.hasAttribute(Idx, Attribute::InReg)) ||
772 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
773 Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes "
774 "'byval, nest, and inreg' 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 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) ||
799 PTy->getElementType()->isSized(),
800 "Attribute 'byval' does not support unsized types!", V);
802 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
803 "Attribute 'byval' only applies to parameters with pointer type!",
807 // VerifyFunctionAttrs - Check parameter attributes against a function type.
808 // The value V is printed in error messages.
809 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
814 bool SawNest = false;
815 bool SawReturned = false;
817 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
818 unsigned Idx = Attrs.getSlotIndex(i);
822 Ty = FT->getReturnType();
823 else if (Idx-1 < FT->getNumParams())
824 Ty = FT->getParamType(Idx-1);
826 break; // VarArgs attributes, verified elsewhere.
828 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
833 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
834 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
838 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
839 Assert1(!SawReturned, "More than one parameter has attribute returned!",
841 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
842 "argument and return types for 'returned' attribute", V);
846 if (Attrs.hasAttribute(Idx, Attribute::StructRet))
847 Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
850 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
853 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
855 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
856 Attribute::ReadNone) &&
857 Attrs.hasAttribute(AttributeSet::FunctionIndex,
858 Attribute::ReadOnly)),
859 "Attributes 'readnone and readonly' are incompatible!", V);
861 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
862 Attribute::NoInline) &&
863 Attrs.hasAttribute(AttributeSet::FunctionIndex,
864 Attribute::AlwaysInline)),
865 "Attributes 'noinline and alwaysinline' are incompatible!", V);
868 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
869 if (Attrs.getNumSlots() == 0)
872 unsigned LastSlot = Attrs.getNumSlots() - 1;
873 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
874 if (LastIndex <= Params
875 || (LastIndex == AttributeSet::FunctionIndex
876 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
882 // visitFunction - Verify that a function is ok.
884 void Verifier::visitFunction(Function &F) {
885 // Check function arguments.
886 FunctionType *FT = F.getFunctionType();
887 unsigned NumArgs = F.arg_size();
889 Assert1(Context == &F.getContext(),
890 "Function context does not match Module context!", &F);
892 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
893 Assert2(FT->getNumParams() == NumArgs,
894 "# formal arguments must match # of arguments for function type!",
896 Assert1(F.getReturnType()->isFirstClassType() ||
897 F.getReturnType()->isVoidTy() ||
898 F.getReturnType()->isStructTy(),
899 "Functions cannot return aggregate values!", &F);
901 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
902 "Invalid struct return type!", &F);
904 AttributeSet Attrs = F.getAttributes();
906 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
907 "Attribute after last parameter!", &F);
909 // Check function attributes.
910 VerifyFunctionAttrs(FT, Attrs, &F);
912 // On function declarations/definitions, we do not support the builtin
913 // attribute. We do not check this in VerifyFunctionAttrs since that is
914 // checking for Attributes that can/can not ever be on functions.
915 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
917 "Attribute 'builtin' can only be applied to a callsite.", &F);
919 // Check that this function meets the restrictions on this calling convention.
920 switch (F.getCallingConv()) {
925 case CallingConv::Fast:
926 case CallingConv::Cold:
927 case CallingConv::X86_FastCall:
928 case CallingConv::X86_ThisCall:
929 case CallingConv::Intel_OCL_BI:
930 case CallingConv::PTX_Kernel:
931 case CallingConv::PTX_Device:
932 Assert1(!F.isVarArg(),
933 "Varargs functions must have C calling conventions!", &F);
937 bool isLLVMdotName = F.getName().size() >= 5 &&
938 F.getName().substr(0, 5) == "llvm.";
940 // Check that the argument values match the function type for this function...
942 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
944 Assert2(I->getType() == FT->getParamType(i),
945 "Argument value does not match function argument type!",
946 I, FT->getParamType(i));
947 Assert1(I->getType()->isFirstClassType(),
948 "Function arguments must have first-class types!", I);
950 Assert2(!I->getType()->isMetadataTy(),
951 "Function takes metadata but isn't an intrinsic", I, &F);
954 if (F.isMaterializable()) {
955 // Function has a body somewhere we can't see.
956 } else if (F.isDeclaration()) {
957 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
958 F.hasExternalWeakLinkage(),
959 "invalid linkage type for function declaration", &F);
961 // Verify that this function (which has a body) is not named "llvm.*". It
962 // is not legal to define intrinsics.
963 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
965 // Check the entry node
966 BasicBlock *Entry = &F.getEntryBlock();
967 Assert1(pred_begin(Entry) == pred_end(Entry),
968 "Entry block to function must not have predecessors!", Entry);
970 // The address of the entry block cannot be taken, unless it is dead.
971 if (Entry->hasAddressTaken()) {
972 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
973 "blockaddress may not be used with the entry block!", Entry);
977 // If this function is actually an intrinsic, verify that it is only used in
978 // direct call/invokes, never having its "address taken".
979 if (F.getIntrinsicID()) {
981 if (F.hasAddressTaken(&U))
982 Assert1(0, "Invalid user of intrinsic instruction!", U);
986 // verifyBasicBlock - Verify that a basic block is well formed...
988 void Verifier::visitBasicBlock(BasicBlock &BB) {
989 InstsInThisBlock.clear();
991 // Ensure that basic blocks have terminators!
992 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
994 // Check constraints that this basic block imposes on all of the PHI nodes in
996 if (isa<PHINode>(BB.front())) {
997 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
998 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
999 std::sort(Preds.begin(), Preds.end());
1001 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1002 // Ensure that PHI nodes have at least one entry!
1003 Assert1(PN->getNumIncomingValues() != 0,
1004 "PHI nodes must have at least one entry. If the block is dead, "
1005 "the PHI should be removed!", PN);
1006 Assert1(PN->getNumIncomingValues() == Preds.size(),
1007 "PHINode should have one entry for each predecessor of its "
1008 "parent basic block!", PN);
1010 // Get and sort all incoming values in the PHI node...
1012 Values.reserve(PN->getNumIncomingValues());
1013 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1014 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1015 PN->getIncomingValue(i)));
1016 std::sort(Values.begin(), Values.end());
1018 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1019 // Check to make sure that if there is more than one entry for a
1020 // particular basic block in this PHI node, that the incoming values are
1023 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
1024 Values[i].second == Values[i-1].second,
1025 "PHI node has multiple entries for the same basic block with "
1026 "different incoming values!", PN, Values[i].first,
1027 Values[i].second, Values[i-1].second);
1029 // Check to make sure that the predecessors and PHI node entries are
1031 Assert3(Values[i].first == Preds[i],
1032 "PHI node entries do not match predecessors!", PN,
1033 Values[i].first, Preds[i]);
1039 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1040 // Ensure that terminators only exist at the end of the basic block.
1041 Assert1(&I == I.getParent()->getTerminator(),
1042 "Terminator found in the middle of a basic block!", I.getParent());
1043 visitInstruction(I);
1046 void Verifier::visitBranchInst(BranchInst &BI) {
1047 if (BI.isConditional()) {
1048 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1049 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1051 visitTerminatorInst(BI);
1054 void Verifier::visitReturnInst(ReturnInst &RI) {
1055 Function *F = RI.getParent()->getParent();
1056 unsigned N = RI.getNumOperands();
1057 if (F->getReturnType()->isVoidTy())
1059 "Found return instr that returns non-void in Function of void "
1060 "return type!", &RI, F->getReturnType());
1062 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1063 "Function return type does not match operand "
1064 "type of return inst!", &RI, F->getReturnType());
1066 // Check to make sure that the return value has necessary properties for
1068 visitTerminatorInst(RI);
1071 void Verifier::visitSwitchInst(SwitchInst &SI) {
1072 // Check to make sure that all of the constants in the switch instruction
1073 // have the same type as the switched-on value.
1074 Type *SwitchTy = SI.getCondition()->getType();
1075 IntegerType *IntTy = cast<IntegerType>(SwitchTy);
1076 IntegersSubsetToBB Mapping;
1077 std::map<IntegersSubset::Range, unsigned> RangeSetMap;
1078 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1079 IntegersSubset CaseRanges = i.getCaseValueEx();
1080 for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
1081 IntegersSubset::Range r = CaseRanges.getItem(ri);
1082 Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
1083 "Switch constants must all be same type as switch value!", &SI);
1084 Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
1085 "Switch constants must all be same type as switch value!", &SI);
1087 RangeSetMap[r] = i.getCaseIndex();
1091 IntegersSubsetToBB::RangeIterator errItem;
1092 if (!Mapping.verify(errItem)) {
1093 unsigned CaseIndex = RangeSetMap[errItem->first];
1094 SwitchInst::CaseIt i(&SI, CaseIndex);
1095 Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
1098 visitTerminatorInst(SI);
1101 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1102 Assert1(BI.getAddress()->getType()->isPointerTy(),
1103 "Indirectbr operand must have pointer type!", &BI);
1104 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1105 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1106 "Indirectbr destinations must all have pointer type!", &BI);
1108 visitTerminatorInst(BI);
1111 void Verifier::visitSelectInst(SelectInst &SI) {
1112 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1114 "Invalid operands for select instruction!", &SI);
1116 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1117 "Select values must have same type as select instruction!", &SI);
1118 visitInstruction(SI);
1121 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1122 /// a pass, if any exist, it's an error.
1124 void Verifier::visitUserOp1(Instruction &I) {
1125 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1128 void Verifier::visitTruncInst(TruncInst &I) {
1129 // Get the source and destination types
1130 Type *SrcTy = I.getOperand(0)->getType();
1131 Type *DestTy = I.getType();
1133 // Get the size of the types in bits, we'll need this later
1134 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1135 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1137 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1138 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1139 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1140 "trunc source and destination must both be a vector or neither", &I);
1141 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1143 visitInstruction(I);
1146 void Verifier::visitZExtInst(ZExtInst &I) {
1147 // Get the source and destination types
1148 Type *SrcTy = I.getOperand(0)->getType();
1149 Type *DestTy = I.getType();
1151 // Get the size of the types in bits, we'll need this later
1152 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1153 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1154 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1155 "zext source and destination must both be a vector or neither", &I);
1156 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1157 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1159 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1161 visitInstruction(I);
1164 void Verifier::visitSExtInst(SExtInst &I) {
1165 // Get the source and destination types
1166 Type *SrcTy = I.getOperand(0)->getType();
1167 Type *DestTy = I.getType();
1169 // Get the size of the types in bits, we'll need this later
1170 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1171 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1173 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1174 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1175 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1176 "sext source and destination must both be a vector or neither", &I);
1177 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1179 visitInstruction(I);
1182 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1183 // Get the source and destination types
1184 Type *SrcTy = I.getOperand(0)->getType();
1185 Type *DestTy = I.getType();
1186 // Get the size of the types in bits, we'll need this later
1187 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1188 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1190 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1191 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1192 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1193 "fptrunc source and destination must both be a vector or neither",&I);
1194 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1196 visitInstruction(I);
1199 void Verifier::visitFPExtInst(FPExtInst &I) {
1200 // Get the source and destination types
1201 Type *SrcTy = I.getOperand(0)->getType();
1202 Type *DestTy = I.getType();
1204 // Get the size of the types in bits, we'll need this later
1205 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1206 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1208 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1209 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1210 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1211 "fpext source and destination must both be a vector or neither", &I);
1212 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1214 visitInstruction(I);
1217 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1218 // Get the source and destination types
1219 Type *SrcTy = I.getOperand(0)->getType();
1220 Type *DestTy = I.getType();
1222 bool SrcVec = SrcTy->isVectorTy();
1223 bool DstVec = DestTy->isVectorTy();
1225 Assert1(SrcVec == DstVec,
1226 "UIToFP source and dest must both be vector or scalar", &I);
1227 Assert1(SrcTy->isIntOrIntVectorTy(),
1228 "UIToFP source must be integer or integer vector", &I);
1229 Assert1(DestTy->isFPOrFPVectorTy(),
1230 "UIToFP result must be FP or FP vector", &I);
1232 if (SrcVec && DstVec)
1233 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1234 cast<VectorType>(DestTy)->getNumElements(),
1235 "UIToFP source and dest vector length mismatch", &I);
1237 visitInstruction(I);
1240 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1241 // Get the source and destination types
1242 Type *SrcTy = I.getOperand(0)->getType();
1243 Type *DestTy = I.getType();
1245 bool SrcVec = SrcTy->isVectorTy();
1246 bool DstVec = DestTy->isVectorTy();
1248 Assert1(SrcVec == DstVec,
1249 "SIToFP source and dest must both be vector or scalar", &I);
1250 Assert1(SrcTy->isIntOrIntVectorTy(),
1251 "SIToFP source must be integer or integer vector", &I);
1252 Assert1(DestTy->isFPOrFPVectorTy(),
1253 "SIToFP result must be FP or FP vector", &I);
1255 if (SrcVec && DstVec)
1256 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1257 cast<VectorType>(DestTy)->getNumElements(),
1258 "SIToFP source and dest vector length mismatch", &I);
1260 visitInstruction(I);
1263 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1264 // Get the source and destination types
1265 Type *SrcTy = I.getOperand(0)->getType();
1266 Type *DestTy = I.getType();
1268 bool SrcVec = SrcTy->isVectorTy();
1269 bool DstVec = DestTy->isVectorTy();
1271 Assert1(SrcVec == DstVec,
1272 "FPToUI source and dest must both be vector or scalar", &I);
1273 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1275 Assert1(DestTy->isIntOrIntVectorTy(),
1276 "FPToUI result must be integer or integer vector", &I);
1278 if (SrcVec && DstVec)
1279 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1280 cast<VectorType>(DestTy)->getNumElements(),
1281 "FPToUI source and dest vector length mismatch", &I);
1283 visitInstruction(I);
1286 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1287 // Get the source and destination types
1288 Type *SrcTy = I.getOperand(0)->getType();
1289 Type *DestTy = I.getType();
1291 bool SrcVec = SrcTy->isVectorTy();
1292 bool DstVec = DestTy->isVectorTy();
1294 Assert1(SrcVec == DstVec,
1295 "FPToSI source and dest must both be vector or scalar", &I);
1296 Assert1(SrcTy->isFPOrFPVectorTy(),
1297 "FPToSI source must be FP or FP vector", &I);
1298 Assert1(DestTy->isIntOrIntVectorTy(),
1299 "FPToSI result must be integer or integer vector", &I);
1301 if (SrcVec && DstVec)
1302 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1303 cast<VectorType>(DestTy)->getNumElements(),
1304 "FPToSI source and dest vector length mismatch", &I);
1306 visitInstruction(I);
1309 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1310 // Get the source and destination types
1311 Type *SrcTy = I.getOperand(0)->getType();
1312 Type *DestTy = I.getType();
1314 Assert1(SrcTy->getScalarType()->isPointerTy(),
1315 "PtrToInt source must be pointer", &I);
1316 Assert1(DestTy->getScalarType()->isIntegerTy(),
1317 "PtrToInt result must be integral", &I);
1318 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1319 "PtrToInt type mismatch", &I);
1321 if (SrcTy->isVectorTy()) {
1322 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1323 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1324 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1325 "PtrToInt Vector width mismatch", &I);
1328 visitInstruction(I);
1331 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1332 // Get the source and destination types
1333 Type *SrcTy = I.getOperand(0)->getType();
1334 Type *DestTy = I.getType();
1336 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1337 "IntToPtr source must be an integral", &I);
1338 Assert1(DestTy->getScalarType()->isPointerTy(),
1339 "IntToPtr result must be a pointer",&I);
1340 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1341 "IntToPtr type mismatch", &I);
1342 if (SrcTy->isVectorTy()) {
1343 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1344 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1345 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1346 "IntToPtr Vector width mismatch", &I);
1348 visitInstruction(I);
1351 void Verifier::visitBitCastInst(BitCastInst &I) {
1352 // Get the source and destination types
1353 Type *SrcTy = I.getOperand(0)->getType();
1354 Type *DestTy = I.getType();
1356 // Get the size of the types in bits, we'll need this later
1357 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1358 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1360 // BitCast implies a no-op cast of type only. No bits change.
1361 // However, you can't cast pointers to anything but pointers.
1362 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
1363 "Bitcast requires both operands to be pointer or neither", &I);
1364 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1366 // Disallow aggregates.
1367 Assert1(!SrcTy->isAggregateType(),
1368 "Bitcast operand must not be aggregate", &I);
1369 Assert1(!DestTy->isAggregateType(),
1370 "Bitcast type must not be aggregate", &I);
1372 visitInstruction(I);
1375 /// visitPHINode - Ensure that a PHI node is well formed.
1377 void Verifier::visitPHINode(PHINode &PN) {
1378 // Ensure that the PHI nodes are all grouped together at the top of the block.
1379 // This can be tested by checking whether the instruction before this is
1380 // either nonexistent (because this is begin()) or is a PHI node. If not,
1381 // then there is some other instruction before a PHI.
1382 Assert2(&PN == &PN.getParent()->front() ||
1383 isa<PHINode>(--BasicBlock::iterator(&PN)),
1384 "PHI nodes not grouped at top of basic block!",
1385 &PN, PN.getParent());
1387 // Check that all of the values of the PHI node have the same type as the
1388 // result, and that the incoming blocks are really basic blocks.
1389 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1390 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1391 "PHI node operands are not the same type as the result!", &PN);
1394 // All other PHI node constraints are checked in the visitBasicBlock method.
1396 visitInstruction(PN);
1399 void Verifier::VerifyCallSite(CallSite CS) {
1400 Instruction *I = CS.getInstruction();
1402 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1403 "Called function must be a pointer!", I);
1404 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1406 Assert1(FPTy->getElementType()->isFunctionTy(),
1407 "Called function is not pointer to function type!", I);
1408 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1410 // Verify that the correct number of arguments are being passed
1411 if (FTy->isVarArg())
1412 Assert1(CS.arg_size() >= FTy->getNumParams(),
1413 "Called function requires more parameters than were provided!",I);
1415 Assert1(CS.arg_size() == FTy->getNumParams(),
1416 "Incorrect number of arguments passed to called function!", I);
1418 // Verify that all arguments to the call match the function type.
1419 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1420 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1421 "Call parameter type does not match function signature!",
1422 CS.getArgument(i), FTy->getParamType(i), I);
1424 AttributeSet Attrs = CS.getAttributes();
1426 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1427 "Attribute after last parameter!", I);
1429 // Verify call attributes.
1430 VerifyFunctionAttrs(FTy, Attrs, I);
1432 if (FTy->isVarArg()) {
1433 // FIXME? is 'nest' even legal here?
1434 bool SawNest = false;
1435 bool SawReturned = false;
1437 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1438 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1440 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1444 // Check attributes on the varargs part.
1445 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1446 Type *Ty = CS.getArgument(Idx-1)->getType();
1447 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1449 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1450 Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1454 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1455 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1457 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1458 "Incompatible argument and return types for 'returned' "
1463 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1464 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1468 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1469 if (CS.getCalledFunction() == 0 ||
1470 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1471 for (FunctionType::param_iterator PI = FTy->param_begin(),
1472 PE = FTy->param_end(); PI != PE; ++PI)
1473 Assert1(!(*PI)->isMetadataTy(),
1474 "Function has metadata parameter but isn't an intrinsic", I);
1477 // If the call site has the 'builtin' attribute, verify that it's applied to a
1478 // direct call to a function with the 'nobuiltin' attribute.
1479 if (CS.hasFnAttr(Attribute::Builtin))
1480 Assert1(CS.getCalledFunction() &&
1481 CS.getCalledFunction()->hasFnAttribute(Attribute::NoBuiltin),
1482 "Attribute 'builtin' can only be used in a call to a function with "
1483 "the 'nobuiltin' attribute.", I);
1485 visitInstruction(*I);
1488 void Verifier::visitCallInst(CallInst &CI) {
1489 VerifyCallSite(&CI);
1491 if (Function *F = CI.getCalledFunction())
1492 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1493 visitIntrinsicFunctionCall(ID, CI);
1496 void Verifier::visitInvokeInst(InvokeInst &II) {
1497 VerifyCallSite(&II);
1499 // Verify that there is a landingpad instruction as the first non-PHI
1500 // instruction of the 'unwind' destination.
1501 Assert1(II.getUnwindDest()->isLandingPad(),
1502 "The unwind destination does not have a landingpad instruction!",&II);
1504 visitTerminatorInst(II);
1507 /// visitBinaryOperator - Check that both arguments to the binary operator are
1508 /// of the same type!
1510 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1511 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1512 "Both operands to a binary operator are not of the same type!", &B);
1514 switch (B.getOpcode()) {
1515 // Check that integer arithmetic operators are only used with
1516 // integral operands.
1517 case Instruction::Add:
1518 case Instruction::Sub:
1519 case Instruction::Mul:
1520 case Instruction::SDiv:
1521 case Instruction::UDiv:
1522 case Instruction::SRem:
1523 case Instruction::URem:
1524 Assert1(B.getType()->isIntOrIntVectorTy(),
1525 "Integer arithmetic operators only work with integral types!", &B);
1526 Assert1(B.getType() == B.getOperand(0)->getType(),
1527 "Integer arithmetic operators must have same type "
1528 "for operands and result!", &B);
1530 // Check that floating-point arithmetic operators are only used with
1531 // floating-point operands.
1532 case Instruction::FAdd:
1533 case Instruction::FSub:
1534 case Instruction::FMul:
1535 case Instruction::FDiv:
1536 case Instruction::FRem:
1537 Assert1(B.getType()->isFPOrFPVectorTy(),
1538 "Floating-point arithmetic operators only work with "
1539 "floating-point types!", &B);
1540 Assert1(B.getType() == B.getOperand(0)->getType(),
1541 "Floating-point arithmetic operators must have same type "
1542 "for operands and result!", &B);
1544 // Check that logical operators are only used with integral operands.
1545 case Instruction::And:
1546 case Instruction::Or:
1547 case Instruction::Xor:
1548 Assert1(B.getType()->isIntOrIntVectorTy(),
1549 "Logical operators only work with integral types!", &B);
1550 Assert1(B.getType() == B.getOperand(0)->getType(),
1551 "Logical operators must have same type for operands and result!",
1554 case Instruction::Shl:
1555 case Instruction::LShr:
1556 case Instruction::AShr:
1557 Assert1(B.getType()->isIntOrIntVectorTy(),
1558 "Shifts only work with integral types!", &B);
1559 Assert1(B.getType() == B.getOperand(0)->getType(),
1560 "Shift return type must be same as operands!", &B);
1563 llvm_unreachable("Unknown BinaryOperator opcode!");
1566 visitInstruction(B);
1569 void Verifier::visitICmpInst(ICmpInst &IC) {
1570 // Check that the operands are the same type
1571 Type *Op0Ty = IC.getOperand(0)->getType();
1572 Type *Op1Ty = IC.getOperand(1)->getType();
1573 Assert1(Op0Ty == Op1Ty,
1574 "Both operands to ICmp instruction are not of the same type!", &IC);
1575 // Check that the operands are the right type
1576 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1577 "Invalid operand types for ICmp instruction", &IC);
1578 // Check that the predicate is valid.
1579 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1580 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1581 "Invalid predicate in ICmp instruction!", &IC);
1583 visitInstruction(IC);
1586 void Verifier::visitFCmpInst(FCmpInst &FC) {
1587 // Check that the operands are the same type
1588 Type *Op0Ty = FC.getOperand(0)->getType();
1589 Type *Op1Ty = FC.getOperand(1)->getType();
1590 Assert1(Op0Ty == Op1Ty,
1591 "Both operands to FCmp instruction are not of the same type!", &FC);
1592 // Check that the operands are the right type
1593 Assert1(Op0Ty->isFPOrFPVectorTy(),
1594 "Invalid operand types for FCmp instruction", &FC);
1595 // Check that the predicate is valid.
1596 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1597 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1598 "Invalid predicate in FCmp instruction!", &FC);
1600 visitInstruction(FC);
1603 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1604 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1606 "Invalid extractelement operands!", &EI);
1607 visitInstruction(EI);
1610 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1611 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1614 "Invalid insertelement operands!", &IE);
1615 visitInstruction(IE);
1618 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1619 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1621 "Invalid shufflevector operands!", &SV);
1622 visitInstruction(SV);
1625 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1626 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1628 Assert1(isa<PointerType>(TargetTy),
1629 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1630 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1631 "GEP into unsized type!", &GEP);
1632 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1633 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1636 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1638 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1639 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1641 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1642 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1643 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1645 if (GEP.getPointerOperandType()->isVectorTy()) {
1646 // Additional checks for vector GEPs.
1647 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1648 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1649 "Vector GEP result width doesn't match operand's", &GEP);
1650 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1651 Type *IndexTy = Idxs[i]->getType();
1652 Assert1(IndexTy->isVectorTy(),
1653 "Vector GEP must have vector indices!", &GEP);
1654 unsigned IndexWidth = IndexTy->getVectorNumElements();
1655 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1658 visitInstruction(GEP);
1661 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1662 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1665 void Verifier::visitLoadInst(LoadInst &LI) {
1666 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1667 Assert1(PTy, "Load operand must be a pointer.", &LI);
1668 Type *ElTy = PTy->getElementType();
1669 Assert2(ElTy == LI.getType(),
1670 "Load result type does not match pointer operand type!", &LI, ElTy);
1671 if (LI.isAtomic()) {
1672 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1673 "Load cannot have Release ordering", &LI);
1674 Assert1(LI.getAlignment() != 0,
1675 "Atomic load must specify explicit alignment", &LI);
1676 if (!ElTy->isPointerTy()) {
1677 Assert2(ElTy->isIntegerTy(),
1678 "atomic store operand must have integer type!",
1680 unsigned Size = ElTy->getPrimitiveSizeInBits();
1681 Assert2(Size >= 8 && !(Size & (Size - 1)),
1682 "atomic store operand must be power-of-two byte-sized integer",
1686 Assert1(LI.getSynchScope() == CrossThread,
1687 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1690 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1691 unsigned NumOperands = Range->getNumOperands();
1692 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1693 unsigned NumRanges = NumOperands / 2;
1694 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1696 ConstantRange LastRange(1); // Dummy initial value
1697 for (unsigned i = 0; i < NumRanges; ++i) {
1698 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1699 Assert1(Low, "The lower limit must be an integer!", Low);
1700 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1701 Assert1(High, "The upper limit must be an integer!", High);
1702 Assert1(High->getType() == Low->getType() &&
1703 High->getType() == ElTy, "Range types must match load type!",
1706 APInt HighV = High->getValue();
1707 APInt LowV = Low->getValue();
1708 ConstantRange CurRange(LowV, HighV);
1709 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1710 "Range must not be empty!", Range);
1712 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1713 "Intervals are overlapping", Range);
1714 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1716 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1719 LastRange = ConstantRange(LowV, HighV);
1721 if (NumRanges > 2) {
1723 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1725 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1726 ConstantRange FirstRange(FirstLow, FirstHigh);
1727 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1728 "Intervals are overlapping", Range);
1729 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1736 visitInstruction(LI);
1739 void Verifier::visitStoreInst(StoreInst &SI) {
1740 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1741 Assert1(PTy, "Store operand must be a pointer.", &SI);
1742 Type *ElTy = PTy->getElementType();
1743 Assert2(ElTy == SI.getOperand(0)->getType(),
1744 "Stored value type does not match pointer operand type!",
1746 if (SI.isAtomic()) {
1747 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1748 "Store cannot have Acquire ordering", &SI);
1749 Assert1(SI.getAlignment() != 0,
1750 "Atomic store must specify explicit alignment", &SI);
1751 if (!ElTy->isPointerTy()) {
1752 Assert2(ElTy->isIntegerTy(),
1753 "atomic store operand must have integer type!",
1755 unsigned Size = ElTy->getPrimitiveSizeInBits();
1756 Assert2(Size >= 8 && !(Size & (Size - 1)),
1757 "atomic store operand must be power-of-two byte-sized integer",
1761 Assert1(SI.getSynchScope() == CrossThread,
1762 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1764 visitInstruction(SI);
1767 void Verifier::visitAllocaInst(AllocaInst &AI) {
1768 PointerType *PTy = AI.getType();
1769 Assert1(PTy->getAddressSpace() == 0,
1770 "Allocation instruction pointer not in the generic address space!",
1772 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1774 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1775 "Alloca array size must have integer type", &AI);
1776 visitInstruction(AI);
1779 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1780 Assert1(CXI.getOrdering() != NotAtomic,
1781 "cmpxchg instructions must be atomic.", &CXI);
1782 Assert1(CXI.getOrdering() != Unordered,
1783 "cmpxchg instructions cannot be unordered.", &CXI);
1784 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1785 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1786 Type *ElTy = PTy->getElementType();
1787 Assert2(ElTy->isIntegerTy(),
1788 "cmpxchg operand must have integer type!",
1790 unsigned Size = ElTy->getPrimitiveSizeInBits();
1791 Assert2(Size >= 8 && !(Size & (Size - 1)),
1792 "cmpxchg operand must be power-of-two byte-sized integer",
1794 Assert2(ElTy == CXI.getOperand(1)->getType(),
1795 "Expected value type does not match pointer operand type!",
1797 Assert2(ElTy == CXI.getOperand(2)->getType(),
1798 "Stored value type does not match pointer operand type!",
1800 visitInstruction(CXI);
1803 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1804 Assert1(RMWI.getOrdering() != NotAtomic,
1805 "atomicrmw instructions must be atomic.", &RMWI);
1806 Assert1(RMWI.getOrdering() != Unordered,
1807 "atomicrmw instructions cannot be unordered.", &RMWI);
1808 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1809 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1810 Type *ElTy = PTy->getElementType();
1811 Assert2(ElTy->isIntegerTy(),
1812 "atomicrmw operand must have integer type!",
1814 unsigned Size = ElTy->getPrimitiveSizeInBits();
1815 Assert2(Size >= 8 && !(Size & (Size - 1)),
1816 "atomicrmw operand must be power-of-two byte-sized integer",
1818 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1819 "Argument value type does not match pointer operand type!",
1821 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1822 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1823 "Invalid binary operation!", &RMWI);
1824 visitInstruction(RMWI);
1827 void Verifier::visitFenceInst(FenceInst &FI) {
1828 const AtomicOrdering Ordering = FI.getOrdering();
1829 Assert1(Ordering == Acquire || Ordering == Release ||
1830 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1831 "fence instructions may only have "
1832 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1833 visitInstruction(FI);
1836 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1837 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1838 EVI.getIndices()) ==
1840 "Invalid ExtractValueInst operands!", &EVI);
1842 visitInstruction(EVI);
1845 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1846 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1847 IVI.getIndices()) ==
1848 IVI.getOperand(1)->getType(),
1849 "Invalid InsertValueInst operands!", &IVI);
1851 visitInstruction(IVI);
1854 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1855 BasicBlock *BB = LPI.getParent();
1857 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1859 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1860 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1862 // The landingpad instruction defines its parent as a landing pad block. The
1863 // landing pad block may be branched to only by the unwind edge of an invoke.
1864 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1865 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1866 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1867 "Block containing LandingPadInst must be jumped to "
1868 "only by the unwind edge of an invoke.", &LPI);
1871 // The landingpad instruction must be the first non-PHI instruction in the
1873 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1874 "LandingPadInst not the first non-PHI instruction in the block.",
1877 // The personality functions for all landingpad instructions within the same
1878 // function should match.
1880 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1881 "Personality function doesn't match others in function", &LPI);
1882 PersonalityFn = LPI.getPersonalityFn();
1884 // All operands must be constants.
1885 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1887 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1888 Value *Clause = LPI.getClause(i);
1889 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1890 if (LPI.isCatch(i)) {
1891 Assert1(isa<PointerType>(Clause->getType()),
1892 "Catch operand does not have pointer type!", &LPI);
1894 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1895 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1896 "Filter operand is not an array of constants!", &LPI);
1900 visitInstruction(LPI);
1903 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1904 Instruction *Op = cast<Instruction>(I.getOperand(i));
1905 // If the we have an invalid invoke, don't try to compute the dominance.
1906 // We already reject it in the invoke specific checks and the dominance
1907 // computation doesn't handle multiple edges.
1908 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1909 if (II->getNormalDest() == II->getUnwindDest())
1913 const Use &U = I.getOperandUse(i);
1914 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1915 "Instruction does not dominate all uses!", Op, &I);
1918 /// verifyInstruction - Verify that an instruction is well formed.
1920 void Verifier::visitInstruction(Instruction &I) {
1921 BasicBlock *BB = I.getParent();
1922 Assert1(BB, "Instruction not embedded in basic block!", &I);
1924 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1925 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1927 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1928 "Only PHI nodes may reference their own value!", &I);
1931 // Check that void typed values don't have names
1932 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1933 "Instruction has a name, but provides a void value!", &I);
1935 // Check that the return value of the instruction is either void or a legal
1937 Assert1(I.getType()->isVoidTy() ||
1938 I.getType()->isFirstClassType(),
1939 "Instruction returns a non-scalar type!", &I);
1941 // Check that the instruction doesn't produce metadata. Calls are already
1942 // checked against the callee type.
1943 Assert1(!I.getType()->isMetadataTy() ||
1944 isa<CallInst>(I) || isa<InvokeInst>(I),
1945 "Invalid use of metadata!", &I);
1947 // Check that all uses of the instruction, if they are instructions
1948 // themselves, actually have parent basic blocks. If the use is not an
1949 // instruction, it is an error!
1950 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1952 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1953 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1954 " embedded in a basic block!", &I, Used);
1956 CheckFailed("Use of instruction is not an instruction!", *UI);
1961 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1962 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1964 // Check to make sure that only first-class-values are operands to
1966 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1967 Assert1(0, "Instruction operands must be first-class values!", &I);
1970 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1971 // Check to make sure that the "address of" an intrinsic function is never
1973 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
1974 "Cannot take the address of an intrinsic!", &I);
1975 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
1976 F->getIntrinsicID() == Intrinsic::donothing,
1977 "Cannot invoke an intrinsinc other than donothing", &I);
1978 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1980 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1981 Assert1(OpBB->getParent() == BB->getParent(),
1982 "Referring to a basic block in another function!", &I);
1983 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1984 Assert1(OpArg->getParent() == BB->getParent(),
1985 "Referring to an argument in another function!", &I);
1986 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1987 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1989 } else if (isa<Instruction>(I.getOperand(i))) {
1990 verifyDominatesUse(I, i);
1991 } else if (isa<InlineAsm>(I.getOperand(i))) {
1992 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1993 (i + 3 == e && isa<InvokeInst>(I)),
1994 "Cannot take the address of an inline asm!", &I);
1998 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
1999 Assert1(I.getType()->isFPOrFPVectorTy(),
2000 "fpmath requires a floating point result!", &I);
2001 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2002 Value *Op0 = MD->getOperand(0);
2003 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2004 APFloat Accuracy = CFP0->getValueAPF();
2005 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2006 "fpmath accuracy not a positive number!", &I);
2008 Assert1(false, "invalid fpmath accuracy!", &I);
2012 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2013 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2015 InstsInThisBlock.insert(&I);
2018 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2019 /// intrinsic argument or return value) matches the type constraints specified
2020 /// by the .td file (e.g. an "any integer" argument really is an integer).
2022 /// This return true on error but does not print a message.
2023 bool Verifier::VerifyIntrinsicType(Type *Ty,
2024 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2025 SmallVectorImpl<Type*> &ArgTys) {
2026 using namespace Intrinsic;
2028 // If we ran out of descriptors, there are too many arguments.
2029 if (Infos.empty()) return true;
2030 IITDescriptor D = Infos.front();
2031 Infos = Infos.slice(1);
2034 case IITDescriptor::Void: return !Ty->isVoidTy();
2035 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2036 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2037 case IITDescriptor::Half: return !Ty->isHalfTy();
2038 case IITDescriptor::Float: return !Ty->isFloatTy();
2039 case IITDescriptor::Double: return !Ty->isDoubleTy();
2040 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2041 case IITDescriptor::Vector: {
2042 VectorType *VT = dyn_cast<VectorType>(Ty);
2043 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
2044 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2046 case IITDescriptor::Pointer: {
2047 PointerType *PT = dyn_cast<PointerType>(Ty);
2048 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2049 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2052 case IITDescriptor::Struct: {
2053 StructType *ST = dyn_cast<StructType>(Ty);
2054 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2057 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2058 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2063 case IITDescriptor::Argument:
2064 // Two cases here - If this is the second occurrence of an argument, verify
2065 // that the later instance matches the previous instance.
2066 if (D.getArgumentNumber() < ArgTys.size())
2067 return Ty != ArgTys[D.getArgumentNumber()];
2069 // Otherwise, if this is the first instance of an argument, record it and
2070 // verify the "Any" kind.
2071 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2072 ArgTys.push_back(Ty);
2074 switch (D.getArgumentKind()) {
2075 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2076 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2077 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2078 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2080 llvm_unreachable("all argument kinds not covered");
2082 case IITDescriptor::ExtendVecArgument:
2083 // This may only be used when referring to a previous vector argument.
2084 return D.getArgumentNumber() >= ArgTys.size() ||
2085 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2086 VectorType::getExtendedElementVectorType(
2087 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2089 case IITDescriptor::TruncVecArgument:
2090 // This may only be used when referring to a previous vector argument.
2091 return D.getArgumentNumber() >= ArgTys.size() ||
2092 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2093 VectorType::getTruncatedElementVectorType(
2094 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2096 llvm_unreachable("unhandled");
2099 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2101 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2102 Function *IF = CI.getCalledFunction();
2103 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2106 // Verify that the intrinsic prototype lines up with what the .td files
2108 FunctionType *IFTy = IF->getFunctionType();
2109 Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
2111 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2112 getIntrinsicInfoTableEntries(ID, Table);
2113 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2115 SmallVector<Type *, 4> ArgTys;
2116 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2117 "Intrinsic has incorrect return type!", IF);
2118 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2119 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2120 "Intrinsic has incorrect argument type!", IF);
2121 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2123 // Now that we have the intrinsic ID and the actual argument types (and we
2124 // know they are legal for the intrinsic!) get the intrinsic name through the
2125 // usual means. This allows us to verify the mangling of argument types into
2127 Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
2128 "Intrinsic name not mangled correctly for type arguments!", IF);
2130 // If the intrinsic takes MDNode arguments, verify that they are either global
2131 // or are local to *this* function.
2132 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2133 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2134 visitMDNode(*MD, CI.getParent()->getParent());
2139 case Intrinsic::ctlz: // llvm.ctlz
2140 case Intrinsic::cttz: // llvm.cttz
2141 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2142 "is_zero_undef argument of bit counting intrinsics must be a "
2143 "constant int", &CI);
2145 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2146 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2147 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2148 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2149 Assert1(MD->getNumOperands() == 1,
2150 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2151 if (!DisableDebugInfoVerifier)
2152 Finder.processDeclare(cast<DbgDeclareInst>(&CI));
2154 case Intrinsic::dbg_value: { //llvm.dbg.value
2155 if (!DisableDebugInfoVerifier) {
2156 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2157 "invalid llvm.dbg.value intrinsic call 1", &CI);
2158 Finder.processValue(cast<DbgValueInst>(&CI));
2162 case Intrinsic::memcpy:
2163 case Intrinsic::memmove:
2164 case Intrinsic::memset:
2165 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2166 "alignment argument of memory intrinsics must be a constant int",
2168 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2169 "isvolatile argument of memory intrinsics must be a constant int",
2172 case Intrinsic::gcroot:
2173 case Intrinsic::gcwrite:
2174 case Intrinsic::gcread:
2175 if (ID == Intrinsic::gcroot) {
2177 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2178 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2179 Assert1(isa<Constant>(CI.getArgOperand(1)),
2180 "llvm.gcroot parameter #2 must be a constant.", &CI);
2181 if (!AI->getType()->getElementType()->isPointerTy()) {
2182 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2183 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2184 "or argument #2 must be a non-null constant.", &CI);
2188 Assert1(CI.getParent()->getParent()->hasGC(),
2189 "Enclosing function does not use GC.", &CI);
2191 case Intrinsic::init_trampoline:
2192 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2193 "llvm.init_trampoline parameter #2 must resolve to a function.",
2196 case Intrinsic::prefetch:
2197 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2198 isa<ConstantInt>(CI.getArgOperand(2)) &&
2199 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2200 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2201 "invalid arguments to llvm.prefetch",
2204 case Intrinsic::stackprotector:
2205 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2206 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2209 case Intrinsic::lifetime_start:
2210 case Intrinsic::lifetime_end:
2211 case Intrinsic::invariant_start:
2212 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2213 "size argument of memory use markers must be a constant integer",
2216 case Intrinsic::invariant_end:
2217 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2218 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2223 void Verifier::verifyDebugInfo(Module &M) {
2224 // Verify Debug Info.
2225 if (!DisableDebugInfoVerifier) {
2226 Finder.processModule(M);
2228 for (DebugInfoFinder::iterator I = Finder.compile_unit_begin(),
2229 E = Finder.compile_unit_end(); I != E; ++I)
2230 Assert1(DICompileUnit(*I).Verify(), "DICompileUnit does not Verify!", *I);
2231 for (DebugInfoFinder::iterator I = Finder.subprogram_begin(),
2232 E = Finder.subprogram_end(); I != E; ++I)
2233 Assert1(DISubprogram(*I).Verify(), "DISubprogram does not Verify!", *I);
2234 for (DebugInfoFinder::iterator I = Finder.global_variable_begin(),
2235 E = Finder.global_variable_end(); I != E; ++I)
2236 Assert1(DIGlobalVariable(*I).Verify(),
2237 "DIGlobalVariable does not Verify!", *I);
2238 for (DebugInfoFinder::iterator I = Finder.type_begin(),
2239 E = Finder.type_end(); I != E; ++I)
2240 Assert1(DIType(*I).Verify(), "DIType does not Verify!", *I);
2241 for (DebugInfoFinder::iterator I = Finder.scope_begin(),
2242 E = Finder.scope_end(); I != E; ++I)
2243 Assert1(DIScope(*I).Verify(), "DIScope does not Verify!", *I);
2247 //===----------------------------------------------------------------------===//
2248 // Implement the public interfaces to this file...
2249 //===----------------------------------------------------------------------===//
2251 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2252 return new Verifier(action);
2256 /// verifyFunction - Check a function for errors, printing messages on stderr.
2257 /// Return true if the function is corrupt.
2259 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2260 Function &F = const_cast<Function&>(f);
2261 assert(!F.isDeclaration() && "Cannot verify external functions");
2263 FunctionPassManager FPM(F.getParent());
2264 Verifier *V = new Verifier(action);
2270 /// verifyModule - Check a module for errors, printing messages on stderr.
2271 /// Return true if the module is corrupt.
2273 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2274 std::string *ErrorInfo) {
2276 Verifier *V = new Verifier(action);
2278 PM.run(const_cast<Module&>(M));
2280 if (ErrorInfo && V->Broken)
2281 *ErrorInfo = V->MessagesStr.str();