1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
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 // * All other things that are tested by asserts spread about the code...
40 //===----------------------------------------------------------------------===//
42 #include "llvm/Analysis/Verifier.h"
43 #include "llvm/CallingConv.h"
44 #include "llvm/Constants.h"
45 #include "llvm/DerivedTypes.h"
46 #include "llvm/InlineAsm.h"
47 #include "llvm/IntrinsicInst.h"
48 #include "llvm/Metadata.h"
49 #include "llvm/Module.h"
50 #include "llvm/Pass.h"
51 #include "llvm/PassManager.h"
52 #include "llvm/TypeSymbolTable.h"
53 #include "llvm/Analysis/Dominators.h"
54 #include "llvm/Assembly/Writer.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/Support/CallSite.h"
57 #include "llvm/Support/CFG.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/InstVisitor.h"
60 #include "llvm/ADT/SetVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/StringExtras.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/raw_ostream.h"
71 namespace { // Anonymous namespace for class
72 struct PreVerifier : public FunctionPass {
73 static char ID; // Pass ID, replacement for typeid
75 PreVerifier() : FunctionPass(&ID) { }
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
81 // Check that the prerequisites for successful DominatorTree construction
83 bool runOnFunction(Function &F) {
86 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
87 if (I->empty() || !I->back().isTerminator()) {
88 dbgs() << "Basic Block does not have terminator!\n";
89 WriteAsOperand(dbgs(), I, true);
96 report_fatal_error("Broken module, no Basic Block terminator!");
103 char PreVerifier::ID = 0;
104 static RegisterPass<PreVerifier>
105 PreVer("preverify", "Preliminary module verification");
106 static const PassInfo *const PreVerifyID = &PreVer;
109 class TypeSet : public AbstractTypeUser {
113 /// Insert a type into the set of types.
114 bool insert(const Type *Ty) {
115 if (!Types.insert(Ty))
117 if (Ty->isAbstract())
118 Ty->addAbstractTypeUser(this);
122 // Remove ourselves as abstract type listeners for any types that remain
123 // abstract when the TypeSet is destroyed.
125 for (SmallSetVector<const Type *, 16>::iterator I = Types.begin(),
126 E = Types.end(); I != E; ++I) {
128 if (Ty->isAbstract())
129 Ty->removeAbstractTypeUser(this);
133 // Abstract type user interface.
135 /// Remove types from the set when refined. Do not insert the type it was
136 /// refined to because that type hasn't been verified yet.
137 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
139 OldTy->removeAbstractTypeUser(this);
142 /// Stop listening for changes to a type which is no longer abstract.
143 void typeBecameConcrete(const DerivedType *AbsTy) {
144 AbsTy->removeAbstractTypeUser(this);
150 SmallSetVector<const Type *, 16> Types;
153 TypeSet(const TypeSet &);
154 TypeSet &operator=(const TypeSet &);
157 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
158 static char ID; // Pass ID, replacement for typeid
159 bool Broken; // Is this module found to be broken?
160 bool RealPass; // Are we not being run by a PassManager?
161 VerifierFailureAction action;
162 // What to do if verification fails.
163 Module *Mod; // Module we are verifying right now
164 LLVMContext *Context; // Context within which we are verifying
165 DominatorTree *DT; // Dominator Tree, caution can be null!
167 std::string Messages;
168 raw_string_ostream MessagesStr;
170 /// InstInThisBlock - when verifying a basic block, keep track of all of the
171 /// instructions we have seen so far. This allows us to do efficient
172 /// dominance checks for the case when an instruction has an operand that is
173 /// an instruction in the same block.
174 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
176 /// Types - keep track of the types that have been checked already.
179 /// MDNodes - keep track of the metadata nodes that have been checked
181 SmallPtrSet<MDNode *, 32> MDNodes;
185 Broken(false), RealPass(true), action(AbortProcessAction),
186 Mod(0), Context(0), DT(0), MessagesStr(Messages) {}
187 explicit Verifier(VerifierFailureAction ctn)
189 Broken(false), RealPass(true), action(ctn), Mod(0), Context(0), DT(0),
190 MessagesStr(Messages) {}
191 explicit Verifier(bool AB)
193 Broken(false), RealPass(true),
194 action( AB ? AbortProcessAction : PrintMessageAction), Mod(0),
195 Context(0), DT(0), MessagesStr(Messages) {}
196 explicit Verifier(DominatorTree &dt)
198 Broken(false), RealPass(false), action(PrintMessageAction), Mod(0),
199 Context(0), DT(&dt), MessagesStr(Messages) {}
202 bool doInitialization(Module &M) {
204 Context = &M.getContext();
205 verifyTypeSymbolTable(M.getTypeSymbolTable());
207 // If this is a real pass, in a pass manager, we must abort before
208 // returning back to the pass manager, or else the pass manager may try to
209 // run other passes on the broken module.
211 return abortIfBroken();
215 bool runOnFunction(Function &F) {
216 // Get dominator information if we are being run by PassManager
217 if (RealPass) DT = &getAnalysis<DominatorTree>();
220 if (!Context) Context = &F.getContext();
223 InstsInThisBlock.clear();
225 // If this is a real pass, in a pass manager, we must abort before
226 // returning back to the pass manager, or else the pass manager may try to
227 // run other passes on the broken module.
229 return abortIfBroken();
234 bool doFinalization(Module &M) {
235 // Scan through, checking all of the external function's linkage now...
236 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
237 visitGlobalValue(*I);
239 // Check to make sure function prototypes are okay.
240 if (I->isDeclaration()) visitFunction(*I);
243 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
245 visitGlobalVariable(*I);
247 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
249 visitGlobalAlias(*I);
251 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
252 E = M.named_metadata_end(); I != E; ++I)
253 visitNamedMDNode(*I);
255 // If the module is broken, abort at this time.
256 return abortIfBroken();
259 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
260 AU.setPreservesAll();
261 AU.addRequiredID(PreVerifyID);
263 AU.addRequired<DominatorTree>();
266 /// abortIfBroken - If the module is broken and we are supposed to abort on
267 /// this condition, do so.
269 bool abortIfBroken() {
270 if (!Broken) return false;
271 MessagesStr << "Broken module found, ";
273 default: llvm_unreachable("Unknown action");
274 case AbortProcessAction:
275 MessagesStr << "compilation aborted!\n";
276 dbgs() << MessagesStr.str();
277 // Client should choose different reaction if abort is not desired
279 case PrintMessageAction:
280 MessagesStr << "verification continues.\n";
281 dbgs() << MessagesStr.str();
283 case ReturnStatusAction:
284 MessagesStr << "compilation terminated.\n";
290 // Verification methods...
291 void verifyTypeSymbolTable(TypeSymbolTable &ST);
292 void visitGlobalValue(GlobalValue &GV);
293 void visitGlobalVariable(GlobalVariable &GV);
294 void visitGlobalAlias(GlobalAlias &GA);
295 void visitNamedMDNode(NamedMDNode &NMD);
296 void visitMDNode(MDNode &MD, Function *F);
297 void visitFunction(Function &F);
298 void visitBasicBlock(BasicBlock &BB);
299 using InstVisitor<Verifier>::visit;
301 void visit(Instruction &I);
303 void visitTruncInst(TruncInst &I);
304 void visitZExtInst(ZExtInst &I);
305 void visitSExtInst(SExtInst &I);
306 void visitFPTruncInst(FPTruncInst &I);
307 void visitFPExtInst(FPExtInst &I);
308 void visitFPToUIInst(FPToUIInst &I);
309 void visitFPToSIInst(FPToSIInst &I);
310 void visitUIToFPInst(UIToFPInst &I);
311 void visitSIToFPInst(SIToFPInst &I);
312 void visitIntToPtrInst(IntToPtrInst &I);
313 void visitPtrToIntInst(PtrToIntInst &I);
314 void visitBitCastInst(BitCastInst &I);
315 void visitPHINode(PHINode &PN);
316 void visitBinaryOperator(BinaryOperator &B);
317 void visitICmpInst(ICmpInst &IC);
318 void visitFCmpInst(FCmpInst &FC);
319 void visitExtractElementInst(ExtractElementInst &EI);
320 void visitInsertElementInst(InsertElementInst &EI);
321 void visitShuffleVectorInst(ShuffleVectorInst &EI);
322 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
323 void visitCallInst(CallInst &CI);
324 void visitInvokeInst(InvokeInst &II);
325 void visitGetElementPtrInst(GetElementPtrInst &GEP);
326 void visitLoadInst(LoadInst &LI);
327 void visitStoreInst(StoreInst &SI);
328 void visitInstruction(Instruction &I);
329 void visitTerminatorInst(TerminatorInst &I);
330 void visitBranchInst(BranchInst &BI);
331 void visitReturnInst(ReturnInst &RI);
332 void visitSwitchInst(SwitchInst &SI);
333 void visitSelectInst(SelectInst &SI);
334 void visitUserOp1(Instruction &I);
335 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
336 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
337 void visitAllocaInst(AllocaInst &AI);
338 void visitExtractValueInst(ExtractValueInst &EVI);
339 void visitInsertValueInst(InsertValueInst &IVI);
341 void VerifyCallSite(CallSite CS);
342 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
343 int VT, unsigned ArgNo, std::string &Suffix);
344 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
345 unsigned RetNum, unsigned ParamNum, ...);
346 void VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
347 bool isReturnValue, const Value *V);
348 void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
350 void VerifyType(const Type *Ty);
352 void WriteValue(const Value *V) {
354 if (isa<Instruction>(V)) {
355 MessagesStr << *V << '\n';
357 WriteAsOperand(MessagesStr, V, true, Mod);
362 void WriteType(const Type *T) {
365 WriteTypeSymbolic(MessagesStr, T, Mod);
369 // CheckFailed - A check failed, so print out the condition and the message
370 // that failed. This provides a nice place to put a breakpoint if you want
371 // to see why something is not correct.
372 void CheckFailed(const Twine &Message,
373 const Value *V1 = 0, const Value *V2 = 0,
374 const Value *V3 = 0, const Value *V4 = 0) {
375 MessagesStr << Message.str() << "\n";
383 void CheckFailed(const Twine &Message, const Value *V1,
384 const Type *T2, const Value *V3 = 0) {
385 MessagesStr << Message.str() << "\n";
392 void CheckFailed(const Twine &Message, const Type *T1,
393 const Type *T2 = 0, const Type *T3 = 0) {
394 MessagesStr << Message.str() << "\n";
401 } // End anonymous namespace
403 char Verifier::ID = 0;
404 static RegisterPass<Verifier> X("verify", "Module Verifier");
406 // Assert - We know that cond should be true, if not print an error message.
407 #define Assert(C, M) \
408 do { if (!(C)) { CheckFailed(M); return; } } while (0)
409 #define Assert1(C, M, V1) \
410 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
411 #define Assert2(C, M, V1, V2) \
412 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
413 #define Assert3(C, M, V1, V2, V3) \
414 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
415 #define Assert4(C, M, V1, V2, V3, V4) \
416 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
418 void Verifier::visit(Instruction &I) {
419 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
420 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
421 InstVisitor<Verifier>::visit(I);
425 void Verifier::visitGlobalValue(GlobalValue &GV) {
426 Assert1(!GV.isDeclaration() ||
427 GV.isMaterializable() ||
428 GV.hasExternalLinkage() ||
429 GV.hasDLLImportLinkage() ||
430 GV.hasExternalWeakLinkage() ||
431 (isa<GlobalAlias>(GV) &&
432 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
433 "Global is external, but doesn't have external or dllimport or weak linkage!",
436 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
437 "Global is marked as dllimport, but not external", &GV);
439 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
440 "Only global variables can have appending linkage!", &GV);
442 if (GV.hasAppendingLinkage()) {
443 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
444 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
445 "Only global arrays can have appending linkage!", GVar);
449 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
450 if (GV.hasInitializer()) {
451 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
452 "Global variable initializer type does not match global "
453 "variable type!", &GV);
455 // If the global has common linkage, it must have a zero initializer and
456 // cannot be constant.
457 if (GV.hasCommonLinkage()) {
458 Assert1(GV.getInitializer()->isNullValue(),
459 "'common' global must have a zero initializer!", &GV);
460 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
464 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
465 GV.hasExternalWeakLinkage(),
466 "invalid linkage type for global declaration", &GV);
469 visitGlobalValue(GV);
472 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
473 Assert1(!GA.getName().empty(),
474 "Alias name cannot be empty!", &GA);
475 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
477 "Alias should have external or external weak linkage!", &GA);
478 Assert1(GA.getAliasee(),
479 "Aliasee cannot be NULL!", &GA);
480 Assert1(GA.getType() == GA.getAliasee()->getType(),
481 "Alias and aliasee types should match!", &GA);
483 if (!isa<GlobalValue>(GA.getAliasee())) {
484 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
486 (CE->getOpcode() == Instruction::BitCast ||
487 CE->getOpcode() == Instruction::GetElementPtr) &&
488 isa<GlobalValue>(CE->getOperand(0)),
489 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
493 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
495 "Aliasing chain should end with function or global variable", &GA);
497 visitGlobalValue(GA);
500 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
501 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
502 MDNode *MD = NMD.getOperand(i);
506 Assert2(!MD->isFunctionLocal(),
507 "Named metadata operand cannot be function local!", &NMD, MD);
512 void Verifier::visitMDNode(MDNode &MD, Function *F) {
513 // Only visit each node once. Metadata can be mutually recursive, so this
514 // avoids infinite recursion here, as well as being an optimization.
515 if (!MDNodes.insert(&MD))
518 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
519 Value *Op = MD.getOperand(i);
522 if (isa<Constant>(Op) || isa<MDString>(Op) || isa<NamedMDNode>(Op))
524 if (MDNode *N = dyn_cast<MDNode>(Op)) {
525 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
526 "Global metadata operand cannot be function local!", &MD, N);
530 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
532 // If this was an instruction, bb, or argument, verify that it is in the
533 // function that we expect.
534 Function *ActualF = 0;
535 if (Instruction *I = dyn_cast<Instruction>(Op))
536 ActualF = I->getParent()->getParent();
537 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
538 ActualF = BB->getParent();
539 else if (Argument *A = dyn_cast<Argument>(Op))
540 ActualF = A->getParent();
541 assert(ActualF && "Unimplemented function local metadata case!");
543 Assert2(ActualF == F, "function-local metadata used in wrong function",
548 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
549 for (TypeSymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
550 VerifyType(I->second);
553 // VerifyParameterAttrs - Check the given attributes for an argument or return
554 // value of the specified type. The value V is printed in error messages.
555 void Verifier::VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
556 bool isReturnValue, const Value *V) {
557 if (Attrs == Attribute::None)
560 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
561 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
562 " only applies to the function!", V);
565 Attributes RetI = Attrs & Attribute::ParameterOnly;
566 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
567 " does not apply to return values!", V);
571 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
572 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
573 Assert1(!(MutI & (MutI - 1)), "Attributes " +
574 Attribute::getAsString(MutI) + " are incompatible!", V);
577 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
578 Assert1(!TypeI, "Wrong type for attribute " +
579 Attribute::getAsString(TypeI), V);
581 Attributes ByValI = Attrs & Attribute::ByVal;
582 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
583 Assert1(!ByValI || PTy->getElementType()->isSized(),
584 "Attribute " + Attribute::getAsString(ByValI) +
585 " does not support unsized types!", V);
588 "Attribute " + Attribute::getAsString(ByValI) +
589 " only applies to parameters with pointer type!", V);
593 // VerifyFunctionAttrs - Check parameter attributes against a function type.
594 // The value V is printed in error messages.
595 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
596 const AttrListPtr &Attrs,
601 bool SawNest = false;
603 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
604 const AttributeWithIndex &Attr = Attrs.getSlot(i);
608 Ty = FT->getReturnType();
609 else if (Attr.Index-1 < FT->getNumParams())
610 Ty = FT->getParamType(Attr.Index-1);
612 break; // VarArgs attributes, verified elsewhere.
614 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
616 if (Attr.Attrs & Attribute::Nest) {
617 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
621 if (Attr.Attrs & Attribute::StructRet)
622 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
625 Attributes FAttrs = Attrs.getFnAttributes();
626 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
627 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
628 " does not apply to the function!", V);
631 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
632 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
633 Assert1(!(MutI & (MutI - 1)), "Attributes " +
634 Attribute::getAsString(MutI) + " are incompatible!", V);
638 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
642 unsigned LastSlot = Attrs.getNumSlots() - 1;
643 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
644 if (LastIndex <= Params
645 || (LastIndex == (unsigned)~0
646 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
652 // visitFunction - Verify that a function is ok.
654 void Verifier::visitFunction(Function &F) {
655 // Check function arguments.
656 const FunctionType *FT = F.getFunctionType();
657 unsigned NumArgs = F.arg_size();
659 Assert1(Context == &F.getContext(),
660 "Function context does not match Module context!", &F);
662 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
663 Assert2(FT->getNumParams() == NumArgs,
664 "# formal arguments must match # of arguments for function type!",
666 Assert1(F.getReturnType()->isFirstClassType() ||
667 F.getReturnType()->isVoidTy() ||
668 F.getReturnType()->isStructTy(),
669 "Functions cannot return aggregate values!", &F);
671 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
672 "Invalid struct return type!", &F);
674 const AttrListPtr &Attrs = F.getAttributes();
676 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
677 "Attributes after last parameter!", &F);
679 // Check function attributes.
680 VerifyFunctionAttrs(FT, Attrs, &F);
682 // Check that this function meets the restrictions on this calling convention.
683 switch (F.getCallingConv()) {
688 case CallingConv::Fast:
689 case CallingConv::Cold:
690 case CallingConv::X86_FastCall:
691 case CallingConv::X86_ThisCall:
692 Assert1(!F.isVarArg(),
693 "Varargs functions must have C calling conventions!", &F);
697 bool isLLVMdotName = F.getName().size() >= 5 &&
698 F.getName().substr(0, 5) == "llvm.";
700 // Check that the argument values match the function type for this function...
702 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
704 Assert2(I->getType() == FT->getParamType(i),
705 "Argument value does not match function argument type!",
706 I, FT->getParamType(i));
707 Assert1(I->getType()->isFirstClassType(),
708 "Function arguments must have first-class types!", I);
710 Assert2(!I->getType()->isMetadataTy(),
711 "Function takes metadata but isn't an intrinsic", I, &F);
714 if (F.isMaterializable()) {
715 // Function has a body somewhere we can't see.
716 } else if (F.isDeclaration()) {
717 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
718 F.hasExternalWeakLinkage(),
719 "invalid linkage type for function declaration", &F);
721 // Verify that this function (which has a body) is not named "llvm.*". It
722 // is not legal to define intrinsics.
723 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
725 // Check the entry node
726 BasicBlock *Entry = &F.getEntryBlock();
727 Assert1(pred_begin(Entry) == pred_end(Entry),
728 "Entry block to function must not have predecessors!", Entry);
730 // The address of the entry block cannot be taken, unless it is dead.
731 if (Entry->hasAddressTaken()) {
732 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
733 "blockaddress may not be used with the entry block!", Entry);
737 // If this function is actually an intrinsic, verify that it is only used in
738 // direct call/invokes, never having its "address taken".
739 if (F.getIntrinsicID()) {
741 if (F.hasAddressTaken(&U))
742 Assert1(0, "Invalid user of intrinsic instruction!", U);
746 // verifyBasicBlock - Verify that a basic block is well formed...
748 void Verifier::visitBasicBlock(BasicBlock &BB) {
749 InstsInThisBlock.clear();
751 // Ensure that basic blocks have terminators!
752 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
754 // Check constraints that this basic block imposes on all of the PHI nodes in
756 if (isa<PHINode>(BB.front())) {
757 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
758 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
759 std::sort(Preds.begin(), Preds.end());
761 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
762 // Ensure that PHI nodes have at least one entry!
763 Assert1(PN->getNumIncomingValues() != 0,
764 "PHI nodes must have at least one entry. If the block is dead, "
765 "the PHI should be removed!", PN);
766 Assert1(PN->getNumIncomingValues() == Preds.size(),
767 "PHINode should have one entry for each predecessor of its "
768 "parent basic block!", PN);
770 // Get and sort all incoming values in the PHI node...
772 Values.reserve(PN->getNumIncomingValues());
773 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
774 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
775 PN->getIncomingValue(i)));
776 std::sort(Values.begin(), Values.end());
778 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
779 // Check to make sure that if there is more than one entry for a
780 // particular basic block in this PHI node, that the incoming values are
783 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
784 Values[i].second == Values[i-1].second,
785 "PHI node has multiple entries for the same basic block with "
786 "different incoming values!", PN, Values[i].first,
787 Values[i].second, Values[i-1].second);
789 // Check to make sure that the predecessors and PHI node entries are
791 Assert3(Values[i].first == Preds[i],
792 "PHI node entries do not match predecessors!", PN,
793 Values[i].first, Preds[i]);
799 void Verifier::visitTerminatorInst(TerminatorInst &I) {
800 // Ensure that terminators only exist at the end of the basic block.
801 Assert1(&I == I.getParent()->getTerminator(),
802 "Terminator found in the middle of a basic block!", I.getParent());
806 void Verifier::visitBranchInst(BranchInst &BI) {
807 if (BI.isConditional()) {
808 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
809 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
811 visitTerminatorInst(BI);
814 void Verifier::visitReturnInst(ReturnInst &RI) {
815 Function *F = RI.getParent()->getParent();
816 unsigned N = RI.getNumOperands();
817 if (F->getReturnType()->isVoidTy())
819 "Found return instr that returns non-void in Function of void "
820 "return type!", &RI, F->getReturnType());
821 else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
822 // Exactly one return value and it matches the return type. Good.
823 } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
824 // The return type is a struct; check for multiple return values.
825 Assert2(STy->getNumElements() == N,
826 "Incorrect number of return values in ret instruction!",
827 &RI, F->getReturnType());
828 for (unsigned i = 0; i != N; ++i)
829 Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
830 "Function return type does not match operand "
831 "type of return inst!", &RI, F->getReturnType());
832 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
833 // The return type is an array; check for multiple return values.
834 Assert2(ATy->getNumElements() == N,
835 "Incorrect number of return values in ret instruction!",
836 &RI, F->getReturnType());
837 for (unsigned i = 0; i != N; ++i)
838 Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
839 "Function return type does not match operand "
840 "type of return inst!", &RI, F->getReturnType());
842 CheckFailed("Function return type does not match operand "
843 "type of return inst!", &RI, F->getReturnType());
846 // Check to make sure that the return value has necessary properties for
848 visitTerminatorInst(RI);
851 void Verifier::visitSwitchInst(SwitchInst &SI) {
852 // Check to make sure that all of the constants in the switch instruction
853 // have the same type as the switched-on value.
854 const Type *SwitchTy = SI.getCondition()->getType();
855 SmallPtrSet<ConstantInt*, 32> Constants;
856 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i) {
857 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
858 "Switch constants must all be same type as switch value!", &SI);
859 Assert2(Constants.insert(SI.getCaseValue(i)),
860 "Duplicate integer as switch case", &SI, SI.getCaseValue(i));
863 visitTerminatorInst(SI);
866 void Verifier::visitSelectInst(SelectInst &SI) {
867 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
869 "Invalid operands for select instruction!", &SI);
871 Assert1(SI.getTrueValue()->getType() == SI.getType(),
872 "Select values must have same type as select instruction!", &SI);
873 visitInstruction(SI);
876 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
877 /// a pass, if any exist, it's an error.
879 void Verifier::visitUserOp1(Instruction &I) {
880 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
883 void Verifier::visitTruncInst(TruncInst &I) {
884 // Get the source and destination types
885 const Type *SrcTy = I.getOperand(0)->getType();
886 const Type *DestTy = I.getType();
888 // Get the size of the types in bits, we'll need this later
889 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
890 unsigned DestBitSize = DestTy->getScalarSizeInBits();
892 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
893 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
894 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
895 "trunc source and destination must both be a vector or neither", &I);
896 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
901 void Verifier::visitZExtInst(ZExtInst &I) {
902 // Get the source and destination types
903 const Type *SrcTy = I.getOperand(0)->getType();
904 const Type *DestTy = I.getType();
906 // Get the size of the types in bits, we'll need this later
907 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
908 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
909 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
910 "zext source and destination must both be a vector or neither", &I);
911 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
912 unsigned DestBitSize = DestTy->getScalarSizeInBits();
914 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
919 void Verifier::visitSExtInst(SExtInst &I) {
920 // Get the source and destination types
921 const Type *SrcTy = I.getOperand(0)->getType();
922 const Type *DestTy = I.getType();
924 // Get the size of the types in bits, we'll need this later
925 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
926 unsigned DestBitSize = DestTy->getScalarSizeInBits();
928 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
929 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
930 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
931 "sext source and destination must both be a vector or neither", &I);
932 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
937 void Verifier::visitFPTruncInst(FPTruncInst &I) {
938 // Get the source and destination types
939 const Type *SrcTy = I.getOperand(0)->getType();
940 const Type *DestTy = I.getType();
941 // Get the size of the types in bits, we'll need this later
942 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
943 unsigned DestBitSize = DestTy->getScalarSizeInBits();
945 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
946 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
947 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
948 "fptrunc source and destination must both be a vector or neither",&I);
949 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
954 void Verifier::visitFPExtInst(FPExtInst &I) {
955 // Get the source and destination types
956 const Type *SrcTy = I.getOperand(0)->getType();
957 const Type *DestTy = I.getType();
959 // Get the size of the types in bits, we'll need this later
960 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
961 unsigned DestBitSize = DestTy->getScalarSizeInBits();
963 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
964 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
965 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
966 "fpext source and destination must both be a vector or neither", &I);
967 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
972 void Verifier::visitUIToFPInst(UIToFPInst &I) {
973 // Get the source and destination types
974 const Type *SrcTy = I.getOperand(0)->getType();
975 const Type *DestTy = I.getType();
977 bool SrcVec = SrcTy->isVectorTy();
978 bool DstVec = DestTy->isVectorTy();
980 Assert1(SrcVec == DstVec,
981 "UIToFP source and dest must both be vector or scalar", &I);
982 Assert1(SrcTy->isIntOrIntVectorTy(),
983 "UIToFP source must be integer or integer vector", &I);
984 Assert1(DestTy->isFPOrFPVectorTy(),
985 "UIToFP result must be FP or FP vector", &I);
987 if (SrcVec && DstVec)
988 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
989 cast<VectorType>(DestTy)->getNumElements(),
990 "UIToFP source and dest vector length mismatch", &I);
995 void Verifier::visitSIToFPInst(SIToFPInst &I) {
996 // Get the source and destination types
997 const Type *SrcTy = I.getOperand(0)->getType();
998 const Type *DestTy = I.getType();
1000 bool SrcVec = SrcTy->isVectorTy();
1001 bool DstVec = DestTy->isVectorTy();
1003 Assert1(SrcVec == DstVec,
1004 "SIToFP source and dest must both be vector or scalar", &I);
1005 Assert1(SrcTy->isIntOrIntVectorTy(),
1006 "SIToFP source must be integer or integer vector", &I);
1007 Assert1(DestTy->isFPOrFPVectorTy(),
1008 "SIToFP result must be FP or FP vector", &I);
1010 if (SrcVec && DstVec)
1011 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1012 cast<VectorType>(DestTy)->getNumElements(),
1013 "SIToFP source and dest vector length mismatch", &I);
1015 visitInstruction(I);
1018 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1019 // Get the source and destination types
1020 const Type *SrcTy = I.getOperand(0)->getType();
1021 const Type *DestTy = I.getType();
1023 bool SrcVec = SrcTy->isVectorTy();
1024 bool DstVec = DestTy->isVectorTy();
1026 Assert1(SrcVec == DstVec,
1027 "FPToUI source and dest must both be vector or scalar", &I);
1028 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1030 Assert1(DestTy->isIntOrIntVectorTy(),
1031 "FPToUI result must be integer or integer vector", &I);
1033 if (SrcVec && DstVec)
1034 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1035 cast<VectorType>(DestTy)->getNumElements(),
1036 "FPToUI source and dest vector length mismatch", &I);
1038 visitInstruction(I);
1041 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1042 // Get the source and destination types
1043 const Type *SrcTy = I.getOperand(0)->getType();
1044 const Type *DestTy = I.getType();
1046 bool SrcVec = SrcTy->isVectorTy();
1047 bool DstVec = DestTy->isVectorTy();
1049 Assert1(SrcVec == DstVec,
1050 "FPToSI source and dest must both be vector or scalar", &I);
1051 Assert1(SrcTy->isFPOrFPVectorTy(),
1052 "FPToSI source must be FP or FP vector", &I);
1053 Assert1(DestTy->isIntOrIntVectorTy(),
1054 "FPToSI result must be integer or integer vector", &I);
1056 if (SrcVec && DstVec)
1057 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1058 cast<VectorType>(DestTy)->getNumElements(),
1059 "FPToSI source and dest vector length mismatch", &I);
1061 visitInstruction(I);
1064 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1065 // Get the source and destination types
1066 const Type *SrcTy = I.getOperand(0)->getType();
1067 const Type *DestTy = I.getType();
1069 Assert1(SrcTy->isPointerTy(), "PtrToInt source must be pointer", &I);
1070 Assert1(DestTy->isIntegerTy(), "PtrToInt result must be integral", &I);
1072 visitInstruction(I);
1075 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1076 // Get the source and destination types
1077 const Type *SrcTy = I.getOperand(0)->getType();
1078 const Type *DestTy = I.getType();
1080 Assert1(SrcTy->isIntegerTy(), "IntToPtr source must be an integral", &I);
1081 Assert1(DestTy->isPointerTy(), "IntToPtr result must be a pointer",&I);
1083 visitInstruction(I);
1086 void Verifier::visitBitCastInst(BitCastInst &I) {
1087 // Get the source and destination types
1088 const Type *SrcTy = I.getOperand(0)->getType();
1089 const Type *DestTy = I.getType();
1091 // Get the size of the types in bits, we'll need this later
1092 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1093 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1095 // BitCast implies a no-op cast of type only. No bits change.
1096 // However, you can't cast pointers to anything but pointers.
1097 Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(),
1098 "Bitcast requires both operands to be pointer or neither", &I);
1099 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1101 // Disallow aggregates.
1102 Assert1(!SrcTy->isAggregateType(),
1103 "Bitcast operand must not be aggregate", &I);
1104 Assert1(!DestTy->isAggregateType(),
1105 "Bitcast type must not be aggregate", &I);
1107 visitInstruction(I);
1110 /// visitPHINode - Ensure that a PHI node is well formed.
1112 void Verifier::visitPHINode(PHINode &PN) {
1113 // Ensure that the PHI nodes are all grouped together at the top of the block.
1114 // This can be tested by checking whether the instruction before this is
1115 // either nonexistent (because this is begin()) or is a PHI node. If not,
1116 // then there is some other instruction before a PHI.
1117 Assert2(&PN == &PN.getParent()->front() ||
1118 isa<PHINode>(--BasicBlock::iterator(&PN)),
1119 "PHI nodes not grouped at top of basic block!",
1120 &PN, PN.getParent());
1122 // Check that all of the values of the PHI node have the same type as the
1123 // result, and that the incoming blocks are really basic blocks.
1124 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1125 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1126 "PHI node operands are not the same type as the result!", &PN);
1127 Assert1(isa<BasicBlock>(PN.getOperand(
1128 PHINode::getOperandNumForIncomingBlock(i))),
1129 "PHI node incoming block is not a BasicBlock!", &PN);
1132 // All other PHI node constraints are checked in the visitBasicBlock method.
1134 visitInstruction(PN);
1137 void Verifier::VerifyCallSite(CallSite CS) {
1138 Instruction *I = CS.getInstruction();
1140 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1141 "Called function must be a pointer!", I);
1142 const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1144 Assert1(FPTy->getElementType()->isFunctionTy(),
1145 "Called function is not pointer to function type!", I);
1146 const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1148 // Verify that the correct number of arguments are being passed
1149 if (FTy->isVarArg())
1150 Assert1(CS.arg_size() >= FTy->getNumParams(),
1151 "Called function requires more parameters than were provided!",I);
1153 Assert1(CS.arg_size() == FTy->getNumParams(),
1154 "Incorrect number of arguments passed to called function!", I);
1156 // Verify that all arguments to the call match the function type.
1157 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1158 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1159 "Call parameter type does not match function signature!",
1160 CS.getArgument(i), FTy->getParamType(i), I);
1162 const AttrListPtr &Attrs = CS.getAttributes();
1164 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1165 "Attributes after last parameter!", I);
1167 // Verify call attributes.
1168 VerifyFunctionAttrs(FTy, Attrs, I);
1170 if (FTy->isVarArg())
1171 // Check attributes on the varargs part.
1172 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1173 Attributes Attr = Attrs.getParamAttributes(Idx);
1175 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1177 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1178 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1179 " cannot be used for vararg call arguments!", I);
1182 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1183 if (!CS.getCalledFunction() ||
1184 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1185 for (FunctionType::param_iterator PI = FTy->param_begin(),
1186 PE = FTy->param_end(); PI != PE; ++PI)
1187 Assert1(!PI->get()->isMetadataTy(),
1188 "Function has metadata parameter but isn't an intrinsic", I);
1191 visitInstruction(*I);
1194 void Verifier::visitCallInst(CallInst &CI) {
1195 VerifyCallSite(&CI);
1197 if (Function *F = CI.getCalledFunction())
1198 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1199 visitIntrinsicFunctionCall(ID, CI);
1202 void Verifier::visitInvokeInst(InvokeInst &II) {
1203 VerifyCallSite(&II);
1206 /// visitBinaryOperator - Check that both arguments to the binary operator are
1207 /// of the same type!
1209 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1210 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1211 "Both operands to a binary operator are not of the same type!", &B);
1213 switch (B.getOpcode()) {
1214 // Check that integer arithmetic operators are only used with
1215 // integral operands.
1216 case Instruction::Add:
1217 case Instruction::Sub:
1218 case Instruction::Mul:
1219 case Instruction::SDiv:
1220 case Instruction::UDiv:
1221 case Instruction::SRem:
1222 case Instruction::URem:
1223 Assert1(B.getType()->isIntOrIntVectorTy(),
1224 "Integer arithmetic operators only work with integral types!", &B);
1225 Assert1(B.getType() == B.getOperand(0)->getType(),
1226 "Integer arithmetic operators must have same type "
1227 "for operands and result!", &B);
1229 // Check that floating-point arithmetic operators are only used with
1230 // floating-point operands.
1231 case Instruction::FAdd:
1232 case Instruction::FSub:
1233 case Instruction::FMul:
1234 case Instruction::FDiv:
1235 case Instruction::FRem:
1236 Assert1(B.getType()->isFPOrFPVectorTy(),
1237 "Floating-point arithmetic operators only work with "
1238 "floating-point types!", &B);
1239 Assert1(B.getType() == B.getOperand(0)->getType(),
1240 "Floating-point arithmetic operators must have same type "
1241 "for operands and result!", &B);
1243 // Check that logical operators are only used with integral operands.
1244 case Instruction::And:
1245 case Instruction::Or:
1246 case Instruction::Xor:
1247 Assert1(B.getType()->isIntOrIntVectorTy(),
1248 "Logical operators only work with integral types!", &B);
1249 Assert1(B.getType() == B.getOperand(0)->getType(),
1250 "Logical operators must have same type for operands and result!",
1253 case Instruction::Shl:
1254 case Instruction::LShr:
1255 case Instruction::AShr:
1256 Assert1(B.getType()->isIntOrIntVectorTy(),
1257 "Shifts only work with integral types!", &B);
1258 Assert1(B.getType() == B.getOperand(0)->getType(),
1259 "Shift return type must be same as operands!", &B);
1262 llvm_unreachable("Unknown BinaryOperator opcode!");
1265 visitInstruction(B);
1268 void Verifier::visitICmpInst(ICmpInst& IC) {
1269 // Check that the operands are the same type
1270 const Type* Op0Ty = IC.getOperand(0)->getType();
1271 const Type* Op1Ty = IC.getOperand(1)->getType();
1272 Assert1(Op0Ty == Op1Ty,
1273 "Both operands to ICmp instruction are not of the same type!", &IC);
1274 // Check that the operands are the right type
1275 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPointerTy(),
1276 "Invalid operand types for ICmp instruction", &IC);
1278 visitInstruction(IC);
1281 void Verifier::visitFCmpInst(FCmpInst& FC) {
1282 // Check that the operands are the same type
1283 const Type* Op0Ty = FC.getOperand(0)->getType();
1284 const Type* Op1Ty = FC.getOperand(1)->getType();
1285 Assert1(Op0Ty == Op1Ty,
1286 "Both operands to FCmp instruction are not of the same type!", &FC);
1287 // Check that the operands are the right type
1288 Assert1(Op0Ty->isFPOrFPVectorTy(),
1289 "Invalid operand types for FCmp instruction", &FC);
1290 visitInstruction(FC);
1293 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1294 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1296 "Invalid extractelement operands!", &EI);
1297 visitInstruction(EI);
1300 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1301 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1304 "Invalid insertelement operands!", &IE);
1305 visitInstruction(IE);
1308 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1309 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1311 "Invalid shufflevector operands!", &SV);
1313 const VectorType *VTy = dyn_cast<VectorType>(SV.getOperand(0)->getType());
1314 Assert1(VTy, "Operands are not a vector type", &SV);
1316 // Check to see if Mask is valid.
1317 if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
1318 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1319 if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1320 Assert1(!CI->uge(VTy->getNumElements()*2),
1321 "Invalid shufflevector shuffle mask!", &SV);
1323 Assert1(isa<UndefValue>(MV->getOperand(i)),
1324 "Invalid shufflevector shuffle mask!", &SV);
1328 Assert1(isa<UndefValue>(SV.getOperand(2)) ||
1329 isa<ConstantAggregateZero>(SV.getOperand(2)),
1330 "Invalid shufflevector shuffle mask!", &SV);
1333 visitInstruction(SV);
1336 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1337 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1339 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
1340 Idxs.begin(), Idxs.end());
1341 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1342 Assert2(GEP.getType()->isPointerTy() &&
1343 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1344 "GEP is not of right type for indices!", &GEP, ElTy);
1345 visitInstruction(GEP);
1348 void Verifier::visitLoadInst(LoadInst &LI) {
1349 const PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1350 Assert1(PTy, "Load operand must be a pointer.", &LI);
1351 const Type *ElTy = PTy->getElementType();
1352 Assert2(ElTy == LI.getType(),
1353 "Load result type does not match pointer operand type!", &LI, ElTy);
1354 visitInstruction(LI);
1357 void Verifier::visitStoreInst(StoreInst &SI) {
1358 const PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1359 Assert1(PTy, "Load operand must be a pointer.", &SI);
1360 const Type *ElTy = PTy->getElementType();
1361 Assert2(ElTy == SI.getOperand(0)->getType(),
1362 "Stored value type does not match pointer operand type!",
1364 visitInstruction(SI);
1367 void Verifier::visitAllocaInst(AllocaInst &AI) {
1368 const PointerType *PTy = AI.getType();
1369 Assert1(PTy->getAddressSpace() == 0,
1370 "Allocation instruction pointer not in the generic address space!",
1372 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1374 Assert1(AI.getArraySize()->getType()->isIntegerTy(32),
1375 "Alloca array size must be i32", &AI);
1376 visitInstruction(AI);
1379 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1380 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1381 EVI.idx_begin(), EVI.idx_end()) ==
1383 "Invalid ExtractValueInst operands!", &EVI);
1385 visitInstruction(EVI);
1388 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1389 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1390 IVI.idx_begin(), IVI.idx_end()) ==
1391 IVI.getOperand(1)->getType(),
1392 "Invalid InsertValueInst operands!", &IVI);
1394 visitInstruction(IVI);
1397 /// verifyInstruction - Verify that an instruction is well formed.
1399 void Verifier::visitInstruction(Instruction &I) {
1400 BasicBlock *BB = I.getParent();
1401 Assert1(BB, "Instruction not embedded in basic block!", &I);
1403 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1404 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1406 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1407 "Only PHI nodes may reference their own value!", &I);
1410 // Verify that if this is a terminator that it is at the end of the block.
1411 if (isa<TerminatorInst>(I))
1412 Assert1(BB->getTerminator() == &I, "Terminator not at end of block!", &I);
1414 // Check that void typed values don't have names
1415 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1416 "Instruction has a name, but provides a void value!", &I);
1418 // Check that the return value of the instruction is either void or a legal
1420 Assert1(I.getType()->isVoidTy() ||
1421 I.getType()->isFirstClassType(),
1422 "Instruction returns a non-scalar type!", &I);
1424 // Check that the instruction doesn't produce metadata. Calls are already
1425 // checked against the callee type.
1426 Assert1(!I.getType()->isMetadataTy() ||
1427 isa<CallInst>(I) || isa<InvokeInst>(I),
1428 "Invalid use of metadata!", &I);
1430 // Check that all uses of the instruction, if they are instructions
1431 // themselves, actually have parent basic blocks. If the use is not an
1432 // instruction, it is an error!
1433 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1435 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1436 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1437 " embedded in a basic block!", &I, Used);
1439 CheckFailed("Use of instruction is not an instruction!", *UI);
1444 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1445 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1447 // Check to make sure that only first-class-values are operands to
1449 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1450 Assert1(0, "Instruction operands must be first-class values!", &I);
1453 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1454 // Check to make sure that the "address of" an intrinsic function is never
1456 Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
1457 "Cannot take the address of an intrinsic!", &I);
1458 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1460 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1461 Assert1(OpBB->getParent() == BB->getParent(),
1462 "Referring to a basic block in another function!", &I);
1463 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1464 Assert1(OpArg->getParent() == BB->getParent(),
1465 "Referring to an argument in another function!", &I);
1466 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1467 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1469 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1470 BasicBlock *OpBlock = Op->getParent();
1472 // Check that a definition dominates all of its uses.
1473 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1474 // Invoke results are only usable in the normal destination, not in the
1475 // exceptional destination.
1476 BasicBlock *NormalDest = II->getNormalDest();
1478 Assert2(NormalDest != II->getUnwindDest(),
1479 "No uses of invoke possible due to dominance structure!",
1482 // PHI nodes differ from other nodes because they actually "use" the
1483 // value in the predecessor basic blocks they correspond to.
1484 BasicBlock *UseBlock = BB;
1485 if (isa<PHINode>(I))
1486 UseBlock = dyn_cast<BasicBlock>(I.getOperand(i+1));
1487 Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1490 if (isa<PHINode>(I) && UseBlock == OpBlock) {
1491 // Special case of a phi node in the normal destination or the unwind
1493 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1494 "Invoke result not available in the unwind destination!",
1497 Assert2(DT->dominates(NormalDest, UseBlock) ||
1498 !DT->isReachableFromEntry(UseBlock),
1499 "Invoke result does not dominate all uses!", Op, &I);
1501 // If the normal successor of an invoke instruction has multiple
1502 // predecessors, then the normal edge from the invoke is critical,
1503 // so the invoke value can only be live if the destination block
1504 // dominates all of it's predecessors (other than the invoke).
1505 if (!NormalDest->getSinglePredecessor() &&
1506 DT->isReachableFromEntry(UseBlock))
1507 // If it is used by something non-phi, then the other case is that
1508 // 'NormalDest' dominates all of its predecessors other than the
1509 // invoke. In this case, the invoke value can still be used.
1510 for (pred_iterator PI = pred_begin(NormalDest),
1511 E = pred_end(NormalDest); PI != E; ++PI)
1512 if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1513 DT->isReachableFromEntry(*PI)) {
1514 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1518 } else if (isa<PHINode>(I)) {
1519 // PHI nodes are more difficult than other nodes because they actually
1520 // "use" the value in the predecessor basic blocks they correspond to.
1521 BasicBlock *PredBB = dyn_cast<BasicBlock>(I.getOperand(i+1));
1522 Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1523 !DT->isReachableFromEntry(PredBB)),
1524 "Instruction does not dominate all uses!", Op, &I);
1526 if (OpBlock == BB) {
1527 // If they are in the same basic block, make sure that the definition
1528 // comes before the use.
1529 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1530 "Instruction does not dominate all uses!", Op, &I);
1533 // Definition must dominate use unless use is unreachable!
1534 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1535 !DT->isReachableFromEntry(BB),
1536 "Instruction does not dominate all uses!", Op, &I);
1538 } else if (isa<InlineAsm>(I.getOperand(i))) {
1539 Assert1((i == 0 && isa<CallInst>(I)) || (i + 3 == e && isa<InvokeInst>(I)),
1540 "Cannot take the address of an inline asm!", &I);
1543 InstsInThisBlock.insert(&I);
1545 VerifyType(I.getType());
1548 /// VerifyType - Verify that a type is well formed.
1550 void Verifier::VerifyType(const Type *Ty) {
1551 if (!Types.insert(Ty)) return;
1553 Assert1(Context == &Ty->getContext(),
1554 "Type context does not match Module context!", Ty);
1556 switch (Ty->getTypeID()) {
1557 case Type::FunctionTyID: {
1558 const FunctionType *FTy = cast<FunctionType>(Ty);
1560 const Type *RetTy = FTy->getReturnType();
1561 Assert2(FunctionType::isValidReturnType(RetTy),
1562 "Function type with invalid return type", RetTy, FTy);
1565 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1566 const Type *ElTy = FTy->getParamType(i);
1567 Assert2(FunctionType::isValidArgumentType(ElTy),
1568 "Function type with invalid parameter type", ElTy, FTy);
1572 case Type::StructTyID: {
1573 const StructType *STy = cast<StructType>(Ty);
1574 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1575 const Type *ElTy = STy->getElementType(i);
1576 Assert2(StructType::isValidElementType(ElTy),
1577 "Structure type with invalid element type", ElTy, STy);
1581 case Type::UnionTyID: {
1582 const UnionType *UTy = cast<UnionType>(Ty);
1583 for (unsigned i = 0, e = UTy->getNumElements(); i != e; ++i) {
1584 const Type *ElTy = UTy->getElementType(i);
1585 Assert2(UnionType::isValidElementType(ElTy),
1586 "Union type with invalid element type", ElTy, UTy);
1590 case Type::ArrayTyID: {
1591 const ArrayType *ATy = cast<ArrayType>(Ty);
1592 Assert1(ArrayType::isValidElementType(ATy->getElementType()),
1593 "Array type with invalid element type", ATy);
1594 VerifyType(ATy->getElementType());
1596 case Type::PointerTyID: {
1597 const PointerType *PTy = cast<PointerType>(Ty);
1598 Assert1(PointerType::isValidElementType(PTy->getElementType()),
1599 "Pointer type with invalid element type", PTy);
1600 VerifyType(PTy->getElementType());
1602 case Type::VectorTyID: {
1603 const VectorType *VTy = cast<VectorType>(Ty);
1604 Assert1(VectorType::isValidElementType(VTy->getElementType()),
1605 "Vector type with invalid element type", VTy);
1606 VerifyType(VTy->getElementType());
1613 // Flags used by TableGen to mark intrinsic parameters with the
1614 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1615 static const unsigned ExtendedElementVectorType = 0x40000000;
1616 static const unsigned TruncatedElementVectorType = 0x20000000;
1618 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1620 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1621 Function *IF = CI.getCalledFunction();
1622 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1625 #define GET_INTRINSIC_VERIFIER
1626 #include "llvm/Intrinsics.gen"
1627 #undef GET_INTRINSIC_VERIFIER
1629 // If the intrinsic takes MDNode arguments, verify that they are either global
1630 // or are local to *this* function.
1631 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1632 if (MDNode *MD = dyn_cast<MDNode>(CI.getOperand(i)))
1633 visitMDNode(*MD, CI.getParent()->getParent());
1638 case Intrinsic::dbg_declare: { // llvm.dbg.declare
1639 Assert1(CI.getOperand(1) && isa<MDNode>(CI.getOperand(1)),
1640 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1641 MDNode *MD = cast<MDNode>(CI.getOperand(1));
1642 Assert1(MD->getNumOperands() == 1,
1643 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1645 case Intrinsic::memcpy:
1646 case Intrinsic::memmove:
1647 case Intrinsic::memset:
1648 Assert1(isa<ConstantInt>(CI.getOperand(4)),
1649 "alignment argument of memory intrinsics must be a constant int",
1652 case Intrinsic::gcroot:
1653 case Intrinsic::gcwrite:
1654 case Intrinsic::gcread:
1655 if (ID == Intrinsic::gcroot) {
1657 dyn_cast<AllocaInst>(CI.getOperand(1)->stripPointerCasts());
1658 Assert1(AI && AI->getType()->getElementType()->isPointerTy(),
1659 "llvm.gcroot parameter #1 must be a pointer alloca.", &CI);
1660 Assert1(isa<Constant>(CI.getOperand(2)),
1661 "llvm.gcroot parameter #2 must be a constant.", &CI);
1664 Assert1(CI.getParent()->getParent()->hasGC(),
1665 "Enclosing function does not use GC.", &CI);
1667 case Intrinsic::init_trampoline:
1668 Assert1(isa<Function>(CI.getOperand(2)->stripPointerCasts()),
1669 "llvm.init_trampoline parameter #2 must resolve to a function.",
1672 case Intrinsic::prefetch:
1673 Assert1(isa<ConstantInt>(CI.getOperand(2)) &&
1674 isa<ConstantInt>(CI.getOperand(3)) &&
1675 cast<ConstantInt>(CI.getOperand(2))->getZExtValue() < 2 &&
1676 cast<ConstantInt>(CI.getOperand(3))->getZExtValue() < 4,
1677 "invalid arguments to llvm.prefetch",
1680 case Intrinsic::stackprotector:
1681 Assert1(isa<AllocaInst>(CI.getOperand(2)->stripPointerCasts()),
1682 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1685 case Intrinsic::lifetime_start:
1686 case Intrinsic::lifetime_end:
1687 case Intrinsic::invariant_start:
1688 Assert1(isa<ConstantInt>(CI.getOperand(1)),
1689 "size argument of memory use markers must be a constant integer",
1692 case Intrinsic::invariant_end:
1693 Assert1(isa<ConstantInt>(CI.getOperand(2)),
1694 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1699 /// Produce a string to identify an intrinsic parameter or return value.
1700 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1701 /// parameters beginning with NumRets.
1703 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1704 if (ArgNo >= NumRets)
1705 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1707 return "Intrinsic result type";
1708 return "Intrinsic result type #" + utostr(ArgNo);
1711 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
1712 int VT, unsigned ArgNo, std::string &Suffix) {
1713 const FunctionType *FTy = F->getFunctionType();
1715 unsigned NumElts = 0;
1716 const Type *EltTy = Ty;
1717 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1719 EltTy = VTy->getElementType();
1720 NumElts = VTy->getNumElements();
1723 const Type *RetTy = FTy->getReturnType();
1724 const StructType *ST = dyn_cast<StructType>(RetTy);
1725 unsigned NumRetVals;
1726 if (RetTy->isVoidTy())
1729 NumRetVals = ST->getNumElements();
1736 // Check flags that indicate a type that is an integral vector type with
1737 // elements that are larger or smaller than the elements of the matched
1739 if ((Match & (ExtendedElementVectorType |
1740 TruncatedElementVectorType)) != 0) {
1741 const IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1742 if (!VTy || !IEltTy) {
1743 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1744 "an integral vector type.", F);
1747 // Adjust the current Ty (in the opposite direction) rather than
1748 // the type being matched against.
1749 if ((Match & ExtendedElementVectorType) != 0) {
1750 if ((IEltTy->getBitWidth() & 1) != 0) {
1751 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector "
1752 "element bit-width is odd.", F);
1755 Ty = VectorType::getTruncatedElementVectorType(VTy);
1757 Ty = VectorType::getExtendedElementVectorType(VTy);
1758 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1761 if (Match <= static_cast<int>(NumRetVals - 1)) {
1763 RetTy = ST->getElementType(Match);
1766 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1767 "match return type.", F);
1771 if (Ty != FTy->getParamType(Match - NumRetVals)) {
1772 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1773 "match parameter %" + utostr(Match - NumRetVals) + ".", F);
1777 } else if (VT == MVT::iAny) {
1778 if (!EltTy->isIntegerTy()) {
1779 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1780 "an integer type.", F);
1784 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1788 Suffix += "v" + utostr(NumElts);
1790 Suffix += "i" + utostr(GotBits);
1792 // Check some constraints on various intrinsics.
1794 default: break; // Not everything needs to be checked.
1795 case Intrinsic::bswap:
1796 if (GotBits < 16 || GotBits % 16 != 0) {
1797 CheckFailed("Intrinsic requires even byte width argument", F);
1802 } else if (VT == MVT::fAny) {
1803 if (!EltTy->isFloatingPointTy()) {
1804 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1805 "a floating-point type.", F);
1812 Suffix += "v" + utostr(NumElts);
1814 Suffix += EVT::getEVT(EltTy).getEVTString();
1815 } else if (VT == MVT::vAny) {
1817 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.",
1821 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1822 } else if (VT == MVT::iPTR) {
1823 if (!Ty->isPointerTy()) {
1824 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1825 "pointer and a pointer is required.", F);
1828 } else if (VT == MVT::iPTRAny) {
1829 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1830 // and iPTR. In the verifier, we can not distinguish which case we have so
1831 // allow either case to be legal.
1832 if (const PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1833 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1834 EVT::getEVT(PTyp->getElementType()).getEVTString();
1836 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1837 "pointer and a pointer is required.", F);
1840 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1841 EVT VVT = EVT((MVT::SimpleValueType)VT);
1843 // If this is a vector argument, verify the number and type of elements.
1844 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1845 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1849 if (VVT.getVectorNumElements() != NumElts) {
1850 CheckFailed("Intrinsic prototype has incorrect number of "
1851 "vector elements!", F);
1854 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1856 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F);
1858 } else if (EltTy != Ty) {
1859 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector "
1860 "and a scalar is required.", F);
1867 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1868 /// Intrinsics.gen. This implements a little state machine that verifies the
1869 /// prototype of intrinsics.
1870 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1871 unsigned NumRetVals,
1872 unsigned NumParams, ...) {
1874 va_start(VA, NumParams);
1875 const FunctionType *FTy = F->getFunctionType();
1877 // For overloaded intrinsics, the Suffix of the function name must match the
1878 // types of the arguments. This variable keeps track of the expected
1879 // suffix, to be checked at the end.
1882 if (FTy->getNumParams() + FTy->isVarArg() != NumParams) {
1883 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1887 const Type *Ty = FTy->getReturnType();
1888 const StructType *ST = dyn_cast<StructType>(Ty);
1890 if (NumRetVals == 0 && !Ty->isVoidTy()) {
1891 CheckFailed("Intrinsic should return void", F);
1895 // Verify the return types.
1896 if (ST && ST->getNumElements() != NumRetVals) {
1897 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1901 for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) {
1902 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1904 if (ST) Ty = ST->getElementType(ArgNo);
1905 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1909 // Verify the parameter types.
1910 for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) {
1911 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1913 if (VT == MVT::isVoid && ArgNo > 0) {
1914 if (!FTy->isVarArg())
1915 CheckFailed("Intrinsic prototype has no '...'!", F);
1919 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT,
1920 ArgNo + NumRetVals, Suffix))
1926 // For intrinsics without pointer arguments, if we computed a Suffix then the
1927 // intrinsic is overloaded and we need to make sure that the name of the
1928 // function is correct. We add the suffix to the name of the intrinsic and
1929 // compare against the given function name. If they are not the same, the
1930 // function name is invalid. This ensures that overloading of intrinsics
1931 // uses a sane and consistent naming convention. Note that intrinsics with
1932 // pointer argument may or may not be overloaded so we will check assuming it
1933 // has a suffix and not.
1934 if (!Suffix.empty()) {
1935 std::string Name(Intrinsic::getName(ID));
1936 if (Name + Suffix != F->getName()) {
1937 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1938 F->getName().substr(Name.length()) + "'. It should be '" +
1943 // Check parameter attributes.
1944 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1945 "Intrinsic has wrong parameter attributes!", F);
1949 //===----------------------------------------------------------------------===//
1950 // Implement the public interfaces to this file...
1951 //===----------------------------------------------------------------------===//
1953 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1954 return new Verifier(action);
1958 /// verifyFunction - Check a function for errors, printing messages on stderr.
1959 /// Return true if the function is corrupt.
1961 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1962 Function &F = const_cast<Function&>(f);
1963 assert(!F.isDeclaration() && "Cannot verify external functions");
1965 FunctionPassManager FPM(F.getParent());
1966 Verifier *V = new Verifier(action);
1972 /// verifyModule - Check a module for errors, printing messages on stderr.
1973 /// Return true if the module is corrupt.
1975 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1976 std::string *ErrorInfo) {
1978 Verifier *V = new Verifier(action);
1980 PM.run(const_cast<Module&>(M));
1982 if (ErrorInfo && V->Broken)
1983 *ErrorInfo = V->MessagesStr.str();