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