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/IR/CallingConv.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/InlineAsm.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/LLVMContext.h"
62 #include "llvm/IR/Metadata.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/InstVisitor.h"
65 #include "llvm/Pass.h"
66 #include "llvm/PassManager.h"
67 #include "llvm/Support/CFG.h"
68 #include "llvm/Support/CallSite.h"
69 #include "llvm/Support/ConstantRange.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/raw_ostream.h"
77 namespace { // Anonymous namespace for class
78 struct PreVerifier : public FunctionPass {
79 static char ID; // Pass ID, replacement for typeid
81 PreVerifier() : FunctionPass(ID) {
82 initializePreVerifierPass(*PassRegistry::getPassRegistry());
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
89 // Check that the prerequisites for successful DominatorTree construction
91 bool runOnFunction(Function &F) {
94 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
95 if (I->empty() || !I->back().isTerminator()) {
96 dbgs() << "Basic Block in function '" << F.getName()
97 << "' does not have terminator!\n";
98 WriteAsOperand(dbgs(), I, true);
105 report_fatal_error("Broken module, no Basic Block terminator!");
112 char PreVerifier::ID = 0;
113 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
115 static char &PreVerifyID = PreVerifier::ID;
118 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
119 static char ID; // Pass ID, replacement for typeid
120 bool Broken; // Is this module found to be broken?
121 VerifierFailureAction action;
122 // What to do if verification fails.
123 Module *Mod; // Module we are verifying right now
124 LLVMContext *Context; // Context within which we are verifying
125 DominatorTree *DT; // Dominator Tree, caution can be null!
127 std::string Messages;
128 raw_string_ostream MessagesStr;
130 /// InstInThisBlock - when verifying a basic block, keep track of all of the
131 /// instructions we have seen so far. This allows us to do efficient
132 /// dominance checks for the case when an instruction has an operand that is
133 /// an instruction in the same block.
134 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
136 /// MDNodes - keep track of the metadata nodes that have been checked
138 SmallPtrSet<MDNode *, 32> MDNodes;
140 /// PersonalityFn - The personality function referenced by the
141 /// LandingPadInsts. All LandingPadInsts within the same function must use
142 /// the same personality function.
143 const Value *PersonalityFn;
146 : FunctionPass(ID), Broken(false),
147 action(AbortProcessAction), Mod(0), Context(0), DT(0),
148 MessagesStr(Messages), PersonalityFn(0) {
149 initializeVerifierPass(*PassRegistry::getPassRegistry());
151 explicit Verifier(VerifierFailureAction ctn)
152 : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
153 Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
154 initializeVerifierPass(*PassRegistry::getPassRegistry());
157 bool doInitialization(Module &M) {
159 Context = &M.getContext();
161 // We must abort before returning back to the pass manager, or else the
162 // pass manager may try to run other passes on the broken module.
163 return abortIfBroken();
166 bool runOnFunction(Function &F) {
167 // Get dominator information if we are being run by PassManager
168 DT = &getAnalysis<DominatorTree>();
171 if (!Context) Context = &F.getContext();
174 InstsInThisBlock.clear();
177 // We must abort before returning back to the pass manager, or else the
178 // pass manager may try to run other passes on the broken module.
179 return abortIfBroken();
182 bool doFinalization(Module &M) {
183 // Scan through, checking all of the external function's linkage now...
184 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
185 visitGlobalValue(*I);
187 // Check to make sure function prototypes are okay.
188 if (I->isDeclaration()) visitFunction(*I);
191 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
193 visitGlobalVariable(*I);
195 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
197 visitGlobalAlias(*I);
199 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
200 E = M.named_metadata_end(); I != E; ++I)
201 visitNamedMDNode(*I);
205 // If the module is broken, abort at this time.
206 return abortIfBroken();
209 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
210 AU.setPreservesAll();
211 AU.addRequiredID(PreVerifyID);
212 AU.addRequired<DominatorTree>();
215 /// abortIfBroken - If the module is broken and we are supposed to abort on
216 /// this condition, do so.
218 bool abortIfBroken() {
219 if (!Broken) return false;
220 MessagesStr << "Broken module found, ";
222 case AbortProcessAction:
223 MessagesStr << "compilation aborted!\n";
224 dbgs() << MessagesStr.str();
225 // Client should choose different reaction if abort is not desired
227 case PrintMessageAction:
228 MessagesStr << "verification continues.\n";
229 dbgs() << MessagesStr.str();
231 case ReturnStatusAction:
232 MessagesStr << "compilation terminated.\n";
235 llvm_unreachable("Invalid action");
239 // Verification methods...
240 void visitGlobalValue(GlobalValue &GV);
241 void visitGlobalVariable(GlobalVariable &GV);
242 void visitGlobalAlias(GlobalAlias &GA);
243 void visitNamedMDNode(NamedMDNode &NMD);
244 void visitMDNode(MDNode &MD, Function *F);
245 void visitModuleFlags(Module &M);
246 void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
247 SmallVectorImpl<MDNode*> &Requirements);
248 void visitFunction(Function &F);
249 void visitBasicBlock(BasicBlock &BB);
250 using InstVisitor<Verifier>::visit;
252 void visit(Instruction &I);
254 void visitTruncInst(TruncInst &I);
255 void visitZExtInst(ZExtInst &I);
256 void visitSExtInst(SExtInst &I);
257 void visitFPTruncInst(FPTruncInst &I);
258 void visitFPExtInst(FPExtInst &I);
259 void visitFPToUIInst(FPToUIInst &I);
260 void visitFPToSIInst(FPToSIInst &I);
261 void visitUIToFPInst(UIToFPInst &I);
262 void visitSIToFPInst(SIToFPInst &I);
263 void visitIntToPtrInst(IntToPtrInst &I);
264 void visitPtrToIntInst(PtrToIntInst &I);
265 void visitBitCastInst(BitCastInst &I);
266 void visitPHINode(PHINode &PN);
267 void visitBinaryOperator(BinaryOperator &B);
268 void visitICmpInst(ICmpInst &IC);
269 void visitFCmpInst(FCmpInst &FC);
270 void visitExtractElementInst(ExtractElementInst &EI);
271 void visitInsertElementInst(InsertElementInst &EI);
272 void visitShuffleVectorInst(ShuffleVectorInst &EI);
273 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
274 void visitCallInst(CallInst &CI);
275 void visitInvokeInst(InvokeInst &II);
276 void visitGetElementPtrInst(GetElementPtrInst &GEP);
277 void visitLoadInst(LoadInst &LI);
278 void visitStoreInst(StoreInst &SI);
279 void verifyDominatesUse(Instruction &I, unsigned i);
280 void visitInstruction(Instruction &I);
281 void visitTerminatorInst(TerminatorInst &I);
282 void visitBranchInst(BranchInst &BI);
283 void visitReturnInst(ReturnInst &RI);
284 void visitSwitchInst(SwitchInst &SI);
285 void visitIndirectBrInst(IndirectBrInst &BI);
286 void visitSelectInst(SelectInst &SI);
287 void visitUserOp1(Instruction &I);
288 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
289 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
290 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
291 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
292 void visitFenceInst(FenceInst &FI);
293 void visitAllocaInst(AllocaInst &AI);
294 void visitExtractValueInst(ExtractValueInst &EVI);
295 void visitInsertValueInst(InsertValueInst &IVI);
296 void visitLandingPadInst(LandingPadInst &LPI);
298 void VerifyCallSite(CallSite CS);
299 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
300 int VT, unsigned ArgNo, std::string &Suffix);
301 bool VerifyIntrinsicType(Type *Ty,
302 ArrayRef<Intrinsic::IITDescriptor> &Infos,
303 SmallVectorImpl<Type*> &ArgTys);
304 void VerifyParameterAttrs(AttributeSet Attrs, uint64_t Idx, Type *Ty,
305 bool isReturnValue, const Value *V);
306 void VerifyFunctionAttrs(FunctionType *FT, const AttributeSet &Attrs,
309 void WriteValue(const Value *V) {
311 if (isa<Instruction>(V)) {
312 MessagesStr << *V << '\n';
314 WriteAsOperand(MessagesStr, V, true, Mod);
319 void WriteType(Type *T) {
321 MessagesStr << ' ' << *T;
325 // CheckFailed - A check failed, so print out the condition and the message
326 // that failed. This provides a nice place to put a breakpoint if you want
327 // to see why something is not correct.
328 void CheckFailed(const Twine &Message,
329 const Value *V1 = 0, const Value *V2 = 0,
330 const Value *V3 = 0, const Value *V4 = 0) {
331 MessagesStr << Message.str() << "\n";
339 void CheckFailed(const Twine &Message, const Value *V1,
340 Type *T2, const Value *V3 = 0) {
341 MessagesStr << Message.str() << "\n";
348 void CheckFailed(const Twine &Message, Type *T1,
349 Type *T2 = 0, Type *T3 = 0) {
350 MessagesStr << Message.str() << "\n";
357 } // End anonymous namespace
359 char Verifier::ID = 0;
360 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
361 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
362 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
363 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
365 // Assert - We know that cond should be true, if not print an error message.
366 #define Assert(C, M) \
367 do { if (!(C)) { CheckFailed(M); return; } } while (0)
368 #define Assert1(C, M, V1) \
369 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
370 #define Assert2(C, M, V1, V2) \
371 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
372 #define Assert3(C, M, V1, V2, V3) \
373 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
374 #define Assert4(C, M, V1, V2, V3, V4) \
375 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
377 void Verifier::visit(Instruction &I) {
378 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
379 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
380 InstVisitor<Verifier>::visit(I);
384 void Verifier::visitGlobalValue(GlobalValue &GV) {
385 Assert1(!GV.isDeclaration() ||
386 GV.isMaterializable() ||
387 GV.hasExternalLinkage() ||
388 GV.hasDLLImportLinkage() ||
389 GV.hasExternalWeakLinkage() ||
390 (isa<GlobalAlias>(GV) &&
391 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
392 "Global is external, but doesn't have external or dllimport or weak linkage!",
395 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
396 "Global is marked as dllimport, but not external", &GV);
398 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
399 "Only global variables can have appending linkage!", &GV);
401 if (GV.hasAppendingLinkage()) {
402 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
403 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
404 "Only global arrays can have appending linkage!", GVar);
407 Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
408 "linkonce_odr_auto_hide can only have default visibility!",
412 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
413 if (GV.hasInitializer()) {
414 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
415 "Global variable initializer type does not match global "
416 "variable type!", &GV);
418 // If the global has common linkage, it must have a zero initializer and
419 // cannot be constant.
420 if (GV.hasCommonLinkage()) {
421 Assert1(GV.getInitializer()->isNullValue(),
422 "'common' global must have a zero initializer!", &GV);
423 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
427 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
428 GV.hasExternalWeakLinkage(),
429 "invalid linkage type for global declaration", &GV);
432 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
433 GV.getName() == "llvm.global_dtors")) {
434 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
435 "invalid linkage for intrinsic global variable", &GV);
436 // Don't worry about emitting an error for it not being an array,
437 // visitGlobalValue will complain on appending non-array.
438 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
439 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
440 PointerType *FuncPtrTy =
441 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
442 Assert1(STy && STy->getNumElements() == 2 &&
443 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
444 STy->getTypeAtIndex(1) == FuncPtrTy,
445 "wrong type for intrinsic global variable", &GV);
449 visitGlobalValue(GV);
452 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
453 Assert1(!GA.getName().empty(),
454 "Alias name cannot be empty!", &GA);
455 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
457 "Alias should have external or external weak linkage!", &GA);
458 Assert1(GA.getAliasee(),
459 "Aliasee cannot be NULL!", &GA);
460 Assert1(GA.getType() == GA.getAliasee()->getType(),
461 "Alias and aliasee types should match!", &GA);
462 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
464 if (!isa<GlobalValue>(GA.getAliasee())) {
465 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
467 (CE->getOpcode() == Instruction::BitCast ||
468 CE->getOpcode() == Instruction::GetElementPtr) &&
469 isa<GlobalValue>(CE->getOperand(0)),
470 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
474 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
476 "Aliasing chain should end with function or global variable", &GA);
478 visitGlobalValue(GA);
481 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
482 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
483 MDNode *MD = NMD.getOperand(i);
487 Assert1(!MD->isFunctionLocal(),
488 "Named metadata operand cannot be function local!", MD);
493 void Verifier::visitMDNode(MDNode &MD, Function *F) {
494 // Only visit each node once. Metadata can be mutually recursive, so this
495 // avoids infinite recursion here, as well as being an optimization.
496 if (!MDNodes.insert(&MD))
499 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
500 Value *Op = MD.getOperand(i);
503 if (isa<Constant>(Op) || isa<MDString>(Op))
505 if (MDNode *N = dyn_cast<MDNode>(Op)) {
506 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
507 "Global metadata operand cannot be function local!", &MD, N);
511 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
513 // If this was an instruction, bb, or argument, verify that it is in the
514 // function that we expect.
515 Function *ActualF = 0;
516 if (Instruction *I = dyn_cast<Instruction>(Op))
517 ActualF = I->getParent()->getParent();
518 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
519 ActualF = BB->getParent();
520 else if (Argument *A = dyn_cast<Argument>(Op))
521 ActualF = A->getParent();
522 assert(ActualF && "Unimplemented function local metadata case!");
524 Assert2(ActualF == F, "function-local metadata used in wrong function",
529 void Verifier::visitModuleFlags(Module &M) {
530 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
533 // Scan each flag, and track the flags and requirements.
534 DenseMap<MDString*, MDNode*> SeenIDs;
535 SmallVector<MDNode*, 16> Requirements;
536 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
537 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
540 // Validate that the requirements in the module are valid.
541 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
542 MDNode *Requirement = Requirements[I];
543 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
544 Value *ReqValue = Requirement->getOperand(1);
546 MDNode *Op = SeenIDs.lookup(Flag);
548 CheckFailed("invalid requirement on flag, flag is not present in module",
553 if (Op->getOperand(2) != ReqValue) {
554 CheckFailed(("invalid requirement on flag, "
555 "flag does not have the required value"),
562 void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
563 SmallVectorImpl<MDNode*> &Requirements) {
564 // Each module flag should have three arguments, the merge behavior (a
565 // constant int), the flag ID (an MDString), and the value.
566 Assert1(Op->getNumOperands() == 3,
567 "incorrect number of operands in module flag", Op);
568 ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
569 MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
571 "invalid behavior operand in module flag (expected constant integer)",
573 unsigned BehaviorValue = Behavior->getZExtValue();
575 "invalid ID operand in module flag (expected metadata string)",
578 // Sanity check the values for behaviors with additional requirements.
579 switch (BehaviorValue) {
582 "invalid behavior operand in module flag (unexpected constant)",
587 case Module::Warning:
588 case Module::Override:
589 // These behavior types accept any value.
592 case Module::Require: {
593 // The value should itself be an MDNode with two operands, a flag ID (an
594 // MDString), and a value.
595 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
596 Assert1(Value && Value->getNumOperands() == 2,
597 "invalid value for 'require' module flag (expected metadata pair)",
599 Assert1(isa<MDString>(Value->getOperand(0)),
600 ("invalid value for 'require' module flag "
601 "(first value operand should be a string)"),
602 Value->getOperand(0));
604 // Append it to the list of requirements, to check once all module flags are
606 Requirements.push_back(Value);
611 case Module::AppendUnique: {
612 // These behavior types require the operand be an MDNode.
613 Assert1(isa<MDNode>(Op->getOperand(2)),
614 "invalid value for 'append'-type module flag "
615 "(expected a metadata node)", Op->getOperand(2));
620 // Unless this is a "requires" flag, check the ID is unique.
621 if (BehaviorValue != Module::Require) {
622 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
624 "module flag identifiers must be unique (or of 'require' type)",
629 // VerifyParameterAttrs - Check the given attributes for an argument or return
630 // value of the specified type. The value V is printed in error messages.
631 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, uint64_t Idx, Type *Ty,
632 bool isReturnValue, const Value *V) {
633 if (!Attrs.hasAttributes(Idx))
636 Assert1(!Attrs.hasAttribute(Idx, Attribute::NoReturn) &&
637 !Attrs.hasAttribute(Idx, Attribute::NoUnwind) &&
638 !Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
639 !Attrs.hasAttribute(Idx, Attribute::ReadOnly) &&
640 !Attrs.hasAttribute(Idx, Attribute::NoInline) &&
641 !Attrs.hasAttribute(Idx, Attribute::AlwaysInline) &&
642 !Attrs.hasAttribute(Idx, Attribute::OptimizeForSize) &&
643 !Attrs.hasAttribute(Idx, Attribute::StackProtect) &&
644 !Attrs.hasAttribute(Idx, Attribute::StackProtectReq) &&
645 !Attrs.hasAttribute(Idx, Attribute::NoRedZone) &&
646 !Attrs.hasAttribute(Idx, Attribute::NoImplicitFloat) &&
647 !Attrs.hasAttribute(Idx, Attribute::Naked) &&
648 !Attrs.hasAttribute(Idx, Attribute::InlineHint) &&
649 !Attrs.hasAttribute(Idx, Attribute::StackAlignment) &&
650 !Attrs.hasAttribute(Idx, Attribute::UWTable) &&
651 !Attrs.hasAttribute(Idx, Attribute::NonLazyBind) &&
652 !Attrs.hasAttribute(Idx, Attribute::ReturnsTwice) &&
653 !Attrs.hasAttribute(Idx, Attribute::AddressSafety) &&
654 !Attrs.hasAttribute(Idx, Attribute::ThreadSafety) &&
655 !Attrs.hasAttribute(Idx, Attribute::UninitializedChecks) &&
656 !Attrs.hasAttribute(Idx, Attribute::MinSize),
657 "Some attributes in '" + Attrs.getAsString(Idx) +
658 "' only apply to functions!", V);
661 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
662 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
663 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
664 !Attrs.hasAttribute(Idx, Attribute::NoCapture),
665 "Attribute 'byval', 'nest', 'sret', and 'nocapture' "
666 "do not apply to return values!", V);
668 // Check for mutually incompatible attributes.
669 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
670 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
671 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
672 Attrs.hasAttribute(Idx, Attribute::StructRet)) ||
673 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
674 Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes "
675 "'byval, nest, and sret' are incompatible!", V);
677 Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
678 Attrs.hasAttribute(Idx, Attribute::Nest)) ||
679 (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
680 Attrs.hasAttribute(Idx, Attribute::InReg)) ||
681 (Attrs.hasAttribute(Idx, Attribute::Nest) &&
682 Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes "
683 "'byval, nest, and inreg' are incompatible!", V);
685 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
686 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
687 "'zeroext and signext' are incompatible!", V);
689 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
690 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
691 "'readnone and readonly' are incompatible!", V);
693 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
694 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
695 "'noinline and alwaysinline' are incompatible!", V);
697 Assert1(!AttrBuilder(Attrs, Idx).
698 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
699 "Wrong types for attribute: " +
700 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
702 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
703 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) ||
704 PTy->getElementType()->isSized(),
705 "Attribute 'byval' does not support unsized types!", V);
707 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
708 "Attribute 'byval' only applies to parameters with pointer type!",
712 // VerifyFunctionAttrs - Check parameter attributes against a function type.
713 // The value V is printed in error messages.
714 void Verifier::VerifyFunctionAttrs(FunctionType *FT,
715 const AttributeSet &Attrs,
720 bool SawNest = false;
722 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
723 unsigned Index = Attrs.getSlotIndex(i);
727 Ty = FT->getReturnType();
728 else if (Index-1 < FT->getNumParams())
729 Ty = FT->getParamType(Index-1);
731 break; // VarArgs attributes, verified elsewhere.
733 VerifyParameterAttrs(Attrs, Index, Ty, Index == 0, V);
735 if (Attrs.hasAttribute(i, Attribute::Nest)) {
736 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
740 if (Attrs.hasAttribute(Index, Attribute::StructRet))
741 Assert1(Index == 1, "Attribute sret is not on first parameter!", V);
744 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
747 AttrBuilder NotFn(Attrs, AttributeSet::FunctionIndex);
748 NotFn.removeFunctionOnlyAttrs();
749 Assert1(NotFn.empty(), "Attributes '" +
750 AttributeSet::get(V->getContext(),
751 AttributeSet::FunctionIndex,
752 NotFn).getAsString(AttributeSet::FunctionIndex) +
753 "' do not apply to the function!", V);
755 // Check for mutually incompatible attributes.
756 Assert1(!((Attrs.hasAttribute(AttributeSet::FunctionIndex,
758 Attrs.hasAttribute(AttributeSet::FunctionIndex,
760 (Attrs.hasAttribute(AttributeSet::FunctionIndex,
762 Attrs.hasAttribute(AttributeSet::FunctionIndex,
763 Attribute::StructRet)) ||
764 (Attrs.hasAttribute(AttributeSet::FunctionIndex,
766 Attrs.hasAttribute(AttributeSet::FunctionIndex,
767 Attribute::StructRet))),
768 "Attributes 'byval, nest, and sret' are incompatible!", V);
770 Assert1(!((Attrs.hasAttribute(AttributeSet::FunctionIndex,
772 Attrs.hasAttribute(AttributeSet::FunctionIndex,
774 (Attrs.hasAttribute(AttributeSet::FunctionIndex,
776 Attrs.hasAttribute(AttributeSet::FunctionIndex,
777 Attribute::InReg)) ||
778 (Attrs.hasAttribute(AttributeSet::FunctionIndex,
780 Attrs.hasAttribute(AttributeSet::FunctionIndex,
782 "Attributes 'byval, nest, and inreg' are incompatible!", V);
784 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
786 Attrs.hasAttribute(AttributeSet::FunctionIndex,
788 "Attributes 'zeroext and signext' are incompatible!", V);
790 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
791 Attribute::ReadNone) &&
792 Attrs.hasAttribute(AttributeSet::FunctionIndex,
793 Attribute::ReadOnly)),
794 "Attributes 'readnone and readonly' are incompatible!", V);
796 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
797 Attribute::NoInline) &&
798 Attrs.hasAttribute(AttributeSet::FunctionIndex,
799 Attribute::AlwaysInline)),
800 "Attributes 'noinline and alwaysinline' are incompatible!", V);
803 static bool VerifyAttributeCount(const AttributeSet &Attrs, unsigned Params) {
804 if (Attrs.getNumSlots() == 0)
807 unsigned LastSlot = Attrs.getNumSlots() - 1;
808 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
809 if (LastIndex <= Params
810 || (LastIndex == AttributeSet::FunctionIndex
811 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
817 // visitFunction - Verify that a function is ok.
819 void Verifier::visitFunction(Function &F) {
820 // Check function arguments.
821 FunctionType *FT = F.getFunctionType();
822 unsigned NumArgs = F.arg_size();
824 Assert1(Context == &F.getContext(),
825 "Function context does not match Module context!", &F);
827 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
828 Assert2(FT->getNumParams() == NumArgs,
829 "# formal arguments must match # of arguments for function type!",
831 Assert1(F.getReturnType()->isFirstClassType() ||
832 F.getReturnType()->isVoidTy() ||
833 F.getReturnType()->isStructTy(),
834 "Functions cannot return aggregate values!", &F);
836 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
837 "Invalid struct return type!", &F);
839 const AttributeSet &Attrs = F.getAttributes();
841 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
842 "Attribute after last parameter!", &F);
844 // Check function attributes.
845 VerifyFunctionAttrs(FT, Attrs, &F);
847 // Check that this function meets the restrictions on this calling convention.
848 switch (F.getCallingConv()) {
853 case CallingConv::Fast:
854 case CallingConv::Cold:
855 case CallingConv::X86_FastCall:
856 case CallingConv::X86_ThisCall:
857 case CallingConv::Intel_OCL_BI:
858 case CallingConv::PTX_Kernel:
859 case CallingConv::PTX_Device:
860 Assert1(!F.isVarArg(),
861 "Varargs functions must have C calling conventions!", &F);
865 bool isLLVMdotName = F.getName().size() >= 5 &&
866 F.getName().substr(0, 5) == "llvm.";
868 // Check that the argument values match the function type for this function...
870 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
872 Assert2(I->getType() == FT->getParamType(i),
873 "Argument value does not match function argument type!",
874 I, FT->getParamType(i));
875 Assert1(I->getType()->isFirstClassType(),
876 "Function arguments must have first-class types!", I);
878 Assert2(!I->getType()->isMetadataTy(),
879 "Function takes metadata but isn't an intrinsic", I, &F);
882 if (F.isMaterializable()) {
883 // Function has a body somewhere we can't see.
884 } else if (F.isDeclaration()) {
885 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
886 F.hasExternalWeakLinkage(),
887 "invalid linkage type for function declaration", &F);
889 // Verify that this function (which has a body) is not named "llvm.*". It
890 // is not legal to define intrinsics.
891 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
893 // Check the entry node
894 BasicBlock *Entry = &F.getEntryBlock();
895 Assert1(pred_begin(Entry) == pred_end(Entry),
896 "Entry block to function must not have predecessors!", Entry);
898 // The address of the entry block cannot be taken, unless it is dead.
899 if (Entry->hasAddressTaken()) {
900 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
901 "blockaddress may not be used with the entry block!", Entry);
905 // If this function is actually an intrinsic, verify that it is only used in
906 // direct call/invokes, never having its "address taken".
907 if (F.getIntrinsicID()) {
909 if (F.hasAddressTaken(&U))
910 Assert1(0, "Invalid user of intrinsic instruction!", U);
914 // verifyBasicBlock - Verify that a basic block is well formed...
916 void Verifier::visitBasicBlock(BasicBlock &BB) {
917 InstsInThisBlock.clear();
919 // Ensure that basic blocks have terminators!
920 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
922 // Check constraints that this basic block imposes on all of the PHI nodes in
924 if (isa<PHINode>(BB.front())) {
925 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
926 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
927 std::sort(Preds.begin(), Preds.end());
929 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
930 // Ensure that PHI nodes have at least one entry!
931 Assert1(PN->getNumIncomingValues() != 0,
932 "PHI nodes must have at least one entry. If the block is dead, "
933 "the PHI should be removed!", PN);
934 Assert1(PN->getNumIncomingValues() == Preds.size(),
935 "PHINode should have one entry for each predecessor of its "
936 "parent basic block!", PN);
938 // Get and sort all incoming values in the PHI node...
940 Values.reserve(PN->getNumIncomingValues());
941 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
942 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
943 PN->getIncomingValue(i)));
944 std::sort(Values.begin(), Values.end());
946 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
947 // Check to make sure that if there is more than one entry for a
948 // particular basic block in this PHI node, that the incoming values are
951 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
952 Values[i].second == Values[i-1].second,
953 "PHI node has multiple entries for the same basic block with "
954 "different incoming values!", PN, Values[i].first,
955 Values[i].second, Values[i-1].second);
957 // Check to make sure that the predecessors and PHI node entries are
959 Assert3(Values[i].first == Preds[i],
960 "PHI node entries do not match predecessors!", PN,
961 Values[i].first, Preds[i]);
967 void Verifier::visitTerminatorInst(TerminatorInst &I) {
968 // Ensure that terminators only exist at the end of the basic block.
969 Assert1(&I == I.getParent()->getTerminator(),
970 "Terminator found in the middle of a basic block!", I.getParent());
974 void Verifier::visitBranchInst(BranchInst &BI) {
975 if (BI.isConditional()) {
976 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
977 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
979 visitTerminatorInst(BI);
982 void Verifier::visitReturnInst(ReturnInst &RI) {
983 Function *F = RI.getParent()->getParent();
984 unsigned N = RI.getNumOperands();
985 if (F->getReturnType()->isVoidTy())
987 "Found return instr that returns non-void in Function of void "
988 "return type!", &RI, F->getReturnType());
990 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
991 "Function return type does not match operand "
992 "type of return inst!", &RI, F->getReturnType());
994 // Check to make sure that the return value has necessary properties for
996 visitTerminatorInst(RI);
999 void Verifier::visitSwitchInst(SwitchInst &SI) {
1000 // Check to make sure that all of the constants in the switch instruction
1001 // have the same type as the switched-on value.
1002 Type *SwitchTy = SI.getCondition()->getType();
1003 IntegerType *IntTy = cast<IntegerType>(SwitchTy);
1004 IntegersSubsetToBB Mapping;
1005 std::map<IntegersSubset::Range, unsigned> RangeSetMap;
1006 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1007 IntegersSubset CaseRanges = i.getCaseValueEx();
1008 for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
1009 IntegersSubset::Range r = CaseRanges.getItem(ri);
1010 Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
1011 "Switch constants must all be same type as switch value!", &SI);
1012 Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
1013 "Switch constants must all be same type as switch value!", &SI);
1015 RangeSetMap[r] = i.getCaseIndex();
1019 IntegersSubsetToBB::RangeIterator errItem;
1020 if (!Mapping.verify(errItem)) {
1021 unsigned CaseIndex = RangeSetMap[errItem->first];
1022 SwitchInst::CaseIt i(&SI, CaseIndex);
1023 Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
1026 visitTerminatorInst(SI);
1029 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1030 Assert1(BI.getAddress()->getType()->isPointerTy(),
1031 "Indirectbr operand must have pointer type!", &BI);
1032 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1033 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1034 "Indirectbr destinations must all have pointer type!", &BI);
1036 visitTerminatorInst(BI);
1039 void Verifier::visitSelectInst(SelectInst &SI) {
1040 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1042 "Invalid operands for select instruction!", &SI);
1044 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1045 "Select values must have same type as select instruction!", &SI);
1046 visitInstruction(SI);
1049 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1050 /// a pass, if any exist, it's an error.
1052 void Verifier::visitUserOp1(Instruction &I) {
1053 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1056 void Verifier::visitTruncInst(TruncInst &I) {
1057 // Get the source and destination types
1058 Type *SrcTy = I.getOperand(0)->getType();
1059 Type *DestTy = I.getType();
1061 // Get the size of the types in bits, we'll need this later
1062 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1063 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1065 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1066 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1067 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1068 "trunc source and destination must both be a vector or neither", &I);
1069 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1071 visitInstruction(I);
1074 void Verifier::visitZExtInst(ZExtInst &I) {
1075 // Get the source and destination types
1076 Type *SrcTy = I.getOperand(0)->getType();
1077 Type *DestTy = I.getType();
1079 // Get the size of the types in bits, we'll need this later
1080 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1081 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1082 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1083 "zext source and destination must both be a vector or neither", &I);
1084 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1085 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1087 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1089 visitInstruction(I);
1092 void Verifier::visitSExtInst(SExtInst &I) {
1093 // Get the source and destination types
1094 Type *SrcTy = I.getOperand(0)->getType();
1095 Type *DestTy = I.getType();
1097 // Get the size of the types in bits, we'll need this later
1098 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1099 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1101 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1102 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1103 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1104 "sext source and destination must both be a vector or neither", &I);
1105 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1107 visitInstruction(I);
1110 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1111 // Get the source and destination types
1112 Type *SrcTy = I.getOperand(0)->getType();
1113 Type *DestTy = I.getType();
1114 // Get the size of the types in bits, we'll need this later
1115 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1116 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1118 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1119 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1120 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1121 "fptrunc source and destination must both be a vector or neither",&I);
1122 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1124 visitInstruction(I);
1127 void Verifier::visitFPExtInst(FPExtInst &I) {
1128 // Get the source and destination types
1129 Type *SrcTy = I.getOperand(0)->getType();
1130 Type *DestTy = I.getType();
1132 // Get the size of the types in bits, we'll need this later
1133 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1134 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1136 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1137 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1138 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1139 "fpext source and destination must both be a vector or neither", &I);
1140 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1142 visitInstruction(I);
1145 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1146 // Get the source and destination types
1147 Type *SrcTy = I.getOperand(0)->getType();
1148 Type *DestTy = I.getType();
1150 bool SrcVec = SrcTy->isVectorTy();
1151 bool DstVec = DestTy->isVectorTy();
1153 Assert1(SrcVec == DstVec,
1154 "UIToFP source and dest must both be vector or scalar", &I);
1155 Assert1(SrcTy->isIntOrIntVectorTy(),
1156 "UIToFP source must be integer or integer vector", &I);
1157 Assert1(DestTy->isFPOrFPVectorTy(),
1158 "UIToFP result must be FP or FP vector", &I);
1160 if (SrcVec && DstVec)
1161 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1162 cast<VectorType>(DestTy)->getNumElements(),
1163 "UIToFP source and dest vector length mismatch", &I);
1165 visitInstruction(I);
1168 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1169 // Get the source and destination types
1170 Type *SrcTy = I.getOperand(0)->getType();
1171 Type *DestTy = I.getType();
1173 bool SrcVec = SrcTy->isVectorTy();
1174 bool DstVec = DestTy->isVectorTy();
1176 Assert1(SrcVec == DstVec,
1177 "SIToFP source and dest must both be vector or scalar", &I);
1178 Assert1(SrcTy->isIntOrIntVectorTy(),
1179 "SIToFP source must be integer or integer vector", &I);
1180 Assert1(DestTy->isFPOrFPVectorTy(),
1181 "SIToFP result must be FP or FP vector", &I);
1183 if (SrcVec && DstVec)
1184 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1185 cast<VectorType>(DestTy)->getNumElements(),
1186 "SIToFP source and dest vector length mismatch", &I);
1188 visitInstruction(I);
1191 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1192 // Get the source and destination types
1193 Type *SrcTy = I.getOperand(0)->getType();
1194 Type *DestTy = I.getType();
1196 bool SrcVec = SrcTy->isVectorTy();
1197 bool DstVec = DestTy->isVectorTy();
1199 Assert1(SrcVec == DstVec,
1200 "FPToUI source and dest must both be vector or scalar", &I);
1201 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1203 Assert1(DestTy->isIntOrIntVectorTy(),
1204 "FPToUI result must be integer or integer vector", &I);
1206 if (SrcVec && DstVec)
1207 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1208 cast<VectorType>(DestTy)->getNumElements(),
1209 "FPToUI source and dest vector length mismatch", &I);
1211 visitInstruction(I);
1214 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1215 // Get the source and destination types
1216 Type *SrcTy = I.getOperand(0)->getType();
1217 Type *DestTy = I.getType();
1219 bool SrcVec = SrcTy->isVectorTy();
1220 bool DstVec = DestTy->isVectorTy();
1222 Assert1(SrcVec == DstVec,
1223 "FPToSI source and dest must both be vector or scalar", &I);
1224 Assert1(SrcTy->isFPOrFPVectorTy(),
1225 "FPToSI source must be FP or FP vector", &I);
1226 Assert1(DestTy->isIntOrIntVectorTy(),
1227 "FPToSI result must be integer or integer vector", &I);
1229 if (SrcVec && DstVec)
1230 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1231 cast<VectorType>(DestTy)->getNumElements(),
1232 "FPToSI source and dest vector length mismatch", &I);
1234 visitInstruction(I);
1237 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1238 // Get the source and destination types
1239 Type *SrcTy = I.getOperand(0)->getType();
1240 Type *DestTy = I.getType();
1242 Assert1(SrcTy->getScalarType()->isPointerTy(),
1243 "PtrToInt source must be pointer", &I);
1244 Assert1(DestTy->getScalarType()->isIntegerTy(),
1245 "PtrToInt result must be integral", &I);
1246 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1247 "PtrToInt type mismatch", &I);
1249 if (SrcTy->isVectorTy()) {
1250 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1251 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1252 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1253 "PtrToInt Vector width mismatch", &I);
1256 visitInstruction(I);
1259 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1260 // Get the source and destination types
1261 Type *SrcTy = I.getOperand(0)->getType();
1262 Type *DestTy = I.getType();
1264 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1265 "IntToPtr source must be an integral", &I);
1266 Assert1(DestTy->getScalarType()->isPointerTy(),
1267 "IntToPtr result must be a pointer",&I);
1268 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1269 "IntToPtr type mismatch", &I);
1270 if (SrcTy->isVectorTy()) {
1271 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1272 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1273 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1274 "IntToPtr Vector width mismatch", &I);
1276 visitInstruction(I);
1279 void Verifier::visitBitCastInst(BitCastInst &I) {
1280 // Get the source and destination types
1281 Type *SrcTy = I.getOperand(0)->getType();
1282 Type *DestTy = I.getType();
1284 // Get the size of the types in bits, we'll need this later
1285 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1286 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1288 // BitCast implies a no-op cast of type only. No bits change.
1289 // However, you can't cast pointers to anything but pointers.
1290 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
1291 "Bitcast requires both operands to be pointer or neither", &I);
1292 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1294 // Disallow aggregates.
1295 Assert1(!SrcTy->isAggregateType(),
1296 "Bitcast operand must not be aggregate", &I);
1297 Assert1(!DestTy->isAggregateType(),
1298 "Bitcast type must not be aggregate", &I);
1300 visitInstruction(I);
1303 /// visitPHINode - Ensure that a PHI node is well formed.
1305 void Verifier::visitPHINode(PHINode &PN) {
1306 // Ensure that the PHI nodes are all grouped together at the top of the block.
1307 // This can be tested by checking whether the instruction before this is
1308 // either nonexistent (because this is begin()) or is a PHI node. If not,
1309 // then there is some other instruction before a PHI.
1310 Assert2(&PN == &PN.getParent()->front() ||
1311 isa<PHINode>(--BasicBlock::iterator(&PN)),
1312 "PHI nodes not grouped at top of basic block!",
1313 &PN, PN.getParent());
1315 // Check that all of the values of the PHI node have the same type as the
1316 // result, and that the incoming blocks are really basic blocks.
1317 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1318 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1319 "PHI node operands are not the same type as the result!", &PN);
1322 // All other PHI node constraints are checked in the visitBasicBlock method.
1324 visitInstruction(PN);
1327 void Verifier::VerifyCallSite(CallSite CS) {
1328 Instruction *I = CS.getInstruction();
1330 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1331 "Called function must be a pointer!", I);
1332 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1334 Assert1(FPTy->getElementType()->isFunctionTy(),
1335 "Called function is not pointer to function type!", I);
1336 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1338 // Verify that the correct number of arguments are being passed
1339 if (FTy->isVarArg())
1340 Assert1(CS.arg_size() >= FTy->getNumParams(),
1341 "Called function requires more parameters than were provided!",I);
1343 Assert1(CS.arg_size() == FTy->getNumParams(),
1344 "Incorrect number of arguments passed to called function!", I);
1346 // Verify that all arguments to the call match the function type.
1347 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1348 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1349 "Call parameter type does not match function signature!",
1350 CS.getArgument(i), FTy->getParamType(i), I);
1352 const AttributeSet &Attrs = CS.getAttributes();
1354 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1355 "Attribute after last parameter!", I);
1357 // Verify call attributes.
1358 VerifyFunctionAttrs(FTy, Attrs, I);
1360 if (FTy->isVarArg())
1361 // Check attributes on the varargs part.
1362 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1363 VerifyParameterAttrs(Attrs, Idx, CS.getArgument(Idx-1)->getType(),
1366 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1367 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1370 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1371 if (CS.getCalledFunction() == 0 ||
1372 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1373 for (FunctionType::param_iterator PI = FTy->param_begin(),
1374 PE = FTy->param_end(); PI != PE; ++PI)
1375 Assert1(!(*PI)->isMetadataTy(),
1376 "Function has metadata parameter but isn't an intrinsic", I);
1379 visitInstruction(*I);
1382 void Verifier::visitCallInst(CallInst &CI) {
1383 VerifyCallSite(&CI);
1385 if (Function *F = CI.getCalledFunction())
1386 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1387 visitIntrinsicFunctionCall(ID, CI);
1390 void Verifier::visitInvokeInst(InvokeInst &II) {
1391 VerifyCallSite(&II);
1393 // Verify that there is a landingpad instruction as the first non-PHI
1394 // instruction of the 'unwind' destination.
1395 Assert1(II.getUnwindDest()->isLandingPad(),
1396 "The unwind destination does not have a landingpad instruction!",&II);
1398 visitTerminatorInst(II);
1401 /// visitBinaryOperator - Check that both arguments to the binary operator are
1402 /// of the same type!
1404 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1405 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1406 "Both operands to a binary operator are not of the same type!", &B);
1408 switch (B.getOpcode()) {
1409 // Check that integer arithmetic operators are only used with
1410 // integral operands.
1411 case Instruction::Add:
1412 case Instruction::Sub:
1413 case Instruction::Mul:
1414 case Instruction::SDiv:
1415 case Instruction::UDiv:
1416 case Instruction::SRem:
1417 case Instruction::URem:
1418 Assert1(B.getType()->isIntOrIntVectorTy(),
1419 "Integer arithmetic operators only work with integral types!", &B);
1420 Assert1(B.getType() == B.getOperand(0)->getType(),
1421 "Integer arithmetic operators must have same type "
1422 "for operands and result!", &B);
1424 // Check that floating-point arithmetic operators are only used with
1425 // floating-point operands.
1426 case Instruction::FAdd:
1427 case Instruction::FSub:
1428 case Instruction::FMul:
1429 case Instruction::FDiv:
1430 case Instruction::FRem:
1431 Assert1(B.getType()->isFPOrFPVectorTy(),
1432 "Floating-point arithmetic operators only work with "
1433 "floating-point types!", &B);
1434 Assert1(B.getType() == B.getOperand(0)->getType(),
1435 "Floating-point arithmetic operators must have same type "
1436 "for operands and result!", &B);
1438 // Check that logical operators are only used with integral operands.
1439 case Instruction::And:
1440 case Instruction::Or:
1441 case Instruction::Xor:
1442 Assert1(B.getType()->isIntOrIntVectorTy(),
1443 "Logical operators only work with integral types!", &B);
1444 Assert1(B.getType() == B.getOperand(0)->getType(),
1445 "Logical operators must have same type for operands and result!",
1448 case Instruction::Shl:
1449 case Instruction::LShr:
1450 case Instruction::AShr:
1451 Assert1(B.getType()->isIntOrIntVectorTy(),
1452 "Shifts only work with integral types!", &B);
1453 Assert1(B.getType() == B.getOperand(0)->getType(),
1454 "Shift return type must be same as operands!", &B);
1457 llvm_unreachable("Unknown BinaryOperator opcode!");
1460 visitInstruction(B);
1463 void Verifier::visitICmpInst(ICmpInst &IC) {
1464 // Check that the operands are the same type
1465 Type *Op0Ty = IC.getOperand(0)->getType();
1466 Type *Op1Ty = IC.getOperand(1)->getType();
1467 Assert1(Op0Ty == Op1Ty,
1468 "Both operands to ICmp instruction are not of the same type!", &IC);
1469 // Check that the operands are the right type
1470 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1471 "Invalid operand types for ICmp instruction", &IC);
1472 // Check that the predicate is valid.
1473 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1474 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1475 "Invalid predicate in ICmp instruction!", &IC);
1477 visitInstruction(IC);
1480 void Verifier::visitFCmpInst(FCmpInst &FC) {
1481 // Check that the operands are the same type
1482 Type *Op0Ty = FC.getOperand(0)->getType();
1483 Type *Op1Ty = FC.getOperand(1)->getType();
1484 Assert1(Op0Ty == Op1Ty,
1485 "Both operands to FCmp instruction are not of the same type!", &FC);
1486 // Check that the operands are the right type
1487 Assert1(Op0Ty->isFPOrFPVectorTy(),
1488 "Invalid operand types for FCmp instruction", &FC);
1489 // Check that the predicate is valid.
1490 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1491 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1492 "Invalid predicate in FCmp instruction!", &FC);
1494 visitInstruction(FC);
1497 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1498 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1500 "Invalid extractelement operands!", &EI);
1501 visitInstruction(EI);
1504 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1505 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1508 "Invalid insertelement operands!", &IE);
1509 visitInstruction(IE);
1512 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1513 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1515 "Invalid shufflevector operands!", &SV);
1516 visitInstruction(SV);
1519 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1520 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1522 Assert1(isa<PointerType>(TargetTy),
1523 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1524 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1525 "GEP into unsized type!", &GEP);
1526 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1527 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1530 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1532 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1533 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1535 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1536 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1537 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1539 if (GEP.getPointerOperandType()->isVectorTy()) {
1540 // Additional checks for vector GEPs.
1541 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1542 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1543 "Vector GEP result width doesn't match operand's", &GEP);
1544 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1545 Type *IndexTy = Idxs[i]->getType();
1546 Assert1(IndexTy->isVectorTy(),
1547 "Vector GEP must have vector indices!", &GEP);
1548 unsigned IndexWidth = IndexTy->getVectorNumElements();
1549 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1552 visitInstruction(GEP);
1555 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1556 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1559 void Verifier::visitLoadInst(LoadInst &LI) {
1560 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1561 Assert1(PTy, "Load operand must be a pointer.", &LI);
1562 Type *ElTy = PTy->getElementType();
1563 Assert2(ElTy == LI.getType(),
1564 "Load result type does not match pointer operand type!", &LI, ElTy);
1565 if (LI.isAtomic()) {
1566 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1567 "Load cannot have Release ordering", &LI);
1568 Assert1(LI.getAlignment() != 0,
1569 "Atomic load must specify explicit alignment", &LI);
1570 if (!ElTy->isPointerTy()) {
1571 Assert2(ElTy->isIntegerTy(),
1572 "atomic store operand must have integer type!",
1574 unsigned Size = ElTy->getPrimitiveSizeInBits();
1575 Assert2(Size >= 8 && !(Size & (Size - 1)),
1576 "atomic store operand must be power-of-two byte-sized integer",
1580 Assert1(LI.getSynchScope() == CrossThread,
1581 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1584 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1585 unsigned NumOperands = Range->getNumOperands();
1586 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1587 unsigned NumRanges = NumOperands / 2;
1588 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1590 ConstantRange LastRange(1); // Dummy initial value
1591 for (unsigned i = 0; i < NumRanges; ++i) {
1592 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1593 Assert1(Low, "The lower limit must be an integer!", Low);
1594 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1595 Assert1(High, "The upper limit must be an integer!", High);
1596 Assert1(High->getType() == Low->getType() &&
1597 High->getType() == ElTy, "Range types must match load type!",
1600 APInt HighV = High->getValue();
1601 APInt LowV = Low->getValue();
1602 ConstantRange CurRange(LowV, HighV);
1603 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1604 "Range must not be empty!", Range);
1606 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1607 "Intervals are overlapping", Range);
1608 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1610 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1613 LastRange = ConstantRange(LowV, HighV);
1615 if (NumRanges > 2) {
1617 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1619 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1620 ConstantRange FirstRange(FirstLow, FirstHigh);
1621 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1622 "Intervals are overlapping", Range);
1623 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1630 visitInstruction(LI);
1633 void Verifier::visitStoreInst(StoreInst &SI) {
1634 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1635 Assert1(PTy, "Store operand must be a pointer.", &SI);
1636 Type *ElTy = PTy->getElementType();
1637 Assert2(ElTy == SI.getOperand(0)->getType(),
1638 "Stored value type does not match pointer operand type!",
1640 if (SI.isAtomic()) {
1641 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1642 "Store cannot have Acquire ordering", &SI);
1643 Assert1(SI.getAlignment() != 0,
1644 "Atomic store must specify explicit alignment", &SI);
1645 if (!ElTy->isPointerTy()) {
1646 Assert2(ElTy->isIntegerTy(),
1647 "atomic store operand must have integer type!",
1649 unsigned Size = ElTy->getPrimitiveSizeInBits();
1650 Assert2(Size >= 8 && !(Size & (Size - 1)),
1651 "atomic store operand must be power-of-two byte-sized integer",
1655 Assert1(SI.getSynchScope() == CrossThread,
1656 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1658 visitInstruction(SI);
1661 void Verifier::visitAllocaInst(AllocaInst &AI) {
1662 PointerType *PTy = AI.getType();
1663 Assert1(PTy->getAddressSpace() == 0,
1664 "Allocation instruction pointer not in the generic address space!",
1666 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1668 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1669 "Alloca array size must have integer type", &AI);
1670 visitInstruction(AI);
1673 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1674 Assert1(CXI.getOrdering() != NotAtomic,
1675 "cmpxchg instructions must be atomic.", &CXI);
1676 Assert1(CXI.getOrdering() != Unordered,
1677 "cmpxchg instructions cannot be unordered.", &CXI);
1678 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1679 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1680 Type *ElTy = PTy->getElementType();
1681 Assert2(ElTy->isIntegerTy(),
1682 "cmpxchg operand must have integer type!",
1684 unsigned Size = ElTy->getPrimitiveSizeInBits();
1685 Assert2(Size >= 8 && !(Size & (Size - 1)),
1686 "cmpxchg operand must be power-of-two byte-sized integer",
1688 Assert2(ElTy == CXI.getOperand(1)->getType(),
1689 "Expected value type does not match pointer operand type!",
1691 Assert2(ElTy == CXI.getOperand(2)->getType(),
1692 "Stored value type does not match pointer operand type!",
1694 visitInstruction(CXI);
1697 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1698 Assert1(RMWI.getOrdering() != NotAtomic,
1699 "atomicrmw instructions must be atomic.", &RMWI);
1700 Assert1(RMWI.getOrdering() != Unordered,
1701 "atomicrmw instructions cannot be unordered.", &RMWI);
1702 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1703 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1704 Type *ElTy = PTy->getElementType();
1705 Assert2(ElTy->isIntegerTy(),
1706 "atomicrmw operand must have integer type!",
1708 unsigned Size = ElTy->getPrimitiveSizeInBits();
1709 Assert2(Size >= 8 && !(Size & (Size - 1)),
1710 "atomicrmw operand must be power-of-two byte-sized integer",
1712 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1713 "Argument value type does not match pointer operand type!",
1715 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1716 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1717 "Invalid binary operation!", &RMWI);
1718 visitInstruction(RMWI);
1721 void Verifier::visitFenceInst(FenceInst &FI) {
1722 const AtomicOrdering Ordering = FI.getOrdering();
1723 Assert1(Ordering == Acquire || Ordering == Release ||
1724 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1725 "fence instructions may only have "
1726 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1727 visitInstruction(FI);
1730 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1731 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1732 EVI.getIndices()) ==
1734 "Invalid ExtractValueInst operands!", &EVI);
1736 visitInstruction(EVI);
1739 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1740 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1741 IVI.getIndices()) ==
1742 IVI.getOperand(1)->getType(),
1743 "Invalid InsertValueInst operands!", &IVI);
1745 visitInstruction(IVI);
1748 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1749 BasicBlock *BB = LPI.getParent();
1751 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1753 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1754 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1756 // The landingpad instruction defines its parent as a landing pad block. The
1757 // landing pad block may be branched to only by the unwind edge of an invoke.
1758 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1759 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1760 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1761 "Block containing LandingPadInst must be jumped to "
1762 "only by the unwind edge of an invoke.", &LPI);
1765 // The landingpad instruction must be the first non-PHI instruction in the
1767 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1768 "LandingPadInst not the first non-PHI instruction in the block.",
1771 // The personality functions for all landingpad instructions within the same
1772 // function should match.
1774 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1775 "Personality function doesn't match others in function", &LPI);
1776 PersonalityFn = LPI.getPersonalityFn();
1778 // All operands must be constants.
1779 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1781 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1782 Value *Clause = LPI.getClause(i);
1783 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1784 if (LPI.isCatch(i)) {
1785 Assert1(isa<PointerType>(Clause->getType()),
1786 "Catch operand does not have pointer type!", &LPI);
1788 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1789 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1790 "Filter operand is not an array of constants!", &LPI);
1794 visitInstruction(LPI);
1797 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1798 Instruction *Op = cast<Instruction>(I.getOperand(i));
1799 // If the we have an invalid invoke, don't try to compute the dominance.
1800 // We already reject it in the invoke specific checks and the dominance
1801 // computation doesn't handle multiple edges.
1802 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1803 if (II->getNormalDest() == II->getUnwindDest())
1807 const Use &U = I.getOperandUse(i);
1808 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1809 "Instruction does not dominate all uses!", Op, &I);
1812 /// verifyInstruction - Verify that an instruction is well formed.
1814 void Verifier::visitInstruction(Instruction &I) {
1815 BasicBlock *BB = I.getParent();
1816 Assert1(BB, "Instruction not embedded in basic block!", &I);
1818 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1819 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1821 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1822 "Only PHI nodes may reference their own value!", &I);
1825 // Check that void typed values don't have names
1826 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1827 "Instruction has a name, but provides a void value!", &I);
1829 // Check that the return value of the instruction is either void or a legal
1831 Assert1(I.getType()->isVoidTy() ||
1832 I.getType()->isFirstClassType(),
1833 "Instruction returns a non-scalar type!", &I);
1835 // Check that the instruction doesn't produce metadata. Calls are already
1836 // checked against the callee type.
1837 Assert1(!I.getType()->isMetadataTy() ||
1838 isa<CallInst>(I) || isa<InvokeInst>(I),
1839 "Invalid use of metadata!", &I);
1841 // Check that all uses of the instruction, if they are instructions
1842 // themselves, actually have parent basic blocks. If the use is not an
1843 // instruction, it is an error!
1844 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1846 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1847 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1848 " embedded in a basic block!", &I, Used);
1850 CheckFailed("Use of instruction is not an instruction!", *UI);
1855 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1856 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1858 // Check to make sure that only first-class-values are operands to
1860 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1861 Assert1(0, "Instruction operands must be first-class values!", &I);
1864 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1865 // Check to make sure that the "address of" an intrinsic function is never
1867 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
1868 "Cannot take the address of an intrinsic!", &I);
1869 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
1870 F->getIntrinsicID() == Intrinsic::donothing,
1871 "Cannot invoke an intrinsinc other than donothing", &I);
1872 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1874 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1875 Assert1(OpBB->getParent() == BB->getParent(),
1876 "Referring to a basic block in another function!", &I);
1877 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1878 Assert1(OpArg->getParent() == BB->getParent(),
1879 "Referring to an argument in another function!", &I);
1880 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1881 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1883 } else if (isa<Instruction>(I.getOperand(i))) {
1884 verifyDominatesUse(I, i);
1885 } else if (isa<InlineAsm>(I.getOperand(i))) {
1886 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1887 (i + 3 == e && isa<InvokeInst>(I)),
1888 "Cannot take the address of an inline asm!", &I);
1892 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
1893 Assert1(I.getType()->isFPOrFPVectorTy(),
1894 "fpmath requires a floating point result!", &I);
1895 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
1896 Value *Op0 = MD->getOperand(0);
1897 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
1898 APFloat Accuracy = CFP0->getValueAPF();
1899 Assert1(Accuracy.isNormal() && !Accuracy.isNegative(),
1900 "fpmath accuracy not a positive number!", &I);
1902 Assert1(false, "invalid fpmath accuracy!", &I);
1906 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
1907 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
1909 InstsInThisBlock.insert(&I);
1912 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
1913 /// intrinsic argument or return value) matches the type constraints specified
1914 /// by the .td file (e.g. an "any integer" argument really is an integer).
1916 /// This return true on error but does not print a message.
1917 bool Verifier::VerifyIntrinsicType(Type *Ty,
1918 ArrayRef<Intrinsic::IITDescriptor> &Infos,
1919 SmallVectorImpl<Type*> &ArgTys) {
1920 using namespace Intrinsic;
1922 // If we ran out of descriptors, there are too many arguments.
1923 if (Infos.empty()) return true;
1924 IITDescriptor D = Infos.front();
1925 Infos = Infos.slice(1);
1928 case IITDescriptor::Void: return !Ty->isVoidTy();
1929 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
1930 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1931 case IITDescriptor::Half: return !Ty->isHalfTy();
1932 case IITDescriptor::Float: return !Ty->isFloatTy();
1933 case IITDescriptor::Double: return !Ty->isDoubleTy();
1934 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1935 case IITDescriptor::Vector: {
1936 VectorType *VT = dyn_cast<VectorType>(Ty);
1937 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
1938 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
1940 case IITDescriptor::Pointer: {
1941 PointerType *PT = dyn_cast<PointerType>(Ty);
1942 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1943 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
1946 case IITDescriptor::Struct: {
1947 StructType *ST = dyn_cast<StructType>(Ty);
1948 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
1951 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1952 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
1957 case IITDescriptor::Argument:
1958 // Two cases here - If this is the second occurrence of an argument, verify
1959 // that the later instance matches the previous instance.
1960 if (D.getArgumentNumber() < ArgTys.size())
1961 return Ty != ArgTys[D.getArgumentNumber()];
1963 // Otherwise, if this is the first instance of an argument, record it and
1964 // verify the "Any" kind.
1965 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
1966 ArgTys.push_back(Ty);
1968 switch (D.getArgumentKind()) {
1969 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1970 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
1971 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
1972 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1974 llvm_unreachable("all argument kinds not covered");
1976 case IITDescriptor::ExtendVecArgument:
1977 // This may only be used when referring to a previous vector argument.
1978 return D.getArgumentNumber() >= ArgTys.size() ||
1979 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1980 VectorType::getExtendedElementVectorType(
1981 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1983 case IITDescriptor::TruncVecArgument:
1984 // This may only be used when referring to a previous vector argument.
1985 return D.getArgumentNumber() >= ArgTys.size() ||
1986 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1987 VectorType::getTruncatedElementVectorType(
1988 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1990 llvm_unreachable("unhandled");
1993 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1995 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1996 Function *IF = CI.getCalledFunction();
1997 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2000 // Verify that the intrinsic prototype lines up with what the .td files
2002 FunctionType *IFTy = IF->getFunctionType();
2003 Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
2005 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2006 getIntrinsicInfoTableEntries(ID, Table);
2007 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2009 SmallVector<Type *, 4> ArgTys;
2010 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2011 "Intrinsic has incorrect return type!", IF);
2012 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2013 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2014 "Intrinsic has incorrect argument type!", IF);
2015 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2017 // Now that we have the intrinsic ID and the actual argument types (and we
2018 // know they are legal for the intrinsic!) get the intrinsic name through the
2019 // usual means. This allows us to verify the mangling of argument types into
2021 Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
2022 "Intrinsic name not mangled correctly for type arguments!", IF);
2024 // If the intrinsic takes MDNode arguments, verify that they are either global
2025 // or are local to *this* function.
2026 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2027 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2028 visitMDNode(*MD, CI.getParent()->getParent());
2033 case Intrinsic::ctlz: // llvm.ctlz
2034 case Intrinsic::cttz: // llvm.cttz
2035 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2036 "is_zero_undef argument of bit counting intrinsics must be a "
2037 "constant int", &CI);
2039 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2040 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2041 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2042 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2043 Assert1(MD->getNumOperands() == 1,
2044 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2046 case Intrinsic::memcpy:
2047 case Intrinsic::memmove:
2048 case Intrinsic::memset:
2049 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2050 "alignment argument of memory intrinsics must be a constant int",
2052 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2053 "isvolatile argument of memory intrinsics must be a constant int",
2056 case Intrinsic::gcroot:
2057 case Intrinsic::gcwrite:
2058 case Intrinsic::gcread:
2059 if (ID == Intrinsic::gcroot) {
2061 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2062 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2063 Assert1(isa<Constant>(CI.getArgOperand(1)),
2064 "llvm.gcroot parameter #2 must be a constant.", &CI);
2065 if (!AI->getType()->getElementType()->isPointerTy()) {
2066 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2067 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2068 "or argument #2 must be a non-null constant.", &CI);
2072 Assert1(CI.getParent()->getParent()->hasGC(),
2073 "Enclosing function does not use GC.", &CI);
2075 case Intrinsic::init_trampoline:
2076 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2077 "llvm.init_trampoline parameter #2 must resolve to a function.",
2080 case Intrinsic::prefetch:
2081 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2082 isa<ConstantInt>(CI.getArgOperand(2)) &&
2083 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2084 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2085 "invalid arguments to llvm.prefetch",
2088 case Intrinsic::stackprotector:
2089 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2090 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2093 case Intrinsic::lifetime_start:
2094 case Intrinsic::lifetime_end:
2095 case Intrinsic::invariant_start:
2096 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2097 "size argument of memory use markers must be a constant integer",
2100 case Intrinsic::invariant_end:
2101 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2102 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2107 //===----------------------------------------------------------------------===//
2108 // Implement the public interfaces to this file...
2109 //===----------------------------------------------------------------------===//
2111 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2112 return new Verifier(action);
2116 /// verifyFunction - Check a function for errors, printing messages on stderr.
2117 /// Return true if the function is corrupt.
2119 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2120 Function &F = const_cast<Function&>(f);
2121 assert(!F.isDeclaration() && "Cannot verify external functions");
2123 FunctionPassManager FPM(F.getParent());
2124 Verifier *V = new Verifier(action);
2130 /// verifyModule - Check a module for errors, printing messages on stderr.
2131 /// Return true if the module is corrupt.
2133 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2134 std::string *ErrorInfo) {
2136 Verifier *V = new Verifier(action);
2138 PM.run(const_cast<Module&>(M));
2140 if (ErrorInfo && V->Broken)
2141 *ErrorInfo = V->MessagesStr.str();