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