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