185b03d5bdf0ccb0530b35079c0090e41f95ddee
[oota-llvm.git] / lib / VMCore / Verifier.cpp
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.
12 //
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.
15 //
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...
39 //
40 //===----------------------------------------------------------------------===//
41
42 #include "llvm/Analysis/Verifier.h"
43 #include "llvm/CallingConv.h"
44 #include "llvm/Constants.h"
45 #include "llvm/DerivedTypes.h"
46 #include "llvm/InlineAsm.h"
47 #include "llvm/IntrinsicInst.h"
48 #include "llvm/Metadata.h"
49 #include "llvm/Module.h"
50 #include "llvm/Pass.h"
51 #include "llvm/PassManager.h"
52 #include "llvm/TypeSymbolTable.h"
53 #include "llvm/Analysis/Dominators.h"
54 #include "llvm/Assembly/Writer.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/Support/CallSite.h"
57 #include "llvm/Support/CFG.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/InstVisitor.h"
60 #include "llvm/ADT/SetVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/StringExtras.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include <algorithm>
68 #include <cstdarg>
69 using namespace llvm;
70
71 namespace {  // Anonymous namespace for class
72   struct PreVerifier : public FunctionPass {
73     static char ID; // Pass ID, replacement for typeid
74
75     PreVerifier() : FunctionPass(ID) { }
76
77     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78       AU.setPreservesAll();
79     }
80
81     // Check that the prerequisites for successful DominatorTree construction
82     // are satisfied.
83     bool runOnFunction(Function &F) {
84       bool Broken = false;
85
86       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
87         if (I->empty() || !I->back().isTerminator()) {
88           dbgs() << "Basic Block in function '" << F.getName() 
89                  << "' does not have terminator!\n";
90           WriteAsOperand(dbgs(), I, true);
91           dbgs() << "\n";
92           Broken = true;
93         }
94       }
95
96       if (Broken)
97         report_fatal_error("Broken module, no Basic Block terminator!");
98
99       return false;
100     }
101   };
102 }
103
104 char PreVerifier::ID = 0;
105 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification", 
106                 false, false);
107 char &PreVerifyID = PreVerifier::ID;
108
109 namespace {
110   class TypeSet : public AbstractTypeUser {
111   public:
112     TypeSet() {}
113
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;
121     }
122
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);
131       }
132     }
133
134     // Abstract type user interface.
135
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);
141     }
142
143     /// Stop listening for changes to a type which is no longer abstract.
144     void typeBecameConcrete(const DerivedType *AbsTy) {
145       AbsTy->removeAbstractTypeUser(this);
146     }
147
148     void dump() const {}
149
150   private:
151     SmallSetVector<const Type *, 16> Types;
152
153     // Disallow copying.
154     TypeSet(const TypeSet &);
155     TypeSet &operator=(const TypeSet &);
156   };
157
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     LLVMContext *Context; // Context within which we are verifying
166     DominatorTree *DT;    // Dominator Tree, caution can be null!
167
168     std::string Messages;
169     raw_string_ostream MessagesStr;
170
171     /// InstInThisBlock - when verifying a basic block, keep track of all of the
172     /// instructions we have seen so far.  This allows us to do efficient
173     /// dominance checks for the case when an instruction has an operand that is
174     /// an instruction in the same block.
175     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
176
177     /// Types - keep track of the types that have been checked already.
178     TypeSet Types;
179
180     /// MDNodes - keep track of the metadata nodes that have been checked
181     /// already.
182     SmallPtrSet<MDNode *, 32> MDNodes;
183
184     Verifier()
185       : FunctionPass(ID), 
186       Broken(false), RealPass(true), action(AbortProcessAction),
187       Mod(0), Context(0), DT(0), MessagesStr(Messages) {}
188     explicit Verifier(VerifierFailureAction ctn)
189       : FunctionPass(ID), 
190       Broken(false), RealPass(true), action(ctn), Mod(0), Context(0), DT(0),
191       MessagesStr(Messages) {}
192
193     bool doInitialization(Module &M) {
194       Mod = &M;
195       Context = &M.getContext();
196       verifyTypeSymbolTable(M.getTypeSymbolTable());
197
198       // If this is a real pass, in a pass manager, we must abort before
199       // returning back to the pass manager, or else the pass manager may try to
200       // run other passes on the broken module.
201       if (RealPass)
202         return abortIfBroken();
203       return false;
204     }
205
206     bool runOnFunction(Function &F) {
207       // Get dominator information if we are being run by PassManager
208       if (RealPass) DT = &getAnalysis<DominatorTree>();
209
210       Mod = F.getParent();
211       if (!Context) Context = &F.getContext();
212
213       visit(F);
214       InstsInThisBlock.clear();
215
216       // If this is a real pass, in a pass manager, we must abort before
217       // returning back to the pass manager, or else the pass manager may try to
218       // run other passes on the broken module.
219       if (RealPass)
220         return abortIfBroken();
221
222       return false;
223     }
224
225     bool doFinalization(Module &M) {
226       // Scan through, checking all of the external function's linkage now...
227       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
228         visitGlobalValue(*I);
229
230         // Check to make sure function prototypes are okay.
231         if (I->isDeclaration()) visitFunction(*I);
232       }
233
234       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
235            I != E; ++I)
236         visitGlobalVariable(*I);
237
238       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 
239            I != E; ++I)
240         visitGlobalAlias(*I);
241
242       for (Module::named_metadata_iterator I = M.named_metadata_begin(),
243            E = M.named_metadata_end(); I != E; ++I)
244         visitNamedMDNode(*I);
245
246       // If the module is broken, abort at this time.
247       return abortIfBroken();
248     }
249
250     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
251       AU.setPreservesAll();
252       AU.addRequiredID(PreVerifyID);
253       if (RealPass)
254         AU.addRequired<DominatorTree>();
255     }
256
257     /// abortIfBroken - If the module is broken and we are supposed to abort on
258     /// this condition, do so.
259     ///
260     bool abortIfBroken() {
261       if (!Broken) return false;
262       MessagesStr << "Broken module found, ";
263       switch (action) {
264       default: llvm_unreachable("Unknown action");
265       case AbortProcessAction:
266         MessagesStr << "compilation aborted!\n";
267         dbgs() << MessagesStr.str();
268         // Client should choose different reaction if abort is not desired
269         abort();
270       case PrintMessageAction:
271         MessagesStr << "verification continues.\n";
272         dbgs() << MessagesStr.str();
273         return false;
274       case ReturnStatusAction:
275         MessagesStr << "compilation terminated.\n";
276         return true;
277       }
278     }
279
280
281     // Verification methods...
282     void verifyTypeSymbolTable(TypeSymbolTable &ST);
283     void visitGlobalValue(GlobalValue &GV);
284     void visitGlobalVariable(GlobalVariable &GV);
285     void visitGlobalAlias(GlobalAlias &GA);
286     void visitNamedMDNode(NamedMDNode &NMD);
287     void visitMDNode(MDNode &MD, Function *F);
288     void visitFunction(Function &F);
289     void visitBasicBlock(BasicBlock &BB);
290     using InstVisitor<Verifier>::visit;
291
292     void visit(Instruction &I);
293
294     void visitTruncInst(TruncInst &I);
295     void visitZExtInst(ZExtInst &I);
296     void visitSExtInst(SExtInst &I);
297     void visitFPTruncInst(FPTruncInst &I);
298     void visitFPExtInst(FPExtInst &I);
299     void visitFPToUIInst(FPToUIInst &I);
300     void visitFPToSIInst(FPToSIInst &I);
301     void visitUIToFPInst(UIToFPInst &I);
302     void visitSIToFPInst(SIToFPInst &I);
303     void visitIntToPtrInst(IntToPtrInst &I);
304     void visitPtrToIntInst(PtrToIntInst &I);
305     void visitBitCastInst(BitCastInst &I);
306     void visitPHINode(PHINode &PN);
307     void visitBinaryOperator(BinaryOperator &B);
308     void visitICmpInst(ICmpInst &IC);
309     void visitFCmpInst(FCmpInst &FC);
310     void visitExtractElementInst(ExtractElementInst &EI);
311     void visitInsertElementInst(InsertElementInst &EI);
312     void visitShuffleVectorInst(ShuffleVectorInst &EI);
313     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
314     void visitCallInst(CallInst &CI);
315     void visitInvokeInst(InvokeInst &II);
316     void visitGetElementPtrInst(GetElementPtrInst &GEP);
317     void visitLoadInst(LoadInst &LI);
318     void visitStoreInst(StoreInst &SI);
319     void visitInstruction(Instruction &I);
320     void visitTerminatorInst(TerminatorInst &I);
321     void visitBranchInst(BranchInst &BI);
322     void visitReturnInst(ReturnInst &RI);
323     void visitSwitchInst(SwitchInst &SI);
324     void visitIndirectBrInst(IndirectBrInst &BI);
325     void visitSelectInst(SelectInst &SI);
326     void visitUserOp1(Instruction &I);
327     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
328     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
329     void visitAllocaInst(AllocaInst &AI);
330     void visitExtractValueInst(ExtractValueInst &EVI);
331     void visitInsertValueInst(InsertValueInst &IVI);
332
333     void VerifyCallSite(CallSite CS);
334     bool PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
335                           int VT, unsigned ArgNo, std::string &Suffix);
336     void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
337                                   unsigned RetNum, unsigned ParamNum, ...);
338     void VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
339                               bool isReturnValue, const Value *V);
340     void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
341                              const Value *V);
342     void VerifyType(const Type *Ty);
343
344     void WriteValue(const Value *V) {
345       if (!V) return;
346       if (isa<Instruction>(V)) {
347         MessagesStr << *V << '\n';
348       } else {
349         WriteAsOperand(MessagesStr, V, true, Mod);
350         MessagesStr << '\n';
351       }
352     }
353
354     void WriteType(const Type *T) {
355       if (!T) return;
356       MessagesStr << ' ';
357       WriteTypeSymbolic(MessagesStr, T, Mod);
358     }
359
360
361     // CheckFailed - A check failed, so print out the condition and the message
362     // that failed.  This provides a nice place to put a breakpoint if you want
363     // to see why something is not correct.
364     void CheckFailed(const Twine &Message,
365                      const Value *V1 = 0, const Value *V2 = 0,
366                      const Value *V3 = 0, const Value *V4 = 0) {
367       MessagesStr << Message.str() << "\n";
368       WriteValue(V1);
369       WriteValue(V2);
370       WriteValue(V3);
371       WriteValue(V4);
372       Broken = true;
373     }
374
375     void CheckFailed(const Twine &Message, const Value *V1,
376                      const Type *T2, const Value *V3 = 0) {
377       MessagesStr << Message.str() << "\n";
378       WriteValue(V1);
379       WriteType(T2);
380       WriteValue(V3);
381       Broken = true;
382     }
383
384     void CheckFailed(const Twine &Message, const Type *T1,
385                      const Type *T2 = 0, const Type *T3 = 0) {
386       MessagesStr << Message.str() << "\n";
387       WriteType(T1);
388       WriteType(T2);
389       WriteType(T3);
390       Broken = true;
391     }
392   };
393 } // End anonymous namespace
394
395 char Verifier::ID = 0;
396 INITIALIZE_PASS(Verifier, "verify", "Module Verifier", false, false);
397
398 // Assert - We know that cond should be true, if not print an error message.
399 #define Assert(C, M) \
400   do { if (!(C)) { CheckFailed(M); return; } } while (0)
401 #define Assert1(C, M, V1) \
402   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
403 #define Assert2(C, M, V1, V2) \
404   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
405 #define Assert3(C, M, V1, V2, V3) \
406   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
407 #define Assert4(C, M, V1, V2, V3, V4) \
408   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
409
410 void Verifier::visit(Instruction &I) {
411   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
412     Assert1(I.getOperand(i) != 0, "Operand is null", &I);
413   InstVisitor<Verifier>::visit(I);
414 }
415
416
417 void Verifier::visitGlobalValue(GlobalValue &GV) {
418   Assert1(!GV.isDeclaration() ||
419           GV.isMaterializable() ||
420           GV.hasExternalLinkage() ||
421           GV.hasDLLImportLinkage() ||
422           GV.hasExternalWeakLinkage() ||
423           (isa<GlobalAlias>(GV) &&
424            (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
425   "Global is external, but doesn't have external or dllimport or weak linkage!",
426           &GV);
427
428   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
429           "Global is marked as dllimport, but not external", &GV);
430
431   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
432           "Only global variables can have appending linkage!", &GV);
433
434   if (GV.hasAppendingLinkage()) {
435     GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
436     Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
437             "Only global arrays can have appending linkage!", GVar);
438   }
439
440   Assert1(!GV.hasLinkerPrivateWeakDefAutoLinkage() || GV.hasDefaultVisibility(),
441           "linker_private_weak_def_auto can only have default visibility!",
442           &GV);
443 }
444
445 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
446   if (GV.hasInitializer()) {
447     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
448             "Global variable initializer type does not match global "
449             "variable type!", &GV);
450
451     // If the global has common linkage, it must have a zero initializer and
452     // cannot be constant.
453     if (GV.hasCommonLinkage()) {
454       Assert1(GV.getInitializer()->isNullValue(),
455               "'common' global must have a zero initializer!", &GV);
456       Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
457               &GV);
458     }
459   } else {
460     Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
461             GV.hasExternalWeakLinkage(),
462             "invalid linkage type for global declaration", &GV);
463   }
464
465   visitGlobalValue(GV);
466 }
467
468 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
469   Assert1(!GA.getName().empty(),
470           "Alias name cannot be empty!", &GA);
471   Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
472           GA.hasWeakLinkage(),
473           "Alias should have external or external weak linkage!", &GA);
474   Assert1(GA.getAliasee(),
475           "Aliasee cannot be NULL!", &GA);
476   Assert1(GA.getType() == GA.getAliasee()->getType(),
477           "Alias and aliasee types should match!", &GA);
478
479   if (!isa<GlobalValue>(GA.getAliasee())) {
480     const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
481     Assert1(CE && 
482             (CE->getOpcode() == Instruction::BitCast ||
483              CE->getOpcode() == Instruction::GetElementPtr) &&
484             isa<GlobalValue>(CE->getOperand(0)),
485             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
486             &GA);
487   }
488
489   const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
490   Assert1(Aliasee,
491           "Aliasing chain should end with function or global variable", &GA);
492
493   visitGlobalValue(GA);
494 }
495
496 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
497   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
498     MDNode *MD = NMD.getOperand(i);
499     if (!MD)
500       continue;
501
502     Assert1(!MD->isFunctionLocal(),
503             "Named metadata operand cannot be function local!", MD);
504     visitMDNode(*MD, 0);
505   }
506 }
507
508 void Verifier::visitMDNode(MDNode &MD, Function *F) {
509   // Only visit each node once.  Metadata can be mutually recursive, so this
510   // avoids infinite recursion here, as well as being an optimization.
511   if (!MDNodes.insert(&MD))
512     return;
513
514   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
515     Value *Op = MD.getOperand(i);
516     if (!Op)
517       continue;
518     if (isa<Constant>(Op) || isa<MDString>(Op))
519       continue;
520     if (MDNode *N = dyn_cast<MDNode>(Op)) {
521       Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
522               "Global metadata operand cannot be function local!", &MD, N);
523       visitMDNode(*N, F);
524       continue;
525     }
526     Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
527
528     // If this was an instruction, bb, or argument, verify that it is in the
529     // function that we expect.
530     Function *ActualF = 0;
531     if (Instruction *I = dyn_cast<Instruction>(Op))
532       ActualF = I->getParent()->getParent();
533     else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
534       ActualF = BB->getParent();
535     else if (Argument *A = dyn_cast<Argument>(Op))
536       ActualF = A->getParent();
537     assert(ActualF && "Unimplemented function local metadata case!");
538
539     Assert2(ActualF == F, "function-local metadata used in wrong function",
540             &MD, Op);
541   }
542 }
543
544 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
545   for (TypeSymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
546     VerifyType(I->second);
547 }
548
549 // VerifyParameterAttrs - Check the given attributes for an argument or return
550 // value of the specified type.  The value V is printed in error messages.
551 void Verifier::VerifyParameterAttrs(Attributes Attrs, const Type *Ty,
552                                     bool isReturnValue, const Value *V) {
553   if (Attrs == Attribute::None)
554     return;
555
556   Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
557   Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
558           " only applies to the function!", V);
559
560   if (isReturnValue) {
561     Attributes RetI = Attrs & Attribute::ParameterOnly;
562     Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
563             " does not apply to return values!", V);
564   }
565
566   for (unsigned i = 0;
567        i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
568     Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
569     Assert1(!(MutI & (MutI - 1)), "Attributes " +
570             Attribute::getAsString(MutI) + " are incompatible!", V);
571   }
572
573   Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
574   Assert1(!TypeI, "Wrong type for attribute " +
575           Attribute::getAsString(TypeI), V);
576
577   Attributes ByValI = Attrs & Attribute::ByVal;
578   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
579     Assert1(!ByValI || PTy->getElementType()->isSized(),
580             "Attribute " + Attribute::getAsString(ByValI) +
581             " does not support unsized types!", V);
582   } else {
583     Assert1(!ByValI,
584             "Attribute " + Attribute::getAsString(ByValI) +
585             " only applies to parameters with pointer type!", V);
586   }
587 }
588
589 // VerifyFunctionAttrs - Check parameter attributes against a function type.
590 // The value V is printed in error messages.
591 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
592                                    const AttrListPtr &Attrs,
593                                    const Value *V) {
594   if (Attrs.isEmpty())
595     return;
596
597   bool SawNest = false;
598
599   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
600     const AttributeWithIndex &Attr = Attrs.getSlot(i);
601
602     const Type *Ty;
603     if (Attr.Index == 0)
604       Ty = FT->getReturnType();
605     else if (Attr.Index-1 < FT->getNumParams())
606       Ty = FT->getParamType(Attr.Index-1);
607     else
608       break;  // VarArgs attributes, verified elsewhere.
609
610     VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
611
612     if (Attr.Attrs & Attribute::Nest) {
613       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
614       SawNest = true;
615     }
616
617     if (Attr.Attrs & Attribute::StructRet)
618       Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
619   }
620
621   Attributes FAttrs = Attrs.getFnAttributes();
622   Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
623   Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
624           " does not apply to the function!", V);
625
626   for (unsigned i = 0;
627        i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
628     Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
629     Assert1(!(MutI & (MutI - 1)), "Attributes " +
630             Attribute::getAsString(MutI) + " are incompatible!", V);
631   }
632 }
633
634 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
635   if (Attrs.isEmpty())
636     return true;
637
638   unsigned LastSlot = Attrs.getNumSlots() - 1;
639   unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
640   if (LastIndex <= Params
641       || (LastIndex == (unsigned)~0
642           && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))  
643     return true;
644
645   return false;
646 }
647
648 // visitFunction - Verify that a function is ok.
649 //
650 void Verifier::visitFunction(Function &F) {
651   // Check function arguments.
652   const FunctionType *FT = F.getFunctionType();
653   unsigned NumArgs = F.arg_size();
654
655   Assert1(Context == &F.getContext(),
656           "Function context does not match Module context!", &F);
657
658   Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
659   Assert2(FT->getNumParams() == NumArgs,
660           "# formal arguments must match # of arguments for function type!",
661           &F, FT);
662   Assert1(F.getReturnType()->isFirstClassType() ||
663           F.getReturnType()->isVoidTy() || 
664           F.getReturnType()->isStructTy(),
665           "Functions cannot return aggregate values!", &F);
666
667   Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
668           "Invalid struct return type!", &F);
669
670   const AttrListPtr &Attrs = F.getAttributes();
671
672   Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
673           "Attributes after last parameter!", &F);
674
675   // Check function attributes.
676   VerifyFunctionAttrs(FT, Attrs, &F);
677
678   // Check that this function meets the restrictions on this calling convention.
679   switch (F.getCallingConv()) {
680   default:
681     break;
682   case CallingConv::C:
683     break;
684   case CallingConv::Fast:
685   case CallingConv::Cold:
686   case CallingConv::X86_FastCall:
687   case CallingConv::X86_ThisCall:
688     Assert1(!F.isVarArg(),
689             "Varargs functions must have C calling conventions!", &F);
690     break;
691   }
692
693   bool isLLVMdotName = F.getName().size() >= 5 &&
694                        F.getName().substr(0, 5) == "llvm.";
695
696   // Check that the argument values match the function type for this function...
697   unsigned i = 0;
698   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
699        I != E; ++I, ++i) {
700     Assert2(I->getType() == FT->getParamType(i),
701             "Argument value does not match function argument type!",
702             I, FT->getParamType(i));
703     Assert1(I->getType()->isFirstClassType(),
704             "Function arguments must have first-class types!", I);
705     if (!isLLVMdotName)
706       Assert2(!I->getType()->isMetadataTy(),
707               "Function takes metadata but isn't an intrinsic", I, &F);
708   }
709
710   if (F.isMaterializable()) {
711     // Function has a body somewhere we can't see.
712   } else if (F.isDeclaration()) {
713     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
714             F.hasExternalWeakLinkage(),
715             "invalid linkage type for function declaration", &F);
716   } else {
717     // Verify that this function (which has a body) is not named "llvm.*".  It
718     // is not legal to define intrinsics.
719     Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
720     
721     // Check the entry node
722     BasicBlock *Entry = &F.getEntryBlock();
723     Assert1(pred_begin(Entry) == pred_end(Entry),
724             "Entry block to function must not have predecessors!", Entry);
725     
726     // The address of the entry block cannot be taken, unless it is dead.
727     if (Entry->hasAddressTaken()) {
728       Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
729               "blockaddress may not be used with the entry block!", Entry);
730     }
731   }
732  
733   // If this function is actually an intrinsic, verify that it is only used in
734   // direct call/invokes, never having its "address taken".
735   if (F.getIntrinsicID()) {
736     const User *U;
737     if (F.hasAddressTaken(&U))
738       Assert1(0, "Invalid user of intrinsic instruction!", U); 
739   }
740 }
741
742 // verifyBasicBlock - Verify that a basic block is well formed...
743 //
744 void Verifier::visitBasicBlock(BasicBlock &BB) {
745   InstsInThisBlock.clear();
746
747   // Ensure that basic blocks have terminators!
748   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
749
750   // Check constraints that this basic block imposes on all of the PHI nodes in
751   // it.
752   if (isa<PHINode>(BB.front())) {
753     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
754     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
755     std::sort(Preds.begin(), Preds.end());
756     PHINode *PN;
757     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
758       // Ensure that PHI nodes have at least one entry!
759       Assert1(PN->getNumIncomingValues() != 0,
760               "PHI nodes must have at least one entry.  If the block is dead, "
761               "the PHI should be removed!", PN);
762       Assert1(PN->getNumIncomingValues() == Preds.size(),
763               "PHINode should have one entry for each predecessor of its "
764               "parent basic block!", PN);
765
766       // Get and sort all incoming values in the PHI node...
767       Values.clear();
768       Values.reserve(PN->getNumIncomingValues());
769       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
770         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
771                                         PN->getIncomingValue(i)));
772       std::sort(Values.begin(), Values.end());
773
774       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
775         // Check to make sure that if there is more than one entry for a
776         // particular basic block in this PHI node, that the incoming values are
777         // all identical.
778         //
779         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
780                 Values[i].second == Values[i-1].second,
781                 "PHI node has multiple entries for the same basic block with "
782                 "different incoming values!", PN, Values[i].first,
783                 Values[i].second, Values[i-1].second);
784
785         // Check to make sure that the predecessors and PHI node entries are
786         // matched up.
787         Assert3(Values[i].first == Preds[i],
788                 "PHI node entries do not match predecessors!", PN,
789                 Values[i].first, Preds[i]);
790       }
791     }
792   }
793 }
794
795 void Verifier::visitTerminatorInst(TerminatorInst &I) {
796   // Ensure that terminators only exist at the end of the basic block.
797   Assert1(&I == I.getParent()->getTerminator(),
798           "Terminator found in the middle of a basic block!", I.getParent());
799   visitInstruction(I);
800 }
801
802 void Verifier::visitBranchInst(BranchInst &BI) {
803   if (BI.isConditional()) {
804     Assert2(BI.getCondition()->getType()->isIntegerTy(1),
805             "Branch condition is not 'i1' type!", &BI, BI.getCondition());
806   }
807   visitTerminatorInst(BI);
808 }
809
810 void Verifier::visitReturnInst(ReturnInst &RI) {
811   Function *F = RI.getParent()->getParent();
812   unsigned N = RI.getNumOperands();
813   if (F->getReturnType()->isVoidTy()) 
814     Assert2(N == 0,
815             "Found return instr that returns non-void in Function of void "
816             "return type!", &RI, F->getReturnType());
817   else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
818     // Exactly one return value and it matches the return type. Good.
819   } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
820     // The return type is a struct; check for multiple return values.
821     Assert2(STy->getNumElements() == N,
822             "Incorrect number of return values in ret instruction!",
823             &RI, F->getReturnType());
824     for (unsigned i = 0; i != N; ++i)
825       Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
826               "Function return type does not match operand "
827               "type of return inst!", &RI, F->getReturnType());
828   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
829     // The return type is an array; check for multiple return values.
830     Assert2(ATy->getNumElements() == N,
831             "Incorrect number of return values in ret instruction!",
832             &RI, F->getReturnType());
833     for (unsigned i = 0; i != N; ++i)
834       Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
835               "Function return type does not match operand "
836               "type of return inst!", &RI, F->getReturnType());
837   } else {
838     CheckFailed("Function return type does not match operand "
839                 "type of return inst!", &RI, F->getReturnType());
840   }
841
842   // Check to make sure that the return value has necessary properties for
843   // terminators...
844   visitTerminatorInst(RI);
845 }
846
847 void Verifier::visitSwitchInst(SwitchInst &SI) {
848   // Check to make sure that all of the constants in the switch instruction
849   // have the same type as the switched-on value.
850   const Type *SwitchTy = SI.getCondition()->getType();
851   SmallPtrSet<ConstantInt*, 32> Constants;
852   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i) {
853     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
854             "Switch constants must all be same type as switch value!", &SI);
855     Assert2(Constants.insert(SI.getCaseValue(i)),
856             "Duplicate integer as switch case", &SI, SI.getCaseValue(i));
857   }
858
859   visitTerminatorInst(SI);
860 }
861
862 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
863   Assert1(BI.getAddress()->getType()->isPointerTy(),
864           "Indirectbr operand must have pointer type!", &BI);
865   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
866     Assert1(BI.getDestination(i)->getType()->isLabelTy(),
867             "Indirectbr destinations must all have pointer type!", &BI);
868
869   visitTerminatorInst(BI);
870 }
871
872 void Verifier::visitSelectInst(SelectInst &SI) {
873   Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
874                                           SI.getOperand(2)),
875           "Invalid operands for select instruction!", &SI);
876
877   Assert1(SI.getTrueValue()->getType() == SI.getType(),
878           "Select values must have same type as select instruction!", &SI);
879   visitInstruction(SI);
880 }
881
882 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
883 /// a pass, if any exist, it's an error.
884 ///
885 void Verifier::visitUserOp1(Instruction &I) {
886   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
887 }
888
889 void Verifier::visitTruncInst(TruncInst &I) {
890   // Get the source and destination types
891   const Type *SrcTy = I.getOperand(0)->getType();
892   const Type *DestTy = I.getType();
893
894   // Get the size of the types in bits, we'll need this later
895   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
896   unsigned DestBitSize = DestTy->getScalarSizeInBits();
897
898   Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
899   Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
900   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
901           "trunc source and destination must both be a vector or neither", &I);
902   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
903
904   visitInstruction(I);
905 }
906
907 void Verifier::visitZExtInst(ZExtInst &I) {
908   // Get the source and destination types
909   const Type *SrcTy = I.getOperand(0)->getType();
910   const Type *DestTy = I.getType();
911
912   // Get the size of the types in bits, we'll need this later
913   Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
914   Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
915   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
916           "zext source and destination must both be a vector or neither", &I);
917   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
918   unsigned DestBitSize = DestTy->getScalarSizeInBits();
919
920   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
921
922   visitInstruction(I);
923 }
924
925 void Verifier::visitSExtInst(SExtInst &I) {
926   // Get the source and destination types
927   const Type *SrcTy = I.getOperand(0)->getType();
928   const Type *DestTy = I.getType();
929
930   // Get the size of the types in bits, we'll need this later
931   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
932   unsigned DestBitSize = DestTy->getScalarSizeInBits();
933
934   Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
935   Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
936   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
937           "sext source and destination must both be a vector or neither", &I);
938   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
939
940   visitInstruction(I);
941 }
942
943 void Verifier::visitFPTruncInst(FPTruncInst &I) {
944   // Get the source and destination types
945   const Type *SrcTy = I.getOperand(0)->getType();
946   const Type *DestTy = I.getType();
947   // Get the size of the types in bits, we'll need this later
948   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
949   unsigned DestBitSize = DestTy->getScalarSizeInBits();
950
951   Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
952   Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
953   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
954           "fptrunc source and destination must both be a vector or neither",&I);
955   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
956
957   visitInstruction(I);
958 }
959
960 void Verifier::visitFPExtInst(FPExtInst &I) {
961   // Get the source and destination types
962   const Type *SrcTy = I.getOperand(0)->getType();
963   const Type *DestTy = I.getType();
964
965   // Get the size of the types in bits, we'll need this later
966   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
967   unsigned DestBitSize = DestTy->getScalarSizeInBits();
968
969   Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
970   Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
971   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
972           "fpext source and destination must both be a vector or neither", &I);
973   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
974
975   visitInstruction(I);
976 }
977
978 void Verifier::visitUIToFPInst(UIToFPInst &I) {
979   // Get the source and destination types
980   const Type *SrcTy = I.getOperand(0)->getType();
981   const Type *DestTy = I.getType();
982
983   bool SrcVec = SrcTy->isVectorTy();
984   bool DstVec = DestTy->isVectorTy();
985
986   Assert1(SrcVec == DstVec,
987           "UIToFP source and dest must both be vector or scalar", &I);
988   Assert1(SrcTy->isIntOrIntVectorTy(),
989           "UIToFP source must be integer or integer vector", &I);
990   Assert1(DestTy->isFPOrFPVectorTy(),
991           "UIToFP result must be FP or FP vector", &I);
992
993   if (SrcVec && DstVec)
994     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
995             cast<VectorType>(DestTy)->getNumElements(),
996             "UIToFP source and dest vector length mismatch", &I);
997
998   visitInstruction(I);
999 }
1000
1001 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1002   // Get the source and destination types
1003   const Type *SrcTy = I.getOperand(0)->getType();
1004   const Type *DestTy = I.getType();
1005
1006   bool SrcVec = SrcTy->isVectorTy();
1007   bool DstVec = DestTy->isVectorTy();
1008
1009   Assert1(SrcVec == DstVec,
1010           "SIToFP source and dest must both be vector or scalar", &I);
1011   Assert1(SrcTy->isIntOrIntVectorTy(),
1012           "SIToFP source must be integer or integer vector", &I);
1013   Assert1(DestTy->isFPOrFPVectorTy(),
1014           "SIToFP result must be FP or FP vector", &I);
1015
1016   if (SrcVec && DstVec)
1017     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1018             cast<VectorType>(DestTy)->getNumElements(),
1019             "SIToFP source and dest vector length mismatch", &I);
1020
1021   visitInstruction(I);
1022 }
1023
1024 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1025   // Get the source and destination types
1026   const Type *SrcTy = I.getOperand(0)->getType();
1027   const Type *DestTy = I.getType();
1028
1029   bool SrcVec = SrcTy->isVectorTy();
1030   bool DstVec = DestTy->isVectorTy();
1031
1032   Assert1(SrcVec == DstVec,
1033           "FPToUI source and dest must both be vector or scalar", &I);
1034   Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1035           &I);
1036   Assert1(DestTy->isIntOrIntVectorTy(),
1037           "FPToUI result must be integer or integer vector", &I);
1038
1039   if (SrcVec && DstVec)
1040     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1041             cast<VectorType>(DestTy)->getNumElements(),
1042             "FPToUI source and dest vector length mismatch", &I);
1043
1044   visitInstruction(I);
1045 }
1046
1047 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1048   // Get the source and destination types
1049   const Type *SrcTy = I.getOperand(0)->getType();
1050   const Type *DestTy = I.getType();
1051
1052   bool SrcVec = SrcTy->isVectorTy();
1053   bool DstVec = DestTy->isVectorTy();
1054
1055   Assert1(SrcVec == DstVec,
1056           "FPToSI source and dest must both be vector or scalar", &I);
1057   Assert1(SrcTy->isFPOrFPVectorTy(),
1058           "FPToSI source must be FP or FP vector", &I);
1059   Assert1(DestTy->isIntOrIntVectorTy(),
1060           "FPToSI result must be integer or integer vector", &I);
1061
1062   if (SrcVec && DstVec)
1063     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1064             cast<VectorType>(DestTy)->getNumElements(),
1065             "FPToSI source and dest vector length mismatch", &I);
1066
1067   visitInstruction(I);
1068 }
1069
1070 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1071   // Get the source and destination types
1072   const Type *SrcTy = I.getOperand(0)->getType();
1073   const Type *DestTy = I.getType();
1074
1075   Assert1(SrcTy->isPointerTy(), "PtrToInt source must be pointer", &I);
1076   Assert1(DestTy->isIntegerTy(), "PtrToInt result must be integral", &I);
1077
1078   visitInstruction(I);
1079 }
1080
1081 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1082   // Get the source and destination types
1083   const Type *SrcTy = I.getOperand(0)->getType();
1084   const Type *DestTy = I.getType();
1085
1086   Assert1(SrcTy->isIntegerTy(), "IntToPtr source must be an integral", &I);
1087   Assert1(DestTy->isPointerTy(), "IntToPtr result must be a pointer",&I);
1088
1089   visitInstruction(I);
1090 }
1091
1092 void Verifier::visitBitCastInst(BitCastInst &I) {
1093   // Get the source and destination types
1094   const Type *SrcTy = I.getOperand(0)->getType();
1095   const Type *DestTy = I.getType();
1096
1097   // Get the size of the types in bits, we'll need this later
1098   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1099   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1100
1101   // BitCast implies a no-op cast of type only. No bits change.
1102   // However, you can't cast pointers to anything but pointers.
1103   Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(),
1104           "Bitcast requires both operands to be pointer or neither", &I);
1105   Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1106
1107   // Disallow aggregates.
1108   Assert1(!SrcTy->isAggregateType(),
1109           "Bitcast operand must not be aggregate", &I);
1110   Assert1(!DestTy->isAggregateType(),
1111           "Bitcast type must not be aggregate", &I);
1112
1113   visitInstruction(I);
1114 }
1115
1116 /// visitPHINode - Ensure that a PHI node is well formed.
1117 ///
1118 void Verifier::visitPHINode(PHINode &PN) {
1119   // Ensure that the PHI nodes are all grouped together at the top of the block.
1120   // This can be tested by checking whether the instruction before this is
1121   // either nonexistent (because this is begin()) or is a PHI node.  If not,
1122   // then there is some other instruction before a PHI.
1123   Assert2(&PN == &PN.getParent()->front() || 
1124           isa<PHINode>(--BasicBlock::iterator(&PN)),
1125           "PHI nodes not grouped at top of basic block!",
1126           &PN, PN.getParent());
1127
1128   // Check that all of the values of the PHI node have the same type as the
1129   // result, and that the incoming blocks are really basic blocks.
1130   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1131     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1132             "PHI node operands are not the same type as the result!", &PN);
1133     Assert1(isa<BasicBlock>(PN.getOperand(
1134                 PHINode::getOperandNumForIncomingBlock(i))),
1135             "PHI node incoming block is not a BasicBlock!", &PN);
1136   }
1137
1138   // All other PHI node constraints are checked in the visitBasicBlock method.
1139
1140   visitInstruction(PN);
1141 }
1142
1143 void Verifier::VerifyCallSite(CallSite CS) {
1144   Instruction *I = CS.getInstruction();
1145
1146   Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1147           "Called function must be a pointer!", I);
1148   const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1149
1150   Assert1(FPTy->getElementType()->isFunctionTy(),
1151           "Called function is not pointer to function type!", I);
1152   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1153
1154   // Verify that the correct number of arguments are being passed
1155   if (FTy->isVarArg())
1156     Assert1(CS.arg_size() >= FTy->getNumParams(),
1157             "Called function requires more parameters than were provided!",I);
1158   else
1159     Assert1(CS.arg_size() == FTy->getNumParams(),
1160             "Incorrect number of arguments passed to called function!", I);
1161
1162   // Verify that all arguments to the call match the function type.
1163   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1164     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1165             "Call parameter type does not match function signature!",
1166             CS.getArgument(i), FTy->getParamType(i), I);
1167
1168   const AttrListPtr &Attrs = CS.getAttributes();
1169
1170   Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1171           "Attributes after last parameter!", I);
1172
1173   // Verify call attributes.
1174   VerifyFunctionAttrs(FTy, Attrs, I);
1175
1176   if (FTy->isVarArg())
1177     // Check attributes on the varargs part.
1178     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1179       Attributes Attr = Attrs.getParamAttributes(Idx);
1180
1181       VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1182
1183       Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1184       Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1185               " cannot be used for vararg call arguments!", I);
1186     }
1187
1188   // Verify that there's no metadata unless it's a direct call to an intrinsic.
1189   if (!CS.getCalledFunction() ||
1190       !CS.getCalledFunction()->getName().startswith("llvm.")) {
1191     for (FunctionType::param_iterator PI = FTy->param_begin(),
1192            PE = FTy->param_end(); PI != PE; ++PI)
1193       Assert1(!PI->get()->isMetadataTy(),
1194               "Function has metadata parameter but isn't an intrinsic", I);
1195   }
1196
1197   visitInstruction(*I);
1198 }
1199
1200 void Verifier::visitCallInst(CallInst &CI) {
1201   VerifyCallSite(&CI);
1202
1203   if (Function *F = CI.getCalledFunction())
1204     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1205       visitIntrinsicFunctionCall(ID, CI);
1206 }
1207
1208 void Verifier::visitInvokeInst(InvokeInst &II) {
1209   VerifyCallSite(&II);
1210   visitTerminatorInst(II);
1211 }
1212
1213 /// visitBinaryOperator - Check that both arguments to the binary operator are
1214 /// of the same type!
1215 ///
1216 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1217   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1218           "Both operands to a binary operator are not of the same type!", &B);
1219
1220   switch (B.getOpcode()) {
1221   // Check that integer arithmetic operators are only used with
1222   // integral operands.
1223   case Instruction::Add:
1224   case Instruction::Sub:
1225   case Instruction::Mul:
1226   case Instruction::SDiv:
1227   case Instruction::UDiv:
1228   case Instruction::SRem:
1229   case Instruction::URem:
1230     Assert1(B.getType()->isIntOrIntVectorTy(),
1231             "Integer arithmetic operators only work with integral types!", &B);
1232     Assert1(B.getType() == B.getOperand(0)->getType(),
1233             "Integer arithmetic operators must have same type "
1234             "for operands and result!", &B);
1235     break;
1236   // Check that floating-point arithmetic operators are only used with
1237   // floating-point operands.
1238   case Instruction::FAdd:
1239   case Instruction::FSub:
1240   case Instruction::FMul:
1241   case Instruction::FDiv:
1242   case Instruction::FRem:
1243     Assert1(B.getType()->isFPOrFPVectorTy(),
1244             "Floating-point arithmetic operators only work with "
1245             "floating-point types!", &B);
1246     Assert1(B.getType() == B.getOperand(0)->getType(),
1247             "Floating-point arithmetic operators must have same type "
1248             "for operands and result!", &B);
1249     break;
1250   // Check that logical operators are only used with integral operands.
1251   case Instruction::And:
1252   case Instruction::Or:
1253   case Instruction::Xor:
1254     Assert1(B.getType()->isIntOrIntVectorTy(),
1255             "Logical operators only work with integral types!", &B);
1256     Assert1(B.getType() == B.getOperand(0)->getType(),
1257             "Logical operators must have same type for operands and result!",
1258             &B);
1259     break;
1260   case Instruction::Shl:
1261   case Instruction::LShr:
1262   case Instruction::AShr:
1263     Assert1(B.getType()->isIntOrIntVectorTy(),
1264             "Shifts only work with integral types!", &B);
1265     Assert1(B.getType() == B.getOperand(0)->getType(),
1266             "Shift return type must be same as operands!", &B);
1267     break;
1268   default:
1269     llvm_unreachable("Unknown BinaryOperator opcode!");
1270   }
1271
1272   visitInstruction(B);
1273 }
1274
1275 void Verifier::visitICmpInst(ICmpInst &IC) {
1276   // Check that the operands are the same type
1277   const Type *Op0Ty = IC.getOperand(0)->getType();
1278   const Type *Op1Ty = IC.getOperand(1)->getType();
1279   Assert1(Op0Ty == Op1Ty,
1280           "Both operands to ICmp instruction are not of the same type!", &IC);
1281   // Check that the operands are the right type
1282   Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPointerTy(),
1283           "Invalid operand types for ICmp instruction", &IC);
1284   // Check that the predicate is valid.
1285   Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1286           IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1287           "Invalid predicate in ICmp instruction!", &IC);
1288
1289   visitInstruction(IC);
1290 }
1291
1292 void Verifier::visitFCmpInst(FCmpInst &FC) {
1293   // Check that the operands are the same type
1294   const Type *Op0Ty = FC.getOperand(0)->getType();
1295   const Type *Op1Ty = FC.getOperand(1)->getType();
1296   Assert1(Op0Ty == Op1Ty,
1297           "Both operands to FCmp instruction are not of the same type!", &FC);
1298   // Check that the operands are the right type
1299   Assert1(Op0Ty->isFPOrFPVectorTy(),
1300           "Invalid operand types for FCmp instruction", &FC);
1301   // Check that the predicate is valid.
1302   Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1303           FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1304           "Invalid predicate in FCmp instruction!", &FC);
1305
1306   visitInstruction(FC);
1307 }
1308
1309 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1310   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1311                                               EI.getOperand(1)),
1312           "Invalid extractelement operands!", &EI);
1313   visitInstruction(EI);
1314 }
1315
1316 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1317   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1318                                              IE.getOperand(1),
1319                                              IE.getOperand(2)),
1320           "Invalid insertelement operands!", &IE);
1321   visitInstruction(IE);
1322 }
1323
1324 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1325   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1326                                              SV.getOperand(2)),
1327           "Invalid shufflevector operands!", &SV);
1328   visitInstruction(SV);
1329 }
1330
1331 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1332   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1333   const Type *ElTy =
1334     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
1335                                       Idxs.begin(), Idxs.end());
1336   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1337   Assert2(GEP.getType()->isPointerTy() &&
1338           cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1339           "GEP is not of right type for indices!", &GEP, ElTy);
1340   visitInstruction(GEP);
1341 }
1342
1343 void Verifier::visitLoadInst(LoadInst &LI) {
1344   const PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1345   Assert1(PTy, "Load operand must be a pointer.", &LI);
1346   const Type *ElTy = PTy->getElementType();
1347   Assert2(ElTy == LI.getType(),
1348           "Load result type does not match pointer operand type!", &LI, ElTy);
1349   visitInstruction(LI);
1350 }
1351
1352 void Verifier::visitStoreInst(StoreInst &SI) {
1353   const PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1354   Assert1(PTy, "Store operand must be a pointer.", &SI);
1355   const Type *ElTy = PTy->getElementType();
1356   Assert2(ElTy == SI.getOperand(0)->getType(),
1357           "Stored value type does not match pointer operand type!",
1358           &SI, ElTy);
1359   visitInstruction(SI);
1360 }
1361
1362 void Verifier::visitAllocaInst(AllocaInst &AI) {
1363   const PointerType *PTy = AI.getType();
1364   Assert1(PTy->getAddressSpace() == 0, 
1365           "Allocation instruction pointer not in the generic address space!",
1366           &AI);
1367   Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1368           &AI);
1369   Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1370           "Alloca array size must have integer type", &AI);
1371   visitInstruction(AI);
1372 }
1373
1374 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1375   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1376                                            EVI.idx_begin(), EVI.idx_end()) ==
1377           EVI.getType(),
1378           "Invalid ExtractValueInst operands!", &EVI);
1379   
1380   visitInstruction(EVI);
1381 }
1382
1383 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1384   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1385                                            IVI.idx_begin(), IVI.idx_end()) ==
1386           IVI.getOperand(1)->getType(),
1387           "Invalid InsertValueInst operands!", &IVI);
1388   
1389   visitInstruction(IVI);
1390 }
1391
1392 /// verifyInstruction - Verify that an instruction is well formed.
1393 ///
1394 void Verifier::visitInstruction(Instruction &I) {
1395   BasicBlock *BB = I.getParent();
1396   Assert1(BB, "Instruction not embedded in basic block!", &I);
1397
1398   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
1399     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1400          UI != UE; ++UI)
1401       Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1402               "Only PHI nodes may reference their own value!", &I);
1403   }
1404
1405   // Check that void typed values don't have names
1406   Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1407           "Instruction has a name, but provides a void value!", &I);
1408
1409   // Check that the return value of the instruction is either void or a legal
1410   // value type.
1411   Assert1(I.getType()->isVoidTy() || 
1412           I.getType()->isFirstClassType(),
1413           "Instruction returns a non-scalar type!", &I);
1414
1415   // Check that the instruction doesn't produce metadata. Calls are already
1416   // checked against the callee type.
1417   Assert1(!I.getType()->isMetadataTy() ||
1418           isa<CallInst>(I) || isa<InvokeInst>(I),
1419           "Invalid use of metadata!", &I);
1420
1421   // Check that all uses of the instruction, if they are instructions
1422   // themselves, actually have parent basic blocks.  If the use is not an
1423   // instruction, it is an error!
1424   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1425        UI != UE; ++UI) {
1426     if (Instruction *Used = dyn_cast<Instruction>(*UI))
1427       Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1428               " embedded in a basic block!", &I, Used);
1429     else {
1430       CheckFailed("Use of instruction is not an instruction!", *UI);
1431       return;
1432     }
1433   }
1434
1435   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1436     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1437
1438     // Check to make sure that only first-class-values are operands to
1439     // instructions.
1440     if (!I.getOperand(i)->getType()->isFirstClassType()) {
1441       Assert1(0, "Instruction operands must be first-class values!", &I);
1442     }
1443
1444     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1445       // Check to make sure that the "address of" an intrinsic function is never
1446       // taken.
1447       Assert1(!F->isIntrinsic() || (i + 1 == e && isa<CallInst>(I)),
1448               "Cannot take the address of an intrinsic!", &I);
1449       Assert1(F->getParent() == Mod, "Referencing function in another module!",
1450               &I);
1451     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1452       Assert1(OpBB->getParent() == BB->getParent(),
1453               "Referring to a basic block in another function!", &I);
1454     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1455       Assert1(OpArg->getParent() == BB->getParent(),
1456               "Referring to an argument in another function!", &I);
1457     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1458       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1459               &I);
1460     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1461       BasicBlock *OpBlock = Op->getParent();
1462
1463       // Check that a definition dominates all of its uses.
1464       if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1465         // Invoke results are only usable in the normal destination, not in the
1466         // exceptional destination.
1467         BasicBlock *NormalDest = II->getNormalDest();
1468
1469         Assert2(NormalDest != II->getUnwindDest(),
1470                 "No uses of invoke possible due to dominance structure!",
1471                 Op, &I);
1472
1473         // PHI nodes differ from other nodes because they actually "use" the
1474         // value in the predecessor basic blocks they correspond to.
1475         BasicBlock *UseBlock = BB;
1476         if (isa<PHINode>(I))
1477           UseBlock = dyn_cast<BasicBlock>(I.getOperand(i+1));
1478         Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1479                 Op, &I);
1480
1481         if (isa<PHINode>(I) && UseBlock == OpBlock) {
1482           // Special case of a phi node in the normal destination or the unwind
1483           // destination.
1484           Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1485                   "Invoke result not available in the unwind destination!",
1486                   Op, &I);
1487         } else {
1488           Assert2(DT->dominates(NormalDest, UseBlock) ||
1489                   !DT->isReachableFromEntry(UseBlock),
1490                   "Invoke result does not dominate all uses!", Op, &I);
1491
1492           // If the normal successor of an invoke instruction has multiple
1493           // predecessors, then the normal edge from the invoke is critical,
1494           // so the invoke value can only be live if the destination block
1495           // dominates all of it's predecessors (other than the invoke).
1496           if (!NormalDest->getSinglePredecessor() &&
1497               DT->isReachableFromEntry(UseBlock))
1498             // If it is used by something non-phi, then the other case is that
1499             // 'NormalDest' dominates all of its predecessors other than the
1500             // invoke.  In this case, the invoke value can still be used.
1501             for (pred_iterator PI = pred_begin(NormalDest),
1502                  E = pred_end(NormalDest); PI != E; ++PI)
1503               if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1504                   DT->isReachableFromEntry(*PI)) {
1505                 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1506                 return;
1507               }
1508         }
1509       } else if (isa<PHINode>(I)) {
1510         // PHI nodes are more difficult than other nodes because they actually
1511         // "use" the value in the predecessor basic blocks they correspond to.
1512         BasicBlock *PredBB = dyn_cast<BasicBlock>(I.getOperand(i+1));
1513         Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1514                            !DT->isReachableFromEntry(PredBB)),
1515                 "Instruction does not dominate all uses!", Op, &I);
1516       } else {
1517         if (OpBlock == BB) {
1518           // If they are in the same basic block, make sure that the definition
1519           // comes before the use.
1520           Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1521                   "Instruction does not dominate all uses!", Op, &I);
1522         }
1523
1524         // Definition must dominate use unless use is unreachable!
1525         Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1526                 !DT->isReachableFromEntry(BB),
1527                 "Instruction does not dominate all uses!", Op, &I);
1528       }
1529     } else if (isa<InlineAsm>(I.getOperand(i))) {
1530       Assert1((i + 1 == e && isa<CallInst>(I)) ||
1531               (i + 3 == e && isa<InvokeInst>(I)),
1532               "Cannot take the address of an inline asm!", &I);
1533     }
1534   }
1535   InstsInThisBlock.insert(&I);
1536
1537   VerifyType(I.getType());
1538 }
1539
1540 /// VerifyType - Verify that a type is well formed.
1541 ///
1542 void Verifier::VerifyType(const Type *Ty) {
1543   if (!Types.insert(Ty)) return;
1544
1545   Assert1(Context == &Ty->getContext(),
1546           "Type context does not match Module context!", Ty);
1547
1548   switch (Ty->getTypeID()) {
1549   case Type::FunctionTyID: {
1550     const FunctionType *FTy = cast<FunctionType>(Ty);
1551
1552     const Type *RetTy = FTy->getReturnType();
1553     Assert2(FunctionType::isValidReturnType(RetTy),
1554             "Function type with invalid return type", RetTy, FTy);
1555     VerifyType(RetTy);
1556
1557     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1558       const Type *ElTy = FTy->getParamType(i);
1559       Assert2(FunctionType::isValidArgumentType(ElTy),
1560               "Function type with invalid parameter type", ElTy, FTy);
1561       VerifyType(ElTy);
1562     }
1563   } break;
1564   case Type::StructTyID: {
1565     const StructType *STy = cast<StructType>(Ty);
1566     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1567       const Type *ElTy = STy->getElementType(i);
1568       Assert2(StructType::isValidElementType(ElTy),
1569               "Structure type with invalid element type", ElTy, STy);
1570       VerifyType(ElTy);
1571     }
1572   } break;
1573   case Type::UnionTyID: {
1574     const UnionType *UTy = cast<UnionType>(Ty);
1575     for (unsigned i = 0, e = UTy->getNumElements(); i != e; ++i) {
1576       const Type *ElTy = UTy->getElementType(i);
1577       Assert2(UnionType::isValidElementType(ElTy),
1578               "Union type with invalid element type", ElTy, UTy);
1579       VerifyType(ElTy);
1580     }
1581   } break;
1582   case Type::ArrayTyID: {
1583     const ArrayType *ATy = cast<ArrayType>(Ty);
1584     Assert1(ArrayType::isValidElementType(ATy->getElementType()),
1585             "Array type with invalid element type", ATy);
1586     VerifyType(ATy->getElementType());
1587   } break;
1588   case Type::PointerTyID: {
1589     const PointerType *PTy = cast<PointerType>(Ty);
1590     Assert1(PointerType::isValidElementType(PTy->getElementType()),
1591             "Pointer type with invalid element type", PTy);
1592     VerifyType(PTy->getElementType());
1593   } break;
1594   case Type::VectorTyID: {
1595     const VectorType *VTy = cast<VectorType>(Ty);
1596     Assert1(VectorType::isValidElementType(VTy->getElementType()),
1597             "Vector type with invalid element type", VTy);
1598     VerifyType(VTy->getElementType());
1599   } break;
1600   default:
1601     break;
1602   }
1603 }
1604
1605 // Flags used by TableGen to mark intrinsic parameters with the
1606 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1607 static const unsigned ExtendedElementVectorType = 0x40000000;
1608 static const unsigned TruncatedElementVectorType = 0x20000000;
1609
1610 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1611 ///
1612 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1613   Function *IF = CI.getCalledFunction();
1614   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1615           IF);
1616
1617 #define GET_INTRINSIC_VERIFIER
1618 #include "llvm/Intrinsics.gen"
1619 #undef GET_INTRINSIC_VERIFIER
1620
1621   // If the intrinsic takes MDNode arguments, verify that they are either global
1622   // or are local to *this* function.
1623   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1624     if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1625       visitMDNode(*MD, CI.getParent()->getParent());
1626
1627   switch (ID) {
1628   default:
1629     break;
1630   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
1631     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1632                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1633     MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1634     Assert1(MD->getNumOperands() == 1,
1635                 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1636   } break;
1637   case Intrinsic::memcpy:
1638   case Intrinsic::memmove:
1639   case Intrinsic::memset:
1640     Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1641             "alignment argument of memory intrinsics must be a constant int",
1642             &CI);
1643     break;
1644   case Intrinsic::gcroot:
1645   case Intrinsic::gcwrite:
1646   case Intrinsic::gcread:
1647     if (ID == Intrinsic::gcroot) {
1648       AllocaInst *AI =
1649         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1650       Assert1(AI && AI->getType()->getElementType()->isPointerTy(),
1651               "llvm.gcroot parameter #1 must be a pointer alloca.", &CI);
1652       Assert1(isa<Constant>(CI.getArgOperand(1)),
1653               "llvm.gcroot parameter #2 must be a constant.", &CI);
1654     }
1655
1656     Assert1(CI.getParent()->getParent()->hasGC(),
1657             "Enclosing function does not use GC.", &CI);
1658     break;
1659   case Intrinsic::init_trampoline:
1660     Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1661             "llvm.init_trampoline parameter #2 must resolve to a function.",
1662             &CI);
1663     break;
1664   case Intrinsic::prefetch:
1665     Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1666             isa<ConstantInt>(CI.getArgOperand(2)) &&
1667             cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1668             cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1669             "invalid arguments to llvm.prefetch",
1670             &CI);
1671     break;
1672   case Intrinsic::stackprotector:
1673     Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1674             "llvm.stackprotector parameter #2 must resolve to an alloca.",
1675             &CI);
1676     break;
1677   case Intrinsic::lifetime_start:
1678   case Intrinsic::lifetime_end:
1679   case Intrinsic::invariant_start:
1680     Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1681             "size argument of memory use markers must be a constant integer",
1682             &CI);
1683     break;
1684   case Intrinsic::invariant_end:
1685     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1686             "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1687     break;
1688   }
1689 }
1690
1691 /// Produce a string to identify an intrinsic parameter or return value.
1692 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1693 /// parameters beginning with NumRets.
1694 ///
1695 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1696   if (ArgNo >= NumRets)
1697     return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1698   if (NumRets == 1)
1699     return "Intrinsic result type";
1700   return "Intrinsic result type #" + utostr(ArgNo);
1701 }
1702
1703 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
1704                                 int VT, unsigned ArgNo, std::string &Suffix) {
1705   const FunctionType *FTy = F->getFunctionType();
1706
1707   unsigned NumElts = 0;
1708   const Type *EltTy = Ty;
1709   const VectorType *VTy = dyn_cast<VectorType>(Ty);
1710   if (VTy) {
1711     EltTy = VTy->getElementType();
1712     NumElts = VTy->getNumElements();
1713   }
1714
1715   const Type *RetTy = FTy->getReturnType();
1716   const StructType *ST = dyn_cast<StructType>(RetTy);
1717   unsigned NumRetVals;
1718   if (RetTy->isVoidTy())
1719     NumRetVals = 0;
1720   else if (ST)
1721     NumRetVals = ST->getNumElements();
1722   else
1723     NumRetVals = 1;
1724
1725   if (VT < 0) {
1726     int Match = ~VT;
1727
1728     // Check flags that indicate a type that is an integral vector type with
1729     // elements that are larger or smaller than the elements of the matched
1730     // type.
1731     if ((Match & (ExtendedElementVectorType |
1732                   TruncatedElementVectorType)) != 0) {
1733       const IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1734       if (!VTy || !IEltTy) {
1735         CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1736                     "an integral vector type.", F);
1737         return false;
1738       }
1739       // Adjust the current Ty (in the opposite direction) rather than
1740       // the type being matched against.
1741       if ((Match & ExtendedElementVectorType) != 0) {
1742         if ((IEltTy->getBitWidth() & 1) != 0) {
1743           CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector "
1744                       "element bit-width is odd.", F);
1745           return false;
1746         }
1747         Ty = VectorType::getTruncatedElementVectorType(VTy);
1748       } else
1749         Ty = VectorType::getExtendedElementVectorType(VTy);
1750       Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1751     }
1752
1753     if (Match <= static_cast<int>(NumRetVals - 1)) {
1754       if (ST)
1755         RetTy = ST->getElementType(Match);
1756
1757       if (Ty != RetTy) {
1758         CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1759                     "match return type.", F);
1760         return false;
1761       }
1762     } else {
1763       if (Ty != FTy->getParamType(Match - NumRetVals)) {
1764         CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1765                     "match parameter %" + utostr(Match - NumRetVals) + ".", F);
1766         return false;
1767       }
1768     }
1769   } else if (VT == MVT::iAny) {
1770     if (!EltTy->isIntegerTy()) {
1771       CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1772                   "an integer type.", F);
1773       return false;
1774     }
1775
1776     unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1777     Suffix += ".";
1778
1779     if (EltTy != Ty)
1780       Suffix += "v" + utostr(NumElts);
1781
1782     Suffix += "i" + utostr(GotBits);
1783
1784     // Check some constraints on various intrinsics.
1785     switch (ID) {
1786     default: break; // Not everything needs to be checked.
1787     case Intrinsic::bswap:
1788       if (GotBits < 16 || GotBits % 16 != 0) {
1789         CheckFailed("Intrinsic requires even byte width argument", F);
1790         return false;
1791       }
1792       break;
1793     }
1794   } else if (VT == MVT::fAny) {
1795     if (!EltTy->isFloatingPointTy()) {
1796       CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1797                   "a floating-point type.", F);
1798       return false;
1799     }
1800
1801     Suffix += ".";
1802
1803     if (EltTy != Ty)
1804       Suffix += "v" + utostr(NumElts);
1805
1806     Suffix += EVT::getEVT(EltTy).getEVTString();
1807   } else if (VT == MVT::vAny) {
1808     if (!VTy) {
1809       CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.",
1810                   F);
1811       return false;
1812     }
1813     Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1814   } else if (VT == MVT::iPTR) {
1815     if (!Ty->isPointerTy()) {
1816       CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1817                   "pointer and a pointer is required.", F);
1818       return false;
1819     }
1820   } else if (VT == MVT::iPTRAny) {
1821     // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1822     // and iPTR. In the verifier, we can not distinguish which case we have so
1823     // allow either case to be legal.
1824     if (const PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1825       EVT PointeeVT = EVT::getEVT(PTyp->getElementType(), true);
1826       if (PointeeVT == MVT::Other) {
1827         CheckFailed("Intrinsic has pointer to complex type.");
1828         return false;
1829       }
1830       Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1831         PointeeVT.getEVTString();
1832     } else {
1833       CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1834                   "pointer and a pointer is required.", F);
1835       return false;
1836     }
1837   } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1838     EVT VVT = EVT((MVT::SimpleValueType)VT);
1839
1840     // If this is a vector argument, verify the number and type of elements.
1841     if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1842       CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1843       return false;
1844     }
1845
1846     if (VVT.getVectorNumElements() != NumElts) {
1847       CheckFailed("Intrinsic prototype has incorrect number of "
1848                   "vector elements!", F);
1849       return false;
1850     }
1851   } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) != 
1852              EltTy) {
1853     CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F);
1854     return false;
1855   } else if (EltTy != Ty) {
1856     CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector "
1857                 "and a scalar is required.", F);
1858     return false;
1859   }
1860
1861   return true;
1862 }
1863
1864 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1865 /// Intrinsics.gen.  This implements a little state machine that verifies the
1866 /// prototype of intrinsics.
1867 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1868                                         unsigned NumRetVals,
1869                                         unsigned NumParams, ...) {
1870   va_list VA;
1871   va_start(VA, NumParams);
1872   const FunctionType *FTy = F->getFunctionType();
1873
1874   // For overloaded intrinsics, the Suffix of the function name must match the
1875   // types of the arguments. This variable keeps track of the expected
1876   // suffix, to be checked at the end.
1877   std::string Suffix;
1878
1879   if (FTy->getNumParams() + FTy->isVarArg() != NumParams) {
1880     CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1881     return;
1882   }
1883
1884   const Type *Ty = FTy->getReturnType();
1885   const StructType *ST = dyn_cast<StructType>(Ty);
1886
1887   if (NumRetVals == 0 && !Ty->isVoidTy()) {
1888     CheckFailed("Intrinsic should return void", F);
1889     return;
1890   }
1891   
1892   // Verify the return types.
1893   if (ST && ST->getNumElements() != NumRetVals) {
1894     CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1895     return;
1896   }
1897   
1898   for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) {
1899     int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1900
1901     if (ST) Ty = ST->getElementType(ArgNo);
1902     if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1903       break;
1904   }
1905
1906   // Verify the parameter types.
1907   for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) {
1908     int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1909
1910     if (VT == MVT::isVoid && ArgNo > 0) {
1911       if (!FTy->isVarArg())
1912         CheckFailed("Intrinsic prototype has no '...'!", F);
1913       break;
1914     }
1915
1916     if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT,
1917                           ArgNo + NumRetVals, Suffix))
1918       break;
1919   }
1920
1921   va_end(VA);
1922
1923   // For intrinsics without pointer arguments, if we computed a Suffix then the
1924   // intrinsic is overloaded and we need to make sure that the name of the
1925   // function is correct. We add the suffix to the name of the intrinsic and
1926   // compare against the given function name. If they are not the same, the
1927   // function name is invalid. This ensures that overloading of intrinsics
1928   // uses a sane and consistent naming convention.  Note that intrinsics with
1929   // pointer argument may or may not be overloaded so we will check assuming it
1930   // has a suffix and not.
1931   if (!Suffix.empty()) {
1932     std::string Name(Intrinsic::getName(ID));
1933     if (Name + Suffix != F->getName()) {
1934       CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1935                   F->getName().substr(Name.length()) + "'. It should be '" +
1936                   Suffix + "'", F);
1937     }
1938   }
1939
1940   // Check parameter attributes.
1941   Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
1942           "Intrinsic has wrong parameter attributes!", F);
1943 }
1944
1945
1946 //===----------------------------------------------------------------------===//
1947 //  Implement the public interfaces to this file...
1948 //===----------------------------------------------------------------------===//
1949
1950 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1951   return new Verifier(action);
1952 }
1953
1954
1955 /// verifyFunction - Check a function for errors, printing messages on stderr.
1956 /// Return true if the function is corrupt.
1957 ///
1958 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1959   Function &F = const_cast<Function&>(f);
1960   assert(!F.isDeclaration() && "Cannot verify external functions");
1961
1962   FunctionPassManager FPM(F.getParent());
1963   Verifier *V = new Verifier(action);
1964   FPM.add(V);
1965   FPM.run(F);
1966   return V->Broken;
1967 }
1968
1969 /// verifyModule - Check a module for errors, printing messages on stderr.
1970 /// Return true if the module is corrupt.
1971 ///
1972 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1973                         std::string *ErrorInfo) {
1974   PassManager PM;
1975   Verifier *V = new Verifier(action);
1976   PM.add(V);
1977   PM.run(const_cast<Module&>(M));
1978
1979   if (ErrorInfo && V->Broken)
1980     *ErrorInfo = V->MessagesStr.str();
1981   return V->Broken;
1982 }