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