Minor cleanup.
[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/Module.h"
49 #include "llvm/ModuleProvider.h"
50 #include "llvm/Pass.h"
51 #include "llvm/PassManager.h"
52 #include "llvm/Analysis/Dominators.h"
53 #include "llvm/Assembly/Writer.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/Support/CallSite.h"
56 #include "llvm/Support/CFG.h"
57 #include "llvm/Support/InstVisitor.h"
58 #include "llvm/Support/Streams.h"
59 #include "llvm/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/StringExtras.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/Support/Compiler.h"
64 #include <algorithm>
65 #include <sstream>
66 #include <cstdarg>
67 using namespace llvm;
68
69 namespace {  // Anonymous namespace for class
70   struct VISIBILITY_HIDDEN PreVerifier : public FunctionPass {
71     static char ID; // Pass ID, replacement for typeid
72
73     PreVerifier() : FunctionPass((intptr_t)&ID) { }
74
75     // Check that the prerequisites for successful DominatorTree construction
76     // are satisfied.
77     bool runOnFunction(Function &F) {
78       bool Broken = false;
79
80       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
81         if (I->empty() || !I->back().isTerminator()) {
82           cerr << "Basic Block does not have terminator!\n";
83           WriteAsOperand(*cerr, I, true);
84           cerr << "\n";
85           Broken = true;
86         }
87       }
88
89       if (Broken)
90         abort();
91
92       return false;
93     }
94   };
95 }
96
97 char PreVerifier::ID = 0;
98 static RegisterPass<PreVerifier>
99 PreVer("preverify", "Preliminary module verification");
100 static const PassInfo *const PreVerifyID = &PreVer;
101
102 namespace {
103   struct VISIBILITY_HIDDEN
104      Verifier : public FunctionPass, InstVisitor<Verifier> {
105     static char ID; // Pass ID, replacement for typeid
106     bool Broken;          // Is this module found to be broken?
107     bool RealPass;        // Are we not being run by a PassManager?
108     VerifierFailureAction action;
109                           // What to do if verification fails.
110     Module *Mod;          // Module we are verifying right now
111     DominatorTree *DT; // Dominator Tree, caution can be null!
112     std::stringstream msgs;  // A stringstream to collect messages
113
114     /// InstInThisBlock - when verifying a basic block, keep track of all of the
115     /// instructions we have seen so far.  This allows us to do efficient
116     /// dominance checks for the case when an instruction has an operand that is
117     /// an instruction in the same block.
118     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
119
120     Verifier()
121       : FunctionPass((intptr_t)&ID), 
122       Broken(false), RealPass(true), action(AbortProcessAction),
123       DT(0), msgs( std::ios::app | std::ios::out ) {}
124     explicit Verifier(VerifierFailureAction ctn)
125       : FunctionPass((intptr_t)&ID), 
126       Broken(false), RealPass(true), action(ctn), DT(0),
127       msgs( std::ios::app | std::ios::out ) {}
128     explicit Verifier(bool AB)
129       : FunctionPass((intptr_t)&ID), 
130       Broken(false), RealPass(true),
131       action( AB ? AbortProcessAction : PrintMessageAction), DT(0),
132       msgs( std::ios::app | std::ios::out ) {}
133     explicit Verifier(DominatorTree &dt)
134       : FunctionPass((intptr_t)&ID), 
135       Broken(false), RealPass(false), action(PrintMessageAction),
136       DT(&dt), msgs( std::ios::app | std::ios::out ) {}
137
138
139     bool doInitialization(Module &M) {
140       Mod = &M;
141       verifyTypeSymbolTable(M.getTypeSymbolTable());
142
143       // If this is a real pass, in a pass manager, we must abort before
144       // returning back to the pass manager, or else the pass manager may try to
145       // run other passes on the broken module.
146       if (RealPass)
147         return abortIfBroken();
148       return false;
149     }
150
151     bool runOnFunction(Function &F) {
152       // Get dominator information if we are being run by PassManager
153       if (RealPass) DT = &getAnalysis<DominatorTree>();
154
155       Mod = F.getParent();
156
157       visit(F);
158       InstsInThisBlock.clear();
159
160       // If this is a real pass, in a pass manager, we must abort before
161       // returning back to the pass manager, or else the pass manager may try to
162       // run other passes on the broken module.
163       if (RealPass)
164         return abortIfBroken();
165
166       return false;
167     }
168
169     bool doFinalization(Module &M) {
170       // Scan through, checking all of the external function's linkage now...
171       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
172         visitGlobalValue(*I);
173
174         // Check to make sure function prototypes are okay.
175         if (I->isDeclaration()) visitFunction(*I);
176       }
177
178       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
179            I != E; ++I)
180         visitGlobalVariable(*I);
181
182       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 
183            I != E; ++I)
184         visitGlobalAlias(*I);
185
186       // If the module is broken, abort at this time.
187       return abortIfBroken();
188     }
189
190     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
191       AU.setPreservesAll();
192       AU.addRequiredID(PreVerifyID);
193       if (RealPass)
194         AU.addRequired<DominatorTree>();
195     }
196
197     /// abortIfBroken - If the module is broken and we are supposed to abort on
198     /// this condition, do so.
199     ///
200     bool abortIfBroken() {
201       if (!Broken) return false;
202       msgs << "Broken module found, ";
203       switch (action) {
204       default: assert(0 && "Unknown action");
205       case AbortProcessAction:
206         msgs << "compilation aborted!\n";
207         cerr << msgs.str();
208         abort();
209       case PrintMessageAction:
210         msgs << "verification continues.\n";
211         cerr << msgs.str();
212         return false;
213       case ReturnStatusAction:
214         msgs << "compilation terminated.\n";
215         return Broken;
216       }
217     }
218
219
220     // Verification methods...
221     void verifyTypeSymbolTable(TypeSymbolTable &ST);
222     void visitGlobalValue(GlobalValue &GV);
223     void visitGlobalVariable(GlobalVariable &GV);
224     void visitGlobalAlias(GlobalAlias &GA);
225     void visitFunction(Function &F);
226     void visitBasicBlock(BasicBlock &BB);
227     void visitTruncInst(TruncInst &I);
228     void visitZExtInst(ZExtInst &I);
229     void visitSExtInst(SExtInst &I);
230     void visitFPTruncInst(FPTruncInst &I);
231     void visitFPExtInst(FPExtInst &I);
232     void visitFPToUIInst(FPToUIInst &I);
233     void visitFPToSIInst(FPToSIInst &I);
234     void visitUIToFPInst(UIToFPInst &I);
235     void visitSIToFPInst(SIToFPInst &I);
236     void visitIntToPtrInst(IntToPtrInst &I);
237     void visitPtrToIntInst(PtrToIntInst &I);
238     void visitBitCastInst(BitCastInst &I);
239     void visitPHINode(PHINode &PN);
240     void visitBinaryOperator(BinaryOperator &B);
241     void visitICmpInst(ICmpInst &IC);
242     void visitFCmpInst(FCmpInst &FC);
243     void visitExtractElementInst(ExtractElementInst &EI);
244     void visitInsertElementInst(InsertElementInst &EI);
245     void visitShuffleVectorInst(ShuffleVectorInst &EI);
246     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
247     void visitCallInst(CallInst &CI);
248     void visitInvokeInst(InvokeInst &II);
249     void visitGetElementPtrInst(GetElementPtrInst &GEP);
250     void visitLoadInst(LoadInst &LI);
251     void visitStoreInst(StoreInst &SI);
252     void visitInstruction(Instruction &I);
253     void visitTerminatorInst(TerminatorInst &I);
254     void visitReturnInst(ReturnInst &RI);
255     void visitSwitchInst(SwitchInst &SI);
256     void visitSelectInst(SelectInst &SI);
257     void visitUserOp1(Instruction &I);
258     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
259     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
260     void visitAllocationInst(AllocationInst &AI);
261     void visitExtractValueInst(ExtractValueInst &EVI);
262     void visitInsertValueInst(InsertValueInst &IVI);
263
264     void VerifyCallSite(CallSite CS);
265     void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
266                                   unsigned Count, ...);
267     void VerifyAttrs(ParameterAttributes Attrs, const Type *Ty,
268                      bool isReturnValue, const Value *V);
269     void VerifyFunctionAttrs(const FunctionType *FT, const PAListPtr &Attrs,
270                              const Value *V);
271
272     void WriteValue(const Value *V) {
273       if (!V) return;
274       if (isa<Instruction>(V)) {
275         msgs << *V;
276       } else {
277         WriteAsOperand(msgs, V, true, Mod);
278         msgs << "\n";
279       }
280     }
281
282     void WriteType(const Type *T) {
283       if ( !T ) return;
284       WriteTypeSymbolic(msgs, T, Mod );
285     }
286
287
288     // CheckFailed - A check failed, so print out the condition and the message
289     // that failed.  This provides a nice place to put a breakpoint if you want
290     // to see why something is not correct.
291     void CheckFailed(const std::string &Message,
292                      const Value *V1 = 0, const Value *V2 = 0,
293                      const Value *V3 = 0, const Value *V4 = 0) {
294       msgs << Message << "\n";
295       WriteValue(V1);
296       WriteValue(V2);
297       WriteValue(V3);
298       WriteValue(V4);
299       Broken = true;
300     }
301
302     void CheckFailed( const std::string& Message, const Value* V1,
303                       const Type* T2, const Value* V3 = 0 ) {
304       msgs << Message << "\n";
305       WriteValue(V1);
306       WriteType(T2);
307       WriteValue(V3);
308       Broken = true;
309     }
310   };
311 } // End anonymous namespace
312
313 char Verifier::ID = 0;
314 static RegisterPass<Verifier> X("verify", "Module Verifier");
315
316 // Assert - We know that cond should be true, if not print an error message.
317 #define Assert(C, M) \
318   do { if (!(C)) { CheckFailed(M); return; } } while (0)
319 #define Assert1(C, M, V1) \
320   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
321 #define Assert2(C, M, V1, V2) \
322   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
323 #define Assert3(C, M, V1, V2, V3) \
324   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
325 #define Assert4(C, M, V1, V2, V3, V4) \
326   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
327
328
329 void Verifier::visitGlobalValue(GlobalValue &GV) {
330   Assert1(!GV.isDeclaration() ||
331           GV.hasExternalLinkage() ||
332           GV.hasDLLImportLinkage() ||
333           GV.hasExternalWeakLinkage() ||
334           GV.hasGhostLinkage() ||
335           (isa<GlobalAlias>(GV) &&
336            (GV.hasInternalLinkage() || GV.hasWeakLinkage())),
337   "Global is external, but doesn't have external or dllimport or weak linkage!",
338           &GV);
339
340   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
341           "Global is marked as dllimport, but not external", &GV);
342   
343   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
344           "Only global variables can have appending linkage!", &GV);
345
346   if (GV.hasAppendingLinkage()) {
347     GlobalVariable &GVar = cast<GlobalVariable>(GV);
348     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
349             "Only global arrays can have appending linkage!", &GV);
350   }
351 }
352
353 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
354   if (GV.hasInitializer()) {
355     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
356             "Global variable initializer type does not match global "
357             "variable type!", &GV);
358   } else {
359     Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
360             GV.hasExternalWeakLinkage(),
361             "invalid linkage type for global declaration", &GV);
362   }
363
364   visitGlobalValue(GV);
365 }
366
367 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
368   Assert1(!GA.getName().empty(),
369           "Alias name cannot be empty!", &GA);
370   Assert1(GA.hasExternalLinkage() || GA.hasInternalLinkage() ||
371           GA.hasWeakLinkage(),
372           "Alias should have external or external weak linkage!", &GA);
373   Assert1(GA.getAliasee(),
374           "Aliasee cannot be NULL!", &GA);
375   Assert1(GA.getType() == GA.getAliasee()->getType(),
376           "Alias and aliasee types should match!", &GA);
377
378   if (!isa<GlobalValue>(GA.getAliasee())) {
379     const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
380     Assert1(CE && CE->getOpcode() == Instruction::BitCast &&
381             isa<GlobalValue>(CE->getOperand(0)),
382             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
383             &GA);
384   }
385
386   const GlobalValue* Aliasee = GA.resolveAliasedGlobal();
387   Assert1(Aliasee,
388           "Aliasing chain should end with function or global variable", &GA);
389
390   visitGlobalValue(GA);
391 }
392
393 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
394 }
395
396 // VerifyAttrs - Check the given parameter attributes for an argument or return
397 // value of the specified type.  The value V is printed in error messages.
398 void Verifier::VerifyAttrs(ParameterAttributes Attrs, const Type *Ty, 
399                            bool isReturnValue, const Value *V) {
400   if (Attrs == ParamAttr::None)
401     return;
402
403   if (isReturnValue) {
404     ParameterAttributes RetI = Attrs & ParamAttr::ParameterOnly;
405     Assert1(!RetI, "Attribute " + ParamAttr::getAsString(RetI) +
406             " does not apply to return values!", V);
407   } else {
408     ParameterAttributes ParmI = Attrs & ParamAttr::ReturnOnly;
409     Assert1(!ParmI, "Attribute " + ParamAttr::getAsString(ParmI) +
410             " only applies to return values!", V);
411   }
412
413   for (unsigned i = 0;
414        i < array_lengthof(ParamAttr::MutuallyIncompatible); ++i) {
415     ParameterAttributes MutI = Attrs & ParamAttr::MutuallyIncompatible[i];
416     Assert1(!(MutI & (MutI - 1)), "Attributes " +
417             ParamAttr::getAsString(MutI) + " are incompatible!", V);
418   }
419
420   ParameterAttributes TypeI = Attrs & ParamAttr::typeIncompatible(Ty);
421   Assert1(!TypeI, "Wrong type for attribute " +
422           ParamAttr::getAsString(TypeI), V);
423
424   ParameterAttributes ByValI = Attrs & ParamAttr::ByVal;
425   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
426     Assert1(!ByValI || PTy->getElementType()->isSized(),
427             "Attribute " + ParamAttr::getAsString(ByValI) +
428             " does not support unsized types!", V);
429   } else {
430     Assert1(!ByValI,
431             "Attribute " + ParamAttr::getAsString(ByValI) +
432             " only applies to parameters with pointer type!", V);
433   }
434 }
435
436 // VerifyFunctionAttrs - Check parameter attributes against a function type.
437 // The value V is printed in error messages.
438 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
439                                    const PAListPtr &Attrs,
440                                    const Value *V) {
441   if (Attrs.isEmpty())
442     return;
443
444   bool SawNest = false;
445
446   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
447     const ParamAttrsWithIndex &Attr = Attrs.getSlot(i);
448
449     const Type *Ty;
450     if (Attr.Index == 0)
451       Ty = FT->getReturnType();
452     else if (Attr.Index-1 < FT->getNumParams())
453       Ty = FT->getParamType(Attr.Index-1);
454     else
455       break;  // VarArgs attributes, don't verify.
456     
457     VerifyAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
458
459     if (Attr.Attrs & ParamAttr::Nest) {
460       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
461       SawNest = true;
462     }
463
464     if (Attr.Attrs & ParamAttr::StructRet)
465       Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
466   }
467 }
468
469 // visitFunction - Verify that a function is ok.
470 //
471 void Verifier::visitFunction(Function &F) {
472   // Check function arguments.
473   const FunctionType *FT = F.getFunctionType();
474   unsigned NumArgs = F.arg_size();
475
476   Assert2(FT->getNumParams() == NumArgs,
477           "# formal arguments must match # of arguments for function type!",
478           &F, FT);
479   Assert1(F.getReturnType()->isFirstClassType() ||
480           F.getReturnType() == Type::VoidTy || 
481           isa<StructType>(F.getReturnType()),
482           "Functions cannot return aggregate values!", &F);
483
484   Assert1(!F.hasStructRetAttr() || F.getReturnType() == Type::VoidTy,
485           "Invalid struct return type!", &F);
486
487   const PAListPtr &Attrs = F.getParamAttrs();
488
489   Assert1(Attrs.isEmpty() ||
490           Attrs.getSlot(Attrs.getNumSlots()-1).Index <= FT->getNumParams(),
491           "Attributes after last parameter!", &F);
492
493   // Check function attributes.
494   VerifyFunctionAttrs(FT, Attrs, &F);
495
496   // Check that this function meets the restrictions on this calling convention.
497   switch (F.getCallingConv()) {
498   default:
499     break;
500   case CallingConv::C:
501   case CallingConv::X86_SSECall:
502     break;
503   case CallingConv::Fast:
504   case CallingConv::Cold:
505   case CallingConv::X86_FastCall:
506     Assert1(!F.isVarArg(),
507             "Varargs functions must have C calling conventions!", &F);
508     break;
509   }
510   
511   // Check that the argument values match the function type for this function...
512   unsigned i = 0;
513   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
514        I != E; ++I, ++i) {
515     Assert2(I->getType() == FT->getParamType(i),
516             "Argument value does not match function argument type!",
517             I, FT->getParamType(i));
518     Assert1(I->getType()->isFirstClassType(),
519             "Function arguments must have first-class types!", I);
520   }
521
522   if (F.isDeclaration()) {
523     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
524             F.hasExternalWeakLinkage() || F.hasGhostLinkage(),
525             "invalid linkage type for function declaration", &F);
526   } else {
527     // Verify that this function (which has a body) is not named "llvm.*".  It
528     // is not legal to define intrinsics.
529     if (F.getName().size() >= 5)
530       Assert1(F.getName().substr(0, 5) != "llvm.",
531               "llvm intrinsics cannot be defined!", &F);
532     
533     // Check the entry node
534     BasicBlock *Entry = &F.getEntryBlock();
535     Assert1(pred_begin(Entry) == pred_end(Entry),
536             "Entry block to function must not have predecessors!", Entry);
537   }
538 }
539
540
541 // verifyBasicBlock - Verify that a basic block is well formed...
542 //
543 void Verifier::visitBasicBlock(BasicBlock &BB) {
544   InstsInThisBlock.clear();
545
546   // Ensure that basic blocks have terminators!
547   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
548
549   // Check constraints that this basic block imposes on all of the PHI nodes in
550   // it.
551   if (isa<PHINode>(BB.front())) {
552     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
553     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
554     std::sort(Preds.begin(), Preds.end());
555     PHINode *PN;
556     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
557
558       // Ensure that PHI nodes have at least one entry!
559       Assert1(PN->getNumIncomingValues() != 0,
560               "PHI nodes must have at least one entry.  If the block is dead, "
561               "the PHI should be removed!", PN);
562       Assert1(PN->getNumIncomingValues() == Preds.size(),
563               "PHINode should have one entry for each predecessor of its "
564               "parent basic block!", PN);
565
566       // Get and sort all incoming values in the PHI node...
567       Values.clear();
568       Values.reserve(PN->getNumIncomingValues());
569       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
570         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
571                                         PN->getIncomingValue(i)));
572       std::sort(Values.begin(), Values.end());
573
574       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
575         // Check to make sure that if there is more than one entry for a
576         // particular basic block in this PHI node, that the incoming values are
577         // all identical.
578         //
579         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
580                 Values[i].second == Values[i-1].second,
581                 "PHI node has multiple entries for the same basic block with "
582                 "different incoming values!", PN, Values[i].first,
583                 Values[i].second, Values[i-1].second);
584
585         // Check to make sure that the predecessors and PHI node entries are
586         // matched up.
587         Assert3(Values[i].first == Preds[i],
588                 "PHI node entries do not match predecessors!", PN,
589                 Values[i].first, Preds[i]);
590       }
591     }
592   }
593 }
594
595 void Verifier::visitTerminatorInst(TerminatorInst &I) {
596   // Ensure that terminators only exist at the end of the basic block.
597   Assert1(&I == I.getParent()->getTerminator(),
598           "Terminator found in the middle of a basic block!", I.getParent());
599   visitInstruction(I);
600 }
601
602 void Verifier::visitReturnInst(ReturnInst &RI) {
603   Function *F = RI.getParent()->getParent();
604   unsigned N = RI.getNumOperands();
605   if (F->getReturnType() == Type::VoidTy) 
606     Assert2(N == 0,
607             "Found return instr that returns void in Function of non-void "
608             "return type!", &RI, F->getReturnType());
609   else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
610     // Exactly one return value and it matches the return type. Good.
611   } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
612     // The return type is a struct; check for multiple return values.
613     Assert2(STy->getNumElements() == N,
614             "Incorrect number of return values in ret instruction!",
615             &RI, F->getReturnType());
616     for (unsigned i = 0; i != N; ++i)
617       Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
618               "Function return type does not match operand "
619               "type of return inst!", &RI, F->getReturnType());
620   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
621     // The return type is an array; check for multiple return values.
622     Assert2(ATy->getNumElements() == N,
623             "Incorrect number of return values in ret instruction!",
624             &RI, F->getReturnType());
625     for (unsigned i = 0; i != N; ++i)
626       Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
627               "Function return type does not match operand "
628               "type of return inst!", &RI, F->getReturnType());
629   } else {
630     CheckFailed("Function return type does not match operand "
631                 "type of return inst!", &RI, F->getReturnType());
632   }
633   
634   // Check to make sure that the return value has necessary properties for
635   // terminators...
636   visitTerminatorInst(RI);
637 }
638
639 void Verifier::visitSwitchInst(SwitchInst &SI) {
640   // Check to make sure that all of the constants in the switch instruction
641   // have the same type as the switched-on value.
642   const Type *SwitchTy = SI.getCondition()->getType();
643   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
644     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
645             "Switch constants must all be same type as switch value!", &SI);
646
647   visitTerminatorInst(SI);
648 }
649
650 void Verifier::visitSelectInst(SelectInst &SI) {
651   Assert1(SI.getCondition()->getType() == Type::Int1Ty,
652           "Select condition type must be bool!", &SI);
653   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
654           "Select values must have identical types!", &SI);
655   Assert1(SI.getTrueValue()->getType() == SI.getType(),
656           "Select values must have same type as select instruction!", &SI);
657   visitInstruction(SI);
658 }
659
660
661 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
662 /// a pass, if any exist, it's an error.
663 ///
664 void Verifier::visitUserOp1(Instruction &I) {
665   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
666 }
667
668 void Verifier::visitTruncInst(TruncInst &I) {
669   // Get the source and destination types
670   const Type *SrcTy = I.getOperand(0)->getType();
671   const Type *DestTy = I.getType();
672
673   // Get the size of the types in bits, we'll need this later
674   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
675   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
676
677   Assert1(SrcTy->isIntOrIntVector(), "Trunc only operates on integer", &I);
678   Assert1(DestTy->isIntOrIntVector(), "Trunc only produces integer", &I);
679   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
680
681   visitInstruction(I);
682 }
683
684 void Verifier::visitZExtInst(ZExtInst &I) {
685   // Get the source and destination types
686   const Type *SrcTy = I.getOperand(0)->getType();
687   const Type *DestTy = I.getType();
688
689   // Get the size of the types in bits, we'll need this later
690   Assert1(SrcTy->isIntOrIntVector(), "ZExt only operates on integer", &I);
691   Assert1(DestTy->isIntOrIntVector(), "ZExt only produces an integer", &I);
692   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
693   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
694
695   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
696
697   visitInstruction(I);
698 }
699
700 void Verifier::visitSExtInst(SExtInst &I) {
701   // Get the source and destination types
702   const Type *SrcTy = I.getOperand(0)->getType();
703   const Type *DestTy = I.getType();
704
705   // Get the size of the types in bits, we'll need this later
706   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
707   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
708
709   Assert1(SrcTy->isIntOrIntVector(), "SExt only operates on integer", &I);
710   Assert1(DestTy->isIntOrIntVector(), "SExt only produces an integer", &I);
711   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
712
713   visitInstruction(I);
714 }
715
716 void Verifier::visitFPTruncInst(FPTruncInst &I) {
717   // Get the source and destination types
718   const Type *SrcTy = I.getOperand(0)->getType();
719   const Type *DestTy = I.getType();
720   // Get the size of the types in bits, we'll need this later
721   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
722   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
723
724   Assert1(SrcTy->isFPOrFPVector(),"FPTrunc only operates on FP", &I);
725   Assert1(DestTy->isFPOrFPVector(),"FPTrunc only produces an FP", &I);
726   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
727
728   visitInstruction(I);
729 }
730
731 void Verifier::visitFPExtInst(FPExtInst &I) {
732   // Get the source and destination types
733   const Type *SrcTy = I.getOperand(0)->getType();
734   const Type *DestTy = I.getType();
735
736   // Get the size of the types in bits, we'll need this later
737   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
738   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
739
740   Assert1(SrcTy->isFPOrFPVector(),"FPExt only operates on FP", &I);
741   Assert1(DestTy->isFPOrFPVector(),"FPExt only produces an FP", &I);
742   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
743
744   visitInstruction(I);
745 }
746
747 void Verifier::visitUIToFPInst(UIToFPInst &I) {
748   // Get the source and destination types
749   const Type *SrcTy = I.getOperand(0)->getType();
750   const Type *DestTy = I.getType();
751
752   bool SrcVec = isa<VectorType>(SrcTy);
753   bool DstVec = isa<VectorType>(DestTy);
754
755   Assert1(SrcVec == DstVec,
756           "UIToFP source and dest must both be vector or scalar", &I);
757   Assert1(SrcTy->isIntOrIntVector(),
758           "UIToFP source must be integer or integer vector", &I);
759   Assert1(DestTy->isFPOrFPVector(),
760           "UIToFP result must be FP or FP vector", &I);
761
762   if (SrcVec && DstVec)
763     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
764             cast<VectorType>(DestTy)->getNumElements(),
765             "UIToFP source and dest vector length mismatch", &I);
766
767   visitInstruction(I);
768 }
769
770 void Verifier::visitSIToFPInst(SIToFPInst &I) {
771   // Get the source and destination types
772   const Type *SrcTy = I.getOperand(0)->getType();
773   const Type *DestTy = I.getType();
774
775   bool SrcVec = SrcTy->getTypeID() == Type::VectorTyID;
776   bool DstVec = DestTy->getTypeID() == Type::VectorTyID;
777
778   Assert1(SrcVec == DstVec,
779           "SIToFP source and dest must both be vector or scalar", &I);
780   Assert1(SrcTy->isIntOrIntVector(),
781           "SIToFP source must be integer or integer vector", &I);
782   Assert1(DestTy->isFPOrFPVector(),
783           "SIToFP result must be FP or FP vector", &I);
784
785   if (SrcVec && DstVec)
786     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
787             cast<VectorType>(DestTy)->getNumElements(),
788             "SIToFP source and dest vector length mismatch", &I);
789
790   visitInstruction(I);
791 }
792
793 void Verifier::visitFPToUIInst(FPToUIInst &I) {
794   // Get the source and destination types
795   const Type *SrcTy = I.getOperand(0)->getType();
796   const Type *DestTy = I.getType();
797
798   bool SrcVec = isa<VectorType>(SrcTy);
799   bool DstVec = isa<VectorType>(DestTy);
800
801   Assert1(SrcVec == DstVec,
802           "FPToUI source and dest must both be vector or scalar", &I);
803   Assert1(SrcTy->isFPOrFPVector(), "FPToUI source must be FP or FP vector", &I);
804   Assert1(DestTy->isIntOrIntVector(),
805           "FPToUI result must be integer or integer vector", &I);
806
807   if (SrcVec && DstVec)
808     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
809             cast<VectorType>(DestTy)->getNumElements(),
810             "FPToUI source and dest vector length mismatch", &I);
811
812   visitInstruction(I);
813 }
814
815 void Verifier::visitFPToSIInst(FPToSIInst &I) {
816   // Get the source and destination types
817   const Type *SrcTy = I.getOperand(0)->getType();
818   const Type *DestTy = I.getType();
819
820   bool SrcVec = isa<VectorType>(SrcTy);
821   bool DstVec = isa<VectorType>(DestTy);
822
823   Assert1(SrcVec == DstVec,
824           "FPToSI source and dest must both be vector or scalar", &I);
825   Assert1(SrcTy->isFPOrFPVector(),
826           "FPToSI source must be FP or FP vector", &I);
827   Assert1(DestTy->isIntOrIntVector(),
828           "FPToSI result must be integer or integer vector", &I);
829
830   if (SrcVec && DstVec)
831     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
832             cast<VectorType>(DestTy)->getNumElements(),
833             "FPToSI source and dest vector length mismatch", &I);
834
835   visitInstruction(I);
836 }
837
838 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
839   // Get the source and destination types
840   const Type *SrcTy = I.getOperand(0)->getType();
841   const Type *DestTy = I.getType();
842
843   Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
844   Assert1(DestTy->isInteger(), "PtrToInt result must be integral", &I);
845
846   visitInstruction(I);
847 }
848
849 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
850   // Get the source and destination types
851   const Type *SrcTy = I.getOperand(0)->getType();
852   const Type *DestTy = I.getType();
853
854   Assert1(SrcTy->isInteger(), "IntToPtr source must be an integral", &I);
855   Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
856
857   visitInstruction(I);
858 }
859
860 void Verifier::visitBitCastInst(BitCastInst &I) {
861   // Get the source and destination types
862   const Type *SrcTy = I.getOperand(0)->getType();
863   const Type *DestTy = I.getType();
864
865   // Get the size of the types in bits, we'll need this later
866   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
867   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
868
869   // BitCast implies a no-op cast of type only. No bits change.
870   // However, you can't cast pointers to anything but pointers.
871   Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
872           "Bitcast requires both operands to be pointer or neither", &I);
873   Assert1(SrcBitSize == DestBitSize, "Bitcast requies types of same width", &I);
874
875   visitInstruction(I);
876 }
877
878 /// visitPHINode - Ensure that a PHI node is well formed.
879 ///
880 void Verifier::visitPHINode(PHINode &PN) {
881   // Ensure that the PHI nodes are all grouped together at the top of the block.
882   // This can be tested by checking whether the instruction before this is
883   // either nonexistent (because this is begin()) or is a PHI node.  If not,
884   // then there is some other instruction before a PHI.
885   Assert2(&PN == &PN.getParent()->front() || 
886           isa<PHINode>(--BasicBlock::iterator(&PN)),
887           "PHI nodes not grouped at top of basic block!",
888           &PN, PN.getParent());
889
890   // Check that all of the operands of the PHI node have the same type as the
891   // result.
892   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
893     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
894             "PHI node operands are not the same type as the result!", &PN);
895
896   // All other PHI node constraints are checked in the visitBasicBlock method.
897
898   visitInstruction(PN);
899 }
900
901 void Verifier::VerifyCallSite(CallSite CS) {
902   Instruction *I = CS.getInstruction();
903
904   Assert1(isa<PointerType>(CS.getCalledValue()->getType()),
905           "Called function must be a pointer!", I);
906   const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
907   Assert1(isa<FunctionType>(FPTy->getElementType()),
908           "Called function is not pointer to function type!", I);
909
910   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
911
912   // Verify that the correct number of arguments are being passed
913   if (FTy->isVarArg())
914     Assert1(CS.arg_size() >= FTy->getNumParams(),
915             "Called function requires more parameters than were provided!",I);
916   else
917     Assert1(CS.arg_size() == FTy->getNumParams(),
918             "Incorrect number of arguments passed to called function!", I);
919
920   // Verify that all arguments to the call match the function type...
921   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
922     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
923             "Call parameter type does not match function signature!",
924             CS.getArgument(i), FTy->getParamType(i), I);
925
926   const PAListPtr &Attrs = CS.getParamAttrs();
927
928   Assert1(Attrs.isEmpty() ||
929           Attrs.getSlot(Attrs.getNumSlots()-1).Index <= CS.arg_size(),
930           "Attributes after last parameter!", I);
931
932   // Verify call attributes.
933   VerifyFunctionAttrs(FTy, Attrs, I);
934
935   if (FTy->isVarArg())
936     // Check attributes on the varargs part.
937     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
938       ParameterAttributes Attr = Attrs.getParamAttrs(Idx);
939
940       VerifyAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
941
942       ParameterAttributes VArgI = Attr & ParamAttr::VarArgsIncompatible;
943       Assert1(!VArgI, "Attribute " + ParamAttr::getAsString(VArgI) +
944               " cannot be used for vararg call arguments!", I);
945     }
946
947   visitInstruction(*I);
948 }
949
950 void Verifier::visitCallInst(CallInst &CI) {
951   VerifyCallSite(&CI);
952
953   if (Function *F = CI.getCalledFunction()) {
954     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
955       visitIntrinsicFunctionCall(ID, CI);
956   }
957 }
958
959 void Verifier::visitInvokeInst(InvokeInst &II) {
960   VerifyCallSite(&II);
961 }
962
963 /// visitBinaryOperator - Check that both arguments to the binary operator are
964 /// of the same type!
965 ///
966 void Verifier::visitBinaryOperator(BinaryOperator &B) {
967   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
968           "Both operands to a binary operator are not of the same type!", &B);
969
970   switch (B.getOpcode()) {
971   // Check that logical operators are only used with integral operands.
972   case Instruction::And:
973   case Instruction::Or:
974   case Instruction::Xor:
975     Assert1(B.getType()->isInteger() ||
976             (isa<VectorType>(B.getType()) && 
977              cast<VectorType>(B.getType())->getElementType()->isInteger()),
978             "Logical operators only work with integral types!", &B);
979     Assert1(B.getType() == B.getOperand(0)->getType(),
980             "Logical operators must have same type for operands and result!",
981             &B);
982     break;
983   case Instruction::Shl:
984   case Instruction::LShr:
985   case Instruction::AShr:
986     Assert1(B.getType()->isInteger() ||
987             (isa<VectorType>(B.getType()) && 
988              cast<VectorType>(B.getType())->getElementType()->isInteger()),
989             "Shifts only work with integral types!", &B);
990     Assert1(B.getType() == B.getOperand(0)->getType(),
991             "Shift return type must be same as operands!", &B);
992     /* FALL THROUGH */
993   default:
994     // Arithmetic operators only work on integer or fp values
995     Assert1(B.getType() == B.getOperand(0)->getType(),
996             "Arithmetic operators must have same type for operands and result!",
997             &B);
998     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
999             isa<VectorType>(B.getType()),
1000             "Arithmetic operators must have integer, fp, or vector type!", &B);
1001     break;
1002   }
1003
1004   visitInstruction(B);
1005 }
1006
1007 void Verifier::visitICmpInst(ICmpInst& IC) {
1008   // Check that the operands are the same type
1009   const Type* Op0Ty = IC.getOperand(0)->getType();
1010   const Type* Op1Ty = IC.getOperand(1)->getType();
1011   Assert1(Op0Ty == Op1Ty,
1012           "Both operands to ICmp instruction are not of the same type!", &IC);
1013   // Check that the operands are the right type
1014   Assert1(Op0Ty->isInteger() || isa<PointerType>(Op0Ty),
1015           "Invalid operand types for ICmp instruction", &IC);
1016   visitInstruction(IC);
1017 }
1018
1019 void Verifier::visitFCmpInst(FCmpInst& FC) {
1020   // Check that the operands are the same type
1021   const Type* Op0Ty = FC.getOperand(0)->getType();
1022   const Type* Op1Ty = FC.getOperand(1)->getType();
1023   Assert1(Op0Ty == Op1Ty,
1024           "Both operands to FCmp instruction are not of the same type!", &FC);
1025   // Check that the operands are the right type
1026   Assert1(Op0Ty->isFloatingPoint(),
1027           "Invalid operand types for FCmp instruction", &FC);
1028   visitInstruction(FC);
1029 }
1030
1031 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1032   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1033                                               EI.getOperand(1)),
1034           "Invalid extractelement operands!", &EI);
1035   visitInstruction(EI);
1036 }
1037
1038 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1039   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1040                                              IE.getOperand(1),
1041                                              IE.getOperand(2)),
1042           "Invalid insertelement operands!", &IE);
1043   visitInstruction(IE);
1044 }
1045
1046 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1047   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1048                                              SV.getOperand(2)),
1049           "Invalid shufflevector operands!", &SV);
1050   Assert1(SV.getType() == SV.getOperand(0)->getType(),
1051           "Result of shufflevector must match first operand type!", &SV);
1052   
1053   // Check to see if Mask is valid.
1054   if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
1055     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1056       if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1057         Assert1(!CI->uge(MV->getNumOperands()*2),
1058                 "Invalid shufflevector shuffle mask!", &SV);
1059       } else {
1060         Assert1(isa<UndefValue>(MV->getOperand(i)),
1061                 "Invalid shufflevector shuffle mask!", &SV);
1062       }
1063     }
1064   } else {
1065     Assert1(isa<UndefValue>(SV.getOperand(2)) || 
1066             isa<ConstantAggregateZero>(SV.getOperand(2)),
1067             "Invalid shufflevector shuffle mask!", &SV);
1068   }
1069   
1070   visitInstruction(SV);
1071 }
1072
1073 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1074   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1075   const Type *ElTy =
1076     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
1077                                       Idxs.begin(), Idxs.end());
1078   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1079   Assert2(isa<PointerType>(GEP.getType()) &&
1080           cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1081           "GEP is not of right type for indices!", &GEP, ElTy);
1082   visitInstruction(GEP);
1083 }
1084
1085 void Verifier::visitLoadInst(LoadInst &LI) {
1086   const Type *ElTy =
1087     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
1088   Assert2(ElTy == LI.getType(),
1089           "Load result type does not match pointer operand type!", &LI, ElTy);
1090   visitInstruction(LI);
1091 }
1092
1093 void Verifier::visitStoreInst(StoreInst &SI) {
1094   const Type *ElTy =
1095     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
1096   Assert2(ElTy == SI.getOperand(0)->getType(),
1097           "Stored value type does not match pointer operand type!", &SI, ElTy);
1098   visitInstruction(SI);
1099 }
1100
1101 void Verifier::visitAllocationInst(AllocationInst &AI) {
1102   const PointerType *PTy = AI.getType();
1103   Assert1(PTy->getAddressSpace() == 0, 
1104           "Allocation instruction pointer not in the generic address space!",
1105           &AI);
1106   Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1107           &AI);
1108   visitInstruction(AI);
1109 }
1110
1111 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1112   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1113                                            EVI.idx_begin(), EVI.idx_end()) ==
1114           EVI.getType(),
1115           "Invalid ExtractValueInst operands!", &EVI);
1116   
1117   visitInstruction(EVI);
1118 }
1119
1120 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1121   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1122                                            IVI.idx_begin(), IVI.idx_end()) ==
1123           IVI.getOperand(1)->getType(),
1124           "Invalid InsertValueInst operands!", &IVI);
1125   
1126   visitInstruction(IVI);
1127 }
1128
1129 /// verifyInstruction - Verify that an instruction is well formed.
1130 ///
1131 void Verifier::visitInstruction(Instruction &I) {
1132   BasicBlock *BB = I.getParent();
1133   Assert1(BB, "Instruction not embedded in basic block!", &I);
1134
1135   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
1136     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1137          UI != UE; ++UI)
1138       Assert1(*UI != (User*)&I ||
1139               !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
1140               "Only PHI nodes may reference their own value!", &I);
1141   }
1142   
1143   // Verify that if this is a terminator that it is at the end of the block.
1144   if (isa<TerminatorInst>(I))
1145     Assert1(BB->getTerminator() == &I, "Terminator not at end of block!", &I);
1146   
1147
1148   // Check that void typed values don't have names
1149   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
1150           "Instruction has a name, but provides a void value!", &I);
1151
1152   // Check that the return value of the instruction is either void or a legal
1153   // value type.
1154   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType()
1155           || ((isa<CallInst>(I) || isa<InvokeInst>(I)) 
1156               && isa<StructType>(I.getType())),
1157           "Instruction returns a non-scalar type!", &I);
1158
1159   // Check that all uses of the instruction, if they are instructions
1160   // themselves, actually have parent basic blocks.  If the use is not an
1161   // instruction, it is an error!
1162   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1163        UI != UE; ++UI) {
1164     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
1165             *UI);
1166     Instruction *Used = cast<Instruction>(*UI);
1167     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1168             " embeded in a basic block!", &I, Used);
1169   }
1170
1171   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1172     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1173
1174     // Check to make sure that only first-class-values are operands to
1175     // instructions.
1176     if (!I.getOperand(i)->getType()->isFirstClassType()) {
1177       Assert1(0, "Instruction operands must be first-class values!", &I);
1178     }
1179     
1180     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1181       // Check to make sure that the "address of" an intrinsic function is never
1182       // taken.
1183       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
1184               "Cannot take the address of an intrinsic!", &I);
1185       Assert1(F->getParent() == Mod, "Referencing function in another module!",
1186               &I);
1187     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1188       Assert1(OpBB->getParent() == BB->getParent(),
1189               "Referring to a basic block in another function!", &I);
1190     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1191       Assert1(OpArg->getParent() == BB->getParent(),
1192               "Referring to an argument in another function!", &I);
1193     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1194       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1195               &I);
1196     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1197       BasicBlock *OpBlock = Op->getParent();
1198
1199       // Check that a definition dominates all of its uses.
1200       if (!isa<PHINode>(I)) {
1201         // Invoke results are only usable in the normal destination, not in the
1202         // exceptional destination.
1203         if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1204           OpBlock = II->getNormalDest();
1205           
1206           Assert2(OpBlock != II->getUnwindDest(),
1207                   "No uses of invoke possible due to dominance structure!",
1208                   Op, II);
1209           
1210           // If the normal successor of an invoke instruction has multiple
1211           // predecessors, then the normal edge from the invoke is critical, so
1212           // the invoke value can only be live if the destination block
1213           // dominates all of it's predecessors (other than the invoke) or if
1214           // the invoke value is only used by a phi in the successor.
1215           if (!OpBlock->getSinglePredecessor() &&
1216               DT->dominates(&BB->getParent()->getEntryBlock(), BB)) {
1217             // The first case we allow is if the use is a PHI operand in the
1218             // normal block, and if that PHI operand corresponds to the invoke's
1219             // block.
1220             bool Bad = true;
1221             if (PHINode *PN = dyn_cast<PHINode>(&I))
1222               if (PN->getParent() == OpBlock &&
1223                   PN->getIncomingBlock(i/2) == Op->getParent())
1224                 Bad = false;
1225             
1226             // If it is used by something non-phi, then the other case is that
1227             // 'OpBlock' dominates all of its predecessors other than the
1228             // invoke.  In this case, the invoke value can still be used.
1229             if (Bad) {
1230               Bad = false;
1231               for (pred_iterator PI = pred_begin(OpBlock),
1232                    E = pred_end(OpBlock); PI != E; ++PI) {
1233                 if (*PI != II->getParent() && !DT->dominates(OpBlock, *PI)) {
1234                   Bad = true;
1235                   break;
1236                 }
1237               }
1238             }
1239             Assert2(!Bad,
1240                     "Invoke value defined on critical edge but not dead!", &I,
1241                     Op);
1242           }
1243         } else if (OpBlock == BB) {
1244           // If they are in the same basic block, make sure that the definition
1245           // comes before the use.
1246           Assert2(InstsInThisBlock.count(Op) ||
1247                   !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
1248                   "Instruction does not dominate all uses!", Op, &I);
1249         }
1250
1251         // Definition must dominate use unless use is unreachable!
1252         Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1253                 !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
1254                 "Instruction does not dominate all uses!", Op, &I);
1255       } else {
1256         // PHI nodes are more difficult than other nodes because they actually
1257         // "use" the value in the predecessor basic blocks they correspond to.
1258         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
1259         Assert2(DT->dominates(OpBlock, PredBB) ||
1260                 !DT->dominates(&BB->getParent()->getEntryBlock(), PredBB),
1261                 "Instruction does not dominate all uses!", Op, &I);
1262       }
1263     } else if (isa<InlineAsm>(I.getOperand(i))) {
1264       Assert1(i == 0 && (isa<CallInst>(I) || isa<InvokeInst>(I)),
1265               "Cannot take the address of an inline asm!", &I);
1266     }
1267   }
1268   InstsInThisBlock.insert(&I);
1269 }
1270
1271 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1272 ///
1273 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1274   Function *IF = CI.getCalledFunction();
1275   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1276           IF);
1277   
1278 #define GET_INTRINSIC_VERIFIER
1279 #include "llvm/Intrinsics.gen"
1280 #undef GET_INTRINSIC_VERIFIER
1281   
1282   switch (ID) {
1283   default:
1284     break;
1285   case Intrinsic::memcpy_i32:
1286   case Intrinsic::memcpy_i64:
1287   case Intrinsic::memmove_i32:
1288   case Intrinsic::memmove_i64:
1289   case Intrinsic::memset_i32:
1290   case Intrinsic::memset_i64:
1291     Assert1(isa<ConstantInt>(CI.getOperand(4)),
1292             "alignment argument of memory intrinsics must be a constant int",
1293             &CI);
1294     break;
1295   case Intrinsic::gcroot:
1296   case Intrinsic::gcwrite:
1297   case Intrinsic::gcread:
1298     if (ID == Intrinsic::gcroot) {
1299       Assert1(isa<AllocaInst>(CI.getOperand(1)->stripPointerCasts()),
1300               "llvm.gcroot parameter #1 must be an alloca.", &CI);
1301       Assert1(isa<Constant>(CI.getOperand(2)),
1302               "llvm.gcroot parameter #2 must be a constant.", &CI);
1303     }
1304       
1305     Assert1(CI.getParent()->getParent()->hasGC(),
1306             "Enclosing function does not use GC.", &CI);
1307     break;
1308   case Intrinsic::init_trampoline:
1309     Assert1(isa<Function>(CI.getOperand(2)->stripPointerCasts()),
1310             "llvm.init_trampoline parameter #2 must resolve to a function.",
1311             &CI);
1312     break;
1313   }
1314 }
1315
1316 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1317 /// Intrinsics.gen.  This implements a little state machine that verifies the
1318 /// prototype of intrinsics.
1319 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID,
1320                                         Function *F,
1321                                         unsigned Count, ...) {
1322   va_list VA;
1323   va_start(VA, Count);
1324   const FunctionType *FTy = F->getFunctionType();
1325   
1326   // For overloaded intrinsics, the Suffix of the function name must match the
1327   // types of the arguments. This variable keeps track of the expected
1328   // suffix, to be checked at the end.
1329   std::string Suffix;
1330
1331   if (FTy->getNumParams() + FTy->isVarArg() != Count - 1) {
1332     CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1333     return;
1334   }
1335
1336   // Note that "arg#0" is the return type.
1337   for (unsigned ArgNo = 0; ArgNo < Count; ++ArgNo) {
1338     int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1339
1340     if (VT == MVT::isVoid && ArgNo > 0) {
1341       if (!FTy->isVarArg())
1342         CheckFailed("Intrinsic prototype has no '...'!", F);
1343       break;
1344     }
1345
1346     const Type *Ty;
1347     if (ArgNo == 0)
1348       Ty = FTy->getReturnType();
1349     else
1350       Ty = FTy->getParamType(ArgNo-1);
1351
1352     unsigned NumElts = 0;
1353     const Type *EltTy = Ty;
1354     if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1355       EltTy = VTy->getElementType();
1356       NumElts = VTy->getNumElements();
1357     }
1358
1359     if (VT < 0) {
1360       int Match = ~VT;
1361       if (Match == 0) {
1362         if (Ty != FTy->getReturnType()) {
1363           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " does not "
1364                       "match return type.", F);
1365           break;
1366         }
1367       } else {
1368         if (Ty != FTy->getParamType(Match-1)) {
1369           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " does not "
1370                       "match parameter %" + utostr(Match-1) + ".", F);
1371           break;
1372         }
1373       }
1374     } else if (VT == MVT::iAny) {
1375       if (!EltTy->isInteger()) {
1376         if (ArgNo == 0)
1377           CheckFailed("Intrinsic result type is not "
1378                       "an integer type.", F);
1379         else
1380           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not "
1381                       "an integer type.", F);
1382         break;
1383       }
1384       unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1385       Suffix += ".";
1386       if (EltTy != Ty)
1387         Suffix += "v" + utostr(NumElts);
1388       Suffix += "i" + utostr(GotBits);;
1389       // Check some constraints on various intrinsics.
1390       switch (ID) {
1391         default: break; // Not everything needs to be checked.
1392         case Intrinsic::bswap:
1393           if (GotBits < 16 || GotBits % 16 != 0)
1394             CheckFailed("Intrinsic requires even byte width argument", F);
1395           break;
1396       }
1397     } else if (VT == MVT::fAny) {
1398       if (!EltTy->isFloatingPoint()) {
1399         if (ArgNo == 0)
1400           CheckFailed("Intrinsic result type is not "
1401                       "a floating-point type.", F);
1402         else
1403           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not "
1404                       "a floating-point type.", F);
1405         break;
1406       }
1407       Suffix += ".";
1408       if (EltTy != Ty)
1409         Suffix += "v" + utostr(NumElts);
1410       Suffix += MVT::getMVT(EltTy).getMVTString();
1411     } else if (VT == MVT::iPTR) {
1412       if (!isa<PointerType>(Ty)) {
1413         if (ArgNo == 0)
1414           CheckFailed("Intrinsic result type is not a "
1415                       "pointer and a pointer is required.", F);
1416         else
1417           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not a "
1418                       "pointer and a pointer is required.", F);
1419       }        
1420     } else if (VT == MVT::iPTRAny) {
1421       // Outside of TableGen, we don't distinguish iPTRAny (to any address
1422       // space) and iPTR. In the verifier, we can not distinguish which case
1423       // we have so allow either case to be legal.
1424       if (const PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1425         Suffix += ".p" + utostr(PTyp->getAddressSpace()) + 
1426         MVT::getMVT(PTyp->getElementType()).getMVTString();
1427       } else {
1428         if (ArgNo == 0)
1429           CheckFailed("Intrinsic result type is not a "
1430                       "pointer and a pointer is required.", F);
1431         else
1432           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not a "
1433                       "pointer and a pointer is required.", F);
1434         break;
1435       }
1436     } else if (MVT((MVT::SimpleValueType)VT).isVector()) {
1437       MVT VVT = MVT((MVT::SimpleValueType)VT);
1438       // If this is a vector argument, verify the number and type of elements.
1439       if (VVT.getVectorElementType() != MVT::getMVT(EltTy)) {
1440         CheckFailed("Intrinsic prototype has incorrect vector element type!",
1441                     F);
1442         break;
1443       }
1444       if (VVT.getVectorNumElements() != NumElts) {
1445         CheckFailed("Intrinsic prototype has incorrect number of "
1446                     "vector elements!",F);
1447         break;
1448       }
1449     } else if (MVT((MVT::SimpleValueType)VT).getTypeForMVT() != EltTy) {
1450       if (ArgNo == 0)
1451         CheckFailed("Intrinsic prototype has incorrect result type!", F);
1452       else
1453         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is wrong!",F);
1454       break;
1455     } else if (EltTy != Ty) {
1456       if (ArgNo == 0)
1457         CheckFailed("Intrinsic result type is vector "
1458                     "and a scalar is required.", F);
1459       else
1460         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is vector "
1461                     "and a scalar is required.", F);
1462     }
1463   }
1464
1465   va_end(VA);
1466
1467   // For intrinsics without pointer arguments, if we computed a Suffix then the
1468   // intrinsic is overloaded and we need to make sure that the name of the
1469   // function is correct. We add the suffix to the name of the intrinsic and
1470   // compare against the given function name. If they are not the same, the
1471   // function name is invalid. This ensures that overloading of intrinsics
1472   // uses a sane and consistent naming convention.  Note that intrinsics with
1473   // pointer argument may or may not be overloaded so we will check assuming it
1474   // has a suffix and not.
1475   if (!Suffix.empty()) {
1476     std::string Name(Intrinsic::getName(ID));
1477     if (Name + Suffix != F->getName()) {
1478       CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1479                   F->getName().substr(Name.length()) + "'. It should be '" +
1480                   Suffix + "'", F);
1481     }
1482   }
1483
1484   // Check parameter attributes.
1485   Assert1(F->getParamAttrs() == Intrinsic::getParamAttrs(ID),
1486           "Intrinsic has wrong parameter attributes!", F);
1487 }
1488
1489
1490 //===----------------------------------------------------------------------===//
1491 //  Implement the public interfaces to this file...
1492 //===----------------------------------------------------------------------===//
1493
1494 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1495   return new Verifier(action);
1496 }
1497
1498
1499 // verifyFunction - Create
1500 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1501   Function &F = const_cast<Function&>(f);
1502   assert(!F.isDeclaration() && "Cannot verify external functions");
1503
1504   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
1505   Verifier *V = new Verifier(action);
1506   FPM.add(V);
1507   FPM.run(F);
1508   return V->Broken;
1509 }
1510
1511 /// verifyModule - Check a module for errors, printing messages on stderr.
1512 /// Return true if the module is corrupt.
1513 ///
1514 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1515                         std::string *ErrorInfo) {
1516   PassManager PM;
1517   Verifier *V = new Verifier(action);
1518   PM.add(V);
1519   PM.run(const_cast<Module&>(M));
1520   
1521   if (ErrorInfo && V->Broken)
1522     *ErrorInfo = V->msgs.str();
1523   return V->Broken;
1524 }
1525
1526 // vim: sw=2