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