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, SmallSetVector<MDString*, 16> &SeenIDs);
247 void visitFunction(Function &F);
248 void visitBasicBlock(BasicBlock &BB);
249 using InstVisitor<Verifier>::visit;
251 void visit(Instruction &I);
253 void visitTruncInst(TruncInst &I);
254 void visitZExtInst(ZExtInst &I);
255 void visitSExtInst(SExtInst &I);
256 void visitFPTruncInst(FPTruncInst &I);
257 void visitFPExtInst(FPExtInst &I);
258 void visitFPToUIInst(FPToUIInst &I);
259 void visitFPToSIInst(FPToSIInst &I);
260 void visitUIToFPInst(UIToFPInst &I);
261 void visitSIToFPInst(SIToFPInst &I);
262 void visitIntToPtrInst(IntToPtrInst &I);
263 void visitPtrToIntInst(PtrToIntInst &I);
264 void visitBitCastInst(BitCastInst &I);
265 void visitPHINode(PHINode &PN);
266 void visitBinaryOperator(BinaryOperator &B);
267 void visitICmpInst(ICmpInst &IC);
268 void visitFCmpInst(FCmpInst &FC);
269 void visitExtractElementInst(ExtractElementInst &EI);
270 void visitInsertElementInst(InsertElementInst &EI);
271 void visitShuffleVectorInst(ShuffleVectorInst &EI);
272 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
273 void visitCallInst(CallInst &CI);
274 void visitInvokeInst(InvokeInst &II);
275 void visitGetElementPtrInst(GetElementPtrInst &GEP);
276 void visitLoadInst(LoadInst &LI);
277 void visitStoreInst(StoreInst &SI);
278 void verifyDominatesUse(Instruction &I, unsigned i);
279 void visitInstruction(Instruction &I);
280 void visitTerminatorInst(TerminatorInst &I);
281 void visitBranchInst(BranchInst &BI);
282 void visitReturnInst(ReturnInst &RI);
283 void visitSwitchInst(SwitchInst &SI);
284 void visitIndirectBrInst(IndirectBrInst &BI);
285 void visitSelectInst(SelectInst &SI);
286 void visitUserOp1(Instruction &I);
287 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
288 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
289 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
290 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
291 void visitFenceInst(FenceInst &FI);
292 void visitAllocaInst(AllocaInst &AI);
293 void visitExtractValueInst(ExtractValueInst &EVI);
294 void visitInsertValueInst(InsertValueInst &IVI);
295 void visitLandingPadInst(LandingPadInst &LPI);
297 void VerifyCallSite(CallSite CS);
298 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
299 int VT, unsigned ArgNo, std::string &Suffix);
300 bool VerifyIntrinsicType(Type *Ty,
301 ArrayRef<Intrinsic::IITDescriptor> &Infos,
302 SmallVectorImpl<Type*> &ArgTys);
303 void VerifyParameterAttrs(Attribute Attrs, Type *Ty,
304 bool isReturnValue, const Value *V);
305 void VerifyFunctionAttrs(FunctionType *FT, const AttributeSet &Attrs,
308 void WriteValue(const Value *V) {
310 if (isa<Instruction>(V)) {
311 MessagesStr << *V << '\n';
313 WriteAsOperand(MessagesStr, V, true, Mod);
318 void WriteType(Type *T) {
320 MessagesStr << ' ' << *T;
324 // CheckFailed - A check failed, so print out the condition and the message
325 // that failed. This provides a nice place to put a breakpoint if you want
326 // to see why something is not correct.
327 void CheckFailed(const Twine &Message,
328 const Value *V1 = 0, const Value *V2 = 0,
329 const Value *V3 = 0, const Value *V4 = 0) {
330 MessagesStr << Message.str() << "\n";
338 void CheckFailed(const Twine &Message, const Value *V1,
339 Type *T2, const Value *V3 = 0) {
340 MessagesStr << Message.str() << "\n";
347 void CheckFailed(const Twine &Message, Type *T1,
348 Type *T2 = 0, Type *T3 = 0) {
349 MessagesStr << Message.str() << "\n";
356 } // End anonymous namespace
358 char Verifier::ID = 0;
359 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
360 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
361 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
362 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
364 // Assert - We know that cond should be true, if not print an error message.
365 #define Assert(C, M) \
366 do { if (!(C)) { CheckFailed(M); return; } } while (0)
367 #define Assert1(C, M, V1) \
368 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
369 #define Assert2(C, M, V1, V2) \
370 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
371 #define Assert3(C, M, V1, V2, V3) \
372 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
373 #define Assert4(C, M, V1, V2, V3, V4) \
374 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
376 void Verifier::visit(Instruction &I) {
377 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
378 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
379 InstVisitor<Verifier>::visit(I);
383 void Verifier::visitGlobalValue(GlobalValue &GV) {
384 Assert1(!GV.isDeclaration() ||
385 GV.isMaterializable() ||
386 GV.hasExternalLinkage() ||
387 GV.hasDLLImportLinkage() ||
388 GV.hasExternalWeakLinkage() ||
389 (isa<GlobalAlias>(GV) &&
390 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
391 "Global is external, but doesn't have external or dllimport or weak linkage!",
394 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
395 "Global is marked as dllimport, but not external", &GV);
397 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
398 "Only global variables can have appending linkage!", &GV);
400 if (GV.hasAppendingLinkage()) {
401 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
402 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
403 "Only global arrays can have appending linkage!", GVar);
406 Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
407 "linkonce_odr_auto_hide can only have default visibility!",
411 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
412 if (GV.hasInitializer()) {
413 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
414 "Global variable initializer type does not match global "
415 "variable type!", &GV);
417 // If the global has common linkage, it must have a zero initializer and
418 // cannot be constant.
419 if (GV.hasCommonLinkage()) {
420 Assert1(GV.getInitializer()->isNullValue(),
421 "'common' global must have a zero initializer!", &GV);
422 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
426 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
427 GV.hasExternalWeakLinkage(),
428 "invalid linkage type for global declaration", &GV);
431 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
432 GV.getName() == "llvm.global_dtors")) {
433 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
434 "invalid linkage for intrinsic global variable", &GV);
435 // Don't worry about emitting an error for it not being an array,
436 // visitGlobalValue will complain on appending non-array.
437 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
438 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
439 PointerType *FuncPtrTy =
440 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
441 Assert1(STy && STy->getNumElements() == 2 &&
442 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
443 STy->getTypeAtIndex(1) == FuncPtrTy,
444 "wrong type for intrinsic global variable", &GV);
448 visitGlobalValue(GV);
451 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
452 Assert1(!GA.getName().empty(),
453 "Alias name cannot be empty!", &GA);
454 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
456 "Alias should have external or external weak linkage!", &GA);
457 Assert1(GA.getAliasee(),
458 "Aliasee cannot be NULL!", &GA);
459 Assert1(GA.getType() == GA.getAliasee()->getType(),
460 "Alias and aliasee types should match!", &GA);
461 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
463 if (!isa<GlobalValue>(GA.getAliasee())) {
464 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
466 (CE->getOpcode() == Instruction::BitCast ||
467 CE->getOpcode() == Instruction::GetElementPtr) &&
468 isa<GlobalValue>(CE->getOperand(0)),
469 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
473 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
475 "Aliasing chain should end with function or global variable", &GA);
477 visitGlobalValue(GA);
480 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
481 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
482 MDNode *MD = NMD.getOperand(i);
486 Assert1(!MD->isFunctionLocal(),
487 "Named metadata operand cannot be function local!", MD);
492 void Verifier::visitMDNode(MDNode &MD, Function *F) {
493 // Only visit each node once. Metadata can be mutually recursive, so this
494 // avoids infinite recursion here, as well as being an optimization.
495 if (!MDNodes.insert(&MD))
498 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
499 Value *Op = MD.getOperand(i);
502 if (isa<Constant>(Op) || isa<MDString>(Op))
504 if (MDNode *N = dyn_cast<MDNode>(Op)) {
505 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
506 "Global metadata operand cannot be function local!", &MD, N);
510 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
512 // If this was an instruction, bb, or argument, verify that it is in the
513 // function that we expect.
514 Function *ActualF = 0;
515 if (Instruction *I = dyn_cast<Instruction>(Op))
516 ActualF = I->getParent()->getParent();
517 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
518 ActualF = BB->getParent();
519 else if (Argument *A = dyn_cast<Argument>(Op))
520 ActualF = A->getParent();
521 assert(ActualF && "Unimplemented function local metadata case!");
523 Assert2(ActualF == F, "function-local metadata used in wrong function",
528 void Verifier::visitModuleFlags(Module &M) {
529 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
533 SmallSetVector<MDString*, 16> SeenIDs;
534 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
535 visitModuleFlag(Flags->getOperand(I), SeenIDs);
539 void Verifier::visitModuleFlag(MDNode *Op,
540 SmallSetVector<MDString*, 16> &SeenIDs) {
541 // Each module flag should have three arguments, the merge behavior (a
542 // constant int), the flag ID (an MDString), and the value.
543 Assert1(Op->getNumOperands() == 3,
544 "incorrect number of operands in module flag", Op);
545 ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
546 MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
548 "invalid behavior operand in module flag (expected constant integer)",
550 unsigned BehaviorValue = Behavior->getZExtValue();
551 Assert1((Module::Error <= BehaviorValue &&
552 BehaviorValue <= Module::Override),
553 "invalid behavior operand in module flag (unexpected constant)",
556 "invalid ID operand in module flag (expected metadata string)",
559 // Unless this is a "requires" flag, check the ID is unique.
560 if (BehaviorValue != Module::Require) {
561 Assert1(SeenIDs.insert(ID),
562 "module flag identifiers must be unique (or of 'require' type)",
566 // If this is a "requires" flag, sanity check the value.
567 if (BehaviorValue == Module::Require) {
568 // The value should itself be an MDNode with two operands, a flag ID (an
569 // MDString), and a value.
570 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
571 Assert1(Value && Value->getNumOperands() == 2,
572 "invalid value for 'require' module flag (expected metadata pair)",
574 Assert1(isa<MDString>(Value->getOperand(0)),
575 ("invalid value for 'require' module flag "
576 "(first value operand should be a string)"),
577 Value->getOperand(0));
581 // VerifyParameterAttrs - Check the given attributes for an argument or return
582 // value of the specified type. The value V is printed in error messages.
583 void Verifier::VerifyParameterAttrs(Attribute Attrs, Type *Ty,
584 bool isReturnValue, const Value *V) {
585 if (!Attrs.hasAttributes())
588 Assert1(!Attrs.hasAttribute(Attribute::NoReturn) &&
589 !Attrs.hasAttribute(Attribute::NoUnwind) &&
590 !Attrs.hasAttribute(Attribute::ReadNone) &&
591 !Attrs.hasAttribute(Attribute::ReadOnly) &&
592 !Attrs.hasAttribute(Attribute::NoInline) &&
593 !Attrs.hasAttribute(Attribute::AlwaysInline) &&
594 !Attrs.hasAttribute(Attribute::OptimizeForSize) &&
595 !Attrs.hasAttribute(Attribute::StackProtect) &&
596 !Attrs.hasAttribute(Attribute::StackProtectReq) &&
597 !Attrs.hasAttribute(Attribute::NoRedZone) &&
598 !Attrs.hasAttribute(Attribute::NoImplicitFloat) &&
599 !Attrs.hasAttribute(Attribute::Naked) &&
600 !Attrs.hasAttribute(Attribute::InlineHint) &&
601 !Attrs.hasAttribute(Attribute::StackAlignment) &&
602 !Attrs.hasAttribute(Attribute::UWTable) &&
603 !Attrs.hasAttribute(Attribute::NonLazyBind) &&
604 !Attrs.hasAttribute(Attribute::ReturnsTwice) &&
605 !Attrs.hasAttribute(Attribute::AddressSafety) &&
606 !Attrs.hasAttribute(Attribute::MinSize),
607 "Some attributes in '" + Attrs.getAsString() +
608 "' only apply to functions!", V);
611 Assert1(!Attrs.hasAttribute(Attribute::ByVal) &&
612 !Attrs.hasAttribute(Attribute::Nest) &&
613 !Attrs.hasAttribute(Attribute::StructRet) &&
614 !Attrs.hasAttribute(Attribute::NoCapture),
615 "Attribute 'byval', 'nest', 'sret', and 'nocapture' "
616 "do not apply to return values!", V);
618 // Check for mutually incompatible attributes.
619 Assert1(!((Attrs.hasAttribute(Attribute::ByVal) &&
620 Attrs.hasAttribute(Attribute::Nest)) ||
621 (Attrs.hasAttribute(Attribute::ByVal) &&
622 Attrs.hasAttribute(Attribute::StructRet)) ||
623 (Attrs.hasAttribute(Attribute::Nest) &&
624 Attrs.hasAttribute(Attribute::StructRet))), "Attributes "
625 "'byval, nest, and sret' are incompatible!", V);
627 Assert1(!((Attrs.hasAttribute(Attribute::ByVal) &&
628 Attrs.hasAttribute(Attribute::Nest)) ||
629 (Attrs.hasAttribute(Attribute::ByVal) &&
630 Attrs.hasAttribute(Attribute::InReg)) ||
631 (Attrs.hasAttribute(Attribute::Nest) &&
632 Attrs.hasAttribute(Attribute::InReg))), "Attributes "
633 "'byval, nest, and inreg' are incompatible!", V);
635 Assert1(!(Attrs.hasAttribute(Attribute::ZExt) &&
636 Attrs.hasAttribute(Attribute::SExt)), "Attributes "
637 "'zeroext and signext' are incompatible!", V);
639 Assert1(!(Attrs.hasAttribute(Attribute::ReadNone) &&
640 Attrs.hasAttribute(Attribute::ReadOnly)), "Attributes "
641 "'readnone and readonly' are incompatible!", V);
643 Assert1(!(Attrs.hasAttribute(Attribute::NoInline) &&
644 Attrs.hasAttribute(Attribute::AlwaysInline)), "Attributes "
645 "'noinline and alwaysinline' are incompatible!", V);
647 Assert1(!AttrBuilder(Attrs).
648 hasAttributes(Attribute::typeIncompatible(Ty)),
649 "Wrong types for attribute: " +
650 Attribute::typeIncompatible(Ty).getAsString(), V);
652 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
653 Assert1(!Attrs.hasAttribute(Attribute::ByVal) ||
654 PTy->getElementType()->isSized(),
655 "Attribute 'byval' does not support unsized types!", V);
657 Assert1(!Attrs.hasAttribute(Attribute::ByVal),
658 "Attribute 'byval' only applies to parameters with pointer type!",
662 // VerifyFunctionAttrs - Check parameter attributes against a function type.
663 // The value V is printed in error messages.
664 void Verifier::VerifyFunctionAttrs(FunctionType *FT,
665 const AttributeSet &Attrs,
670 bool SawNest = false;
672 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
673 const AttributeWithIndex &Attr = Attrs.getSlot(i);
677 Ty = FT->getReturnType();
678 else if (Attr.Index-1 < FT->getNumParams())
679 Ty = FT->getParamType(Attr.Index-1);
681 break; // VarArgs attributes, verified elsewhere.
683 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
685 if (Attr.Attrs.hasAttribute(Attribute::Nest)) {
686 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
690 if (Attr.Attrs.hasAttribute(Attribute::StructRet))
691 Assert1(Attr.Index == 1, "Attribute sret is not on first parameter!", V);
694 Attribute FAttrs = Attrs.getFnAttributes();
695 AttrBuilder NotFn(FAttrs);
696 NotFn.removeFunctionOnlyAttrs();
697 Assert1(!NotFn.hasAttributes(), "Attribute '" +
698 Attribute::get(V->getContext(), NotFn).getAsString() +
699 "' do not apply to the function!", V);
701 // Check for mutually incompatible attributes.
702 Assert1(!((FAttrs.hasAttribute(Attribute::ByVal) &&
703 FAttrs.hasAttribute(Attribute::Nest)) ||
704 (FAttrs.hasAttribute(Attribute::ByVal) &&
705 FAttrs.hasAttribute(Attribute::StructRet)) ||
706 (FAttrs.hasAttribute(Attribute::Nest) &&
707 FAttrs.hasAttribute(Attribute::StructRet))), "Attributes "
708 "'byval, nest, and sret' are incompatible!", V);
710 Assert1(!((FAttrs.hasAttribute(Attribute::ByVal) &&
711 FAttrs.hasAttribute(Attribute::Nest)) ||
712 (FAttrs.hasAttribute(Attribute::ByVal) &&
713 FAttrs.hasAttribute(Attribute::InReg)) ||
714 (FAttrs.hasAttribute(Attribute::Nest) &&
715 FAttrs.hasAttribute(Attribute::InReg))), "Attributes "
716 "'byval, nest, and inreg' are incompatible!", V);
718 Assert1(!(FAttrs.hasAttribute(Attribute::ZExt) &&
719 FAttrs.hasAttribute(Attribute::SExt)), "Attributes "
720 "'zeroext and signext' are incompatible!", V);
722 Assert1(!(FAttrs.hasAttribute(Attribute::ReadNone) &&
723 FAttrs.hasAttribute(Attribute::ReadOnly)), "Attributes "
724 "'readnone and readonly' are incompatible!", V);
726 Assert1(!(FAttrs.hasAttribute(Attribute::NoInline) &&
727 FAttrs.hasAttribute(Attribute::AlwaysInline)), "Attributes "
728 "'noinline and alwaysinline' are incompatible!", V);
731 static bool VerifyAttributeCount(const AttributeSet &Attrs, unsigned Params) {
735 unsigned LastSlot = Attrs.getNumSlots() - 1;
736 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
737 if (LastIndex <= Params
738 || (LastIndex == (unsigned)~0
739 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
745 // visitFunction - Verify that a function is ok.
747 void Verifier::visitFunction(Function &F) {
748 // Check function arguments.
749 FunctionType *FT = F.getFunctionType();
750 unsigned NumArgs = F.arg_size();
752 Assert1(Context == &F.getContext(),
753 "Function context does not match Module context!", &F);
755 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
756 Assert2(FT->getNumParams() == NumArgs,
757 "# formal arguments must match # of arguments for function type!",
759 Assert1(F.getReturnType()->isFirstClassType() ||
760 F.getReturnType()->isVoidTy() ||
761 F.getReturnType()->isStructTy(),
762 "Functions cannot return aggregate values!", &F);
764 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
765 "Invalid struct return type!", &F);
767 const AttributeSet &Attrs = F.getAttributes();
769 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
770 "Attribute after last parameter!", &F);
772 // Check function attributes.
773 VerifyFunctionAttrs(FT, Attrs, &F);
775 // Check that this function meets the restrictions on this calling convention.
776 switch (F.getCallingConv()) {
781 case CallingConv::Fast:
782 case CallingConv::Cold:
783 case CallingConv::X86_FastCall:
784 case CallingConv::X86_ThisCall:
785 case CallingConv::Intel_OCL_BI:
786 case CallingConv::PTX_Kernel:
787 case CallingConv::PTX_Device:
788 Assert1(!F.isVarArg(),
789 "Varargs functions must have C calling conventions!", &F);
793 bool isLLVMdotName = F.getName().size() >= 5 &&
794 F.getName().substr(0, 5) == "llvm.";
796 // Check that the argument values match the function type for this function...
798 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
800 Assert2(I->getType() == FT->getParamType(i),
801 "Argument value does not match function argument type!",
802 I, FT->getParamType(i));
803 Assert1(I->getType()->isFirstClassType(),
804 "Function arguments must have first-class types!", I);
806 Assert2(!I->getType()->isMetadataTy(),
807 "Function takes metadata but isn't an intrinsic", I, &F);
810 if (F.isMaterializable()) {
811 // Function has a body somewhere we can't see.
812 } else if (F.isDeclaration()) {
813 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
814 F.hasExternalWeakLinkage(),
815 "invalid linkage type for function declaration", &F);
817 // Verify that this function (which has a body) is not named "llvm.*". It
818 // is not legal to define intrinsics.
819 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
821 // Check the entry node
822 BasicBlock *Entry = &F.getEntryBlock();
823 Assert1(pred_begin(Entry) == pred_end(Entry),
824 "Entry block to function must not have predecessors!", Entry);
826 // The address of the entry block cannot be taken, unless it is dead.
827 if (Entry->hasAddressTaken()) {
828 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
829 "blockaddress may not be used with the entry block!", Entry);
833 // If this function is actually an intrinsic, verify that it is only used in
834 // direct call/invokes, never having its "address taken".
835 if (F.getIntrinsicID()) {
837 if (F.hasAddressTaken(&U))
838 Assert1(0, "Invalid user of intrinsic instruction!", U);
842 // verifyBasicBlock - Verify that a basic block is well formed...
844 void Verifier::visitBasicBlock(BasicBlock &BB) {
845 InstsInThisBlock.clear();
847 // Ensure that basic blocks have terminators!
848 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
850 // Check constraints that this basic block imposes on all of the PHI nodes in
852 if (isa<PHINode>(BB.front())) {
853 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
854 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
855 std::sort(Preds.begin(), Preds.end());
857 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
858 // Ensure that PHI nodes have at least one entry!
859 Assert1(PN->getNumIncomingValues() != 0,
860 "PHI nodes must have at least one entry. If the block is dead, "
861 "the PHI should be removed!", PN);
862 Assert1(PN->getNumIncomingValues() == Preds.size(),
863 "PHINode should have one entry for each predecessor of its "
864 "parent basic block!", PN);
866 // Get and sort all incoming values in the PHI node...
868 Values.reserve(PN->getNumIncomingValues());
869 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
870 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
871 PN->getIncomingValue(i)));
872 std::sort(Values.begin(), Values.end());
874 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
875 // Check to make sure that if there is more than one entry for a
876 // particular basic block in this PHI node, that the incoming values are
879 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
880 Values[i].second == Values[i-1].second,
881 "PHI node has multiple entries for the same basic block with "
882 "different incoming values!", PN, Values[i].first,
883 Values[i].second, Values[i-1].second);
885 // Check to make sure that the predecessors and PHI node entries are
887 Assert3(Values[i].first == Preds[i],
888 "PHI node entries do not match predecessors!", PN,
889 Values[i].first, Preds[i]);
895 void Verifier::visitTerminatorInst(TerminatorInst &I) {
896 // Ensure that terminators only exist at the end of the basic block.
897 Assert1(&I == I.getParent()->getTerminator(),
898 "Terminator found in the middle of a basic block!", I.getParent());
902 void Verifier::visitBranchInst(BranchInst &BI) {
903 if (BI.isConditional()) {
904 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
905 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
907 visitTerminatorInst(BI);
910 void Verifier::visitReturnInst(ReturnInst &RI) {
911 Function *F = RI.getParent()->getParent();
912 unsigned N = RI.getNumOperands();
913 if (F->getReturnType()->isVoidTy())
915 "Found return instr that returns non-void in Function of void "
916 "return type!", &RI, F->getReturnType());
918 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
919 "Function return type does not match operand "
920 "type of return inst!", &RI, F->getReturnType());
922 // Check to make sure that the return value has necessary properties for
924 visitTerminatorInst(RI);
927 void Verifier::visitSwitchInst(SwitchInst &SI) {
928 // Check to make sure that all of the constants in the switch instruction
929 // have the same type as the switched-on value.
930 Type *SwitchTy = SI.getCondition()->getType();
931 IntegerType *IntTy = cast<IntegerType>(SwitchTy);
932 IntegersSubsetToBB Mapping;
933 std::map<IntegersSubset::Range, unsigned> RangeSetMap;
934 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
935 IntegersSubset CaseRanges = i.getCaseValueEx();
936 for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
937 IntegersSubset::Range r = CaseRanges.getItem(ri);
938 Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
939 "Switch constants must all be same type as switch value!", &SI);
940 Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
941 "Switch constants must all be same type as switch value!", &SI);
943 RangeSetMap[r] = i.getCaseIndex();
947 IntegersSubsetToBB::RangeIterator errItem;
948 if (!Mapping.verify(errItem)) {
949 unsigned CaseIndex = RangeSetMap[errItem->first];
950 SwitchInst::CaseIt i(&SI, CaseIndex);
951 Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
954 visitTerminatorInst(SI);
957 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
958 Assert1(BI.getAddress()->getType()->isPointerTy(),
959 "Indirectbr operand must have pointer type!", &BI);
960 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
961 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
962 "Indirectbr destinations must all have pointer type!", &BI);
964 visitTerminatorInst(BI);
967 void Verifier::visitSelectInst(SelectInst &SI) {
968 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
970 "Invalid operands for select instruction!", &SI);
972 Assert1(SI.getTrueValue()->getType() == SI.getType(),
973 "Select values must have same type as select instruction!", &SI);
974 visitInstruction(SI);
977 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
978 /// a pass, if any exist, it's an error.
980 void Verifier::visitUserOp1(Instruction &I) {
981 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
984 void Verifier::visitTruncInst(TruncInst &I) {
985 // Get the source and destination types
986 Type *SrcTy = I.getOperand(0)->getType();
987 Type *DestTy = I.getType();
989 // Get the size of the types in bits, we'll need this later
990 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
991 unsigned DestBitSize = DestTy->getScalarSizeInBits();
993 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
994 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
995 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
996 "trunc source and destination must both be a vector or neither", &I);
997 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1002 void Verifier::visitZExtInst(ZExtInst &I) {
1003 // Get the source and destination types
1004 Type *SrcTy = I.getOperand(0)->getType();
1005 Type *DestTy = I.getType();
1007 // Get the size of the types in bits, we'll need this later
1008 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1009 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1010 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1011 "zext source and destination must both be a vector or neither", &I);
1012 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1013 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1015 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1017 visitInstruction(I);
1020 void Verifier::visitSExtInst(SExtInst &I) {
1021 // Get the source and destination types
1022 Type *SrcTy = I.getOperand(0)->getType();
1023 Type *DestTy = I.getType();
1025 // Get the size of the types in bits, we'll need this later
1026 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1027 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1029 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1030 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1031 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1032 "sext source and destination must both be a vector or neither", &I);
1033 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1035 visitInstruction(I);
1038 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1039 // Get the source and destination types
1040 Type *SrcTy = I.getOperand(0)->getType();
1041 Type *DestTy = I.getType();
1042 // Get the size of the types in bits, we'll need this later
1043 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1044 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1046 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1047 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1048 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1049 "fptrunc source and destination must both be a vector or neither",&I);
1050 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1052 visitInstruction(I);
1055 void Verifier::visitFPExtInst(FPExtInst &I) {
1056 // Get the source and destination types
1057 Type *SrcTy = I.getOperand(0)->getType();
1058 Type *DestTy = I.getType();
1060 // Get the size of the types in bits, we'll need this later
1061 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1062 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1064 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1065 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1066 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1067 "fpext source and destination must both be a vector or neither", &I);
1068 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1070 visitInstruction(I);
1073 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1074 // Get the source and destination types
1075 Type *SrcTy = I.getOperand(0)->getType();
1076 Type *DestTy = I.getType();
1078 bool SrcVec = SrcTy->isVectorTy();
1079 bool DstVec = DestTy->isVectorTy();
1081 Assert1(SrcVec == DstVec,
1082 "UIToFP source and dest must both be vector or scalar", &I);
1083 Assert1(SrcTy->isIntOrIntVectorTy(),
1084 "UIToFP source must be integer or integer vector", &I);
1085 Assert1(DestTy->isFPOrFPVectorTy(),
1086 "UIToFP result must be FP or FP vector", &I);
1088 if (SrcVec && DstVec)
1089 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1090 cast<VectorType>(DestTy)->getNumElements(),
1091 "UIToFP source and dest vector length mismatch", &I);
1093 visitInstruction(I);
1096 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1097 // Get the source and destination types
1098 Type *SrcTy = I.getOperand(0)->getType();
1099 Type *DestTy = I.getType();
1101 bool SrcVec = SrcTy->isVectorTy();
1102 bool DstVec = DestTy->isVectorTy();
1104 Assert1(SrcVec == DstVec,
1105 "SIToFP source and dest must both be vector or scalar", &I);
1106 Assert1(SrcTy->isIntOrIntVectorTy(),
1107 "SIToFP source must be integer or integer vector", &I);
1108 Assert1(DestTy->isFPOrFPVectorTy(),
1109 "SIToFP result must be FP or FP vector", &I);
1111 if (SrcVec && DstVec)
1112 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1113 cast<VectorType>(DestTy)->getNumElements(),
1114 "SIToFP source and dest vector length mismatch", &I);
1116 visitInstruction(I);
1119 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1120 // Get the source and destination types
1121 Type *SrcTy = I.getOperand(0)->getType();
1122 Type *DestTy = I.getType();
1124 bool SrcVec = SrcTy->isVectorTy();
1125 bool DstVec = DestTy->isVectorTy();
1127 Assert1(SrcVec == DstVec,
1128 "FPToUI source and dest must both be vector or scalar", &I);
1129 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1131 Assert1(DestTy->isIntOrIntVectorTy(),
1132 "FPToUI result must be integer or integer vector", &I);
1134 if (SrcVec && DstVec)
1135 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1136 cast<VectorType>(DestTy)->getNumElements(),
1137 "FPToUI source and dest vector length mismatch", &I);
1139 visitInstruction(I);
1142 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1143 // Get the source and destination types
1144 Type *SrcTy = I.getOperand(0)->getType();
1145 Type *DestTy = I.getType();
1147 bool SrcVec = SrcTy->isVectorTy();
1148 bool DstVec = DestTy->isVectorTy();
1150 Assert1(SrcVec == DstVec,
1151 "FPToSI source and dest must both be vector or scalar", &I);
1152 Assert1(SrcTy->isFPOrFPVectorTy(),
1153 "FPToSI source must be FP or FP vector", &I);
1154 Assert1(DestTy->isIntOrIntVectorTy(),
1155 "FPToSI result must be integer or integer vector", &I);
1157 if (SrcVec && DstVec)
1158 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1159 cast<VectorType>(DestTy)->getNumElements(),
1160 "FPToSI source and dest vector length mismatch", &I);
1162 visitInstruction(I);
1165 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1166 // Get the source and destination types
1167 Type *SrcTy = I.getOperand(0)->getType();
1168 Type *DestTy = I.getType();
1170 Assert1(SrcTy->getScalarType()->isPointerTy(),
1171 "PtrToInt source must be pointer", &I);
1172 Assert1(DestTy->getScalarType()->isIntegerTy(),
1173 "PtrToInt result must be integral", &I);
1174 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1175 "PtrToInt type mismatch", &I);
1177 if (SrcTy->isVectorTy()) {
1178 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1179 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1180 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1181 "PtrToInt Vector width mismatch", &I);
1184 visitInstruction(I);
1187 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1188 // Get the source and destination types
1189 Type *SrcTy = I.getOperand(0)->getType();
1190 Type *DestTy = I.getType();
1192 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1193 "IntToPtr source must be an integral", &I);
1194 Assert1(DestTy->getScalarType()->isPointerTy(),
1195 "IntToPtr result must be a pointer",&I);
1196 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1197 "IntToPtr type mismatch", &I);
1198 if (SrcTy->isVectorTy()) {
1199 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1200 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1201 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1202 "IntToPtr Vector width mismatch", &I);
1204 visitInstruction(I);
1207 void Verifier::visitBitCastInst(BitCastInst &I) {
1208 // Get the source and destination types
1209 Type *SrcTy = I.getOperand(0)->getType();
1210 Type *DestTy = I.getType();
1212 // Get the size of the types in bits, we'll need this later
1213 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1214 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1216 // BitCast implies a no-op cast of type only. No bits change.
1217 // However, you can't cast pointers to anything but pointers.
1218 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
1219 "Bitcast requires both operands to be pointer or neither", &I);
1220 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1222 // Disallow aggregates.
1223 Assert1(!SrcTy->isAggregateType(),
1224 "Bitcast operand must not be aggregate", &I);
1225 Assert1(!DestTy->isAggregateType(),
1226 "Bitcast type must not be aggregate", &I);
1228 visitInstruction(I);
1231 /// visitPHINode - Ensure that a PHI node is well formed.
1233 void Verifier::visitPHINode(PHINode &PN) {
1234 // Ensure that the PHI nodes are all grouped together at the top of the block.
1235 // This can be tested by checking whether the instruction before this is
1236 // either nonexistent (because this is begin()) or is a PHI node. If not,
1237 // then there is some other instruction before a PHI.
1238 Assert2(&PN == &PN.getParent()->front() ||
1239 isa<PHINode>(--BasicBlock::iterator(&PN)),
1240 "PHI nodes not grouped at top of basic block!",
1241 &PN, PN.getParent());
1243 // Check that all of the values of the PHI node have the same type as the
1244 // result, and that the incoming blocks are really basic blocks.
1245 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1246 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1247 "PHI node operands are not the same type as the result!", &PN);
1250 // All other PHI node constraints are checked in the visitBasicBlock method.
1252 visitInstruction(PN);
1255 void Verifier::VerifyCallSite(CallSite CS) {
1256 Instruction *I = CS.getInstruction();
1258 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1259 "Called function must be a pointer!", I);
1260 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1262 Assert1(FPTy->getElementType()->isFunctionTy(),
1263 "Called function is not pointer to function type!", I);
1264 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1266 // Verify that the correct number of arguments are being passed
1267 if (FTy->isVarArg())
1268 Assert1(CS.arg_size() >= FTy->getNumParams(),
1269 "Called function requires more parameters than were provided!",I);
1271 Assert1(CS.arg_size() == FTy->getNumParams(),
1272 "Incorrect number of arguments passed to called function!", I);
1274 // Verify that all arguments to the call match the function type.
1275 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1276 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1277 "Call parameter type does not match function signature!",
1278 CS.getArgument(i), FTy->getParamType(i), I);
1280 const AttributeSet &Attrs = CS.getAttributes();
1282 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1283 "Attribute after last parameter!", I);
1285 // Verify call attributes.
1286 VerifyFunctionAttrs(FTy, Attrs, I);
1288 if (FTy->isVarArg())
1289 // Check attributes on the varargs part.
1290 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1291 Attribute Attr = Attrs.getParamAttributes(Idx);
1293 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1295 Assert1(!Attr.hasAttribute(Attribute::StructRet),
1296 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1299 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1300 if (CS.getCalledFunction() == 0 ||
1301 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1302 for (FunctionType::param_iterator PI = FTy->param_begin(),
1303 PE = FTy->param_end(); PI != PE; ++PI)
1304 Assert1(!(*PI)->isMetadataTy(),
1305 "Function has metadata parameter but isn't an intrinsic", I);
1308 visitInstruction(*I);
1311 void Verifier::visitCallInst(CallInst &CI) {
1312 VerifyCallSite(&CI);
1314 if (Function *F = CI.getCalledFunction())
1315 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1316 visitIntrinsicFunctionCall(ID, CI);
1319 void Verifier::visitInvokeInst(InvokeInst &II) {
1320 VerifyCallSite(&II);
1322 // Verify that there is a landingpad instruction as the first non-PHI
1323 // instruction of the 'unwind' destination.
1324 Assert1(II.getUnwindDest()->isLandingPad(),
1325 "The unwind destination does not have a landingpad instruction!",&II);
1327 visitTerminatorInst(II);
1330 /// visitBinaryOperator - Check that both arguments to the binary operator are
1331 /// of the same type!
1333 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1334 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1335 "Both operands to a binary operator are not of the same type!", &B);
1337 switch (B.getOpcode()) {
1338 // Check that integer arithmetic operators are only used with
1339 // integral operands.
1340 case Instruction::Add:
1341 case Instruction::Sub:
1342 case Instruction::Mul:
1343 case Instruction::SDiv:
1344 case Instruction::UDiv:
1345 case Instruction::SRem:
1346 case Instruction::URem:
1347 Assert1(B.getType()->isIntOrIntVectorTy(),
1348 "Integer arithmetic operators only work with integral types!", &B);
1349 Assert1(B.getType() == B.getOperand(0)->getType(),
1350 "Integer arithmetic operators must have same type "
1351 "for operands and result!", &B);
1353 // Check that floating-point arithmetic operators are only used with
1354 // floating-point operands.
1355 case Instruction::FAdd:
1356 case Instruction::FSub:
1357 case Instruction::FMul:
1358 case Instruction::FDiv:
1359 case Instruction::FRem:
1360 Assert1(B.getType()->isFPOrFPVectorTy(),
1361 "Floating-point arithmetic operators only work with "
1362 "floating-point types!", &B);
1363 Assert1(B.getType() == B.getOperand(0)->getType(),
1364 "Floating-point arithmetic operators must have same type "
1365 "for operands and result!", &B);
1367 // Check that logical operators are only used with integral operands.
1368 case Instruction::And:
1369 case Instruction::Or:
1370 case Instruction::Xor:
1371 Assert1(B.getType()->isIntOrIntVectorTy(),
1372 "Logical operators only work with integral types!", &B);
1373 Assert1(B.getType() == B.getOperand(0)->getType(),
1374 "Logical operators must have same type for operands and result!",
1377 case Instruction::Shl:
1378 case Instruction::LShr:
1379 case Instruction::AShr:
1380 Assert1(B.getType()->isIntOrIntVectorTy(),
1381 "Shifts only work with integral types!", &B);
1382 Assert1(B.getType() == B.getOperand(0)->getType(),
1383 "Shift return type must be same as operands!", &B);
1386 llvm_unreachable("Unknown BinaryOperator opcode!");
1389 visitInstruction(B);
1392 void Verifier::visitICmpInst(ICmpInst &IC) {
1393 // Check that the operands are the same type
1394 Type *Op0Ty = IC.getOperand(0)->getType();
1395 Type *Op1Ty = IC.getOperand(1)->getType();
1396 Assert1(Op0Ty == Op1Ty,
1397 "Both operands to ICmp instruction are not of the same type!", &IC);
1398 // Check that the operands are the right type
1399 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1400 "Invalid operand types for ICmp instruction", &IC);
1401 // Check that the predicate is valid.
1402 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1403 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1404 "Invalid predicate in ICmp instruction!", &IC);
1406 visitInstruction(IC);
1409 void Verifier::visitFCmpInst(FCmpInst &FC) {
1410 // Check that the operands are the same type
1411 Type *Op0Ty = FC.getOperand(0)->getType();
1412 Type *Op1Ty = FC.getOperand(1)->getType();
1413 Assert1(Op0Ty == Op1Ty,
1414 "Both operands to FCmp instruction are not of the same type!", &FC);
1415 // Check that the operands are the right type
1416 Assert1(Op0Ty->isFPOrFPVectorTy(),
1417 "Invalid operand types for FCmp instruction", &FC);
1418 // Check that the predicate is valid.
1419 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1420 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1421 "Invalid predicate in FCmp instruction!", &FC);
1423 visitInstruction(FC);
1426 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1427 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1429 "Invalid extractelement operands!", &EI);
1430 visitInstruction(EI);
1433 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1434 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1437 "Invalid insertelement operands!", &IE);
1438 visitInstruction(IE);
1441 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1442 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1444 "Invalid shufflevector operands!", &SV);
1445 visitInstruction(SV);
1448 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1449 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1451 Assert1(isa<PointerType>(TargetTy),
1452 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1453 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1454 "GEP into unsized type!", &GEP);
1455 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1456 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1459 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1461 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1462 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1464 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1465 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1466 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1468 if (GEP.getPointerOperandType()->isVectorTy()) {
1469 // Additional checks for vector GEPs.
1470 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1471 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1472 "Vector GEP result width doesn't match operand's", &GEP);
1473 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1474 Type *IndexTy = Idxs[i]->getType();
1475 Assert1(IndexTy->isVectorTy(),
1476 "Vector GEP must have vector indices!", &GEP);
1477 unsigned IndexWidth = IndexTy->getVectorNumElements();
1478 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1481 visitInstruction(GEP);
1484 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1485 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1488 void Verifier::visitLoadInst(LoadInst &LI) {
1489 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1490 Assert1(PTy, "Load operand must be a pointer.", &LI);
1491 Type *ElTy = PTy->getElementType();
1492 Assert2(ElTy == LI.getType(),
1493 "Load result type does not match pointer operand type!", &LI, ElTy);
1494 if (LI.isAtomic()) {
1495 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1496 "Load cannot have Release ordering", &LI);
1497 Assert1(LI.getAlignment() != 0,
1498 "Atomic load must specify explicit alignment", &LI);
1499 if (!ElTy->isPointerTy()) {
1500 Assert2(ElTy->isIntegerTy(),
1501 "atomic store operand must have integer type!",
1503 unsigned Size = ElTy->getPrimitiveSizeInBits();
1504 Assert2(Size >= 8 && !(Size & (Size - 1)),
1505 "atomic store operand must be power-of-two byte-sized integer",
1509 Assert1(LI.getSynchScope() == CrossThread,
1510 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1513 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1514 unsigned NumOperands = Range->getNumOperands();
1515 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1516 unsigned NumRanges = NumOperands / 2;
1517 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1519 ConstantRange LastRange(1); // Dummy initial value
1520 for (unsigned i = 0; i < NumRanges; ++i) {
1521 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1522 Assert1(Low, "The lower limit must be an integer!", Low);
1523 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1524 Assert1(High, "The upper limit must be an integer!", High);
1525 Assert1(High->getType() == Low->getType() &&
1526 High->getType() == ElTy, "Range types must match load type!",
1529 APInt HighV = High->getValue();
1530 APInt LowV = Low->getValue();
1531 ConstantRange CurRange(LowV, HighV);
1532 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1533 "Range must not be empty!", Range);
1535 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1536 "Intervals are overlapping", Range);
1537 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1539 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1542 LastRange = ConstantRange(LowV, HighV);
1544 if (NumRanges > 2) {
1546 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1548 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1549 ConstantRange FirstRange(FirstLow, FirstHigh);
1550 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1551 "Intervals are overlapping", Range);
1552 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1559 visitInstruction(LI);
1562 void Verifier::visitStoreInst(StoreInst &SI) {
1563 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1564 Assert1(PTy, "Store operand must be a pointer.", &SI);
1565 Type *ElTy = PTy->getElementType();
1566 Assert2(ElTy == SI.getOperand(0)->getType(),
1567 "Stored value type does not match pointer operand type!",
1569 if (SI.isAtomic()) {
1570 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1571 "Store cannot have Acquire ordering", &SI);
1572 Assert1(SI.getAlignment() != 0,
1573 "Atomic store must specify explicit alignment", &SI);
1574 if (!ElTy->isPointerTy()) {
1575 Assert2(ElTy->isIntegerTy(),
1576 "atomic store operand must have integer type!",
1578 unsigned Size = ElTy->getPrimitiveSizeInBits();
1579 Assert2(Size >= 8 && !(Size & (Size - 1)),
1580 "atomic store operand must be power-of-two byte-sized integer",
1584 Assert1(SI.getSynchScope() == CrossThread,
1585 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1587 visitInstruction(SI);
1590 void Verifier::visitAllocaInst(AllocaInst &AI) {
1591 PointerType *PTy = AI.getType();
1592 Assert1(PTy->getAddressSpace() == 0,
1593 "Allocation instruction pointer not in the generic address space!",
1595 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1597 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1598 "Alloca array size must have integer type", &AI);
1599 visitInstruction(AI);
1602 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1603 Assert1(CXI.getOrdering() != NotAtomic,
1604 "cmpxchg instructions must be atomic.", &CXI);
1605 Assert1(CXI.getOrdering() != Unordered,
1606 "cmpxchg instructions cannot be unordered.", &CXI);
1607 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1608 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1609 Type *ElTy = PTy->getElementType();
1610 Assert2(ElTy->isIntegerTy(),
1611 "cmpxchg operand must have integer type!",
1613 unsigned Size = ElTy->getPrimitiveSizeInBits();
1614 Assert2(Size >= 8 && !(Size & (Size - 1)),
1615 "cmpxchg operand must be power-of-two byte-sized integer",
1617 Assert2(ElTy == CXI.getOperand(1)->getType(),
1618 "Expected value type does not match pointer operand type!",
1620 Assert2(ElTy == CXI.getOperand(2)->getType(),
1621 "Stored value type does not match pointer operand type!",
1623 visitInstruction(CXI);
1626 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1627 Assert1(RMWI.getOrdering() != NotAtomic,
1628 "atomicrmw instructions must be atomic.", &RMWI);
1629 Assert1(RMWI.getOrdering() != Unordered,
1630 "atomicrmw instructions cannot be unordered.", &RMWI);
1631 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1632 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1633 Type *ElTy = PTy->getElementType();
1634 Assert2(ElTy->isIntegerTy(),
1635 "atomicrmw operand must have integer type!",
1637 unsigned Size = ElTy->getPrimitiveSizeInBits();
1638 Assert2(Size >= 8 && !(Size & (Size - 1)),
1639 "atomicrmw operand must be power-of-two byte-sized integer",
1641 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1642 "Argument value type does not match pointer operand type!",
1644 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1645 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1646 "Invalid binary operation!", &RMWI);
1647 visitInstruction(RMWI);
1650 void Verifier::visitFenceInst(FenceInst &FI) {
1651 const AtomicOrdering Ordering = FI.getOrdering();
1652 Assert1(Ordering == Acquire || Ordering == Release ||
1653 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1654 "fence instructions may only have "
1655 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1656 visitInstruction(FI);
1659 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1660 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1661 EVI.getIndices()) ==
1663 "Invalid ExtractValueInst operands!", &EVI);
1665 visitInstruction(EVI);
1668 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1669 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1670 IVI.getIndices()) ==
1671 IVI.getOperand(1)->getType(),
1672 "Invalid InsertValueInst operands!", &IVI);
1674 visitInstruction(IVI);
1677 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1678 BasicBlock *BB = LPI.getParent();
1680 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1682 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1683 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1685 // The landingpad instruction defines its parent as a landing pad block. The
1686 // landing pad block may be branched to only by the unwind edge of an invoke.
1687 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1688 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1689 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1690 "Block containing LandingPadInst must be jumped to "
1691 "only by the unwind edge of an invoke.", &LPI);
1694 // The landingpad instruction must be the first non-PHI instruction in the
1696 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1697 "LandingPadInst not the first non-PHI instruction in the block.",
1700 // The personality functions for all landingpad instructions within the same
1701 // function should match.
1703 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1704 "Personality function doesn't match others in function", &LPI);
1705 PersonalityFn = LPI.getPersonalityFn();
1707 // All operands must be constants.
1708 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1710 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1711 Value *Clause = LPI.getClause(i);
1712 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1713 if (LPI.isCatch(i)) {
1714 Assert1(isa<PointerType>(Clause->getType()),
1715 "Catch operand does not have pointer type!", &LPI);
1717 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1718 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1719 "Filter operand is not an array of constants!", &LPI);
1723 visitInstruction(LPI);
1726 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1727 Instruction *Op = cast<Instruction>(I.getOperand(i));
1728 // If the we have an invalid invoke, don't try to compute the dominance.
1729 // We already reject it in the invoke specific checks and the dominance
1730 // computation doesn't handle multiple edges.
1731 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1732 if (II->getNormalDest() == II->getUnwindDest())
1736 const Use &U = I.getOperandUse(i);
1737 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1738 "Instruction does not dominate all uses!", Op, &I);
1741 /// verifyInstruction - Verify that an instruction is well formed.
1743 void Verifier::visitInstruction(Instruction &I) {
1744 BasicBlock *BB = I.getParent();
1745 Assert1(BB, "Instruction not embedded in basic block!", &I);
1747 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1748 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1750 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1751 "Only PHI nodes may reference their own value!", &I);
1754 // Check that void typed values don't have names
1755 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1756 "Instruction has a name, but provides a void value!", &I);
1758 // Check that the return value of the instruction is either void or a legal
1760 Assert1(I.getType()->isVoidTy() ||
1761 I.getType()->isFirstClassType(),
1762 "Instruction returns a non-scalar type!", &I);
1764 // Check that the instruction doesn't produce metadata. Calls are already
1765 // checked against the callee type.
1766 Assert1(!I.getType()->isMetadataTy() ||
1767 isa<CallInst>(I) || isa<InvokeInst>(I),
1768 "Invalid use of metadata!", &I);
1770 // Check that all uses of the instruction, if they are instructions
1771 // themselves, actually have parent basic blocks. If the use is not an
1772 // instruction, it is an error!
1773 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1775 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1776 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1777 " embedded in a basic block!", &I, Used);
1779 CheckFailed("Use of instruction is not an instruction!", *UI);
1784 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1785 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1787 // Check to make sure that only first-class-values are operands to
1789 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1790 Assert1(0, "Instruction operands must be first-class values!", &I);
1793 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1794 // Check to make sure that the "address of" an intrinsic function is never
1796 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
1797 "Cannot take the address of an intrinsic!", &I);
1798 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
1799 F->getIntrinsicID() == Intrinsic::donothing,
1800 "Cannot invoke an intrinsinc other than donothing", &I);
1801 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1803 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1804 Assert1(OpBB->getParent() == BB->getParent(),
1805 "Referring to a basic block in another function!", &I);
1806 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1807 Assert1(OpArg->getParent() == BB->getParent(),
1808 "Referring to an argument in another function!", &I);
1809 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1810 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1812 } else if (isa<Instruction>(I.getOperand(i))) {
1813 verifyDominatesUse(I, i);
1814 } else if (isa<InlineAsm>(I.getOperand(i))) {
1815 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1816 (i + 3 == e && isa<InvokeInst>(I)),
1817 "Cannot take the address of an inline asm!", &I);
1821 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
1822 Assert1(I.getType()->isFPOrFPVectorTy(),
1823 "fpmath requires a floating point result!", &I);
1824 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
1825 Value *Op0 = MD->getOperand(0);
1826 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
1827 APFloat Accuracy = CFP0->getValueAPF();
1828 Assert1(Accuracy.isNormal() && !Accuracy.isNegative(),
1829 "fpmath accuracy not a positive number!", &I);
1831 Assert1(false, "invalid fpmath accuracy!", &I);
1835 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
1836 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
1838 InstsInThisBlock.insert(&I);
1841 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
1842 /// intrinsic argument or return value) matches the type constraints specified
1843 /// by the .td file (e.g. an "any integer" argument really is an integer).
1845 /// This return true on error but does not print a message.
1846 bool Verifier::VerifyIntrinsicType(Type *Ty,
1847 ArrayRef<Intrinsic::IITDescriptor> &Infos,
1848 SmallVectorImpl<Type*> &ArgTys) {
1849 using namespace Intrinsic;
1851 // If we ran out of descriptors, there are too many arguments.
1852 if (Infos.empty()) return true;
1853 IITDescriptor D = Infos.front();
1854 Infos = Infos.slice(1);
1857 case IITDescriptor::Void: return !Ty->isVoidTy();
1858 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
1859 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1860 case IITDescriptor::Half: return !Ty->isHalfTy();
1861 case IITDescriptor::Float: return !Ty->isFloatTy();
1862 case IITDescriptor::Double: return !Ty->isDoubleTy();
1863 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1864 case IITDescriptor::Vector: {
1865 VectorType *VT = dyn_cast<VectorType>(Ty);
1866 return VT == 0 || VT->getNumElements() != D.Vector_Width ||
1867 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
1869 case IITDescriptor::Pointer: {
1870 PointerType *PT = dyn_cast<PointerType>(Ty);
1871 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1872 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
1875 case IITDescriptor::Struct: {
1876 StructType *ST = dyn_cast<StructType>(Ty);
1877 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
1880 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1881 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
1886 case IITDescriptor::Argument:
1887 // Two cases here - If this is the second occurrence of an argument, verify
1888 // that the later instance matches the previous instance.
1889 if (D.getArgumentNumber() < ArgTys.size())
1890 return Ty != ArgTys[D.getArgumentNumber()];
1892 // Otherwise, if this is the first instance of an argument, record it and
1893 // verify the "Any" kind.
1894 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
1895 ArgTys.push_back(Ty);
1897 switch (D.getArgumentKind()) {
1898 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1899 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
1900 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
1901 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1903 llvm_unreachable("all argument kinds not covered");
1905 case IITDescriptor::ExtendVecArgument:
1906 // This may only be used when referring to a previous vector argument.
1907 return D.getArgumentNumber() >= ArgTys.size() ||
1908 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1909 VectorType::getExtendedElementVectorType(
1910 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1912 case IITDescriptor::TruncVecArgument:
1913 // This may only be used when referring to a previous vector argument.
1914 return D.getArgumentNumber() >= ArgTys.size() ||
1915 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1916 VectorType::getTruncatedElementVectorType(
1917 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1919 llvm_unreachable("unhandled");
1922 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1924 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1925 Function *IF = CI.getCalledFunction();
1926 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1929 // Verify that the intrinsic prototype lines up with what the .td files
1931 FunctionType *IFTy = IF->getFunctionType();
1932 Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
1934 SmallVector<Intrinsic::IITDescriptor, 8> Table;
1935 getIntrinsicInfoTableEntries(ID, Table);
1936 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1938 SmallVector<Type *, 4> ArgTys;
1939 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
1940 "Intrinsic has incorrect return type!", IF);
1941 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
1942 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
1943 "Intrinsic has incorrect argument type!", IF);
1944 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
1946 // Now that we have the intrinsic ID and the actual argument types (and we
1947 // know they are legal for the intrinsic!) get the intrinsic name through the
1948 // usual means. This allows us to verify the mangling of argument types into
1950 Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
1951 "Intrinsic name not mangled correctly for type arguments!", IF);
1953 // If the intrinsic takes MDNode arguments, verify that they are either global
1954 // or are local to *this* function.
1955 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1956 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1957 visitMDNode(*MD, CI.getParent()->getParent());
1962 case Intrinsic::ctlz: // llvm.ctlz
1963 case Intrinsic::cttz: // llvm.cttz
1964 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1965 "is_zero_undef argument of bit counting intrinsics must be a "
1966 "constant int", &CI);
1968 case Intrinsic::dbg_declare: { // llvm.dbg.declare
1969 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1970 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1971 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1972 Assert1(MD->getNumOperands() == 1,
1973 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1975 case Intrinsic::memcpy:
1976 case Intrinsic::memmove:
1977 case Intrinsic::memset:
1978 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1979 "alignment argument of memory intrinsics must be a constant int",
1981 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
1982 "isvolatile argument of memory intrinsics must be a constant int",
1985 case Intrinsic::gcroot:
1986 case Intrinsic::gcwrite:
1987 case Intrinsic::gcread:
1988 if (ID == Intrinsic::gcroot) {
1990 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1991 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1992 Assert1(isa<Constant>(CI.getArgOperand(1)),
1993 "llvm.gcroot parameter #2 must be a constant.", &CI);
1994 if (!AI->getType()->getElementType()->isPointerTy()) {
1995 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1996 "llvm.gcroot parameter #1 must either be a pointer alloca, "
1997 "or argument #2 must be a non-null constant.", &CI);
2001 Assert1(CI.getParent()->getParent()->hasGC(),
2002 "Enclosing function does not use GC.", &CI);
2004 case Intrinsic::init_trampoline:
2005 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2006 "llvm.init_trampoline parameter #2 must resolve to a function.",
2009 case Intrinsic::prefetch:
2010 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2011 isa<ConstantInt>(CI.getArgOperand(2)) &&
2012 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2013 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2014 "invalid arguments to llvm.prefetch",
2017 case Intrinsic::stackprotector:
2018 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2019 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2022 case Intrinsic::lifetime_start:
2023 case Intrinsic::lifetime_end:
2024 case Intrinsic::invariant_start:
2025 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2026 "size argument of memory use markers must be a constant integer",
2029 case Intrinsic::invariant_end:
2030 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2031 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2036 //===----------------------------------------------------------------------===//
2037 // Implement the public interfaces to this file...
2038 //===----------------------------------------------------------------------===//
2040 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2041 return new Verifier(action);
2045 /// verifyFunction - Check a function for errors, printing messages on stderr.
2046 /// Return true if the function is corrupt.
2048 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2049 Function &F = const_cast<Function&>(f);
2050 assert(!F.isDeclaration() && "Cannot verify external functions");
2052 FunctionPassManager FPM(F.getParent());
2053 Verifier *V = new Verifier(action);
2059 /// verifyModule - Check a module for errors, printing messages on stderr.
2060 /// Return true if the module is corrupt.
2062 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2063 std::string *ErrorInfo) {
2065 Verifier *V = new Verifier(action);
2067 PM.run(const_cast<Module&>(M));
2069 if (ErrorInfo && V->Broken)
2070 *ErrorInfo = V->MessagesStr.str();