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