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/CallingConv.h"
50 #include "llvm/Constants.h"
51 #include "llvm/DerivedTypes.h"
52 #include "llvm/InlineAsm.h"
53 #include "llvm/IntrinsicInst.h"
54 #include "llvm/LLVMContext.h"
55 #include "llvm/Metadata.h"
56 #include "llvm/Module.h"
57 #include "llvm/Pass.h"
58 #include "llvm/PassManager.h"
59 #include "llvm/Analysis/Dominators.h"
60 #include "llvm/Assembly/Writer.h"
61 #include "llvm/CodeGen/ValueTypes.h"
62 #include "llvm/Support/CallSite.h"
63 #include "llvm/Support/CFG.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/InstVisitor.h"
66 #include "llvm/ADT/SetVector.h"
67 #include "llvm/ADT/SmallPtrSet.h"
68 #include "llvm/ADT/SmallVector.h"
69 #include "llvm/ADT/StringExtras.h"
70 #include "llvm/ADT/STLExtras.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);
203 // If the module is broken, abort at this time.
204 return abortIfBroken();
207 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
208 AU.setPreservesAll();
209 AU.addRequiredID(PreVerifyID);
210 AU.addRequired<DominatorTree>();
213 /// abortIfBroken - If the module is broken and we are supposed to abort on
214 /// this condition, do so.
216 bool abortIfBroken() {
217 if (!Broken) return false;
218 MessagesStr << "Broken module found, ";
220 case AbortProcessAction:
221 MessagesStr << "compilation aborted!\n";
222 dbgs() << MessagesStr.str();
223 // Client should choose different reaction if abort is not desired
225 case PrintMessageAction:
226 MessagesStr << "verification continues.\n";
227 dbgs() << MessagesStr.str();
229 case ReturnStatusAction:
230 MessagesStr << "compilation terminated.\n";
233 llvm_unreachable("Invalid action");
237 // Verification methods...
238 void visitGlobalValue(GlobalValue &GV);
239 void visitGlobalVariable(GlobalVariable &GV);
240 void visitGlobalAlias(GlobalAlias &GA);
241 void visitNamedMDNode(NamedMDNode &NMD);
242 void visitMDNode(MDNode &MD, Function *F);
243 void visitFunction(Function &F);
244 void visitBasicBlock(BasicBlock &BB);
245 using InstVisitor<Verifier>::visit;
247 void visit(Instruction &I);
249 void visitTruncInst(TruncInst &I);
250 void visitZExtInst(ZExtInst &I);
251 void visitSExtInst(SExtInst &I);
252 void visitFPTruncInst(FPTruncInst &I);
253 void visitFPExtInst(FPExtInst &I);
254 void visitFPToUIInst(FPToUIInst &I);
255 void visitFPToSIInst(FPToSIInst &I);
256 void visitUIToFPInst(UIToFPInst &I);
257 void visitSIToFPInst(SIToFPInst &I);
258 void visitIntToPtrInst(IntToPtrInst &I);
259 void visitPtrToIntInst(PtrToIntInst &I);
260 void visitBitCastInst(BitCastInst &I);
261 void visitPHINode(PHINode &PN);
262 void visitBinaryOperator(BinaryOperator &B);
263 void visitICmpInst(ICmpInst &IC);
264 void visitFCmpInst(FCmpInst &FC);
265 void visitExtractElementInst(ExtractElementInst &EI);
266 void visitInsertElementInst(InsertElementInst &EI);
267 void visitShuffleVectorInst(ShuffleVectorInst &EI);
268 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
269 void visitCallInst(CallInst &CI);
270 void visitInvokeInst(InvokeInst &II);
271 void visitGetElementPtrInst(GetElementPtrInst &GEP);
272 void visitLoadInst(LoadInst &LI);
273 void visitStoreInst(StoreInst &SI);
274 void verifyDominatesUse(Instruction &I, unsigned i);
275 void visitInstruction(Instruction &I);
276 void visitTerminatorInst(TerminatorInst &I);
277 void visitBranchInst(BranchInst &BI);
278 void visitReturnInst(ReturnInst &RI);
279 void visitSwitchInst(SwitchInst &SI);
280 void visitIndirectBrInst(IndirectBrInst &BI);
281 void visitSelectInst(SelectInst &SI);
282 void visitUserOp1(Instruction &I);
283 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
284 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
285 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
286 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
287 void visitFenceInst(FenceInst &FI);
288 void visitAllocaInst(AllocaInst &AI);
289 void visitExtractValueInst(ExtractValueInst &EVI);
290 void visitInsertValueInst(InsertValueInst &IVI);
291 void visitLandingPadInst(LandingPadInst &LPI);
293 void VerifyCallSite(CallSite CS);
294 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
295 int VT, unsigned ArgNo, std::string &Suffix);
296 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
297 unsigned RetNum, unsigned ParamNum, ...);
298 void VerifyParameterAttrs(Attributes Attrs, Type *Ty,
299 bool isReturnValue, const Value *V);
300 void VerifyFunctionAttrs(FunctionType *FT, const AttrListPtr &Attrs,
303 void WriteValue(const Value *V) {
305 if (isa<Instruction>(V)) {
306 MessagesStr << *V << '\n';
308 WriteAsOperand(MessagesStr, V, true, Mod);
313 void WriteType(Type *T) {
315 MessagesStr << ' ' << *T;
319 // CheckFailed - A check failed, so print out the condition and the message
320 // that failed. This provides a nice place to put a breakpoint if you want
321 // to see why something is not correct.
322 void CheckFailed(const Twine &Message,
323 const Value *V1 = 0, const Value *V2 = 0,
324 const Value *V3 = 0, const Value *V4 = 0) {
325 MessagesStr << Message.str() << "\n";
333 void CheckFailed(const Twine &Message, const Value *V1,
334 Type *T2, const Value *V3 = 0) {
335 MessagesStr << Message.str() << "\n";
342 void CheckFailed(const Twine &Message, Type *T1,
343 Type *T2 = 0, Type *T3 = 0) {
344 MessagesStr << Message.str() << "\n";
351 } // End anonymous namespace
353 char Verifier::ID = 0;
354 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
355 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
356 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
357 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
359 // Assert - We know that cond should be true, if not print an error message.
360 #define Assert(C, M) \
361 do { if (!(C)) { CheckFailed(M); return; } } while (0)
362 #define Assert1(C, M, V1) \
363 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
364 #define Assert2(C, M, V1, V2) \
365 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
366 #define Assert3(C, M, V1, V2, V3) \
367 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
368 #define Assert4(C, M, V1, V2, V3, V4) \
369 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
371 void Verifier::visit(Instruction &I) {
372 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
373 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
374 InstVisitor<Verifier>::visit(I);
378 void Verifier::visitGlobalValue(GlobalValue &GV) {
379 Assert1(!GV.isDeclaration() ||
380 GV.isMaterializable() ||
381 GV.hasExternalLinkage() ||
382 GV.hasDLLImportLinkage() ||
383 GV.hasExternalWeakLinkage() ||
384 (isa<GlobalAlias>(GV) &&
385 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
386 "Global is external, but doesn't have external or dllimport or weak linkage!",
389 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
390 "Global is marked as dllimport, but not external", &GV);
392 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
393 "Only global variables can have appending linkage!", &GV);
395 if (GV.hasAppendingLinkage()) {
396 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
397 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
398 "Only global arrays can have appending linkage!", GVar);
401 Assert1(!GV.hasLinkerPrivateWeakDefAutoLinkage() || GV.hasDefaultVisibility(),
402 "linker_private_weak_def_auto can only have default visibility!",
406 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
407 if (GV.hasInitializer()) {
408 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
409 "Global variable initializer type does not match global "
410 "variable type!", &GV);
412 // If the global has common linkage, it must have a zero initializer and
413 // cannot be constant.
414 if (GV.hasCommonLinkage()) {
415 Assert1(GV.getInitializer()->isNullValue(),
416 "'common' global must have a zero initializer!", &GV);
417 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
421 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
422 GV.hasExternalWeakLinkage(),
423 "invalid linkage type for global declaration", &GV);
426 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
427 GV.getName() == "llvm.global_dtors")) {
428 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
429 "invalid linkage for intrinsic global variable", &GV);
430 // Don't worry about emitting an error for it not being an array,
431 // visitGlobalValue will complain on appending non-array.
432 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
433 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
434 PointerType *FuncPtrTy =
435 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
436 Assert1(STy && STy->getNumElements() == 2 &&
437 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
438 STy->getTypeAtIndex(1) == FuncPtrTy,
439 "wrong type for intrinsic global variable", &GV);
443 visitGlobalValue(GV);
446 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
447 Assert1(!GA.getName().empty(),
448 "Alias name cannot be empty!", &GA);
449 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
451 "Alias should have external or external weak linkage!", &GA);
452 Assert1(GA.getAliasee(),
453 "Aliasee cannot be NULL!", &GA);
454 Assert1(GA.getType() == GA.getAliasee()->getType(),
455 "Alias and aliasee types should match!", &GA);
456 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
458 if (!isa<GlobalValue>(GA.getAliasee())) {
459 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
461 (CE->getOpcode() == Instruction::BitCast ||
462 CE->getOpcode() == Instruction::GetElementPtr) &&
463 isa<GlobalValue>(CE->getOperand(0)),
464 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
468 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
470 "Aliasing chain should end with function or global variable", &GA);
472 visitGlobalValue(GA);
475 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
476 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
477 MDNode *MD = NMD.getOperand(i);
481 Assert1(!MD->isFunctionLocal(),
482 "Named metadata operand cannot be function local!", MD);
487 void Verifier::visitMDNode(MDNode &MD, Function *F) {
488 // Only visit each node once. Metadata can be mutually recursive, so this
489 // avoids infinite recursion here, as well as being an optimization.
490 if (!MDNodes.insert(&MD))
493 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
494 Value *Op = MD.getOperand(i);
497 if (isa<Constant>(Op) || isa<MDString>(Op))
499 if (MDNode *N = dyn_cast<MDNode>(Op)) {
500 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
501 "Global metadata operand cannot be function local!", &MD, N);
505 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
507 // If this was an instruction, bb, or argument, verify that it is in the
508 // function that we expect.
509 Function *ActualF = 0;
510 if (Instruction *I = dyn_cast<Instruction>(Op))
511 ActualF = I->getParent()->getParent();
512 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
513 ActualF = BB->getParent();
514 else if (Argument *A = dyn_cast<Argument>(Op))
515 ActualF = A->getParent();
516 assert(ActualF && "Unimplemented function local metadata case!");
518 Assert2(ActualF == F, "function-local metadata used in wrong function",
523 // VerifyParameterAttrs - Check the given attributes for an argument or return
524 // value of the specified type. The value V is printed in error messages.
525 void Verifier::VerifyParameterAttrs(Attributes Attrs, Type *Ty,
526 bool isReturnValue, const Value *V) {
527 if (Attrs == Attribute::None)
530 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
531 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
532 " only applies to the function!", V);
535 Attributes RetI = Attrs & Attribute::ParameterOnly;
536 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
537 " does not apply to return values!", V);
541 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
542 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
543 Assert1(MutI.isEmptyOrSingleton(), "Attributes " +
544 Attribute::getAsString(MutI) + " are incompatible!", V);
547 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
548 Assert1(!TypeI, "Wrong type for attribute " +
549 Attribute::getAsString(TypeI), V);
551 Attributes ByValI = Attrs & Attribute::ByVal;
552 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
553 Assert1(!ByValI || PTy->getElementType()->isSized(),
554 "Attribute " + Attribute::getAsString(ByValI) +
555 " does not support unsized types!", V);
558 "Attribute " + Attribute::getAsString(ByValI) +
559 " only applies to parameters with pointer type!", V);
563 // VerifyFunctionAttrs - Check parameter attributes against a function type.
564 // The value V is printed in error messages.
565 void Verifier::VerifyFunctionAttrs(FunctionType *FT,
566 const AttrListPtr &Attrs,
571 bool SawNest = false;
573 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
574 const AttributeWithIndex &Attr = Attrs.getSlot(i);
578 Ty = FT->getReturnType();
579 else if (Attr.Index-1 < FT->getNumParams())
580 Ty = FT->getParamType(Attr.Index-1);
582 break; // VarArgs attributes, verified elsewhere.
584 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
586 if (Attr.Attrs & Attribute::Nest) {
587 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
591 if (Attr.Attrs & Attribute::StructRet)
592 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
595 Attributes FAttrs = Attrs.getFnAttributes();
596 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
597 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
598 " does not apply to the function!", V);
601 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
602 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
603 Assert1(MutI.isEmptyOrSingleton(), "Attributes " +
604 Attribute::getAsString(MutI) + " are incompatible!", V);
608 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
612 unsigned LastSlot = Attrs.getNumSlots() - 1;
613 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
614 if (LastIndex <= Params
615 || (LastIndex == (unsigned)~0
616 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
622 // visitFunction - Verify that a function is ok.
624 void Verifier::visitFunction(Function &F) {
625 // Check function arguments.
626 FunctionType *FT = F.getFunctionType();
627 unsigned NumArgs = F.arg_size();
629 Assert1(Context == &F.getContext(),
630 "Function context does not match Module context!", &F);
632 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
633 Assert2(FT->getNumParams() == NumArgs,
634 "# formal arguments must match # of arguments for function type!",
636 Assert1(F.getReturnType()->isFirstClassType() ||
637 F.getReturnType()->isVoidTy() ||
638 F.getReturnType()->isStructTy(),
639 "Functions cannot return aggregate values!", &F);
641 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
642 "Invalid struct return type!", &F);
644 const AttrListPtr &Attrs = F.getAttributes();
646 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
647 "Attributes after last parameter!", &F);
649 // Check function attributes.
650 VerifyFunctionAttrs(FT, Attrs, &F);
652 // Check that this function meets the restrictions on this calling convention.
653 switch (F.getCallingConv()) {
658 case CallingConv::Fast:
659 case CallingConv::Cold:
660 case CallingConv::X86_FastCall:
661 case CallingConv::X86_ThisCall:
662 case CallingConv::PTX_Kernel:
663 case CallingConv::PTX_Device:
664 Assert1(!F.isVarArg(),
665 "Varargs functions must have C calling conventions!", &F);
669 bool isLLVMdotName = F.getName().size() >= 5 &&
670 F.getName().substr(0, 5) == "llvm.";
672 // Check that the argument values match the function type for this function...
674 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
676 Assert2(I->getType() == FT->getParamType(i),
677 "Argument value does not match function argument type!",
678 I, FT->getParamType(i));
679 Assert1(I->getType()->isFirstClassType(),
680 "Function arguments must have first-class types!", I);
682 Assert2(!I->getType()->isMetadataTy(),
683 "Function takes metadata but isn't an intrinsic", I, &F);
686 if (F.isMaterializable()) {
687 // Function has a body somewhere we can't see.
688 } else if (F.isDeclaration()) {
689 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
690 F.hasExternalWeakLinkage(),
691 "invalid linkage type for function declaration", &F);
693 // Verify that this function (which has a body) is not named "llvm.*". It
694 // is not legal to define intrinsics.
695 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
697 // Check the entry node
698 BasicBlock *Entry = &F.getEntryBlock();
699 Assert1(pred_begin(Entry) == pred_end(Entry),
700 "Entry block to function must not have predecessors!", Entry);
702 // The address of the entry block cannot be taken, unless it is dead.
703 if (Entry->hasAddressTaken()) {
704 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
705 "blockaddress may not be used with the entry block!", Entry);
709 // If this function is actually an intrinsic, verify that it is only used in
710 // direct call/invokes, never having its "address taken".
711 if (F.getIntrinsicID()) {
713 if (F.hasAddressTaken(&U))
714 Assert1(0, "Invalid user of intrinsic instruction!", U);
718 // verifyBasicBlock - Verify that a basic block is well formed...
720 void Verifier::visitBasicBlock(BasicBlock &BB) {
721 InstsInThisBlock.clear();
723 // Ensure that basic blocks have terminators!
724 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
726 // Check constraints that this basic block imposes on all of the PHI nodes in
728 if (isa<PHINode>(BB.front())) {
729 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
730 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
731 std::sort(Preds.begin(), Preds.end());
733 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
734 // Ensure that PHI nodes have at least one entry!
735 Assert1(PN->getNumIncomingValues() != 0,
736 "PHI nodes must have at least one entry. If the block is dead, "
737 "the PHI should be removed!", PN);
738 Assert1(PN->getNumIncomingValues() == Preds.size(),
739 "PHINode should have one entry for each predecessor of its "
740 "parent basic block!", PN);
742 // Get and sort all incoming values in the PHI node...
744 Values.reserve(PN->getNumIncomingValues());
745 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
746 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
747 PN->getIncomingValue(i)));
748 std::sort(Values.begin(), Values.end());
750 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
751 // Check to make sure that if there is more than one entry for a
752 // particular basic block in this PHI node, that the incoming values are
755 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
756 Values[i].second == Values[i-1].second,
757 "PHI node has multiple entries for the same basic block with "
758 "different incoming values!", PN, Values[i].first,
759 Values[i].second, Values[i-1].second);
761 // Check to make sure that the predecessors and PHI node entries are
763 Assert3(Values[i].first == Preds[i],
764 "PHI node entries do not match predecessors!", PN,
765 Values[i].first, Preds[i]);
771 void Verifier::visitTerminatorInst(TerminatorInst &I) {
772 // Ensure that terminators only exist at the end of the basic block.
773 Assert1(&I == I.getParent()->getTerminator(),
774 "Terminator found in the middle of a basic block!", I.getParent());
778 void Verifier::visitBranchInst(BranchInst &BI) {
779 if (BI.isConditional()) {
780 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
781 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
783 visitTerminatorInst(BI);
786 void Verifier::visitReturnInst(ReturnInst &RI) {
787 Function *F = RI.getParent()->getParent();
788 unsigned N = RI.getNumOperands();
789 if (F->getReturnType()->isVoidTy())
791 "Found return instr that returns non-void in Function of void "
792 "return type!", &RI, F->getReturnType());
794 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
795 "Function return type does not match operand "
796 "type of return inst!", &RI, F->getReturnType());
798 // Check to make sure that the return value has necessary properties for
800 visitTerminatorInst(RI);
803 void Verifier::visitSwitchInst(SwitchInst &SI) {
804 // Check to make sure that all of the constants in the switch instruction
805 // have the same type as the switched-on value.
806 Type *SwitchTy = SI.getCondition()->getType();
807 SmallPtrSet<ConstantInt*, 32> Constants;
808 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
809 Assert1(i.getCaseValue()->getType() == SwitchTy,
810 "Switch constants must all be same type as switch value!", &SI);
811 Assert2(Constants.insert(i.getCaseValue()),
812 "Duplicate integer as switch case", &SI, i.getCaseValue());
815 visitTerminatorInst(SI);
818 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
819 Assert1(BI.getAddress()->getType()->isPointerTy(),
820 "Indirectbr operand must have pointer type!", &BI);
821 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
822 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
823 "Indirectbr destinations must all have pointer type!", &BI);
825 visitTerminatorInst(BI);
828 void Verifier::visitSelectInst(SelectInst &SI) {
829 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
831 "Invalid operands for select instruction!", &SI);
833 Assert1(SI.getTrueValue()->getType() == SI.getType(),
834 "Select values must have same type as select instruction!", &SI);
835 visitInstruction(SI);
838 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
839 /// a pass, if any exist, it's an error.
841 void Verifier::visitUserOp1(Instruction &I) {
842 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
845 void Verifier::visitTruncInst(TruncInst &I) {
846 // Get the source and destination types
847 Type *SrcTy = I.getOperand(0)->getType();
848 Type *DestTy = I.getType();
850 // Get the size of the types in bits, we'll need this later
851 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
852 unsigned DestBitSize = DestTy->getScalarSizeInBits();
854 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
855 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
856 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
857 "trunc source and destination must both be a vector or neither", &I);
858 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
863 void Verifier::visitZExtInst(ZExtInst &I) {
864 // Get the source and destination types
865 Type *SrcTy = I.getOperand(0)->getType();
866 Type *DestTy = I.getType();
868 // Get the size of the types in bits, we'll need this later
869 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
870 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
871 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
872 "zext source and destination must both be a vector or neither", &I);
873 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
874 unsigned DestBitSize = DestTy->getScalarSizeInBits();
876 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
881 void Verifier::visitSExtInst(SExtInst &I) {
882 // Get the source and destination types
883 Type *SrcTy = I.getOperand(0)->getType();
884 Type *DestTy = I.getType();
886 // Get the size of the types in bits, we'll need this later
887 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
888 unsigned DestBitSize = DestTy->getScalarSizeInBits();
890 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
891 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
892 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
893 "sext source and destination must both be a vector or neither", &I);
894 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
899 void Verifier::visitFPTruncInst(FPTruncInst &I) {
900 // Get the source and destination types
901 Type *SrcTy = I.getOperand(0)->getType();
902 Type *DestTy = I.getType();
903 // Get the size of the types in bits, we'll need this later
904 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
905 unsigned DestBitSize = DestTy->getScalarSizeInBits();
907 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
908 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
909 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
910 "fptrunc source and destination must both be a vector or neither",&I);
911 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
916 void Verifier::visitFPExtInst(FPExtInst &I) {
917 // Get the source and destination types
918 Type *SrcTy = I.getOperand(0)->getType();
919 Type *DestTy = I.getType();
921 // Get the size of the types in bits, we'll need this later
922 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
923 unsigned DestBitSize = DestTy->getScalarSizeInBits();
925 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
926 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
927 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
928 "fpext source and destination must both be a vector or neither", &I);
929 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
934 void Verifier::visitUIToFPInst(UIToFPInst &I) {
935 // Get the source and destination types
936 Type *SrcTy = I.getOperand(0)->getType();
937 Type *DestTy = I.getType();
939 bool SrcVec = SrcTy->isVectorTy();
940 bool DstVec = DestTy->isVectorTy();
942 Assert1(SrcVec == DstVec,
943 "UIToFP source and dest must both be vector or scalar", &I);
944 Assert1(SrcTy->isIntOrIntVectorTy(),
945 "UIToFP source must be integer or integer vector", &I);
946 Assert1(DestTy->isFPOrFPVectorTy(),
947 "UIToFP result must be FP or FP vector", &I);
949 if (SrcVec && DstVec)
950 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
951 cast<VectorType>(DestTy)->getNumElements(),
952 "UIToFP source and dest vector length mismatch", &I);
957 void Verifier::visitSIToFPInst(SIToFPInst &I) {
958 // Get the source and destination types
959 Type *SrcTy = I.getOperand(0)->getType();
960 Type *DestTy = I.getType();
962 bool SrcVec = SrcTy->isVectorTy();
963 bool DstVec = DestTy->isVectorTy();
965 Assert1(SrcVec == DstVec,
966 "SIToFP source and dest must both be vector or scalar", &I);
967 Assert1(SrcTy->isIntOrIntVectorTy(),
968 "SIToFP source must be integer or integer vector", &I);
969 Assert1(DestTy->isFPOrFPVectorTy(),
970 "SIToFP result must be FP or FP vector", &I);
972 if (SrcVec && DstVec)
973 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
974 cast<VectorType>(DestTy)->getNumElements(),
975 "SIToFP source and dest vector length mismatch", &I);
980 void Verifier::visitFPToUIInst(FPToUIInst &I) {
981 // Get the source and destination types
982 Type *SrcTy = I.getOperand(0)->getType();
983 Type *DestTy = I.getType();
985 bool SrcVec = SrcTy->isVectorTy();
986 bool DstVec = DestTy->isVectorTy();
988 Assert1(SrcVec == DstVec,
989 "FPToUI source and dest must both be vector or scalar", &I);
990 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
992 Assert1(DestTy->isIntOrIntVectorTy(),
993 "FPToUI result must be integer or integer vector", &I);
995 if (SrcVec && DstVec)
996 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
997 cast<VectorType>(DestTy)->getNumElements(),
998 "FPToUI source and dest vector length mismatch", &I);
1000 visitInstruction(I);
1003 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1004 // Get the source and destination types
1005 Type *SrcTy = I.getOperand(0)->getType();
1006 Type *DestTy = I.getType();
1008 bool SrcVec = SrcTy->isVectorTy();
1009 bool DstVec = DestTy->isVectorTy();
1011 Assert1(SrcVec == DstVec,
1012 "FPToSI source and dest must both be vector or scalar", &I);
1013 Assert1(SrcTy->isFPOrFPVectorTy(),
1014 "FPToSI source must be FP or FP vector", &I);
1015 Assert1(DestTy->isIntOrIntVectorTy(),
1016 "FPToSI result must be integer or integer vector", &I);
1018 if (SrcVec && DstVec)
1019 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1020 cast<VectorType>(DestTy)->getNumElements(),
1021 "FPToSI source and dest vector length mismatch", &I);
1023 visitInstruction(I);
1026 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1027 // Get the source and destination types
1028 Type *SrcTy = I.getOperand(0)->getType();
1029 Type *DestTy = I.getType();
1031 Assert1(SrcTy->getScalarType()->isPointerTy(),
1032 "PtrToInt source must be pointer", &I);
1033 Assert1(DestTy->getScalarType()->isIntegerTy(),
1034 "PtrToInt result must be integral", &I);
1035 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1036 "PtrToInt type mismatch", &I);
1038 if (SrcTy->isVectorTy()) {
1039 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1040 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1041 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1042 "PtrToInt Vector width mismatch", &I);
1045 visitInstruction(I);
1048 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1049 // Get the source and destination types
1050 Type *SrcTy = I.getOperand(0)->getType();
1051 Type *DestTy = I.getType();
1053 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1054 "IntToPtr source must be an integral", &I);
1055 Assert1(DestTy->getScalarType()->isPointerTy(),
1056 "IntToPtr result must be a pointer",&I);
1057 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1058 "IntToPtr type mismatch", &I);
1059 if (SrcTy->isVectorTy()) {
1060 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1061 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1062 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1063 "IntToPtr Vector width mismatch", &I);
1065 visitInstruction(I);
1068 void Verifier::visitBitCastInst(BitCastInst &I) {
1069 // Get the source and destination types
1070 Type *SrcTy = I.getOperand(0)->getType();
1071 Type *DestTy = I.getType();
1073 // Get the size of the types in bits, we'll need this later
1074 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1075 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1077 // BitCast implies a no-op cast of type only. No bits change.
1078 // However, you can't cast pointers to anything but pointers.
1079 Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(),
1080 "Bitcast requires both operands to be pointer or neither", &I);
1081 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1083 // Disallow aggregates.
1084 Assert1(!SrcTy->isAggregateType(),
1085 "Bitcast operand must not be aggregate", &I);
1086 Assert1(!DestTy->isAggregateType(),
1087 "Bitcast type must not be aggregate", &I);
1089 visitInstruction(I);
1092 /// visitPHINode - Ensure that a PHI node is well formed.
1094 void Verifier::visitPHINode(PHINode &PN) {
1095 // Ensure that the PHI nodes are all grouped together at the top of the block.
1096 // This can be tested by checking whether the instruction before this is
1097 // either nonexistent (because this is begin()) or is a PHI node. If not,
1098 // then there is some other instruction before a PHI.
1099 Assert2(&PN == &PN.getParent()->front() ||
1100 isa<PHINode>(--BasicBlock::iterator(&PN)),
1101 "PHI nodes not grouped at top of basic block!",
1102 &PN, PN.getParent());
1104 // Check that all of the values of the PHI node have the same type as the
1105 // result, and that the incoming blocks are really basic blocks.
1106 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1107 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1108 "PHI node operands are not the same type as the result!", &PN);
1111 // All other PHI node constraints are checked in the visitBasicBlock method.
1113 visitInstruction(PN);
1116 void Verifier::VerifyCallSite(CallSite CS) {
1117 Instruction *I = CS.getInstruction();
1119 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1120 "Called function must be a pointer!", I);
1121 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1123 Assert1(FPTy->getElementType()->isFunctionTy(),
1124 "Called function is not pointer to function type!", I);
1125 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1127 // Verify that the correct number of arguments are being passed
1128 if (FTy->isVarArg())
1129 Assert1(CS.arg_size() >= FTy->getNumParams(),
1130 "Called function requires more parameters than were provided!",I);
1132 Assert1(CS.arg_size() == FTy->getNumParams(),
1133 "Incorrect number of arguments passed to called function!", I);
1135 // Verify that all arguments to the call match the function type.
1136 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1137 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1138 "Call parameter type does not match function signature!",
1139 CS.getArgument(i), FTy->getParamType(i), I);
1141 const AttrListPtr &Attrs = CS.getAttributes();
1143 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1144 "Attributes after last parameter!", I);
1146 // Verify call attributes.
1147 VerifyFunctionAttrs(FTy, Attrs, I);
1149 if (FTy->isVarArg())
1150 // Check attributes on the varargs part.
1151 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1152 Attributes Attr = Attrs.getParamAttributes(Idx);
1154 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1156 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1157 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1158 " cannot be used for vararg call arguments!", I);
1161 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1162 if (CS.getCalledFunction() == 0 ||
1163 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1164 for (FunctionType::param_iterator PI = FTy->param_begin(),
1165 PE = FTy->param_end(); PI != PE; ++PI)
1166 Assert1(!(*PI)->isMetadataTy(),
1167 "Function has metadata parameter but isn't an intrinsic", I);
1170 visitInstruction(*I);
1173 void Verifier::visitCallInst(CallInst &CI) {
1174 VerifyCallSite(&CI);
1176 if (Function *F = CI.getCalledFunction())
1177 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1178 visitIntrinsicFunctionCall(ID, CI);
1181 void Verifier::visitInvokeInst(InvokeInst &II) {
1182 VerifyCallSite(&II);
1184 // Verify that there is a landingpad instruction as the first non-PHI
1185 // instruction of the 'unwind' destination.
1186 Assert1(II.getUnwindDest()->isLandingPad(),
1187 "The unwind destination does not have a landingpad instruction!",&II);
1189 visitTerminatorInst(II);
1192 /// visitBinaryOperator - Check that both arguments to the binary operator are
1193 /// of the same type!
1195 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1196 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1197 "Both operands to a binary operator are not of the same type!", &B);
1199 switch (B.getOpcode()) {
1200 // Check that integer arithmetic operators are only used with
1201 // integral operands.
1202 case Instruction::Add:
1203 case Instruction::Sub:
1204 case Instruction::Mul:
1205 case Instruction::SDiv:
1206 case Instruction::UDiv:
1207 case Instruction::SRem:
1208 case Instruction::URem:
1209 Assert1(B.getType()->isIntOrIntVectorTy(),
1210 "Integer arithmetic operators only work with integral types!", &B);
1211 Assert1(B.getType() == B.getOperand(0)->getType(),
1212 "Integer arithmetic operators must have same type "
1213 "for operands and result!", &B);
1215 // Check that floating-point arithmetic operators are only used with
1216 // floating-point operands.
1217 case Instruction::FAdd:
1218 case Instruction::FSub:
1219 case Instruction::FMul:
1220 case Instruction::FDiv:
1221 case Instruction::FRem:
1222 Assert1(B.getType()->isFPOrFPVectorTy(),
1223 "Floating-point arithmetic operators only work with "
1224 "floating-point types!", &B);
1225 Assert1(B.getType() == B.getOperand(0)->getType(),
1226 "Floating-point arithmetic operators must have same type "
1227 "for operands and result!", &B);
1229 // Check that logical operators are only used with integral operands.
1230 case Instruction::And:
1231 case Instruction::Or:
1232 case Instruction::Xor:
1233 Assert1(B.getType()->isIntOrIntVectorTy(),
1234 "Logical operators only work with integral types!", &B);
1235 Assert1(B.getType() == B.getOperand(0)->getType(),
1236 "Logical operators must have same type for operands and result!",
1239 case Instruction::Shl:
1240 case Instruction::LShr:
1241 case Instruction::AShr:
1242 Assert1(B.getType()->isIntOrIntVectorTy(),
1243 "Shifts only work with integral types!", &B);
1244 Assert1(B.getType() == B.getOperand(0)->getType(),
1245 "Shift return type must be same as operands!", &B);
1248 llvm_unreachable("Unknown BinaryOperator opcode!");
1251 visitInstruction(B);
1254 void Verifier::visitICmpInst(ICmpInst &IC) {
1255 // Check that the operands are the same type
1256 Type *Op0Ty = IC.getOperand(0)->getType();
1257 Type *Op1Ty = IC.getOperand(1)->getType();
1258 Assert1(Op0Ty == Op1Ty,
1259 "Both operands to ICmp instruction are not of the same type!", &IC);
1260 // Check that the operands are the right type
1261 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1262 "Invalid operand types for ICmp instruction", &IC);
1263 // Check that the predicate is valid.
1264 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1265 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1266 "Invalid predicate in ICmp instruction!", &IC);
1268 visitInstruction(IC);
1271 void Verifier::visitFCmpInst(FCmpInst &FC) {
1272 // Check that the operands are the same type
1273 Type *Op0Ty = FC.getOperand(0)->getType();
1274 Type *Op1Ty = FC.getOperand(1)->getType();
1275 Assert1(Op0Ty == Op1Ty,
1276 "Both operands to FCmp instruction are not of the same type!", &FC);
1277 // Check that the operands are the right type
1278 Assert1(Op0Ty->isFPOrFPVectorTy(),
1279 "Invalid operand types for FCmp instruction", &FC);
1280 // Check that the predicate is valid.
1281 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1282 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1283 "Invalid predicate in FCmp instruction!", &FC);
1285 visitInstruction(FC);
1288 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1289 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1291 "Invalid extractelement operands!", &EI);
1292 visitInstruction(EI);
1295 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1296 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1299 "Invalid insertelement operands!", &IE);
1300 visitInstruction(IE);
1303 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1304 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1306 "Invalid shufflevector operands!", &SV);
1307 visitInstruction(SV);
1310 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1311 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1313 Assert1(isa<PointerType>(TargetTy),
1314 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1315 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1316 "GEP into unsized type!", &GEP);
1318 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1320 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1321 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1323 if (GEP.getPointerOperandType()->isPointerTy()) {
1324 // Validate GEPs with scalar indices.
1325 Assert2(GEP.getType()->isPointerTy() &&
1326 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1327 "GEP is not of right type for indices!", &GEP, ElTy);
1329 // Validate GEPs with a vector index.
1330 Assert1(Idxs.size() == 1, "Invalid number of indices!", &GEP);
1331 Value *Index = Idxs[0];
1332 Type *IndexTy = Index->getType();
1333 Assert1(IndexTy->isVectorTy(),
1334 "Vector GEP must have vector indices!", &GEP);
1335 Assert1(GEP.getType()->isVectorTy(),
1336 "Vector GEP must return a vector value", &GEP);
1337 Type *ElemPtr = cast<VectorType>(GEP.getType())->getElementType();
1338 Assert1(ElemPtr->isPointerTy(),
1339 "Vector GEP pointer operand is not a pointer!", &GEP);
1340 unsigned IndexWidth = cast<VectorType>(IndexTy)->getNumElements();
1341 unsigned GepWidth = cast<VectorType>(GEP.getType())->getNumElements();
1342 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1343 Assert1(ElTy == cast<PointerType>(ElemPtr)->getElementType(),
1344 "Vector GEP type does not match pointer type!", &GEP);
1346 visitInstruction(GEP);
1349 void Verifier::visitLoadInst(LoadInst &LI) {
1350 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1351 Assert1(PTy, "Load operand must be a pointer.", &LI);
1352 Type *ElTy = PTy->getElementType();
1353 Assert2(ElTy == LI.getType(),
1354 "Load result type does not match pointer operand type!", &LI, ElTy);
1355 if (LI.isAtomic()) {
1356 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1357 "Load cannot have Release ordering", &LI);
1358 Assert1(LI.getAlignment() != 0,
1359 "Atomic load must specify explicit alignment", &LI);
1361 Assert1(LI.getSynchScope() == CrossThread,
1362 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1365 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1366 unsigned NumOperands = Range->getNumOperands();
1367 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1368 unsigned NumRanges = NumOperands / 2;
1369 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1370 for (unsigned i = 0; i < NumRanges; ++i) {
1371 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1372 Assert1(Low, "The lower limit must be an integer!", Low);
1373 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1374 Assert1(High, "The upper limit must be an integer!", High);
1375 Assert1(High->getType() == Low->getType() &&
1376 High->getType() == ElTy, "Range types must match load type!",
1378 Assert1(High->getValue() != Low->getValue(), "Range must not be empty!",
1383 visitInstruction(LI);
1386 void Verifier::visitStoreInst(StoreInst &SI) {
1387 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1388 Assert1(PTy, "Store operand must be a pointer.", &SI);
1389 Type *ElTy = PTy->getElementType();
1390 Assert2(ElTy == SI.getOperand(0)->getType(),
1391 "Stored value type does not match pointer operand type!",
1393 if (SI.isAtomic()) {
1394 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1395 "Store cannot have Acquire ordering", &SI);
1396 Assert1(SI.getAlignment() != 0,
1397 "Atomic store must specify explicit alignment", &SI);
1399 Assert1(SI.getSynchScope() == CrossThread,
1400 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1402 visitInstruction(SI);
1405 void Verifier::visitAllocaInst(AllocaInst &AI) {
1406 PointerType *PTy = AI.getType();
1407 Assert1(PTy->getAddressSpace() == 0,
1408 "Allocation instruction pointer not in the generic address space!",
1410 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1412 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1413 "Alloca array size must have integer type", &AI);
1414 visitInstruction(AI);
1417 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1418 Assert1(CXI.getOrdering() != NotAtomic,
1419 "cmpxchg instructions must be atomic.", &CXI);
1420 Assert1(CXI.getOrdering() != Unordered,
1421 "cmpxchg instructions cannot be unordered.", &CXI);
1422 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1423 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1424 Type *ElTy = PTy->getElementType();
1425 Assert2(ElTy == CXI.getOperand(1)->getType(),
1426 "Expected value type does not match pointer operand type!",
1428 Assert2(ElTy == CXI.getOperand(2)->getType(),
1429 "Stored value type does not match pointer operand type!",
1431 visitInstruction(CXI);
1434 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1435 Assert1(RMWI.getOrdering() != NotAtomic,
1436 "atomicrmw instructions must be atomic.", &RMWI);
1437 Assert1(RMWI.getOrdering() != Unordered,
1438 "atomicrmw instructions cannot be unordered.", &RMWI);
1439 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1440 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1441 Type *ElTy = PTy->getElementType();
1442 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1443 "Argument value type does not match pointer operand type!",
1445 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1446 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1447 "Invalid binary operation!", &RMWI);
1448 visitInstruction(RMWI);
1451 void Verifier::visitFenceInst(FenceInst &FI) {
1452 const AtomicOrdering Ordering = FI.getOrdering();
1453 Assert1(Ordering == Acquire || Ordering == Release ||
1454 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1455 "fence instructions may only have "
1456 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1457 visitInstruction(FI);
1460 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1461 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1462 EVI.getIndices()) ==
1464 "Invalid ExtractValueInst operands!", &EVI);
1466 visitInstruction(EVI);
1469 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1470 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1471 IVI.getIndices()) ==
1472 IVI.getOperand(1)->getType(),
1473 "Invalid InsertValueInst operands!", &IVI);
1475 visitInstruction(IVI);
1478 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1479 BasicBlock *BB = LPI.getParent();
1481 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1483 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1484 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1486 // The landingpad instruction defines its parent as a landing pad block. The
1487 // landing pad block may be branched to only by the unwind edge of an invoke.
1488 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1489 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1490 Assert1(II && II->getUnwindDest() == BB,
1491 "Block containing LandingPadInst must be jumped to "
1492 "only by the unwind edge of an invoke.", &LPI);
1495 // The landingpad instruction must be the first non-PHI instruction in the
1497 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1498 "LandingPadInst not the first non-PHI instruction in the block.",
1501 // The personality functions for all landingpad instructions within the same
1502 // function should match.
1504 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1505 "Personality function doesn't match others in function", &LPI);
1506 PersonalityFn = LPI.getPersonalityFn();
1508 // All operands must be constants.
1509 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1511 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1512 Value *Clause = LPI.getClause(i);
1513 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1514 if (LPI.isCatch(i)) {
1515 Assert1(isa<PointerType>(Clause->getType()),
1516 "Catch operand does not have pointer type!", &LPI);
1518 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1519 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1520 "Filter operand is not an array of constants!", &LPI);
1524 visitInstruction(LPI);
1527 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1528 Instruction *Op = cast<Instruction>(I.getOperand(i));
1529 BasicBlock *BB = I.getParent();
1530 BasicBlock *OpBlock = Op->getParent();
1531 PHINode *PN = dyn_cast<PHINode>(&I);
1533 // DT can handle non phi instructions for us.
1535 // Definition must dominate use unless use is unreachable!
1536 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB) ||
1537 DT->dominates(Op, &I),
1538 "Instruction does not dominate all uses!", Op, &I);
1542 // Check that a definition dominates all of its uses.
1543 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1544 // Invoke results are only usable in the normal destination, not in the
1545 // exceptional destination.
1546 BasicBlock *NormalDest = II->getNormalDest();
1549 // PHI nodes differ from other nodes because they actually "use" the
1550 // value in the predecessor basic blocks they correspond to.
1551 BasicBlock *UseBlock = BB;
1552 unsigned j = PHINode::getIncomingValueNumForOperand(i);
1553 UseBlock = PN->getIncomingBlock(j);
1554 Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1557 if (UseBlock == OpBlock) {
1558 // Special case of a phi node in the normal destination or the unwind
1560 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1561 "Invoke result not available in the unwind destination!",
1564 Assert2(DT->dominates(II, UseBlock) ||
1565 !DT->isReachableFromEntry(UseBlock),
1566 "Invoke result does not dominate all uses!", Op, &I);
1570 // PHI nodes are more difficult than other nodes because they actually
1571 // "use" the value in the predecessor basic blocks they correspond to.
1572 unsigned j = PHINode::getIncomingValueNumForOperand(i);
1573 BasicBlock *PredBB = PN->getIncomingBlock(j);
1574 Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1575 !DT->isReachableFromEntry(PredBB)),
1576 "Instruction does not dominate all uses!", Op, &I);
1579 /// verifyInstruction - Verify that an instruction is well formed.
1581 void Verifier::visitInstruction(Instruction &I) {
1582 BasicBlock *BB = I.getParent();
1583 Assert1(BB, "Instruction not embedded in basic block!", &I);
1585 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1586 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1588 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1589 "Only PHI nodes may reference their own value!", &I);
1592 // Check that void typed values don't have names
1593 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1594 "Instruction has a name, but provides a void value!", &I);
1596 // Check that the return value of the instruction is either void or a legal
1598 Assert1(I.getType()->isVoidTy() ||
1599 I.getType()->isFirstClassType(),
1600 "Instruction returns a non-scalar type!", &I);
1602 // Check that the instruction doesn't produce metadata. Calls are already
1603 // checked against the callee type.
1604 Assert1(!I.getType()->isMetadataTy() ||
1605 isa<CallInst>(I) || isa<InvokeInst>(I),
1606 "Invalid use of metadata!", &I);
1608 // Check that all uses of the instruction, if they are instructions
1609 // themselves, actually have parent basic blocks. If the use is not an
1610 // instruction, it is an error!
1611 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1613 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1614 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1615 " embedded in a basic block!", &I, Used);
1617 CheckFailed("Use of instruction is not an instruction!", *UI);
1622 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1623 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1625 // Check to make sure that only first-class-values are operands to
1627 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1628 Assert1(0, "Instruction operands must be first-class values!", &I);
1631 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1632 // Check to make sure that the "address of" an intrinsic function is never
1634 Assert1(!F->isIntrinsic() || (i + 1 == e && isa<CallInst>(I)),
1635 "Cannot take the address of an intrinsic!", &I);
1636 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1638 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1639 Assert1(OpBB->getParent() == BB->getParent(),
1640 "Referring to a basic block in another function!", &I);
1641 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1642 Assert1(OpArg->getParent() == BB->getParent(),
1643 "Referring to an argument in another function!", &I);
1644 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1645 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1647 } else if (isa<Instruction>(I.getOperand(i))) {
1648 verifyDominatesUse(I, i);
1649 } else if (isa<InlineAsm>(I.getOperand(i))) {
1650 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1651 (i + 3 == e && isa<InvokeInst>(I)),
1652 "Cannot take the address of an inline asm!", &I);
1656 MDNode *MD = I.getMetadata(LLVMContext::MD_range);
1657 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
1659 InstsInThisBlock.insert(&I);
1662 // Flags used by TableGen to mark intrinsic parameters with the
1663 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1664 static const unsigned ExtendedElementVectorType = 0x40000000;
1665 static const unsigned TruncatedElementVectorType = 0x20000000;
1667 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1669 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1670 Function *IF = CI.getCalledFunction();
1671 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1674 #define GET_INTRINSIC_VERIFIER
1675 #include "llvm/Intrinsics.gen"
1676 #undef GET_INTRINSIC_VERIFIER
1678 // If the intrinsic takes MDNode arguments, verify that they are either global
1679 // or are local to *this* function.
1680 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1681 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1682 visitMDNode(*MD, CI.getParent()->getParent());
1687 case Intrinsic::ctlz: // llvm.ctlz
1688 case Intrinsic::cttz: // llvm.cttz
1689 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1690 "is_zero_undef argument of bit counting intrinsics must be a "
1691 "constant int", &CI);
1693 case Intrinsic::dbg_declare: { // llvm.dbg.declare
1694 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1695 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1696 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1697 Assert1(MD->getNumOperands() == 1,
1698 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1700 case Intrinsic::memcpy:
1701 case Intrinsic::memmove:
1702 case Intrinsic::memset:
1703 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1704 "alignment argument of memory intrinsics must be a constant int",
1706 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
1707 "isvolatile argument of memory intrinsics must be a constant int",
1710 case Intrinsic::gcroot:
1711 case Intrinsic::gcwrite:
1712 case Intrinsic::gcread:
1713 if (ID == Intrinsic::gcroot) {
1715 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1716 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1717 Assert1(isa<Constant>(CI.getArgOperand(1)),
1718 "llvm.gcroot parameter #2 must be a constant.", &CI);
1719 if (!AI->getType()->getElementType()->isPointerTy()) {
1720 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1721 "llvm.gcroot parameter #1 must either be a pointer alloca, "
1722 "or argument #2 must be a non-null constant.", &CI);
1726 Assert1(CI.getParent()->getParent()->hasGC(),
1727 "Enclosing function does not use GC.", &CI);
1729 case Intrinsic::init_trampoline:
1730 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1731 "llvm.init_trampoline parameter #2 must resolve to a function.",
1734 case Intrinsic::prefetch:
1735 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1736 isa<ConstantInt>(CI.getArgOperand(2)) &&
1737 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1738 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1739 "invalid arguments to llvm.prefetch",
1742 case Intrinsic::stackprotector:
1743 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1744 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1747 case Intrinsic::lifetime_start:
1748 case Intrinsic::lifetime_end:
1749 case Intrinsic::invariant_start:
1750 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1751 "size argument of memory use markers must be a constant integer",
1754 case Intrinsic::invariant_end:
1755 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1756 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1761 /// Produce a string to identify an intrinsic parameter or return value.
1762 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1763 /// parameters beginning with NumRets.
1765 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1766 if (ArgNo >= NumRets)
1767 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1769 return "Intrinsic result type";
1770 return "Intrinsic result type #" + utostr(ArgNo);
1773 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
1774 int VT, unsigned ArgNo, std::string &Suffix) {
1775 FunctionType *FTy = F->getFunctionType();
1777 unsigned NumElts = 0;
1779 VectorType *VTy = dyn_cast<VectorType>(Ty);
1781 EltTy = VTy->getElementType();
1782 NumElts = VTy->getNumElements();
1785 Type *RetTy = FTy->getReturnType();
1786 StructType *ST = dyn_cast<StructType>(RetTy);
1787 unsigned NumRetVals;
1788 if (RetTy->isVoidTy())
1791 NumRetVals = ST->getNumElements();
1798 // Check flags that indicate a type that is an integral vector type with
1799 // elements that are larger or smaller than the elements of the matched
1801 if ((Match & (ExtendedElementVectorType |
1802 TruncatedElementVectorType)) != 0) {
1803 IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1804 if (!VTy || !IEltTy) {
1805 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1806 "an integral vector type.", F);
1809 // Adjust the current Ty (in the opposite direction) rather than
1810 // the type being matched against.
1811 if ((Match & ExtendedElementVectorType) != 0) {
1812 if ((IEltTy->getBitWidth() & 1) != 0) {
1813 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector "
1814 "element bit-width is odd.", F);
1817 Ty = VectorType::getTruncatedElementVectorType(VTy);
1819 Ty = VectorType::getExtendedElementVectorType(VTy);
1820 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1823 if (Match <= static_cast<int>(NumRetVals - 1)) {
1825 RetTy = ST->getElementType(Match);
1828 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1829 "match return type.", F);
1833 if (Ty != FTy->getParamType(Match - NumRetVals)) {
1834 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1835 "match parameter %" + utostr(Match - NumRetVals) + ".", F);
1839 } else if (VT == MVT::iAny) {
1840 if (!EltTy->isIntegerTy()) {
1841 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1842 "an integer type.", F);
1846 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1850 Suffix += "v" + utostr(NumElts);
1852 Suffix += "i" + utostr(GotBits);
1854 // Check some constraints on various intrinsics.
1856 default: break; // Not everything needs to be checked.
1857 case Intrinsic::bswap:
1858 if (GotBits < 16 || GotBits % 16 != 0) {
1859 CheckFailed("Intrinsic requires even byte width argument", F);
1864 } else if (VT == MVT::fAny) {
1865 if (!EltTy->isFloatingPointTy()) {
1866 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1867 "a floating-point type.", F);
1874 Suffix += "v" + utostr(NumElts);
1876 Suffix += EVT::getEVT(EltTy).getEVTString();
1877 } else if (VT == MVT::vAny) {
1879 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.",
1883 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1884 } else if (VT == MVT::iPTR) {
1885 if (!Ty->isPointerTy()) {
1886 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1887 "pointer and a pointer is required.", F);
1890 } else if (VT == MVT::iPTRAny) {
1891 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1892 // and iPTR. In the verifier, we can not distinguish which case we have so
1893 // allow either case to be legal.
1894 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1895 EVT PointeeVT = EVT::getEVT(PTyp->getElementType(), true);
1896 if (PointeeVT == MVT::Other) {
1897 CheckFailed("Intrinsic has pointer to complex type.");
1900 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1901 PointeeVT.getEVTString();
1903 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1904 "pointer and a pointer is required.", F);
1907 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1908 EVT VVT = EVT((MVT::SimpleValueType)VT);
1910 // If this is a vector argument, verify the number and type of elements.
1911 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1912 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1916 if (VVT.getVectorNumElements() != NumElts) {
1917 CheckFailed("Intrinsic prototype has incorrect number of "
1918 "vector elements!", F);
1921 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1923 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F);
1925 } else if (EltTy != Ty) {
1926 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector "
1927 "and a scalar is required.", F);
1934 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1935 /// Intrinsics.gen. This implements a little state machine that verifies the
1936 /// prototype of intrinsics.
1937 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1938 unsigned NumRetVals,
1939 unsigned NumParams, ...) {
1941 va_start(VA, NumParams);
1942 FunctionType *FTy = F->getFunctionType();
1944 // For overloaded intrinsics, the Suffix of the function name must match the
1945 // types of the arguments. This variable keeps track of the expected
1946 // suffix, to be checked at the end.
1949 if (FTy->getNumParams() + FTy->isVarArg() != NumParams) {
1950 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1954 Type *Ty = FTy->getReturnType();
1955 StructType *ST = dyn_cast<StructType>(Ty);
1957 if (NumRetVals == 0 && !Ty->isVoidTy()) {
1958 CheckFailed("Intrinsic should return void", F);
1962 // Verify the return types.
1963 if (ST && ST->getNumElements() != NumRetVals) {
1964 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1968 for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) {
1969 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1971 if (ST) Ty = ST->getElementType(ArgNo);
1972 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1976 // Verify the parameter types.
1977 for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) {
1978 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1980 if (VT == MVT::isVoid && ArgNo > 0) {
1981 if (!FTy->isVarArg())
1982 CheckFailed("Intrinsic prototype has no '...'!", F);
1986 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT,
1987 ArgNo + NumRetVals, Suffix))
1993 // For intrinsics without pointer arguments, if we computed a Suffix then the
1994 // intrinsic is overloaded and we need to make sure that the name of the
1995 // function is correct. We add the suffix to the name of the intrinsic and
1996 // compare against the given function name. If they are not the same, the
1997 // function name is invalid. This ensures that overloading of intrinsics
1998 // uses a sane and consistent naming convention. Note that intrinsics with
1999 // pointer argument may or may not be overloaded so we will check assuming it
2000 // has a suffix and not.
2001 if (!Suffix.empty()) {
2002 std::string Name(Intrinsic::getName(ID));
2003 if (Name + Suffix != F->getName()) {
2004 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
2005 F->getName().substr(Name.length()) + "'. It should be '" +
2010 // Check parameter attributes.
2011 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
2012 "Intrinsic has wrong parameter attributes!", F);
2016 //===----------------------------------------------------------------------===//
2017 // Implement the public interfaces to this file...
2018 //===----------------------------------------------------------------------===//
2020 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2021 return new Verifier(action);
2025 /// verifyFunction - Check a function for errors, printing messages on stderr.
2026 /// Return true if the function is corrupt.
2028 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2029 Function &F = const_cast<Function&>(f);
2030 assert(!F.isDeclaration() && "Cannot verify external functions");
2032 FunctionPassManager FPM(F.getParent());
2033 Verifier *V = new Verifier(action);
2039 /// verifyModule - Check a module for errors, printing messages on stderr.
2040 /// Return true if the module is corrupt.
2042 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2043 std::string *ErrorInfo) {
2045 Verifier *V = new Verifier(action);
2047 PM.run(const_cast<Module&>(M));
2049 if (ErrorInfo && V->Broken)
2050 *ErrorInfo = V->MessagesStr.str();