remove a dead bool.
[llvm/avr.git] / lib / VMCore / Verifier.cpp
blob140e6bd8b15a78c1ffeefa091b28afc4247bc77a
1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/ModuleProvider.h"
51 #include "llvm/Pass.h"
52 #include "llvm/PassManager.h"
53 #include "llvm/TypeSymbolTable.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/Assembly/Writer.h"
56 #include "llvm/CodeGen/ValueTypes.h"
57 #include "llvm/Support/CallSite.h"
58 #include "llvm/Support/CFG.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/Compiler.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include <algorithm>
69 #include <cstdarg>
70 using namespace llvm;
72 namespace { // Anonymous namespace for class
73 struct VISIBILITY_HIDDEN PreVerifier : public FunctionPass {
74 static char ID; // Pass ID, replacement for typeid
76 PreVerifier() : FunctionPass(&ID) { }
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
79 AU.setPreservesAll();
82 // Check that the prerequisites for successful DominatorTree construction
83 // are satisfied.
84 bool runOnFunction(Function &F) {
85 bool Broken = false;
87 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
88 if (I->empty() || !I->back().isTerminator()) {
89 errs() << "Basic Block does not have terminator!\n";
90 WriteAsOperand(errs(), I, true);
91 errs() << "\n";
92 Broken = true;
96 if (Broken)
97 llvm_report_error("Broken module, no Basic Block terminator!");
99 return false;
104 char PreVerifier::ID = 0;
105 static RegisterPass<PreVerifier>
106 PreVer("preverify", "Preliminary module verification");
107 static const PassInfo *const PreVerifyID = &PreVer;
109 namespace {
110 class TypeSet : public AbstractTypeUser {
111 public:
112 TypeSet() {}
114 /// Insert a type into the set of types.
115 bool insert(const Type *Ty) {
116 if (!Types.insert(Ty))
117 return false;
118 if (Ty->isAbstract())
119 Ty->addAbstractTypeUser(this);
120 return true;
123 // Remove ourselves as abstract type listeners for any types that remain
124 // abstract when the TypeSet is destroyed.
125 ~TypeSet() {
126 for (SmallSetVector<const Type *, 16>::iterator I = Types.begin(),
127 E = Types.end(); I != E; ++I) {
128 const Type *Ty = *I;
129 if (Ty->isAbstract())
130 Ty->removeAbstractTypeUser(this);
134 // Abstract type user interface.
136 /// Remove types from the set when refined. Do not insert the type it was
137 /// refined to because that type hasn't been verified yet.
138 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
139 Types.remove(OldTy);
140 OldTy->removeAbstractTypeUser(this);
143 /// Stop listening for changes to a type which is no longer abstract.
144 void typeBecameConcrete(const DerivedType *AbsTy) {
145 AbsTy->removeAbstractTypeUser(this);
148 void dump() const {}
150 private:
151 SmallSetVector<const Type *, 16> Types;
153 // Disallow copying.
154 TypeSet(const TypeSet &);
155 TypeSet &operator=(const TypeSet &);
158 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
159 static char ID; // Pass ID, replacement for typeid
160 bool Broken; // Is this module found to be broken?
161 bool RealPass; // Are we not being run by a PassManager?
162 VerifierFailureAction action;
163 // What to do if verification fails.
164 Module *Mod; // Module we are verifying right now
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.
177 TypeSet Types;
179 Verifier()
180 : FunctionPass(&ID),
181 Broken(false), RealPass(true), action(AbortProcessAction),
182 DT(0), MessagesStr(Messages) {}
183 explicit Verifier(VerifierFailureAction ctn)
184 : FunctionPass(&ID),
185 Broken(false), RealPass(true), action(ctn), DT(0),
186 MessagesStr(Messages) {}
187 explicit Verifier(bool AB)
188 : FunctionPass(&ID),
189 Broken(false), RealPass(true),
190 action( AB ? AbortProcessAction : PrintMessageAction), DT(0),
191 MessagesStr(Messages) {}
192 explicit Verifier(DominatorTree &dt)
193 : FunctionPass(&ID),
194 Broken(false), RealPass(false), action(PrintMessageAction),
195 DT(&dt), MessagesStr(Messages) {}
198 bool doInitialization(Module &M) {
199 Mod = &M;
200 verifyTypeSymbolTable(M.getTypeSymbolTable());
202 // If this is a real pass, in a pass manager, we must abort before
203 // returning back to the pass manager, or else the pass manager may try to
204 // run other passes on the broken module.
205 if (RealPass)
206 return abortIfBroken();
207 return false;
210 bool runOnFunction(Function &F) {
211 // Get dominator information if we are being run by PassManager
212 if (RealPass) DT = &getAnalysis<DominatorTree>();
214 Mod = F.getParent();
216 visit(F);
217 InstsInThisBlock.clear();
219 // If this is a real pass, in a pass manager, we must abort before
220 // returning back to the pass manager, or else the pass manager may try to
221 // run other passes on the broken module.
222 if (RealPass)
223 return abortIfBroken();
225 return false;
228 bool doFinalization(Module &M) {
229 // Scan through, checking all of the external function's linkage now...
230 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
231 visitGlobalValue(*I);
233 // Check to make sure function prototypes are okay.
234 if (I->isDeclaration()) visitFunction(*I);
237 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
238 I != E; ++I)
239 visitGlobalVariable(*I);
241 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
242 I != E; ++I)
243 visitGlobalAlias(*I);
245 // If the module is broken, abort at this time.
246 return abortIfBroken();
249 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
250 AU.setPreservesAll();
251 AU.addRequiredID(PreVerifyID);
252 if (RealPass)
253 AU.addRequired<DominatorTree>();
256 /// abortIfBroken - If the module is broken and we are supposed to abort on
257 /// this condition, do so.
259 bool abortIfBroken() {
260 if (!Broken) return false;
261 MessagesStr << "Broken module found, ";
262 switch (action) {
263 default: llvm_unreachable("Unknown action");
264 case AbortProcessAction:
265 MessagesStr << "compilation aborted!\n";
266 errs() << MessagesStr.str();
267 // Client should choose different reaction if abort is not desired
268 abort();
269 case PrintMessageAction:
270 MessagesStr << "verification continues.\n";
271 errs() << MessagesStr.str();
272 return false;
273 case ReturnStatusAction:
274 MessagesStr << "compilation terminated.\n";
275 return true;
280 // Verification methods...
281 void verifyTypeSymbolTable(TypeSymbolTable &ST);
282 void visitGlobalValue(GlobalValue &GV);
283 void visitGlobalVariable(GlobalVariable &GV);
284 void visitGlobalAlias(GlobalAlias &GA);
285 void visitFunction(Function &F);
286 void visitBasicBlock(BasicBlock &BB);
287 using InstVisitor<Verifier>::visit;
289 void visit(Instruction &I);
291 void visitTruncInst(TruncInst &I);
292 void visitZExtInst(ZExtInst &I);
293 void visitSExtInst(SExtInst &I);
294 void visitFPTruncInst(FPTruncInst &I);
295 void visitFPExtInst(FPExtInst &I);
296 void visitFPToUIInst(FPToUIInst &I);
297 void visitFPToSIInst(FPToSIInst &I);
298 void visitUIToFPInst(UIToFPInst &I);
299 void visitSIToFPInst(SIToFPInst &I);
300 void visitIntToPtrInst(IntToPtrInst &I);
301 void visitPtrToIntInst(PtrToIntInst &I);
302 void visitBitCastInst(BitCastInst &I);
303 void visitPHINode(PHINode &PN);
304 void visitBinaryOperator(BinaryOperator &B);
305 void visitICmpInst(ICmpInst &IC);
306 void visitFCmpInst(FCmpInst &FC);
307 void visitExtractElementInst(ExtractElementInst &EI);
308 void visitInsertElementInst(InsertElementInst &EI);
309 void visitShuffleVectorInst(ShuffleVectorInst &EI);
310 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
311 void visitCallInst(CallInst &CI);
312 void visitInvokeInst(InvokeInst &II);
313 void visitGetElementPtrInst(GetElementPtrInst &GEP);
314 void visitLoadInst(LoadInst &LI);
315 void visitStoreInst(StoreInst &SI);
316 void visitInstruction(Instruction &I);
317 void visitTerminatorInst(TerminatorInst &I);
318 void visitReturnInst(ReturnInst &RI);
319 void visitSwitchInst(SwitchInst &SI);
320 void visitSelectInst(SelectInst &SI);
321 void visitUserOp1(Instruction &I);
322 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
323 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
324 void visitAllocationInst(AllocationInst &AI);
325 void visitExtractValueInst(ExtractValueInst &EVI);
326 void visitInsertValueInst(InsertValueInst &IVI);
328 void VerifyCallSite(CallSite CS);
329 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
330 int VT, unsigned ArgNo, std::string &Suffix);
331 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
332 unsigned RetNum, unsigned ParamNum, ...);
333 void VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
334 bool isReturnValue, const Value *V);
335 void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
336 const Value *V);
337 void VerifyType(const Type *Ty);
339 void WriteValue(const Value *V) {
340 if (!V) return;
341 if (isa<Instruction>(V)) {
342 MessagesStr << *V;
343 } else {
344 WriteAsOperand(MessagesStr, V, true, Mod);
345 MessagesStr << "\n";
349 void WriteType(const Type *T) {
350 if (!T) return;
351 MessagesStr << ' ';
352 WriteTypeSymbolic(MessagesStr, T, Mod);
356 // CheckFailed - A check failed, so print out the condition and the message
357 // that failed. This provides a nice place to put a breakpoint if you want
358 // to see why something is not correct.
359 void CheckFailed(const Twine &Message,
360 const Value *V1 = 0, const Value *V2 = 0,
361 const Value *V3 = 0, const Value *V4 = 0) {
362 MessagesStr << Message.str() << "\n";
363 WriteValue(V1);
364 WriteValue(V2);
365 WriteValue(V3);
366 WriteValue(V4);
367 Broken = true;
370 void CheckFailed(const Twine &Message, const Value *V1,
371 const Type *T2, const Value *V3 = 0) {
372 MessagesStr << Message.str() << "\n";
373 WriteValue(V1);
374 WriteType(T2);
375 WriteValue(V3);
376 Broken = true;
379 void CheckFailed(const Twine &Message, const Type *T1,
380 const Type *T2 = 0, const Type *T3 = 0) {
381 MessagesStr << Message.str() << "\n";
382 WriteType(T1);
383 WriteType(T2);
384 WriteType(T3);
385 Broken = true;
388 } // End anonymous namespace
390 char Verifier::ID = 0;
391 static RegisterPass<Verifier> X("verify", "Module Verifier");
393 // Assert - We know that cond should be true, if not print an error message.
394 #define Assert(C, M) \
395 do { if (!(C)) { CheckFailed(M); return; } } while (0)
396 #define Assert1(C, M, V1) \
397 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
398 #define Assert2(C, M, V1, V2) \
399 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
400 #define Assert3(C, M, V1, V2, V3) \
401 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
402 #define Assert4(C, M, V1, V2, V3, V4) \
403 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
405 void Verifier::visit(Instruction &I) {
406 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
407 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
408 InstVisitor<Verifier>::visit(I);
412 void Verifier::visitGlobalValue(GlobalValue &GV) {
413 Assert1(!GV.isDeclaration() ||
414 GV.hasExternalLinkage() ||
415 GV.hasDLLImportLinkage() ||
416 GV.hasExternalWeakLinkage() ||
417 GV.hasGhostLinkage() ||
418 (isa<GlobalAlias>(GV) &&
419 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
420 "Global is external, but doesn't have external or dllimport or weak linkage!",
421 &GV);
423 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
424 "Global is marked as dllimport, but not external", &GV);
426 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
427 "Only global variables can have appending linkage!", &GV);
429 if (GV.hasAppendingLinkage()) {
430 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
431 Assert1(GVar && isa<ArrayType>(GVar->getType()->getElementType()),
432 "Only global arrays can have appending linkage!", GVar);
436 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
437 if (GV.hasInitializer()) {
438 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
439 "Global variable initializer type does not match global "
440 "variable type!", &GV);
442 // If the global has common linkage, it must have a zero initializer and
443 // cannot be constant.
444 if (GV.hasCommonLinkage()) {
445 Assert1(GV.getInitializer()->isNullValue(),
446 "'common' global must have a zero initializer!", &GV);
447 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
448 &GV);
451 // Verify that any metadata used in a global initializer points only to
452 // other globals.
453 if (MDNode *FirstNode = dyn_cast<MDNode>(GV.getInitializer())) {
454 SmallVector<const MDNode *, 4> NodesToAnalyze;
455 NodesToAnalyze.push_back(FirstNode);
456 while (!NodesToAnalyze.empty()) {
457 const MDNode *N = NodesToAnalyze.back();
458 NodesToAnalyze.pop_back();
460 for (MDNode::const_elem_iterator I = N->elem_begin(),
461 E = N->elem_end(); I != E; ++I)
462 if (const Value *V = *I) {
463 if (const MDNode *Next = dyn_cast<MDNode>(V))
464 NodesToAnalyze.push_back(Next);
465 else
466 Assert3(isa<Constant>(V),
467 "reference to instruction from global metadata node",
468 &GV, N, V);
472 } else {
473 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
474 GV.hasExternalWeakLinkage(),
475 "invalid linkage type for global declaration", &GV);
478 visitGlobalValue(GV);
481 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
482 Assert1(!GA.getName().empty(),
483 "Alias name cannot be empty!", &GA);
484 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
485 GA.hasWeakLinkage(),
486 "Alias should have external or external weak linkage!", &GA);
487 Assert1(GA.getAliasee(),
488 "Aliasee cannot be NULL!", &GA);
489 Assert1(GA.getType() == GA.getAliasee()->getType(),
490 "Alias and aliasee types should match!", &GA);
492 if (!isa<GlobalValue>(GA.getAliasee())) {
493 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
494 Assert1(CE &&
495 (CE->getOpcode() == Instruction::BitCast ||
496 CE->getOpcode() == Instruction::GetElementPtr) &&
497 isa<GlobalValue>(CE->getOperand(0)),
498 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
499 &GA);
502 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
503 Assert1(Aliasee,
504 "Aliasing chain should end with function or global variable", &GA);
506 visitGlobalValue(GA);
509 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
510 for (TypeSymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
511 VerifyType(I->second);
514 // VerifyParameterAttrs - Check the given attributes for an argument or return
515 // value of the specified type. The value V is printed in error messages.
516 void Verifier::VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
517 bool isReturnValue, const Value *V) {
518 if (Attrs == Attribute::None)
519 return;
521 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
522 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
523 " only applies to the function!", V);
525 if (isReturnValue) {
526 Attributes RetI = Attrs & Attribute::ParameterOnly;
527 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
528 " does not apply to return values!", V);
531 for (unsigned i = 0;
532 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
533 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
534 Assert1(!(MutI & (MutI - 1)), "Attributes " +
535 Attribute::getAsString(MutI) + " are incompatible!", V);
538 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
539 Assert1(!TypeI, "Wrong type for attribute " +
540 Attribute::getAsString(TypeI), V);
542 Attributes ByValI = Attrs & Attribute::ByVal;
543 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
544 Assert1(!ByValI || PTy->getElementType()->isSized(),
545 "Attribute " + Attribute::getAsString(ByValI) +
546 " does not support unsized types!", V);
547 } else {
548 Assert1(!ByValI,
549 "Attribute " + Attribute::getAsString(ByValI) +
550 " only applies to parameters with pointer type!", V);
554 // VerifyFunctionAttrs - Check parameter attributes against a function type.
555 // The value V is printed in error messages.
556 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
557 const AttrListPtr &Attrs,
558 const Value *V) {
559 if (Attrs.isEmpty())
560 return;
562 bool SawNest = false;
564 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
565 const AttributeWithIndex &Attr = Attrs.getSlot(i);
567 const Type *Ty;
568 if (Attr.Index == 0)
569 Ty = FT->getReturnType();
570 else if (Attr.Index-1 < FT->getNumParams())
571 Ty = FT->getParamType(Attr.Index-1);
572 else
573 break; // VarArgs attributes, verified elsewhere.
575 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
577 if (Attr.Attrs & Attribute::Nest) {
578 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
579 SawNest = true;
582 if (Attr.Attrs & Attribute::StructRet)
583 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
586 Attributes FAttrs = Attrs.getFnAttributes();
587 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
588 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
589 " does not apply to the function!", V);
591 for (unsigned i = 0;
592 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
593 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
594 Assert1(!(MutI & (MutI - 1)), "Attributes " +
595 Attribute::getAsString(MutI) + " are incompatible!", V);
599 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
600 if (Attrs.isEmpty())
601 return true;
603 unsigned LastSlot = Attrs.getNumSlots() - 1;
604 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
605 if (LastIndex <= Params
606 || (LastIndex == (unsigned)~0
607 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
608 return true;
610 return false;
613 // visitFunction - Verify that a function is ok.
615 void Verifier::visitFunction(Function &F) {
616 // Check function arguments.
617 const FunctionType *FT = F.getFunctionType();
618 unsigned NumArgs = F.arg_size();
620 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
621 Assert2(FT->getNumParams() == NumArgs,
622 "# formal arguments must match # of arguments for function type!",
623 &F, FT);
624 Assert1(F.getReturnType()->isFirstClassType() ||
625 F.getReturnType() == Type::getVoidTy(F.getContext()) ||
626 isa<StructType>(F.getReturnType()),
627 "Functions cannot return aggregate values!", &F);
629 Assert1(!F.hasStructRetAttr() ||
630 F.getReturnType() == Type::getVoidTy(F.getContext()),
631 "Invalid struct return type!", &F);
633 const AttrListPtr &Attrs = F.getAttributes();
635 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
636 "Attributes after last parameter!", &F);
638 // Check function attributes.
639 VerifyFunctionAttrs(FT, Attrs, &F);
641 // Check that this function meets the restrictions on this calling convention.
642 switch (F.getCallingConv()) {
643 default:
644 break;
645 case CallingConv::C:
646 break;
647 case CallingConv::Fast:
648 case CallingConv::Cold:
649 case CallingConv::X86_FastCall:
650 Assert1(!F.isVarArg(),
651 "Varargs functions must have C calling conventions!", &F);
652 break;
655 bool isLLVMdotName = F.getName().size() >= 5 &&
656 F.getName().substr(0, 5) == "llvm.";
657 if (!isLLVMdotName)
658 Assert1(F.getReturnType() != Type::getMetadataTy(F.getContext()),
659 "Function may not return metadata unless it's an intrinsic", &F);
661 // Check that the argument values match the function type for this function...
662 unsigned i = 0;
663 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
664 I != E; ++I, ++i) {
665 Assert2(I->getType() == FT->getParamType(i),
666 "Argument value does not match function argument type!",
667 I, FT->getParamType(i));
668 Assert1(I->getType()->isFirstClassType(),
669 "Function arguments must have first-class types!", I);
670 if (!isLLVMdotName)
671 Assert2(I->getType() != Type::getMetadataTy(F.getContext()),
672 "Function takes metadata but isn't an intrinsic", I, &F);
675 if (F.isDeclaration()) {
676 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
677 F.hasExternalWeakLinkage() || F.hasGhostLinkage(),
678 "invalid linkage type for function declaration", &F);
679 } else {
680 // Verify that this function (which has a body) is not named "llvm.*". It
681 // is not legal to define intrinsics.
682 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
684 // Check the entry node
685 BasicBlock *Entry = &F.getEntryBlock();
686 Assert1(pred_begin(Entry) == pred_end(Entry),
687 "Entry block to function must not have predecessors!", Entry);
690 // If this function is actually an intrinsic, verify that it is only used in
691 // direct call/invokes, never having its "address taken".
692 if (F.getIntrinsicID()) {
693 for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E;++UI){
694 User *U = cast<User>(UI);
695 if ((isa<CallInst>(U) || isa<InvokeInst>(U)) && UI.getOperandNo() == 0)
696 continue; // Direct calls/invokes are ok.
698 Assert1(0, "Invalid user of intrinsic instruction!", U);
703 // verifyBasicBlock - Verify that a basic block is well formed...
705 void Verifier::visitBasicBlock(BasicBlock &BB) {
706 InstsInThisBlock.clear();
708 // Ensure that basic blocks have terminators!
709 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
711 // Check constraints that this basic block imposes on all of the PHI nodes in
712 // it.
713 if (isa<PHINode>(BB.front())) {
714 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
715 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
716 std::sort(Preds.begin(), Preds.end());
717 PHINode *PN;
718 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
719 // Ensure that PHI nodes have at least one entry!
720 Assert1(PN->getNumIncomingValues() != 0,
721 "PHI nodes must have at least one entry. If the block is dead, "
722 "the PHI should be removed!", PN);
723 Assert1(PN->getNumIncomingValues() == Preds.size(),
724 "PHINode should have one entry for each predecessor of its "
725 "parent basic block!", PN);
727 // Get and sort all incoming values in the PHI node...
728 Values.clear();
729 Values.reserve(PN->getNumIncomingValues());
730 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
731 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
732 PN->getIncomingValue(i)));
733 std::sort(Values.begin(), Values.end());
735 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
736 // Check to make sure that if there is more than one entry for a
737 // particular basic block in this PHI node, that the incoming values are
738 // all identical.
740 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
741 Values[i].second == Values[i-1].second,
742 "PHI node has multiple entries for the same basic block with "
743 "different incoming values!", PN, Values[i].first,
744 Values[i].second, Values[i-1].second);
746 // Check to make sure that the predecessors and PHI node entries are
747 // matched up.
748 Assert3(Values[i].first == Preds[i],
749 "PHI node entries do not match predecessors!", PN,
750 Values[i].first, Preds[i]);
756 void Verifier::visitTerminatorInst(TerminatorInst &I) {
757 // Ensure that terminators only exist at the end of the basic block.
758 Assert1(&I == I.getParent()->getTerminator(),
759 "Terminator found in the middle of a basic block!", I.getParent());
760 visitInstruction(I);
763 void Verifier::visitReturnInst(ReturnInst &RI) {
764 Function *F = RI.getParent()->getParent();
765 unsigned N = RI.getNumOperands();
766 if (F->getReturnType() == Type::getVoidTy(RI.getContext()))
767 Assert2(N == 0,
768 "Found return instr that returns non-void in Function of void "
769 "return type!", &RI, F->getReturnType());
770 else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
771 // Exactly one return value and it matches the return type. Good.
772 } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
773 // The return type is a struct; check for multiple return values.
774 Assert2(STy->getNumElements() == N,
775 "Incorrect number of return values in ret instruction!",
776 &RI, F->getReturnType());
777 for (unsigned i = 0; i != N; ++i)
778 Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
779 "Function return type does not match operand "
780 "type of return inst!", &RI, F->getReturnType());
781 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
782 // The return type is an array; check for multiple return values.
783 Assert2(ATy->getNumElements() == N,
784 "Incorrect number of return values in ret instruction!",
785 &RI, F->getReturnType());
786 for (unsigned i = 0; i != N; ++i)
787 Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
788 "Function return type does not match operand "
789 "type of return inst!", &RI, F->getReturnType());
790 } else {
791 CheckFailed("Function return type does not match operand "
792 "type of return inst!", &RI, F->getReturnType());
795 // Check to make sure that the return value has necessary properties for
796 // terminators...
797 visitTerminatorInst(RI);
800 void Verifier::visitSwitchInst(SwitchInst &SI) {
801 // Check to make sure that all of the constants in the switch instruction
802 // have the same type as the switched-on value.
803 const Type *SwitchTy = SI.getCondition()->getType();
804 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
805 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
806 "Switch constants must all be same type as switch value!", &SI);
808 visitTerminatorInst(SI);
811 void Verifier::visitSelectInst(SelectInst &SI) {
812 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
813 SI.getOperand(2)),
814 "Invalid operands for select instruction!", &SI);
816 Assert1(SI.getTrueValue()->getType() == SI.getType(),
817 "Select values must have same type as select instruction!", &SI);
818 visitInstruction(SI);
821 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
822 /// a pass, if any exist, it's an error.
824 void Verifier::visitUserOp1(Instruction &I) {
825 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
828 void Verifier::visitTruncInst(TruncInst &I) {
829 // Get the source and destination types
830 const Type *SrcTy = I.getOperand(0)->getType();
831 const Type *DestTy = I.getType();
833 // Get the size of the types in bits, we'll need this later
834 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
835 unsigned DestBitSize = DestTy->getScalarSizeInBits();
837 Assert1(SrcTy->isIntOrIntVector(), "Trunc only operates on integer", &I);
838 Assert1(DestTy->isIntOrIntVector(), "Trunc only produces integer", &I);
839 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
840 "trunc source and destination must both be a vector or neither", &I);
841 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
843 visitInstruction(I);
846 void Verifier::visitZExtInst(ZExtInst &I) {
847 // Get the source and destination types
848 const Type *SrcTy = I.getOperand(0)->getType();
849 const Type *DestTy = I.getType();
851 // Get the size of the types in bits, we'll need this later
852 Assert1(SrcTy->isIntOrIntVector(), "ZExt only operates on integer", &I);
853 Assert1(DestTy->isIntOrIntVector(), "ZExt only produces an integer", &I);
854 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
855 "zext source and destination must both be a vector or neither", &I);
856 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
857 unsigned DestBitSize = DestTy->getScalarSizeInBits();
859 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
861 visitInstruction(I);
864 void Verifier::visitSExtInst(SExtInst &I) {
865 // Get the source and destination types
866 const Type *SrcTy = I.getOperand(0)->getType();
867 const Type *DestTy = I.getType();
869 // Get the size of the types in bits, we'll need this later
870 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
871 unsigned DestBitSize = DestTy->getScalarSizeInBits();
873 Assert1(SrcTy->isIntOrIntVector(), "SExt only operates on integer", &I);
874 Assert1(DestTy->isIntOrIntVector(), "SExt only produces an integer", &I);
875 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
876 "sext source and destination must both be a vector or neither", &I);
877 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
879 visitInstruction(I);
882 void Verifier::visitFPTruncInst(FPTruncInst &I) {
883 // Get the source and destination types
884 const Type *SrcTy = I.getOperand(0)->getType();
885 const 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->isFPOrFPVector(),"FPTrunc only operates on FP", &I);
891 Assert1(DestTy->isFPOrFPVector(),"FPTrunc only produces an FP", &I);
892 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
893 "fptrunc source and destination must both be a vector or neither",&I);
894 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
896 visitInstruction(I);
899 void Verifier::visitFPExtInst(FPExtInst &I) {
900 // Get the source and destination types
901 const Type *SrcTy = I.getOperand(0)->getType();
902 const Type *DestTy = I.getType();
904 // Get the size of the types in bits, we'll need this later
905 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
906 unsigned DestBitSize = DestTy->getScalarSizeInBits();
908 Assert1(SrcTy->isFPOrFPVector(),"FPExt only operates on FP", &I);
909 Assert1(DestTy->isFPOrFPVector(),"FPExt only produces an FP", &I);
910 Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
911 "fpext source and destination must both be a vector or neither", &I);
912 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
914 visitInstruction(I);
917 void Verifier::visitUIToFPInst(UIToFPInst &I) {
918 // Get the source and destination types
919 const Type *SrcTy = I.getOperand(0)->getType();
920 const Type *DestTy = I.getType();
922 bool SrcVec = isa<VectorType>(SrcTy);
923 bool DstVec = isa<VectorType>(DestTy);
925 Assert1(SrcVec == DstVec,
926 "UIToFP source and dest must both be vector or scalar", &I);
927 Assert1(SrcTy->isIntOrIntVector(),
928 "UIToFP source must be integer or integer vector", &I);
929 Assert1(DestTy->isFPOrFPVector(),
930 "UIToFP result must be FP or FP vector", &I);
932 if (SrcVec && DstVec)
933 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
934 cast<VectorType>(DestTy)->getNumElements(),
935 "UIToFP source and dest vector length mismatch", &I);
937 visitInstruction(I);
940 void Verifier::visitSIToFPInst(SIToFPInst &I) {
941 // Get the source and destination types
942 const Type *SrcTy = I.getOperand(0)->getType();
943 const Type *DestTy = I.getType();
945 bool SrcVec = isa<VectorType>(SrcTy);
946 bool DstVec = isa<VectorType>(DestTy);
948 Assert1(SrcVec == DstVec,
949 "SIToFP source and dest must both be vector or scalar", &I);
950 Assert1(SrcTy->isIntOrIntVector(),
951 "SIToFP source must be integer or integer vector", &I);
952 Assert1(DestTy->isFPOrFPVector(),
953 "SIToFP result must be FP or FP vector", &I);
955 if (SrcVec && DstVec)
956 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
957 cast<VectorType>(DestTy)->getNumElements(),
958 "SIToFP source and dest vector length mismatch", &I);
960 visitInstruction(I);
963 void Verifier::visitFPToUIInst(FPToUIInst &I) {
964 // Get the source and destination types
965 const Type *SrcTy = I.getOperand(0)->getType();
966 const Type *DestTy = I.getType();
968 bool SrcVec = isa<VectorType>(SrcTy);
969 bool DstVec = isa<VectorType>(DestTy);
971 Assert1(SrcVec == DstVec,
972 "FPToUI source and dest must both be vector or scalar", &I);
973 Assert1(SrcTy->isFPOrFPVector(), "FPToUI source must be FP or FP vector", &I);
974 Assert1(DestTy->isIntOrIntVector(),
975 "FPToUI result must be integer or integer vector", &I);
977 if (SrcVec && DstVec)
978 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
979 cast<VectorType>(DestTy)->getNumElements(),
980 "FPToUI source and dest vector length mismatch", &I);
982 visitInstruction(I);
985 void Verifier::visitFPToSIInst(FPToSIInst &I) {
986 // Get the source and destination types
987 const Type *SrcTy = I.getOperand(0)->getType();
988 const Type *DestTy = I.getType();
990 bool SrcVec = isa<VectorType>(SrcTy);
991 bool DstVec = isa<VectorType>(DestTy);
993 Assert1(SrcVec == DstVec,
994 "FPToSI source and dest must both be vector or scalar", &I);
995 Assert1(SrcTy->isFPOrFPVector(),
996 "FPToSI source must be FP or FP vector", &I);
997 Assert1(DestTy->isIntOrIntVector(),
998 "FPToSI result must be integer or integer vector", &I);
1000 if (SrcVec && DstVec)
1001 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1002 cast<VectorType>(DestTy)->getNumElements(),
1003 "FPToSI source and dest vector length mismatch", &I);
1005 visitInstruction(I);
1008 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1009 // Get the source and destination types
1010 const Type *SrcTy = I.getOperand(0)->getType();
1011 const Type *DestTy = I.getType();
1013 Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
1014 Assert1(DestTy->isInteger(), "PtrToInt result must be integral", &I);
1016 visitInstruction(I);
1019 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1020 // Get the source and destination types
1021 const Type *SrcTy = I.getOperand(0)->getType();
1022 const Type *DestTy = I.getType();
1024 Assert1(SrcTy->isInteger(), "IntToPtr source must be an integral", &I);
1025 Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
1027 visitInstruction(I);
1030 void Verifier::visitBitCastInst(BitCastInst &I) {
1031 // Get the source and destination types
1032 const Type *SrcTy = I.getOperand(0)->getType();
1033 const Type *DestTy = I.getType();
1035 // Get the size of the types in bits, we'll need this later
1036 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1037 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1039 // BitCast implies a no-op cast of type only. No bits change.
1040 // However, you can't cast pointers to anything but pointers.
1041 Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
1042 "Bitcast requires both operands to be pointer or neither", &I);
1043 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1045 // Disallow aggregates.
1046 Assert1(!SrcTy->isAggregateType(),
1047 "Bitcast operand must not be aggregate", &I);
1048 Assert1(!DestTy->isAggregateType(),
1049 "Bitcast type must not be aggregate", &I);
1051 visitInstruction(I);
1054 /// visitPHINode - Ensure that a PHI node is well formed.
1056 void Verifier::visitPHINode(PHINode &PN) {
1057 // Ensure that the PHI nodes are all grouped together at the top of the block.
1058 // This can be tested by checking whether the instruction before this is
1059 // either nonexistent (because this is begin()) or is a PHI node. If not,
1060 // then there is some other instruction before a PHI.
1061 Assert2(&PN == &PN.getParent()->front() ||
1062 isa<PHINode>(--BasicBlock::iterator(&PN)),
1063 "PHI nodes not grouped at top of basic block!",
1064 &PN, PN.getParent());
1066 // Check that all of the values of the PHI node have the same type as the
1067 // result, and that the incoming blocks are really basic blocks.
1068 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1069 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1070 "PHI node operands are not the same type as the result!", &PN);
1071 Assert1(isa<BasicBlock>(PN.getOperand(
1072 PHINode::getOperandNumForIncomingBlock(i))),
1073 "PHI node incoming block is not a BasicBlock!", &PN);
1076 // All other PHI node constraints are checked in the visitBasicBlock method.
1078 visitInstruction(PN);
1081 void Verifier::VerifyCallSite(CallSite CS) {
1082 Instruction *I = CS.getInstruction();
1084 Assert1(isa<PointerType>(CS.getCalledValue()->getType()),
1085 "Called function must be a pointer!", I);
1086 const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1088 Assert1(isa<FunctionType>(FPTy->getElementType()),
1089 "Called function is not pointer to function type!", I);
1090 const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1092 // Verify that the correct number of arguments are being passed
1093 if (FTy->isVarArg())
1094 Assert1(CS.arg_size() >= FTy->getNumParams(),
1095 "Called function requires more parameters than were provided!",I);
1096 else
1097 Assert1(CS.arg_size() == FTy->getNumParams(),
1098 "Incorrect number of arguments passed to called function!", I);
1100 // Verify that all arguments to the call match the function type...
1101 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1102 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1103 "Call parameter type does not match function signature!",
1104 CS.getArgument(i), FTy->getParamType(i), I);
1106 const AttrListPtr &Attrs = CS.getAttributes();
1108 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1109 "Attributes after last parameter!", I);
1111 // Verify call attributes.
1112 VerifyFunctionAttrs(FTy, Attrs, I);
1114 if (FTy->isVarArg())
1115 // Check attributes on the varargs part.
1116 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1117 Attributes Attr = Attrs.getParamAttributes(Idx);
1119 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1121 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1122 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1123 " cannot be used for vararg call arguments!", I);
1126 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1127 if (!CS.getCalledFunction() || CS.getCalledFunction()->getName().size() < 5 ||
1128 CS.getCalledFunction()->getName().substr(0, 5) != "llvm.") {
1129 Assert1(FTy->getReturnType() != Type::getMetadataTy(I->getContext()),
1130 "Only intrinsics may return metadata", I);
1131 for (FunctionType::param_iterator PI = FTy->param_begin(),
1132 PE = FTy->param_end(); PI != PE; ++PI)
1133 Assert1(PI->get() != Type::getMetadataTy(I->getContext()),
1134 "Function has metadata parameter but isn't an intrinsic", I);
1137 visitInstruction(*I);
1140 void Verifier::visitCallInst(CallInst &CI) {
1141 VerifyCallSite(&CI);
1143 if (Function *F = CI.getCalledFunction())
1144 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1145 visitIntrinsicFunctionCall(ID, CI);
1148 void Verifier::visitInvokeInst(InvokeInst &II) {
1149 VerifyCallSite(&II);
1152 /// visitBinaryOperator - Check that both arguments to the binary operator are
1153 /// of the same type!
1155 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1156 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1157 "Both operands to a binary operator are not of the same type!", &B);
1159 switch (B.getOpcode()) {
1160 // Check that integer arithmetic operators are only used with
1161 // integral operands.
1162 case Instruction::Add:
1163 case Instruction::Sub:
1164 case Instruction::Mul:
1165 case Instruction::SDiv:
1166 case Instruction::UDiv:
1167 case Instruction::SRem:
1168 case Instruction::URem:
1169 Assert1(B.getType()->isIntOrIntVector(),
1170 "Integer arithmetic operators only work with integral types!", &B);
1171 Assert1(B.getType() == B.getOperand(0)->getType(),
1172 "Integer arithmetic operators must have same type "
1173 "for operands and result!", &B);
1174 break;
1175 // Check that floating-point arithmetic operators are only used with
1176 // floating-point operands.
1177 case Instruction::FAdd:
1178 case Instruction::FSub:
1179 case Instruction::FMul:
1180 case Instruction::FDiv:
1181 case Instruction::FRem:
1182 Assert1(B.getType()->isFPOrFPVector(),
1183 "Floating-point arithmetic operators only work with "
1184 "floating-point types!", &B);
1185 Assert1(B.getType() == B.getOperand(0)->getType(),
1186 "Floating-point arithmetic operators must have same type "
1187 "for operands and result!", &B);
1188 break;
1189 // Check that logical operators are only used with integral operands.
1190 case Instruction::And:
1191 case Instruction::Or:
1192 case Instruction::Xor:
1193 Assert1(B.getType()->isIntOrIntVector(),
1194 "Logical operators only work with integral types!", &B);
1195 Assert1(B.getType() == B.getOperand(0)->getType(),
1196 "Logical operators must have same type for operands and result!",
1197 &B);
1198 break;
1199 case Instruction::Shl:
1200 case Instruction::LShr:
1201 case Instruction::AShr:
1202 Assert1(B.getType()->isIntOrIntVector(),
1203 "Shifts only work with integral types!", &B);
1204 Assert1(B.getType() == B.getOperand(0)->getType(),
1205 "Shift return type must be same as operands!", &B);
1206 break;
1207 default:
1208 llvm_unreachable("Unknown BinaryOperator opcode!");
1211 visitInstruction(B);
1214 void Verifier::visitICmpInst(ICmpInst& IC) {
1215 // Check that the operands are the same type
1216 const Type* Op0Ty = IC.getOperand(0)->getType();
1217 const Type* Op1Ty = IC.getOperand(1)->getType();
1218 Assert1(Op0Ty == Op1Ty,
1219 "Both operands to ICmp instruction are not of the same type!", &IC);
1220 // Check that the operands are the right type
1221 Assert1(Op0Ty->isIntOrIntVector() || isa<PointerType>(Op0Ty),
1222 "Invalid operand types for ICmp instruction", &IC);
1224 visitInstruction(IC);
1227 void Verifier::visitFCmpInst(FCmpInst& FC) {
1228 // Check that the operands are the same type
1229 const Type* Op0Ty = FC.getOperand(0)->getType();
1230 const Type* Op1Ty = FC.getOperand(1)->getType();
1231 Assert1(Op0Ty == Op1Ty,
1232 "Both operands to FCmp instruction are not of the same type!", &FC);
1233 // Check that the operands are the right type
1234 Assert1(Op0Ty->isFPOrFPVector(),
1235 "Invalid operand types for FCmp instruction", &FC);
1236 visitInstruction(FC);
1239 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1240 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1241 EI.getOperand(1)),
1242 "Invalid extractelement operands!", &EI);
1243 visitInstruction(EI);
1246 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1247 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1248 IE.getOperand(1),
1249 IE.getOperand(2)),
1250 "Invalid insertelement operands!", &IE);
1251 visitInstruction(IE);
1254 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1255 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1256 SV.getOperand(2)),
1257 "Invalid shufflevector operands!", &SV);
1259 const VectorType *VTy = dyn_cast<VectorType>(SV.getOperand(0)->getType());
1260 Assert1(VTy, "Operands are not a vector type", &SV);
1262 // Check to see if Mask is valid.
1263 if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
1264 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1265 if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1266 Assert1(!CI->uge(VTy->getNumElements()*2),
1267 "Invalid shufflevector shuffle mask!", &SV);
1268 } else {
1269 Assert1(isa<UndefValue>(MV->getOperand(i)),
1270 "Invalid shufflevector shuffle mask!", &SV);
1273 } else {
1274 Assert1(isa<UndefValue>(SV.getOperand(2)) ||
1275 isa<ConstantAggregateZero>(SV.getOperand(2)),
1276 "Invalid shufflevector shuffle mask!", &SV);
1279 visitInstruction(SV);
1282 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1283 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1284 const Type *ElTy =
1285 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
1286 Idxs.begin(), Idxs.end());
1287 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1288 Assert2(isa<PointerType>(GEP.getType()) &&
1289 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1290 "GEP is not of right type for indices!", &GEP, ElTy);
1291 visitInstruction(GEP);
1294 void Verifier::visitLoadInst(LoadInst &LI) {
1295 const PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1296 Assert1(PTy, "Load operand must be a pointer.", &LI);
1297 const Type *ElTy = PTy->getElementType();
1298 Assert2(ElTy == LI.getType(),
1299 "Load result type does not match pointer operand type!", &LI, ElTy);
1300 Assert1(ElTy != Type::getMetadataTy(LI.getContext()),
1301 "Can't load metadata!", &LI);
1302 visitInstruction(LI);
1305 void Verifier::visitStoreInst(StoreInst &SI) {
1306 const PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1307 Assert1(PTy, "Load operand must be a pointer.", &SI);
1308 const Type *ElTy = PTy->getElementType();
1309 Assert2(ElTy == SI.getOperand(0)->getType(),
1310 "Stored value type does not match pointer operand type!",
1311 &SI, ElTy);
1312 Assert1(ElTy != Type::getMetadataTy(SI.getContext()),
1313 "Can't store metadata!", &SI);
1314 visitInstruction(SI);
1317 void Verifier::visitAllocationInst(AllocationInst &AI) {
1318 const PointerType *PTy = AI.getType();
1319 Assert1(PTy->getAddressSpace() == 0,
1320 "Allocation instruction pointer not in the generic address space!",
1321 &AI);
1322 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1323 &AI);
1324 visitInstruction(AI);
1327 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1328 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1329 EVI.idx_begin(), EVI.idx_end()) ==
1330 EVI.getType(),
1331 "Invalid ExtractValueInst operands!", &EVI);
1333 visitInstruction(EVI);
1336 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1337 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1338 IVI.idx_begin(), IVI.idx_end()) ==
1339 IVI.getOperand(1)->getType(),
1340 "Invalid InsertValueInst operands!", &IVI);
1342 visitInstruction(IVI);
1345 /// verifyInstruction - Verify that an instruction is well formed.
1347 void Verifier::visitInstruction(Instruction &I) {
1348 BasicBlock *BB = I.getParent();
1349 Assert1(BB, "Instruction not embedded in basic block!", &I);
1351 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1352 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1353 UI != UE; ++UI)
1354 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1355 "Only PHI nodes may reference their own value!", &I);
1358 // Verify that if this is a terminator that it is at the end of the block.
1359 if (isa<TerminatorInst>(I))
1360 Assert1(BB->getTerminator() == &I, "Terminator not at end of block!", &I);
1362 // Check that void typed values don't have names
1363 Assert1(I.getType() != Type::getVoidTy(I.getContext()) || !I.hasName(),
1364 "Instruction has a name, but provides a void value!", &I);
1366 // Check that the return value of the instruction is either void or a legal
1367 // value type.
1368 Assert1(I.getType() == Type::getVoidTy(I.getContext()) ||
1369 I.getType()->isFirstClassType()
1370 || ((isa<CallInst>(I) || isa<InvokeInst>(I))
1371 && isa<StructType>(I.getType())),
1372 "Instruction returns a non-scalar type!", &I);
1374 // Check that the instruction doesn't produce metadata or metadata*. Calls
1375 // all already checked against the callee type.
1376 Assert1(I.getType() != Type::getMetadataTy(I.getContext()) ||
1377 isa<CallInst>(I) || isa<InvokeInst>(I),
1378 "Invalid use of metadata!", &I);
1380 if (const PointerType *PTy = dyn_cast<PointerType>(I.getType()))
1381 Assert1(PTy->getElementType() != Type::getMetadataTy(I.getContext()),
1382 "Instructions may not produce pointer to metadata.", &I);
1384 // Check that all uses of the instruction, if they are instructions
1385 // themselves, actually have parent basic blocks. If the use is not an
1386 // instruction, it is an error!
1387 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1388 UI != UE; ++UI) {
1389 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1390 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1391 " embedded in a basic block!", &I, Used);
1392 else {
1393 CheckFailed("Use of instruction is not an instruction!", *UI);
1394 return;
1398 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1399 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1401 // Check to make sure that only first-class-values are operands to
1402 // instructions.
1403 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1404 Assert1(0, "Instruction operands must be first-class values!", &I);
1407 if (const PointerType *PTy =
1408 dyn_cast<PointerType>(I.getOperand(i)->getType()))
1409 Assert1(PTy->getElementType() != Type::getMetadataTy(I.getContext()),
1410 "Invalid use of metadata pointer.", &I);
1412 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1413 // Check to make sure that the "address of" an intrinsic function is never
1414 // taken.
1415 Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
1416 "Cannot take the address of an intrinsic!", &I);
1417 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1418 &I);
1419 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1420 Assert1(OpBB->getParent() == BB->getParent(),
1421 "Referring to a basic block in another function!", &I);
1422 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1423 Assert1(OpArg->getParent() == BB->getParent(),
1424 "Referring to an argument in another function!", &I);
1425 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1426 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1427 &I);
1428 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1429 BasicBlock *OpBlock = Op->getParent();
1431 // Check that a definition dominates all of its uses.
1432 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1433 // Invoke results are only usable in the normal destination, not in the
1434 // exceptional destination.
1435 BasicBlock *NormalDest = II->getNormalDest();
1437 Assert2(NormalDest != II->getUnwindDest(),
1438 "No uses of invoke possible due to dominance structure!",
1439 Op, &I);
1441 // PHI nodes differ from other nodes because they actually "use" the
1442 // value in the predecessor basic blocks they correspond to.
1443 BasicBlock *UseBlock = BB;
1444 if (isa<PHINode>(I))
1445 UseBlock = dyn_cast<BasicBlock>(I.getOperand(i+1));
1446 Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1447 Op, &I);
1449 if (isa<PHINode>(I) && UseBlock == OpBlock) {
1450 // Special case of a phi node in the normal destination or the unwind
1451 // destination.
1452 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1453 "Invoke result not available in the unwind destination!",
1454 Op, &I);
1455 } else {
1456 Assert2(DT->dominates(NormalDest, UseBlock) ||
1457 !DT->isReachableFromEntry(UseBlock),
1458 "Invoke result does not dominate all uses!", Op, &I);
1460 // If the normal successor of an invoke instruction has multiple
1461 // predecessors, then the normal edge from the invoke is critical,
1462 // so the invoke value can only be live if the destination block
1463 // dominates all of it's predecessors (other than the invoke).
1464 if (!NormalDest->getSinglePredecessor() &&
1465 DT->isReachableFromEntry(UseBlock))
1466 // If it is used by something non-phi, then the other case is that
1467 // 'NormalDest' dominates all of its predecessors other than the
1468 // invoke. In this case, the invoke value can still be used.
1469 for (pred_iterator PI = pred_begin(NormalDest),
1470 E = pred_end(NormalDest); PI != E; ++PI)
1471 if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1472 DT->isReachableFromEntry(*PI)) {
1473 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1474 return;
1477 } else if (isa<PHINode>(I)) {
1478 // PHI nodes are more difficult than other nodes because they actually
1479 // "use" the value in the predecessor basic blocks they correspond to.
1480 BasicBlock *PredBB = dyn_cast<BasicBlock>(I.getOperand(i+1));
1481 Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1482 !DT->isReachableFromEntry(PredBB)),
1483 "Instruction does not dominate all uses!", Op, &I);
1484 } else {
1485 if (OpBlock == BB) {
1486 // If they are in the same basic block, make sure that the definition
1487 // comes before the use.
1488 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1489 "Instruction does not dominate all uses!", Op, &I);
1492 // Definition must dominate use unless use is unreachable!
1493 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1494 !DT->isReachableFromEntry(BB),
1495 "Instruction does not dominate all uses!", Op, &I);
1497 } else if (isa<InlineAsm>(I.getOperand(i))) {
1498 Assert1(i == 0 && (isa<CallInst>(I) || isa<InvokeInst>(I)),
1499 "Cannot take the address of an inline asm!", &I);
1502 InstsInThisBlock.insert(&I);
1504 VerifyType(I.getType());
1507 /// VerifyType - Verify that a type is well formed.
1509 void Verifier::VerifyType(const Type *Ty) {
1510 if (!Types.insert(Ty)) return;
1512 switch (Ty->getTypeID()) {
1513 case Type::FunctionTyID: {
1514 const FunctionType *FTy = cast<FunctionType>(Ty);
1516 const Type *RetTy = FTy->getReturnType();
1517 Assert2(FunctionType::isValidReturnType(RetTy),
1518 "Function type with invalid return type", RetTy, FTy);
1519 VerifyType(RetTy);
1521 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1522 const Type *ElTy = FTy->getParamType(i);
1523 Assert2(FunctionType::isValidArgumentType(ElTy),
1524 "Function type with invalid parameter type", ElTy, FTy);
1525 VerifyType(ElTy);
1527 } break;
1528 case Type::StructTyID: {
1529 const StructType *STy = cast<StructType>(Ty);
1530 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1531 const Type *ElTy = STy->getElementType(i);
1532 Assert2(StructType::isValidElementType(ElTy),
1533 "Structure type with invalid element type", ElTy, STy);
1534 VerifyType(ElTy);
1536 } break;
1537 case Type::ArrayTyID: {
1538 const ArrayType *ATy = cast<ArrayType>(Ty);
1539 Assert1(ArrayType::isValidElementType(ATy->getElementType()),
1540 "Array type with invalid element type", ATy);
1541 VerifyType(ATy->getElementType());
1542 } break;
1543 case Type::PointerTyID: {
1544 const PointerType *PTy = cast<PointerType>(Ty);
1545 Assert1(PointerType::isValidElementType(PTy->getElementType()),
1546 "Pointer type with invalid element type", PTy);
1547 VerifyType(PTy->getElementType());
1548 } break;
1549 case Type::VectorTyID: {
1550 const VectorType *VTy = cast<VectorType>(Ty);
1551 Assert1(VectorType::isValidElementType(VTy->getElementType()),
1552 "Vector type with invalid element type", VTy);
1553 VerifyType(VTy->getElementType());
1554 } break;
1555 default:
1556 break;
1560 // Flags used by TableGen to mark intrinsic parameters with the
1561 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1562 static const unsigned ExtendedElementVectorType = 0x40000000;
1563 static const unsigned TruncatedElementVectorType = 0x20000000;
1565 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1567 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1568 Function *IF = CI.getCalledFunction();
1569 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1570 IF);
1572 #define GET_INTRINSIC_VERIFIER
1573 #include "llvm/Intrinsics.gen"
1574 #undef GET_INTRINSIC_VERIFIER
1576 switch (ID) {
1577 default:
1578 break;
1579 case Intrinsic::dbg_declare: // llvm.dbg.declare
1580 if (Constant *C = dyn_cast<Constant>(CI.getOperand(1)))
1581 Assert1(C && !isa<ConstantPointerNull>(C),
1582 "invalid llvm.dbg.declare intrinsic call", &CI);
1583 break;
1584 case Intrinsic::memcpy:
1585 case Intrinsic::memmove:
1586 case Intrinsic::memset:
1587 Assert1(isa<ConstantInt>(CI.getOperand(4)),
1588 "alignment argument of memory intrinsics must be a constant int",
1589 &CI);
1590 break;
1591 case Intrinsic::gcroot:
1592 case Intrinsic::gcwrite:
1593 case Intrinsic::gcread:
1594 if (ID == Intrinsic::gcroot) {
1595 AllocaInst *AI =
1596 dyn_cast<AllocaInst>(CI.getOperand(1)->stripPointerCasts());
1597 Assert1(AI && isa<PointerType>(AI->getType()->getElementType()),
1598 "llvm.gcroot parameter #1 must be a pointer alloca.", &CI);
1599 Assert1(isa<Constant>(CI.getOperand(2)),
1600 "llvm.gcroot parameter #2 must be a constant.", &CI);
1603 Assert1(CI.getParent()->getParent()->hasGC(),
1604 "Enclosing function does not use GC.", &CI);
1605 break;
1606 case Intrinsic::init_trampoline:
1607 Assert1(isa<Function>(CI.getOperand(2)->stripPointerCasts()),
1608 "llvm.init_trampoline parameter #2 must resolve to a function.",
1609 &CI);
1610 break;
1611 case Intrinsic::prefetch:
1612 Assert1(isa<ConstantInt>(CI.getOperand(2)) &&
1613 isa<ConstantInt>(CI.getOperand(3)) &&
1614 cast<ConstantInt>(CI.getOperand(2))->getZExtValue() < 2 &&
1615 cast<ConstantInt>(CI.getOperand(3))->getZExtValue() < 4,
1616 "invalid arguments to llvm.prefetch",
1617 &CI);
1618 break;
1619 case Intrinsic::stackprotector:
1620 Assert1(isa<AllocaInst>(CI.getOperand(2)->stripPointerCasts()),
1621 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1622 &CI);
1623 break;
1627 /// Produce a string to identify an intrinsic parameter or return value.
1628 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1629 /// parameters beginning with NumRets.
1631 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1632 if (ArgNo < NumRets) {
1633 if (NumRets == 1)
1634 return "Intrinsic result type";
1635 else
1636 return "Intrinsic result type #" + utostr(ArgNo);
1637 } else
1638 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1641 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
1642 int VT, unsigned ArgNo, std::string &Suffix) {
1643 const FunctionType *FTy = F->getFunctionType();
1645 unsigned NumElts = 0;
1646 const Type *EltTy = Ty;
1647 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1648 if (VTy) {
1649 EltTy = VTy->getElementType();
1650 NumElts = VTy->getNumElements();
1653 const Type *RetTy = FTy->getReturnType();
1654 const StructType *ST = dyn_cast<StructType>(RetTy);
1655 unsigned NumRets = 1;
1656 if (ST)
1657 NumRets = ST->getNumElements();
1659 if (VT < 0) {
1660 int Match = ~VT;
1662 // Check flags that indicate a type that is an integral vector type with
1663 // elements that are larger or smaller than the elements of the matched
1664 // type.
1665 if ((Match & (ExtendedElementVectorType |
1666 TruncatedElementVectorType)) != 0) {
1667 const IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1668 if (!VTy || !IEltTy) {
1669 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1670 "an integral vector type.", F);
1671 return false;
1673 // Adjust the current Ty (in the opposite direction) rather than
1674 // the type being matched against.
1675 if ((Match & ExtendedElementVectorType) != 0) {
1676 if ((IEltTy->getBitWidth() & 1) != 0) {
1677 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " vector "
1678 "element bit-width is odd.", F);
1679 return false;
1681 Ty = VectorType::getTruncatedElementVectorType(VTy);
1682 } else
1683 Ty = VectorType::getExtendedElementVectorType(VTy);
1684 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1687 if (Match <= static_cast<int>(NumRets - 1)) {
1688 if (ST)
1689 RetTy = ST->getElementType(Match);
1691 if (Ty != RetTy) {
1692 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " does not "
1693 "match return type.", F);
1694 return false;
1696 } else {
1697 if (Ty != FTy->getParamType(Match - NumRets)) {
1698 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " does not "
1699 "match parameter %" + utostr(Match - NumRets) + ".", F);
1700 return false;
1703 } else if (VT == MVT::iAny) {
1704 if (!EltTy->isInteger()) {
1705 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1706 "an integer type.", F);
1707 return false;
1710 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1711 Suffix += ".";
1713 if (EltTy != Ty)
1714 Suffix += "v" + utostr(NumElts);
1716 Suffix += "i" + utostr(GotBits);
1718 // Check some constraints on various intrinsics.
1719 switch (ID) {
1720 default: break; // Not everything needs to be checked.
1721 case Intrinsic::bswap:
1722 if (GotBits < 16 || GotBits % 16 != 0) {
1723 CheckFailed("Intrinsic requires even byte width argument", F);
1724 return false;
1726 break;
1728 } else if (VT == MVT::fAny) {
1729 if (!EltTy->isFloatingPoint()) {
1730 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
1731 "a floating-point type.", F);
1732 return false;
1735 Suffix += ".";
1737 if (EltTy != Ty)
1738 Suffix += "v" + utostr(NumElts);
1740 Suffix += EVT::getEVT(EltTy).getEVTString();
1741 } else if (VT == MVT::vAny) {
1742 if (!VTy) {
1743 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a vector type.", F);
1744 return false;
1746 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1747 } else if (VT == MVT::iPTR) {
1748 if (!isa<PointerType>(Ty)) {
1749 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a "
1750 "pointer and a pointer is required.", F);
1751 return false;
1753 } else if (VT == MVT::iPTRAny) {
1754 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1755 // and iPTR. In the verifier, we can not distinguish which case we have so
1756 // allow either case to be legal.
1757 if (const PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1758 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1759 EVT::getEVT(PTyp->getElementType()).getEVTString();
1760 } else {
1761 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a "
1762 "pointer and a pointer is required.", F);
1763 return false;
1765 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1766 EVT VVT = EVT((MVT::SimpleValueType)VT);
1768 // If this is a vector argument, verify the number and type of elements.
1769 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1770 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1771 return false;
1774 if (VVT.getVectorNumElements() != NumElts) {
1775 CheckFailed("Intrinsic prototype has incorrect number of "
1776 "vector elements!", F);
1777 return false;
1779 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1780 EltTy) {
1781 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is wrong!", F);
1782 return false;
1783 } else if (EltTy != Ty) {
1784 CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is a vector "
1785 "and a scalar is required.", F);
1786 return false;
1789 return true;
1792 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1793 /// Intrinsics.gen. This implements a little state machine that verifies the
1794 /// prototype of intrinsics.
1795 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1796 unsigned RetNum,
1797 unsigned ParamNum, ...) {
1798 va_list VA;
1799 va_start(VA, ParamNum);
1800 const FunctionType *FTy = F->getFunctionType();
1802 // For overloaded intrinsics, the Suffix of the function name must match the
1803 // types of the arguments. This variable keeps track of the expected
1804 // suffix, to be checked at the end.
1805 std::string Suffix;
1807 if (FTy->getNumParams() + FTy->isVarArg() != ParamNum) {
1808 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1809 return;
1812 const Type *Ty = FTy->getReturnType();
1813 const StructType *ST = dyn_cast<StructType>(Ty);
1815 // Verify the return types.
1816 if (ST && ST->getNumElements() != RetNum) {
1817 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1818 return;
1821 for (unsigned ArgNo = 0; ArgNo < RetNum; ++ArgNo) {
1822 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1824 if (ST) Ty = ST->getElementType(ArgNo);
1826 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1827 break;
1830 // Verify the parameter types.
1831 for (unsigned ArgNo = 0; ArgNo < ParamNum; ++ArgNo) {
1832 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1834 if (VT == MVT::isVoid && ArgNo > 0) {
1835 if (!FTy->isVarArg())
1836 CheckFailed("Intrinsic prototype has no '...'!", F);
1837 break;
1840 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT, ArgNo + RetNum,
1841 Suffix))
1842 break;
1845 va_end(VA);
1847 // For intrinsics without pointer arguments, if we computed a Suffix then the
1848 // intrinsic is overloaded and we need to make sure that the name of the
1849 // function is correct. We add the suffix to the name of the intrinsic and
1850 // compare against the given function name. If they are not the same, the
1851 // function name is invalid. This ensures that overloading of intrinsics
1852 // uses a sane and consistent naming convention. Note that intrinsics with
1853 // pointer argument may or may not be overloaded so we will check assuming it
1854 // has a suffix and not.
1855 if (!Suffix.empty()) {
1856 std::string Name(Intrinsic::getName(ID));
1857 if (Name + Suffix != F->getName()) {
1858 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1859 F->getName().substr(Name.length()) + "'. It should be '" +
1860 Suffix + "'", F);
1864 // Check parameter attributes.
1865 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1866 "Intrinsic has wrong parameter attributes!", F);
1870 //===----------------------------------------------------------------------===//
1871 // Implement the public interfaces to this file...
1872 //===----------------------------------------------------------------------===//
1874 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1875 return new Verifier(action);
1879 // verifyFunction - Create
1880 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1881 Function &F = const_cast<Function&>(f);
1882 assert(!F.isDeclaration() && "Cannot verify external functions");
1884 ExistingModuleProvider MP(F.getParent());
1885 FunctionPassManager FPM(&MP);
1886 Verifier *V = new Verifier(action);
1887 FPM.add(V);
1888 FPM.run(F);
1889 MP.releaseModule();
1890 return V->Broken;
1893 /// verifyModule - Check a module for errors, printing messages on stderr.
1894 /// Return true if the module is corrupt.
1896 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1897 std::string *ErrorInfo) {
1898 PassManager PM;
1899 Verifier *V = new Verifier(action);
1900 PM.add(V);
1901 PM.run(const_cast<Module&>(M));
1903 if (ErrorInfo && V->Broken)
1904 *ErrorInfo = V->MessagesStr.str();
1905 return V->Broken;