650e34af829ddbcc697578e14f6672f23fbadb95
[oota-llvm.git] / lib / IR / 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/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/DebugInfo.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/Constants.h"
58 #include "llvm/IR/DataLayout.h"
59 #include "llvm/IR/DerivedTypes.h"
60 #include "llvm/IR/InlineAsm.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/Metadata.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/Writer.h"
66 #include "llvm/InstVisitor.h"
67 #include "llvm/Pass.h"
68 #include "llvm/PassManager.h"
69 #include "llvm/Support/CFG.h"
70 #include "llvm/Support/CallSite.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/ConstantRange.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include <algorithm>
77 #include <cstdarg>
78 using namespace llvm;
79
80 static cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier",
81                                               cl::init(true));
82
83 namespace {  // Anonymous namespace for class
84   struct PreVerifier : public FunctionPass {
85     static char ID; // Pass ID, replacement for typeid
86
87     PreVerifier() : FunctionPass(ID) {
88       initializePreVerifierPass(*PassRegistry::getPassRegistry());
89     }
90
91     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92       AU.setPreservesAll();
93     }
94
95     // Check that the prerequisites for successful DominatorTree construction
96     // are satisfied.
97     bool runOnFunction(Function &F) {
98       bool Broken = false;
99
100       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
101         if (I->empty() || !I->back().isTerminator()) {
102           dbgs() << "Basic Block in function '" << F.getName()
103                  << "' does not have terminator!\n";
104           WriteAsOperand(dbgs(), I, true);
105           dbgs() << "\n";
106           Broken = true;
107         }
108       }
109
110       if (Broken)
111         report_fatal_error("Broken module, no Basic Block terminator!");
112
113       return false;
114     }
115   };
116 }
117
118 char PreVerifier::ID = 0;
119 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
120                 false, false)
121 static char &PreVerifyID = PreVerifier::ID;
122
123 namespace {
124   struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
125     static char ID; // Pass ID, replacement for typeid
126     bool Broken;          // Is this module found to be broken?
127     VerifierFailureAction action;
128                           // What to do if verification fails.
129     Module *Mod;          // Module we are verifying right now
130     LLVMContext *Context; // Context within which we are verifying
131     DominatorTree *DT;    // Dominator Tree, caution can be null!
132     const DataLayout *DL;
133
134     std::string Messages;
135     raw_string_ostream MessagesStr;
136
137     /// InstInThisBlock - when verifying a basic block, keep track of all of the
138     /// instructions we have seen so far.  This allows us to do efficient
139     /// dominance checks for the case when an instruction has an operand that is
140     /// an instruction in the same block.
141     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
142
143     /// MDNodes - keep track of the metadata nodes that have been checked
144     /// already.
145     SmallPtrSet<MDNode *, 32> MDNodes;
146
147     /// PersonalityFn - The personality function referenced by the
148     /// LandingPadInsts. All LandingPadInsts within the same function must use
149     /// the same personality function.
150     const Value *PersonalityFn;
151
152     /// Finder keeps track of all debug info MDNodes in a Module.
153     DebugInfoFinder Finder;
154
155     Verifier()
156       : FunctionPass(ID), Broken(false),
157         action(AbortProcessAction), Mod(0), Context(0), DT(0), DL(0),
158         MessagesStr(Messages), PersonalityFn(0) {
159       initializeVerifierPass(*PassRegistry::getPassRegistry());
160     }
161     explicit Verifier(VerifierFailureAction ctn)
162       : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
163         Context(0), DT(0), DL(0), MessagesStr(Messages), PersonalityFn(0) {
164       initializeVerifierPass(*PassRegistry::getPassRegistry());
165     }
166
167     bool doInitialization(Module &M) {
168       Mod = &M;
169       Context = &M.getContext();
170
171       DL = getAnalysisIfAvailable<DataLayout>();
172
173       // We must abort before returning back to the pass manager, or else the
174       // pass manager may try to run other passes on the broken module.
175       return abortIfBroken();
176     }
177
178     bool runOnFunction(Function &F) {
179       // Get dominator information if we are being run by PassManager
180       DT = &getAnalysis<DominatorTree>();
181
182       Mod = F.getParent();
183       if (!Context) Context = &F.getContext();
184
185       Finder.reset();
186       visit(F);
187       InstsInThisBlock.clear();
188       PersonalityFn = 0;
189
190       if (!DisableDebugInfoVerifier)
191         // Verify Debug Info.
192         verifyDebugInfo();
193
194       // We must abort before returning back to the pass manager, or else the
195       // pass manager may try to run other passes on the broken module.
196       return abortIfBroken();
197     }
198
199     bool doFinalization(Module &M) {
200       // Scan through, checking all of the external function's linkage now...
201       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
202         visitGlobalValue(*I);
203
204         // Check to make sure function prototypes are okay.
205         if (I->isDeclaration()) visitFunction(*I);
206       }
207
208       for (Module::global_iterator I = M.global_begin(), E = M.global_end();
209            I != E; ++I)
210         visitGlobalVariable(*I);
211
212       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
213            I != E; ++I)
214         visitGlobalAlias(*I);
215
216       for (Module::named_metadata_iterator I = M.named_metadata_begin(),
217            E = M.named_metadata_end(); I != E; ++I)
218         visitNamedMDNode(*I);
219
220       visitModuleFlags(M);
221       visitModuleIdents(M);
222
223       if (!DisableDebugInfoVerifier) {
224         Finder.reset();
225         Finder.processModule(M);
226         // Verify Debug Info.
227         verifyDebugInfo();
228       }
229
230       // If the module is broken, abort at this time.
231       return abortIfBroken();
232     }
233
234     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
235       AU.setPreservesAll();
236       AU.addRequiredID(PreVerifyID);
237       AU.addRequired<DominatorTree>();
238     }
239
240     /// abortIfBroken - If the module is broken and we are supposed to abort on
241     /// this condition, do so.
242     ///
243     bool abortIfBroken() {
244       if (!Broken) return false;
245       MessagesStr << "Broken module found, ";
246       switch (action) {
247       case AbortProcessAction:
248         MessagesStr << "compilation aborted!\n";
249         dbgs() << MessagesStr.str();
250         // Client should choose different reaction if abort is not desired
251         abort();
252       case PrintMessageAction:
253         MessagesStr << "verification continues.\n";
254         dbgs() << MessagesStr.str();
255         return false;
256       case ReturnStatusAction:
257         MessagesStr << "compilation terminated.\n";
258         return true;
259       }
260       llvm_unreachable("Invalid action");
261     }
262
263
264     // Verification methods...
265     void visitGlobalValue(GlobalValue &GV);
266     void visitGlobalVariable(GlobalVariable &GV);
267     void visitGlobalAlias(GlobalAlias &GA);
268     void visitNamedMDNode(NamedMDNode &NMD);
269     void visitMDNode(MDNode &MD, Function *F);
270     void visitModuleIdents(Module &M);
271     void visitModuleFlags(Module &M);
272     void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
273                          SmallVectorImpl<MDNode*> &Requirements);
274     void visitFunction(Function &F);
275     void visitBasicBlock(BasicBlock &BB);
276     using InstVisitor<Verifier>::visit;
277
278     void visit(Instruction &I);
279
280     void visitTruncInst(TruncInst &I);
281     void visitZExtInst(ZExtInst &I);
282     void visitSExtInst(SExtInst &I);
283     void visitFPTruncInst(FPTruncInst &I);
284     void visitFPExtInst(FPExtInst &I);
285     void visitFPToUIInst(FPToUIInst &I);
286     void visitFPToSIInst(FPToSIInst &I);
287     void visitUIToFPInst(UIToFPInst &I);
288     void visitSIToFPInst(SIToFPInst &I);
289     void visitIntToPtrInst(IntToPtrInst &I);
290     void visitPtrToIntInst(PtrToIntInst &I);
291     void visitBitCastInst(BitCastInst &I);
292     void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
293     void visitPHINode(PHINode &PN);
294     void visitBinaryOperator(BinaryOperator &B);
295     void visitICmpInst(ICmpInst &IC);
296     void visitFCmpInst(FCmpInst &FC);
297     void visitExtractElementInst(ExtractElementInst &EI);
298     void visitInsertElementInst(InsertElementInst &EI);
299     void visitShuffleVectorInst(ShuffleVectorInst &EI);
300     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
301     void visitCallInst(CallInst &CI);
302     void visitInvokeInst(InvokeInst &II);
303     void visitGetElementPtrInst(GetElementPtrInst &GEP);
304     void visitLoadInst(LoadInst &LI);
305     void visitStoreInst(StoreInst &SI);
306     void verifyDominatesUse(Instruction &I, unsigned i);
307     void visitInstruction(Instruction &I);
308     void visitTerminatorInst(TerminatorInst &I);
309     void visitBranchInst(BranchInst &BI);
310     void visitReturnInst(ReturnInst &RI);
311     void visitSwitchInst(SwitchInst &SI);
312     void visitIndirectBrInst(IndirectBrInst &BI);
313     void visitSelectInst(SelectInst &SI);
314     void visitUserOp1(Instruction &I);
315     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
316     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
317     void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
318     void visitAtomicRMWInst(AtomicRMWInst &RMWI);
319     void visitFenceInst(FenceInst &FI);
320     void visitAllocaInst(AllocaInst &AI);
321     void visitExtractValueInst(ExtractValueInst &EVI);
322     void visitInsertValueInst(InsertValueInst &IVI);
323     void visitLandingPadInst(LandingPadInst &LPI);
324
325     void VerifyCallSite(CallSite CS);
326     bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
327                           int VT, unsigned ArgNo, std::string &Suffix);
328     bool VerifyIntrinsicType(Type *Ty,
329                              ArrayRef<Intrinsic::IITDescriptor> &Infos,
330                              SmallVectorImpl<Type*> &ArgTys);
331     bool VerifyIntrinsicIsVarArg(bool isVarArg,
332                                  ArrayRef<Intrinsic::IITDescriptor> &Infos);
333     bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
334     void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
335                               bool isFunction, const Value *V);
336     void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
337                               bool isReturnValue, const Value *V);
338     void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
339                              const Value *V);
340
341     void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
342     void VerifyConstantExprBitcastType(const ConstantExpr *CE);
343
344     void verifyDebugInfo();
345
346     void WriteValue(const Value *V) {
347       if (!V) return;
348       if (isa<Instruction>(V)) {
349         MessagesStr << *V << '\n';
350       } else {
351         WriteAsOperand(MessagesStr, V, true, Mod);
352         MessagesStr << '\n';
353       }
354     }
355
356     void WriteType(Type *T) {
357       if (!T) return;
358       MessagesStr << ' ' << *T;
359     }
360
361
362     // CheckFailed - A check failed, so print out the condition and the message
363     // that failed.  This provides a nice place to put a breakpoint if you want
364     // to see why something is not correct.
365     void CheckFailed(const Twine &Message,
366                      const Value *V1 = 0, const Value *V2 = 0,
367                      const Value *V3 = 0, const Value *V4 = 0) {
368       MessagesStr << Message.str() << "\n";
369       WriteValue(V1);
370       WriteValue(V2);
371       WriteValue(V3);
372       WriteValue(V4);
373       Broken = true;
374     }
375
376     void CheckFailed(const Twine &Message, const Value *V1,
377                      Type *T2, const Value *V3 = 0) {
378       MessagesStr << Message.str() << "\n";
379       WriteValue(V1);
380       WriteType(T2);
381       WriteValue(V3);
382       Broken = true;
383     }
384
385     void CheckFailed(const Twine &Message, Type *T1,
386                      Type *T2 = 0, Type *T3 = 0) {
387       MessagesStr << Message.str() << "\n";
388       WriteType(T1);
389       WriteType(T2);
390       WriteType(T3);
391       Broken = true;
392     }
393   };
394 } // End anonymous namespace
395
396 char Verifier::ID = 0;
397 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
398 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
399 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
400 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
401
402 // Assert - We know that cond should be true, if not print an error message.
403 #define Assert(C, M) \
404   do { if (!(C)) { CheckFailed(M); return; } } while (0)
405 #define Assert1(C, M, V1) \
406   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
407 #define Assert2(C, M, V1, V2) \
408   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
409 #define Assert3(C, M, V1, V2, V3) \
410   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
411 #define Assert4(C, M, V1, V2, V3, V4) \
412   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
413
414 void Verifier::visit(Instruction &I) {
415   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
416     Assert1(I.getOperand(i) != 0, "Operand is null", &I);
417   InstVisitor<Verifier>::visit(I);
418 }
419
420
421 void Verifier::visitGlobalValue(GlobalValue &GV) {
422   Assert1(!GV.isDeclaration() ||
423           GV.isMaterializable() ||
424           GV.hasExternalLinkage() ||
425           GV.hasDLLImportLinkage() ||
426           GV.hasExternalWeakLinkage() ||
427           (isa<GlobalAlias>(GV) &&
428            (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
429   "Global is external, but doesn't have external or dllimport or weak linkage!",
430           &GV);
431
432   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
433           "Global is marked as dllimport, but not external", &GV);
434
435   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
436           "Only global variables can have appending linkage!", &GV);
437
438   if (GV.hasAppendingLinkage()) {
439     GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
440     Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
441             "Only global arrays can have appending linkage!", GVar);
442   }
443 }
444
445 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
446   if (GV.hasInitializer()) {
447     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
448             "Global variable initializer type does not match global "
449             "variable type!", &GV);
450
451     // If the global has common linkage, it must have a zero initializer and
452     // cannot be constant.
453     if (GV.hasCommonLinkage()) {
454       Assert1(GV.getInitializer()->isNullValue(),
455               "'common' global must have a zero initializer!", &GV);
456       Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
457               &GV);
458     }
459   } else {
460     Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
461             GV.hasExternalWeakLinkage(),
462             "invalid linkage type for global declaration", &GV);
463   }
464
465   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
466                        GV.getName() == "llvm.global_dtors")) {
467     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
468             "invalid linkage for intrinsic global variable", &GV);
469     // Don't worry about emitting an error for it not being an array,
470     // visitGlobalValue will complain on appending non-array.
471     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
472       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
473       PointerType *FuncPtrTy =
474           FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
475       Assert1(STy && STy->getNumElements() == 2 &&
476               STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
477               STy->getTypeAtIndex(1) == FuncPtrTy,
478               "wrong type for intrinsic global variable", &GV);
479     }
480   }
481
482   if (GV.hasName() && (GV.getName() == "llvm.used" ||
483                        GV.getName() == "llvm.compiler.used")) {
484     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
485             "invalid linkage for intrinsic global variable", &GV);
486     Type *GVType = GV.getType()->getElementType();
487     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
488       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
489       Assert1(PTy, "wrong type for intrinsic global variable", &GV);
490       if (GV.hasInitializer()) {
491         Constant *Init = GV.getInitializer();
492         ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
493         Assert1(InitArray, "wrong initalizer for intrinsic global variable",
494                 Init);
495         for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
496           Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
497           Assert1(
498               isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
499               "invalid llvm.used member", V);
500           Assert1(V->hasName(), "members of llvm.used must be named", V);
501         }
502       }
503     }
504   }
505
506   if (!GV.hasInitializer()) {
507     visitGlobalValue(GV);
508     return;
509   }
510
511   // Walk any aggregate initializers looking for bitcasts between address spaces
512   SmallPtrSet<const Value *, 4> Visited;
513   SmallVector<const Value *, 4> WorkStack;
514   WorkStack.push_back(cast<Value>(GV.getInitializer()));
515
516   while (!WorkStack.empty()) {
517     const Value *V = WorkStack.pop_back_val();
518     if (!Visited.insert(V))
519       continue;
520
521     if (const User *U = dyn_cast<User>(V)) {
522       for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
523         WorkStack.push_back(U->getOperand(I));
524     }
525
526     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
527       VerifyConstantExprBitcastType(CE);
528       if (Broken)
529         return;
530     }
531   }
532
533   visitGlobalValue(GV);
534 }
535
536 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
537   Assert1(!GA.getName().empty(),
538           "Alias name cannot be empty!", &GA);
539   Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
540           "Alias should have external or external weak linkage!", &GA);
541   Assert1(GA.getAliasee(),
542           "Aliasee cannot be NULL!", &GA);
543   Assert1(GA.getType() == GA.getAliasee()->getType(),
544           "Alias and aliasee types should match!", &GA);
545   Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
546
547   Constant *Aliasee = GA.getAliasee();
548
549   if (!isa<GlobalValue>(Aliasee)) {
550     ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
551     Assert1(CE &&
552             (CE->getOpcode() == Instruction::BitCast ||
553              CE->getOpcode() == Instruction::AddrSpaceCast ||
554              CE->getOpcode() == Instruction::GetElementPtr) &&
555             isa<GlobalValue>(CE->getOperand(0)),
556             "Aliasee should be either GlobalValue, bitcast or "
557              "addrspacecast of GlobalValue",
558             &GA);
559
560     if (CE->getOpcode() == Instruction::BitCast) {
561       unsigned SrcAS = CE->getOperand(0)->getType()->getPointerAddressSpace();
562       unsigned DstAS = CE->getType()->getPointerAddressSpace();
563
564       Assert1(SrcAS == DstAS,
565               "Alias bitcasts cannot be between different address spaces",
566               &GA);
567     }
568   }
569
570   const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
571   Assert1(Resolved,
572           "Aliasing chain should end with function or global variable", &GA);
573
574   visitGlobalValue(GA);
575 }
576
577 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
578   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
579     MDNode *MD = NMD.getOperand(i);
580     if (!MD)
581       continue;
582
583     Assert1(!MD->isFunctionLocal(),
584             "Named metadata operand cannot be function local!", MD);
585     visitMDNode(*MD, 0);
586   }
587 }
588
589 void Verifier::visitMDNode(MDNode &MD, Function *F) {
590   // Only visit each node once.  Metadata can be mutually recursive, so this
591   // avoids infinite recursion here, as well as being an optimization.
592   if (!MDNodes.insert(&MD))
593     return;
594
595   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
596     Value *Op = MD.getOperand(i);
597     if (!Op)
598       continue;
599     if (isa<Constant>(Op) || isa<MDString>(Op))
600       continue;
601     if (MDNode *N = dyn_cast<MDNode>(Op)) {
602       Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
603               "Global metadata operand cannot be function local!", &MD, N);
604       visitMDNode(*N, F);
605       continue;
606     }
607     Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
608
609     // If this was an instruction, bb, or argument, verify that it is in the
610     // function that we expect.
611     Function *ActualF = 0;
612     if (Instruction *I = dyn_cast<Instruction>(Op))
613       ActualF = I->getParent()->getParent();
614     else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
615       ActualF = BB->getParent();
616     else if (Argument *A = dyn_cast<Argument>(Op))
617       ActualF = A->getParent();
618     assert(ActualF && "Unimplemented function local metadata case!");
619
620     Assert2(ActualF == F, "function-local metadata used in wrong function",
621             &MD, Op);
622   }
623 }
624
625 void Verifier::visitModuleIdents(Module &M) {
626   const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
627   if (!Idents) 
628     return;
629   
630   // llvm.ident takes a list of metadata entry. Each entry has only one string.
631   // Scan each llvm.ident entry and make sure that this requirement is met.
632   for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
633     const MDNode *N = Idents->getOperand(i);
634     Assert1(N->getNumOperands() == 1,
635             "incorrect number of operands in llvm.ident metadata", N);
636     Assert1(isa<MDString>(N->getOperand(0)),
637             ("invalid value for llvm.ident metadata entry operand"
638              "(the operand should be a string)"),
639             N->getOperand(0));
640   } 
641 }
642
643 void Verifier::visitModuleFlags(Module &M) {
644   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
645   if (!Flags) return;
646
647   // Scan each flag, and track the flags and requirements.
648   DenseMap<MDString*, MDNode*> SeenIDs;
649   SmallVector<MDNode*, 16> Requirements;
650   for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
651     visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
652   }
653
654   // Validate that the requirements in the module are valid.
655   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
656     MDNode *Requirement = Requirements[I];
657     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
658     Value *ReqValue = Requirement->getOperand(1);
659
660     MDNode *Op = SeenIDs.lookup(Flag);
661     if (!Op) {
662       CheckFailed("invalid requirement on flag, flag is not present in module",
663                   Flag);
664       continue;
665     }
666
667     if (Op->getOperand(2) != ReqValue) {
668       CheckFailed(("invalid requirement on flag, "
669                    "flag does not have the required value"),
670                   Flag);
671       continue;
672     }
673   }
674 }
675
676 void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
677                                SmallVectorImpl<MDNode*> &Requirements) {
678   // Each module flag should have three arguments, the merge behavior (a
679   // constant int), the flag ID (an MDString), and the value.
680   Assert1(Op->getNumOperands() == 3,
681           "incorrect number of operands in module flag", Op);
682   ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
683   MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
684   Assert1(Behavior,
685           "invalid behavior operand in module flag (expected constant integer)",
686           Op->getOperand(0));
687   unsigned BehaviorValue = Behavior->getZExtValue();
688   Assert1(ID,
689           "invalid ID operand in module flag (expected metadata string)",
690           Op->getOperand(1));
691
692   // Sanity check the values for behaviors with additional requirements.
693   switch (BehaviorValue) {
694   default:
695     Assert1(false,
696             "invalid behavior operand in module flag (unexpected constant)",
697             Op->getOperand(0));
698     break;
699
700   case Module::Error:
701   case Module::Warning:
702   case Module::Override:
703     // These behavior types accept any value.
704     break;
705
706   case Module::Require: {
707     // The value should itself be an MDNode with two operands, a flag ID (an
708     // MDString), and a value.
709     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
710     Assert1(Value && Value->getNumOperands() == 2,
711             "invalid value for 'require' module flag (expected metadata pair)",
712             Op->getOperand(2));
713     Assert1(isa<MDString>(Value->getOperand(0)),
714             ("invalid value for 'require' module flag "
715              "(first value operand should be a string)"),
716             Value->getOperand(0));
717
718     // Append it to the list of requirements, to check once all module flags are
719     // scanned.
720     Requirements.push_back(Value);
721     break;
722   }
723
724   case Module::Append:
725   case Module::AppendUnique: {
726     // These behavior types require the operand be an MDNode.
727     Assert1(isa<MDNode>(Op->getOperand(2)),
728             "invalid value for 'append'-type module flag "
729             "(expected a metadata node)", Op->getOperand(2));
730     break;
731   }
732   }
733
734   // Unless this is a "requires" flag, check the ID is unique.
735   if (BehaviorValue != Module::Require) {
736     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
737     Assert1(Inserted,
738             "module flag identifiers must be unique (or of 'require' type)",
739             ID);
740   }
741 }
742
743 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
744                                     bool isFunction, const Value *V) {
745   unsigned Slot = ~0U;
746   for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
747     if (Attrs.getSlotIndex(I) == Idx) {
748       Slot = I;
749       break;
750     }
751
752   assert(Slot != ~0U && "Attribute set inconsistency!");
753
754   for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
755          I != E; ++I) {
756     if (I->isStringAttribute())
757       continue;
758
759     if (I->getKindAsEnum() == Attribute::NoReturn ||
760         I->getKindAsEnum() == Attribute::NoUnwind ||
761         I->getKindAsEnum() == Attribute::NoInline ||
762         I->getKindAsEnum() == Attribute::AlwaysInline ||
763         I->getKindAsEnum() == Attribute::OptimizeForSize ||
764         I->getKindAsEnum() == Attribute::StackProtect ||
765         I->getKindAsEnum() == Attribute::StackProtectReq ||
766         I->getKindAsEnum() == Attribute::StackProtectStrong ||
767         I->getKindAsEnum() == Attribute::NoRedZone ||
768         I->getKindAsEnum() == Attribute::NoImplicitFloat ||
769         I->getKindAsEnum() == Attribute::Naked ||
770         I->getKindAsEnum() == Attribute::InlineHint ||
771         I->getKindAsEnum() == Attribute::StackAlignment ||
772         I->getKindAsEnum() == Attribute::UWTable ||
773         I->getKindAsEnum() == Attribute::NonLazyBind ||
774         I->getKindAsEnum() == Attribute::ReturnsTwice ||
775         I->getKindAsEnum() == Attribute::SanitizeAddress ||
776         I->getKindAsEnum() == Attribute::SanitizeThread ||
777         I->getKindAsEnum() == Attribute::SanitizeMemory ||
778         I->getKindAsEnum() == Attribute::MinSize ||
779         I->getKindAsEnum() == Attribute::NoDuplicate ||
780         I->getKindAsEnum() == Attribute::Builtin ||
781         I->getKindAsEnum() == Attribute::NoBuiltin ||
782         I->getKindAsEnum() == Attribute::Cold ||
783         I->getKindAsEnum() == Attribute::OptimizeNone) {
784       if (!isFunction) {
785         CheckFailed("Attribute '" + I->getAsString() +
786                     "' only applies to functions!", V);
787         return;
788       }
789     } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
790                I->getKindAsEnum() == Attribute::ReadNone) {
791       if (Idx == 0) {
792         CheckFailed("Attribute '" + I->getAsString() +
793                     "' does not apply to function returns");
794         return;
795       }
796     } else if (isFunction) {
797       CheckFailed("Attribute '" + I->getAsString() +
798                   "' does not apply to functions!", V);
799       return;
800     }
801   }
802 }
803
804 // VerifyParameterAttrs - Check the given attributes for an argument or return
805 // value of the specified type.  The value V is printed in error messages.
806 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
807                                     bool isReturnValue, const Value *V) {
808   if (!Attrs.hasAttributes(Idx))
809     return;
810
811   VerifyAttributeTypes(Attrs, Idx, false, V);
812
813   if (isReturnValue)
814     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
815             !Attrs.hasAttribute(Idx, Attribute::Nest) &&
816             !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
817             !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
818             !Attrs.hasAttribute(Idx, Attribute::Returned) &&
819             !Attrs.hasAttribute(Idx, Attribute::InAlloca),
820             "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
821             "'returned' do not apply to return values!", V);
822
823   // Check for mutually incompatible attributes.  Only inreg is compatible with
824   // sret.
825   unsigned AttrCount = 0;
826   AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
827   AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
828   AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
829                Attrs.hasAttribute(Idx, Attribute::InReg);
830   AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
831   Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
832                           "and 'sret' are incompatible!", V);
833
834   Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
835             Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
836           "'inalloca and readonly' are incompatible!", V);
837
838   Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
839             Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
840           "'sret and returned' are incompatible!", V);
841
842   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
843             Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
844           "'zeroext and signext' are incompatible!", V);
845
846   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
847             Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
848           "'readnone and readonly' are incompatible!", V);
849
850   Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
851             Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
852           "'noinline and alwaysinline' are incompatible!", V);
853
854   Assert1(!AttrBuilder(Attrs, Idx).
855             hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
856           "Wrong types for attribute: " +
857           AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
858
859   if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
860     if (!PTy->getElementType()->isSized()) {
861       Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
862               !Attrs.hasAttribute(Idx, Attribute::InAlloca),
863               "Attributes 'byval' and 'inalloca' do not support unsized types!",
864               V);
865     }
866   } else {
867     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
868             "Attribute 'byval' only applies to parameters with pointer type!",
869             V);
870   }
871 }
872
873 // VerifyFunctionAttrs - Check parameter attributes against a function type.
874 // The value V is printed in error messages.
875 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
876                                    const Value *V) {
877   if (Attrs.isEmpty())
878     return;
879
880   bool SawNest = false;
881   bool SawReturned = false;
882
883   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
884     unsigned Idx = Attrs.getSlotIndex(i);
885
886     Type *Ty;
887     if (Idx == 0)
888       Ty = FT->getReturnType();
889     else if (Idx-1 < FT->getNumParams())
890       Ty = FT->getParamType(Idx-1);
891     else
892       break;  // VarArgs attributes, verified elsewhere.
893
894     VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
895
896     if (Idx == 0)
897       continue;
898
899     if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
900       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
901       SawNest = true;
902     }
903
904     if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
905       Assert1(!SawReturned, "More than one parameter has attribute returned!",
906               V);
907       Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
908               "argument and return types for 'returned' attribute", V);
909       SawReturned = true;
910     }
911
912     if (Attrs.hasAttribute(Idx, Attribute::StructRet))
913       Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
914   }
915
916   if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
917     return;
918
919   VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
920
921   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
922                                Attribute::ReadNone) &&
923             Attrs.hasAttribute(AttributeSet::FunctionIndex,
924                                Attribute::ReadOnly)),
925           "Attributes 'readnone and readonly' are incompatible!", V);
926
927   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
928                                Attribute::NoInline) &&
929             Attrs.hasAttribute(AttributeSet::FunctionIndex,
930                                Attribute::AlwaysInline)),
931           "Attributes 'noinline and alwaysinline' are incompatible!", V);
932
933   if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 
934                          Attribute::OptimizeNone)) {
935     Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
936                                Attribute::NoInline),
937             "Attribute 'optnone' requires 'noinline'!", V);
938
939     Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
940                                 Attribute::OptimizeForSize),
941             "Attributes 'optsize and optnone' are incompatible!", V);
942
943     Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
944                                 Attribute::MinSize),
945             "Attributes 'minsize and optnone' are incompatible!", V);
946   }
947 }
948
949 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
950   // Get the size of the types in bits, we'll need this later
951   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
952   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
953
954   // BitCast implies a no-op cast of type only. No bits change.
955   // However, you can't cast pointers to anything but pointers.
956   Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
957           "Bitcast requires both operands to be pointer or neither", V);
958   Assert1(SrcBitSize == DestBitSize,
959           "Bitcast requires types of same width", V);
960
961   // Disallow aggregates.
962   Assert1(!SrcTy->isAggregateType(),
963           "Bitcast operand must not be aggregate", V);
964   Assert1(!DestTy->isAggregateType(),
965           "Bitcast type must not be aggregate", V);
966
967   // Without datalayout, assume all address spaces are the same size.
968   // Don't check if both types are not pointers.
969   // Skip casts between scalars and vectors.
970   if (!DL ||
971       !SrcTy->isPtrOrPtrVectorTy() ||
972       !DestTy->isPtrOrPtrVectorTy() ||
973       SrcTy->isVectorTy() != DestTy->isVectorTy()) {
974     return;
975   }
976
977   unsigned SrcAS = SrcTy->getPointerAddressSpace();
978   unsigned DstAS = DestTy->getPointerAddressSpace();
979
980   Assert1(SrcAS == DstAS,
981           "Bitcasts between pointers of different address spaces is not legal."
982           "Use AddrSpaceCast instead.", V);
983 }
984
985 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
986   if (CE->getOpcode() == Instruction::BitCast) {
987     Type *SrcTy = CE->getOperand(0)->getType();
988     Type *DstTy = CE->getType();
989     VerifyBitcastType(CE, DstTy, SrcTy);
990   }
991 }
992
993 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
994   if (Attrs.getNumSlots() == 0)
995     return true;
996
997   unsigned LastSlot = Attrs.getNumSlots() - 1;
998   unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
999   if (LastIndex <= Params
1000       || (LastIndex == AttributeSet::FunctionIndex
1001           && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1002     return true;
1003
1004   return false;
1005 }
1006
1007 // visitFunction - Verify that a function is ok.
1008 //
1009 void Verifier::visitFunction(Function &F) {
1010   // Check function arguments.
1011   FunctionType *FT = F.getFunctionType();
1012   unsigned NumArgs = F.arg_size();
1013
1014   Assert1(Context == &F.getContext(),
1015           "Function context does not match Module context!", &F);
1016
1017   Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1018   Assert2(FT->getNumParams() == NumArgs,
1019           "# formal arguments must match # of arguments for function type!",
1020           &F, FT);
1021   Assert1(F.getReturnType()->isFirstClassType() ||
1022           F.getReturnType()->isVoidTy() ||
1023           F.getReturnType()->isStructTy(),
1024           "Functions cannot return aggregate values!", &F);
1025
1026   Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1027           "Invalid struct return type!", &F);
1028
1029   AttributeSet Attrs = F.getAttributes();
1030
1031   Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
1032           "Attribute after last parameter!", &F);
1033
1034   // Check function attributes.
1035   VerifyFunctionAttrs(FT, Attrs, &F);
1036
1037   // On function declarations/definitions, we do not support the builtin
1038   // attribute. We do not check this in VerifyFunctionAttrs since that is
1039   // checking for Attributes that can/can not ever be on functions.
1040   Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1041                               Attribute::Builtin),
1042           "Attribute 'builtin' can only be applied to a callsite.", &F);
1043
1044   // Check that this function meets the restrictions on this calling convention.
1045   switch (F.getCallingConv()) {
1046   default:
1047     break;
1048   case CallingConv::C:
1049     break;
1050   case CallingConv::Fast:
1051   case CallingConv::Cold:
1052   case CallingConv::X86_FastCall:
1053   case CallingConv::X86_ThisCall:
1054   case CallingConv::Intel_OCL_BI:
1055   case CallingConv::PTX_Kernel:
1056   case CallingConv::PTX_Device:
1057     Assert1(!F.isVarArg(),
1058             "Varargs functions must have C calling conventions!", &F);
1059     break;
1060   }
1061
1062   bool isLLVMdotName = F.getName().size() >= 5 &&
1063                        F.getName().substr(0, 5) == "llvm.";
1064
1065   // Check that the argument values match the function type for this function...
1066   unsigned i = 0;
1067   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1068        I != E; ++I, ++i) {
1069     Assert2(I->getType() == FT->getParamType(i),
1070             "Argument value does not match function argument type!",
1071             I, FT->getParamType(i));
1072     Assert1(I->getType()->isFirstClassType(),
1073             "Function arguments must have first-class types!", I);
1074     if (!isLLVMdotName)
1075       Assert2(!I->getType()->isMetadataTy(),
1076               "Function takes metadata but isn't an intrinsic", I, &F);
1077   }
1078
1079   if (F.isMaterializable()) {
1080     // Function has a body somewhere we can't see.
1081   } else if (F.isDeclaration()) {
1082     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
1083             F.hasExternalWeakLinkage(),
1084             "invalid linkage type for function declaration", &F);
1085   } else {
1086     // Verify that this function (which has a body) is not named "llvm.*".  It
1087     // is not legal to define intrinsics.
1088     Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1089
1090     // Check the entry node
1091     BasicBlock *Entry = &F.getEntryBlock();
1092     Assert1(pred_begin(Entry) == pred_end(Entry),
1093             "Entry block to function must not have predecessors!", Entry);
1094
1095     // The address of the entry block cannot be taken, unless it is dead.
1096     if (Entry->hasAddressTaken()) {
1097       Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
1098               "blockaddress may not be used with the entry block!", Entry);
1099     }
1100   }
1101
1102   // If this function is actually an intrinsic, verify that it is only used in
1103   // direct call/invokes, never having its "address taken".
1104   if (F.getIntrinsicID()) {
1105     const User *U;
1106     if (F.hasAddressTaken(&U))
1107       Assert1(0, "Invalid user of intrinsic instruction!", U);
1108   }
1109 }
1110
1111 // verifyBasicBlock - Verify that a basic block is well formed...
1112 //
1113 void Verifier::visitBasicBlock(BasicBlock &BB) {
1114   InstsInThisBlock.clear();
1115
1116   // Ensure that basic blocks have terminators!
1117   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1118
1119   // Check constraints that this basic block imposes on all of the PHI nodes in
1120   // it.
1121   if (isa<PHINode>(BB.front())) {
1122     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1123     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1124     std::sort(Preds.begin(), Preds.end());
1125     PHINode *PN;
1126     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1127       // Ensure that PHI nodes have at least one entry!
1128       Assert1(PN->getNumIncomingValues() != 0,
1129               "PHI nodes must have at least one entry.  If the block is dead, "
1130               "the PHI should be removed!", PN);
1131       Assert1(PN->getNumIncomingValues() == Preds.size(),
1132               "PHINode should have one entry for each predecessor of its "
1133               "parent basic block!", PN);
1134
1135       // Get and sort all incoming values in the PHI node...
1136       Values.clear();
1137       Values.reserve(PN->getNumIncomingValues());
1138       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1139         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1140                                         PN->getIncomingValue(i)));
1141       std::sort(Values.begin(), Values.end());
1142
1143       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1144         // Check to make sure that if there is more than one entry for a
1145         // particular basic block in this PHI node, that the incoming values are
1146         // all identical.
1147         //
1148         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
1149                 Values[i].second == Values[i-1].second,
1150                 "PHI node has multiple entries for the same basic block with "
1151                 "different incoming values!", PN, Values[i].first,
1152                 Values[i].second, Values[i-1].second);
1153
1154         // Check to make sure that the predecessors and PHI node entries are
1155         // matched up.
1156         Assert3(Values[i].first == Preds[i],
1157                 "PHI node entries do not match predecessors!", PN,
1158                 Values[i].first, Preds[i]);
1159       }
1160     }
1161   }
1162 }
1163
1164 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1165   // Ensure that terminators only exist at the end of the basic block.
1166   Assert1(&I == I.getParent()->getTerminator(),
1167           "Terminator found in the middle of a basic block!", I.getParent());
1168   visitInstruction(I);
1169 }
1170
1171 void Verifier::visitBranchInst(BranchInst &BI) {
1172   if (BI.isConditional()) {
1173     Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1174             "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1175   }
1176   visitTerminatorInst(BI);
1177 }
1178
1179 void Verifier::visitReturnInst(ReturnInst &RI) {
1180   Function *F = RI.getParent()->getParent();
1181   unsigned N = RI.getNumOperands();
1182   if (F->getReturnType()->isVoidTy())
1183     Assert2(N == 0,
1184             "Found return instr that returns non-void in Function of void "
1185             "return type!", &RI, F->getReturnType());
1186   else
1187     Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1188             "Function return type does not match operand "
1189             "type of return inst!", &RI, F->getReturnType());
1190
1191   // Check to make sure that the return value has necessary properties for
1192   // terminators...
1193   visitTerminatorInst(RI);
1194 }
1195
1196 void Verifier::visitSwitchInst(SwitchInst &SI) {
1197   // Check to make sure that all of the constants in the switch instruction
1198   // have the same type as the switched-on value.
1199   Type *SwitchTy = SI.getCondition()->getType();
1200   SmallPtrSet<ConstantInt*, 32> Constants;
1201   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1202     Assert1(i.getCaseValue()->getType() == SwitchTy,
1203             "Switch constants must all be same type as switch value!", &SI);
1204     Assert2(Constants.insert(i.getCaseValue()),
1205             "Duplicate integer as switch case", &SI, i.getCaseValue());
1206   }
1207
1208   visitTerminatorInst(SI);
1209 }
1210
1211 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1212   Assert1(BI.getAddress()->getType()->isPointerTy(),
1213           "Indirectbr operand must have pointer type!", &BI);
1214   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1215     Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1216             "Indirectbr destinations must all have pointer type!", &BI);
1217
1218   visitTerminatorInst(BI);
1219 }
1220
1221 void Verifier::visitSelectInst(SelectInst &SI) {
1222   Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1223                                           SI.getOperand(2)),
1224           "Invalid operands for select instruction!", &SI);
1225
1226   Assert1(SI.getTrueValue()->getType() == SI.getType(),
1227           "Select values must have same type as select instruction!", &SI);
1228   visitInstruction(SI);
1229 }
1230
1231 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1232 /// a pass, if any exist, it's an error.
1233 ///
1234 void Verifier::visitUserOp1(Instruction &I) {
1235   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1236 }
1237
1238 void Verifier::visitTruncInst(TruncInst &I) {
1239   // Get the source and destination types
1240   Type *SrcTy = I.getOperand(0)->getType();
1241   Type *DestTy = I.getType();
1242
1243   // Get the size of the types in bits, we'll need this later
1244   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1245   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1246
1247   Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1248   Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1249   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1250           "trunc source and destination must both be a vector or neither", &I);
1251   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1252
1253   visitInstruction(I);
1254 }
1255
1256 void Verifier::visitZExtInst(ZExtInst &I) {
1257   // Get the source and destination types
1258   Type *SrcTy = I.getOperand(0)->getType();
1259   Type *DestTy = I.getType();
1260
1261   // Get the size of the types in bits, we'll need this later
1262   Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1263   Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1264   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1265           "zext source and destination must both be a vector or neither", &I);
1266   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1267   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1268
1269   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1270
1271   visitInstruction(I);
1272 }
1273
1274 void Verifier::visitSExtInst(SExtInst &I) {
1275   // Get the source and destination types
1276   Type *SrcTy = I.getOperand(0)->getType();
1277   Type *DestTy = I.getType();
1278
1279   // Get the size of the types in bits, we'll need this later
1280   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1281   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1282
1283   Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1284   Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1285   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1286           "sext source and destination must both be a vector or neither", &I);
1287   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1288
1289   visitInstruction(I);
1290 }
1291
1292 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1293   // Get the source and destination types
1294   Type *SrcTy = I.getOperand(0)->getType();
1295   Type *DestTy = I.getType();
1296   // Get the size of the types in bits, we'll need this later
1297   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1298   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1299
1300   Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1301   Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1302   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1303           "fptrunc source and destination must both be a vector or neither",&I);
1304   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1305
1306   visitInstruction(I);
1307 }
1308
1309 void Verifier::visitFPExtInst(FPExtInst &I) {
1310   // Get the source and destination types
1311   Type *SrcTy = I.getOperand(0)->getType();
1312   Type *DestTy = I.getType();
1313
1314   // Get the size of the types in bits, we'll need this later
1315   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1316   unsigned DestBitSize = DestTy->getScalarSizeInBits();
1317
1318   Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1319   Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1320   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1321           "fpext source and destination must both be a vector or neither", &I);
1322   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1323
1324   visitInstruction(I);
1325 }
1326
1327 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1328   // Get the source and destination types
1329   Type *SrcTy = I.getOperand(0)->getType();
1330   Type *DestTy = I.getType();
1331
1332   bool SrcVec = SrcTy->isVectorTy();
1333   bool DstVec = DestTy->isVectorTy();
1334
1335   Assert1(SrcVec == DstVec,
1336           "UIToFP source and dest must both be vector or scalar", &I);
1337   Assert1(SrcTy->isIntOrIntVectorTy(),
1338           "UIToFP source must be integer or integer vector", &I);
1339   Assert1(DestTy->isFPOrFPVectorTy(),
1340           "UIToFP result must be FP or FP vector", &I);
1341
1342   if (SrcVec && DstVec)
1343     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1344             cast<VectorType>(DestTy)->getNumElements(),
1345             "UIToFP source and dest vector length mismatch", &I);
1346
1347   visitInstruction(I);
1348 }
1349
1350 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1351   // Get the source and destination types
1352   Type *SrcTy = I.getOperand(0)->getType();
1353   Type *DestTy = I.getType();
1354
1355   bool SrcVec = SrcTy->isVectorTy();
1356   bool DstVec = DestTy->isVectorTy();
1357
1358   Assert1(SrcVec == DstVec,
1359           "SIToFP source and dest must both be vector or scalar", &I);
1360   Assert1(SrcTy->isIntOrIntVectorTy(),
1361           "SIToFP source must be integer or integer vector", &I);
1362   Assert1(DestTy->isFPOrFPVectorTy(),
1363           "SIToFP result must be FP or FP vector", &I);
1364
1365   if (SrcVec && DstVec)
1366     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1367             cast<VectorType>(DestTy)->getNumElements(),
1368             "SIToFP source and dest vector length mismatch", &I);
1369
1370   visitInstruction(I);
1371 }
1372
1373 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1374   // Get the source and destination types
1375   Type *SrcTy = I.getOperand(0)->getType();
1376   Type *DestTy = I.getType();
1377
1378   bool SrcVec = SrcTy->isVectorTy();
1379   bool DstVec = DestTy->isVectorTy();
1380
1381   Assert1(SrcVec == DstVec,
1382           "FPToUI source and dest must both be vector or scalar", &I);
1383   Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1384           &I);
1385   Assert1(DestTy->isIntOrIntVectorTy(),
1386           "FPToUI result must be integer or integer vector", &I);
1387
1388   if (SrcVec && DstVec)
1389     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1390             cast<VectorType>(DestTy)->getNumElements(),
1391             "FPToUI source and dest vector length mismatch", &I);
1392
1393   visitInstruction(I);
1394 }
1395
1396 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1397   // Get the source and destination types
1398   Type *SrcTy = I.getOperand(0)->getType();
1399   Type *DestTy = I.getType();
1400
1401   bool SrcVec = SrcTy->isVectorTy();
1402   bool DstVec = DestTy->isVectorTy();
1403
1404   Assert1(SrcVec == DstVec,
1405           "FPToSI source and dest must both be vector or scalar", &I);
1406   Assert1(SrcTy->isFPOrFPVectorTy(),
1407           "FPToSI source must be FP or FP vector", &I);
1408   Assert1(DestTy->isIntOrIntVectorTy(),
1409           "FPToSI result must be integer or integer vector", &I);
1410
1411   if (SrcVec && DstVec)
1412     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1413             cast<VectorType>(DestTy)->getNumElements(),
1414             "FPToSI source and dest vector length mismatch", &I);
1415
1416   visitInstruction(I);
1417 }
1418
1419 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1420   // Get the source and destination types
1421   Type *SrcTy = I.getOperand(0)->getType();
1422   Type *DestTy = I.getType();
1423
1424   Assert1(SrcTy->getScalarType()->isPointerTy(),
1425           "PtrToInt source must be pointer", &I);
1426   Assert1(DestTy->getScalarType()->isIntegerTy(),
1427           "PtrToInt result must be integral", &I);
1428   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1429           "PtrToInt type mismatch", &I);
1430
1431   if (SrcTy->isVectorTy()) {
1432     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1433     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1434     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1435           "PtrToInt Vector width mismatch", &I);
1436   }
1437
1438   visitInstruction(I);
1439 }
1440
1441 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1442   // Get the source and destination types
1443   Type *SrcTy = I.getOperand(0)->getType();
1444   Type *DestTy = I.getType();
1445
1446   Assert1(SrcTy->getScalarType()->isIntegerTy(),
1447           "IntToPtr source must be an integral", &I);
1448   Assert1(DestTy->getScalarType()->isPointerTy(),
1449           "IntToPtr result must be a pointer",&I);
1450   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1451           "IntToPtr type mismatch", &I);
1452   if (SrcTy->isVectorTy()) {
1453     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1454     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1455     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1456           "IntToPtr Vector width mismatch", &I);
1457   }
1458   visitInstruction(I);
1459 }
1460
1461 void Verifier::visitBitCastInst(BitCastInst &I) {
1462   Type *SrcTy = I.getOperand(0)->getType();
1463   Type *DestTy = I.getType();
1464   VerifyBitcastType(&I, DestTy, SrcTy);
1465   visitInstruction(I);
1466 }
1467
1468 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1469   Type *SrcTy = I.getOperand(0)->getType();
1470   Type *DestTy = I.getType();
1471
1472   Assert1(SrcTy->isPtrOrPtrVectorTy(),
1473           "AddrSpaceCast source must be a pointer", &I);
1474   Assert1(DestTy->isPtrOrPtrVectorTy(),
1475           "AddrSpaceCast result must be a pointer", &I);
1476   Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1477           "AddrSpaceCast must be between different address spaces", &I);
1478   if (SrcTy->isVectorTy())
1479     Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1480             "AddrSpaceCast vector pointer number of elements mismatch", &I);
1481   visitInstruction(I);
1482 }
1483
1484 /// visitPHINode - Ensure that a PHI node is well formed.
1485 ///
1486 void Verifier::visitPHINode(PHINode &PN) {
1487   // Ensure that the PHI nodes are all grouped together at the top of the block.
1488   // This can be tested by checking whether the instruction before this is
1489   // either nonexistent (because this is begin()) or is a PHI node.  If not,
1490   // then there is some other instruction before a PHI.
1491   Assert2(&PN == &PN.getParent()->front() ||
1492           isa<PHINode>(--BasicBlock::iterator(&PN)),
1493           "PHI nodes not grouped at top of basic block!",
1494           &PN, PN.getParent());
1495
1496   // Check that all of the values of the PHI node have the same type as the
1497   // result, and that the incoming blocks are really basic blocks.
1498   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1499     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1500             "PHI node operands are not the same type as the result!", &PN);
1501   }
1502
1503   // All other PHI node constraints are checked in the visitBasicBlock method.
1504
1505   visitInstruction(PN);
1506 }
1507
1508 void Verifier::VerifyCallSite(CallSite CS) {
1509   Instruction *I = CS.getInstruction();
1510
1511   Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1512           "Called function must be a pointer!", I);
1513   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1514
1515   Assert1(FPTy->getElementType()->isFunctionTy(),
1516           "Called function is not pointer to function type!", I);
1517   FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1518
1519   // Verify that the correct number of arguments are being passed
1520   if (FTy->isVarArg())
1521     Assert1(CS.arg_size() >= FTy->getNumParams(),
1522             "Called function requires more parameters than were provided!",I);
1523   else
1524     Assert1(CS.arg_size() == FTy->getNumParams(),
1525             "Incorrect number of arguments passed to called function!", I);
1526
1527   // Verify that all arguments to the call match the function type.
1528   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1529     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1530             "Call parameter type does not match function signature!",
1531             CS.getArgument(i), FTy->getParamType(i), I);
1532
1533   AttributeSet Attrs = CS.getAttributes();
1534
1535   Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1536           "Attribute after last parameter!", I);
1537
1538   // Verify call attributes.
1539   VerifyFunctionAttrs(FTy, Attrs, I);
1540
1541   // Verify that values used for inalloca parameters are in fact allocas.
1542   for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) {
1543     if (!Attrs.hasAttribute(1 + i, Attribute::InAlloca))
1544       continue;
1545     Value *Arg = CS.getArgument(i);
1546     Assert2(isa<AllocaInst>(Arg), "Inalloca argument is not an alloca!", I,
1547             Arg);
1548   }
1549
1550   if (FTy->isVarArg()) {
1551     // FIXME? is 'nest' even legal here?
1552     bool SawNest = false;
1553     bool SawReturned = false;
1554
1555     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1556       if (Attrs.hasAttribute(Idx, Attribute::Nest))
1557         SawNest = true;
1558       if (Attrs.hasAttribute(Idx, Attribute::Returned))
1559         SawReturned = true;
1560     }
1561
1562     // Check attributes on the varargs part.
1563     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1564       Type *Ty = CS.getArgument(Idx-1)->getType();
1565       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1566
1567       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1568         Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1569         SawNest = true;
1570       }
1571
1572       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1573         Assert1(!SawReturned, "More than one parameter has attribute returned!",
1574                 I);
1575         Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1576                 "Incompatible argument and return types for 'returned' "
1577                 "attribute", I);
1578         SawReturned = true;
1579       }
1580
1581       Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1582               "Attribute 'sret' cannot be used for vararg call arguments!", I);
1583     }
1584   }
1585
1586   // Verify that there's no metadata unless it's a direct call to an intrinsic.
1587   if (CS.getCalledFunction() == 0 ||
1588       !CS.getCalledFunction()->getName().startswith("llvm.")) {
1589     for (FunctionType::param_iterator PI = FTy->param_begin(),
1590            PE = FTy->param_end(); PI != PE; ++PI)
1591       Assert1(!(*PI)->isMetadataTy(),
1592               "Function has metadata parameter but isn't an intrinsic", I);
1593   }
1594
1595   visitInstruction(*I);
1596 }
1597
1598 void Verifier::visitCallInst(CallInst &CI) {
1599   VerifyCallSite(&CI);
1600
1601   if (Function *F = CI.getCalledFunction())
1602     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1603       visitIntrinsicFunctionCall(ID, CI);
1604 }
1605
1606 void Verifier::visitInvokeInst(InvokeInst &II) {
1607   VerifyCallSite(&II);
1608
1609   // Verify that there is a landingpad instruction as the first non-PHI
1610   // instruction of the 'unwind' destination.
1611   Assert1(II.getUnwindDest()->isLandingPad(),
1612           "The unwind destination does not have a landingpad instruction!",&II);
1613
1614   visitTerminatorInst(II);
1615 }
1616
1617 /// visitBinaryOperator - Check that both arguments to the binary operator are
1618 /// of the same type!
1619 ///
1620 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1621   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1622           "Both operands to a binary operator are not of the same type!", &B);
1623
1624   switch (B.getOpcode()) {
1625   // Check that integer arithmetic operators are only used with
1626   // integral operands.
1627   case Instruction::Add:
1628   case Instruction::Sub:
1629   case Instruction::Mul:
1630   case Instruction::SDiv:
1631   case Instruction::UDiv:
1632   case Instruction::SRem:
1633   case Instruction::URem:
1634     Assert1(B.getType()->isIntOrIntVectorTy(),
1635             "Integer arithmetic operators only work with integral types!", &B);
1636     Assert1(B.getType() == B.getOperand(0)->getType(),
1637             "Integer arithmetic operators must have same type "
1638             "for operands and result!", &B);
1639     break;
1640   // Check that floating-point arithmetic operators are only used with
1641   // floating-point operands.
1642   case Instruction::FAdd:
1643   case Instruction::FSub:
1644   case Instruction::FMul:
1645   case Instruction::FDiv:
1646   case Instruction::FRem:
1647     Assert1(B.getType()->isFPOrFPVectorTy(),
1648             "Floating-point arithmetic operators only work with "
1649             "floating-point types!", &B);
1650     Assert1(B.getType() == B.getOperand(0)->getType(),
1651             "Floating-point arithmetic operators must have same type "
1652             "for operands and result!", &B);
1653     break;
1654   // Check that logical operators are only used with integral operands.
1655   case Instruction::And:
1656   case Instruction::Or:
1657   case Instruction::Xor:
1658     Assert1(B.getType()->isIntOrIntVectorTy(),
1659             "Logical operators only work with integral types!", &B);
1660     Assert1(B.getType() == B.getOperand(0)->getType(),
1661             "Logical operators must have same type for operands and result!",
1662             &B);
1663     break;
1664   case Instruction::Shl:
1665   case Instruction::LShr:
1666   case Instruction::AShr:
1667     Assert1(B.getType()->isIntOrIntVectorTy(),
1668             "Shifts only work with integral types!", &B);
1669     Assert1(B.getType() == B.getOperand(0)->getType(),
1670             "Shift return type must be same as operands!", &B);
1671     break;
1672   default:
1673     llvm_unreachable("Unknown BinaryOperator opcode!");
1674   }
1675
1676   visitInstruction(B);
1677 }
1678
1679 void Verifier::visitICmpInst(ICmpInst &IC) {
1680   // Check that the operands are the same type
1681   Type *Op0Ty = IC.getOperand(0)->getType();
1682   Type *Op1Ty = IC.getOperand(1)->getType();
1683   Assert1(Op0Ty == Op1Ty,
1684           "Both operands to ICmp instruction are not of the same type!", &IC);
1685   // Check that the operands are the right type
1686   Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1687           "Invalid operand types for ICmp instruction", &IC);
1688   // Check that the predicate is valid.
1689   Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1690           IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1691           "Invalid predicate in ICmp instruction!", &IC);
1692
1693   visitInstruction(IC);
1694 }
1695
1696 void Verifier::visitFCmpInst(FCmpInst &FC) {
1697   // Check that the operands are the same type
1698   Type *Op0Ty = FC.getOperand(0)->getType();
1699   Type *Op1Ty = FC.getOperand(1)->getType();
1700   Assert1(Op0Ty == Op1Ty,
1701           "Both operands to FCmp instruction are not of the same type!", &FC);
1702   // Check that the operands are the right type
1703   Assert1(Op0Ty->isFPOrFPVectorTy(),
1704           "Invalid operand types for FCmp instruction", &FC);
1705   // Check that the predicate is valid.
1706   Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1707           FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1708           "Invalid predicate in FCmp instruction!", &FC);
1709
1710   visitInstruction(FC);
1711 }
1712
1713 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1714   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1715                                               EI.getOperand(1)),
1716           "Invalid extractelement operands!", &EI);
1717   visitInstruction(EI);
1718 }
1719
1720 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1721   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1722                                              IE.getOperand(1),
1723                                              IE.getOperand(2)),
1724           "Invalid insertelement operands!", &IE);
1725   visitInstruction(IE);
1726 }
1727
1728 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1729   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1730                                              SV.getOperand(2)),
1731           "Invalid shufflevector operands!", &SV);
1732   visitInstruction(SV);
1733 }
1734
1735 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1736   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1737
1738   Assert1(isa<PointerType>(TargetTy),
1739     "GEP base pointer is not a vector or a vector of pointers", &GEP);
1740   Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1741           "GEP into unsized type!", &GEP);
1742   Assert1(GEP.getPointerOperandType()->isVectorTy() ==
1743           GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
1744           &GEP);
1745
1746   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1747   Type *ElTy =
1748     GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1749   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1750
1751   Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
1752           cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
1753           == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
1754
1755   if (GEP.getPointerOperandType()->isVectorTy()) {
1756     // Additional checks for vector GEPs.
1757     unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
1758     Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
1759             "Vector GEP result width doesn't match operand's", &GEP);
1760     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1761       Type *IndexTy = Idxs[i]->getType();
1762       Assert1(IndexTy->isVectorTy(),
1763               "Vector GEP must have vector indices!", &GEP);
1764       unsigned IndexWidth = IndexTy->getVectorNumElements();
1765       Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1766     }
1767   }
1768   visitInstruction(GEP);
1769 }
1770
1771 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1772   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1773 }
1774
1775 void Verifier::visitLoadInst(LoadInst &LI) {
1776   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1777   Assert1(PTy, "Load operand must be a pointer.", &LI);
1778   Type *ElTy = PTy->getElementType();
1779   Assert2(ElTy == LI.getType(),
1780           "Load result type does not match pointer operand type!", &LI, ElTy);
1781   if (LI.isAtomic()) {
1782     Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1783             "Load cannot have Release ordering", &LI);
1784     Assert1(LI.getAlignment() != 0,
1785             "Atomic load must specify explicit alignment", &LI);
1786     if (!ElTy->isPointerTy()) {
1787       Assert2(ElTy->isIntegerTy(),
1788               "atomic store operand must have integer type!",
1789               &LI, ElTy);
1790       unsigned Size = ElTy->getPrimitiveSizeInBits();
1791       Assert2(Size >= 8 && !(Size & (Size - 1)),
1792               "atomic store operand must be power-of-two byte-sized integer",
1793               &LI, ElTy);
1794     }
1795   } else {
1796     Assert1(LI.getSynchScope() == CrossThread,
1797             "Non-atomic load cannot have SynchronizationScope specified", &LI);
1798   }
1799
1800   if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1801     unsigned NumOperands = Range->getNumOperands();
1802     Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1803     unsigned NumRanges = NumOperands / 2;
1804     Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1805
1806     ConstantRange LastRange(1); // Dummy initial value
1807     for (unsigned i = 0; i < NumRanges; ++i) {
1808       ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1809       Assert1(Low, "The lower limit must be an integer!", Low);
1810       ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1811       Assert1(High, "The upper limit must be an integer!", High);
1812       Assert1(High->getType() == Low->getType() &&
1813               High->getType() == ElTy, "Range types must match load type!",
1814               &LI);
1815
1816       APInt HighV = High->getValue();
1817       APInt LowV = Low->getValue();
1818       ConstantRange CurRange(LowV, HighV);
1819       Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1820               "Range must not be empty!", Range);
1821       if (i != 0) {
1822         Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1823                 "Intervals are overlapping", Range);
1824         Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1825                 Range);
1826         Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1827                 Range);
1828       }
1829       LastRange = ConstantRange(LowV, HighV);
1830     }
1831     if (NumRanges > 2) {
1832       APInt FirstLow =
1833         dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1834       APInt FirstHigh =
1835         dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1836       ConstantRange FirstRange(FirstLow, FirstHigh);
1837       Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1838               "Intervals are overlapping", Range);
1839       Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1840               Range);
1841     }
1842
1843
1844   }
1845
1846   visitInstruction(LI);
1847 }
1848
1849 void Verifier::visitStoreInst(StoreInst &SI) {
1850   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1851   Assert1(PTy, "Store operand must be a pointer.", &SI);
1852   Type *ElTy = PTy->getElementType();
1853   Assert2(ElTy == SI.getOperand(0)->getType(),
1854           "Stored value type does not match pointer operand type!",
1855           &SI, ElTy);
1856   if (SI.isAtomic()) {
1857     Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1858             "Store cannot have Acquire ordering", &SI);
1859     Assert1(SI.getAlignment() != 0,
1860             "Atomic store must specify explicit alignment", &SI);
1861     if (!ElTy->isPointerTy()) {
1862       Assert2(ElTy->isIntegerTy(),
1863               "atomic store operand must have integer type!",
1864               &SI, ElTy);
1865       unsigned Size = ElTy->getPrimitiveSizeInBits();
1866       Assert2(Size >= 8 && !(Size & (Size - 1)),
1867               "atomic store operand must be power-of-two byte-sized integer",
1868               &SI, ElTy);
1869     }
1870   } else {
1871     Assert1(SI.getSynchScope() == CrossThread,
1872             "Non-atomic store cannot have SynchronizationScope specified", &SI);
1873   }
1874   visitInstruction(SI);
1875 }
1876
1877 void Verifier::visitAllocaInst(AllocaInst &AI) {
1878   SmallPtrSet<const Type*, 4> Visited;
1879   PointerType *PTy = AI.getType();
1880   Assert1(PTy->getAddressSpace() == 0,
1881           "Allocation instruction pointer not in the generic address space!",
1882           &AI);
1883   Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
1884           &AI);
1885   Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1886           "Alloca array size must have integer type", &AI);
1887
1888   // Verify that an alloca instruction is not used with inalloca more than once.
1889   unsigned InAllocaUses = 0;
1890   for (User::use_iterator UI = AI.use_begin(), UE = AI.use_end(); UI != UE;
1891        ++UI) {
1892     CallSite CS(*UI);
1893     if (!CS)
1894       continue;
1895     unsigned ArgNo = CS.getArgumentNo(UI);
1896     if (CS.isInAllocaArgument(ArgNo)) {
1897       InAllocaUses++;
1898       Assert1(InAllocaUses <= 1,
1899               "Allocas can be used at most once with inalloca!", &AI);
1900     }
1901   }
1902
1903   visitInstruction(AI);
1904 }
1905
1906 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1907   Assert1(CXI.getOrdering() != NotAtomic,
1908           "cmpxchg instructions must be atomic.", &CXI);
1909   Assert1(CXI.getOrdering() != Unordered,
1910           "cmpxchg instructions cannot be unordered.", &CXI);
1911   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1912   Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1913   Type *ElTy = PTy->getElementType();
1914   Assert2(ElTy->isIntegerTy(),
1915           "cmpxchg operand must have integer type!",
1916           &CXI, ElTy);
1917   unsigned Size = ElTy->getPrimitiveSizeInBits();
1918   Assert2(Size >= 8 && !(Size & (Size - 1)),
1919           "cmpxchg operand must be power-of-two byte-sized integer",
1920           &CXI, ElTy);
1921   Assert2(ElTy == CXI.getOperand(1)->getType(),
1922           "Expected value type does not match pointer operand type!",
1923           &CXI, ElTy);
1924   Assert2(ElTy == CXI.getOperand(2)->getType(),
1925           "Stored value type does not match pointer operand type!",
1926           &CXI, ElTy);
1927   visitInstruction(CXI);
1928 }
1929
1930 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1931   Assert1(RMWI.getOrdering() != NotAtomic,
1932           "atomicrmw instructions must be atomic.", &RMWI);
1933   Assert1(RMWI.getOrdering() != Unordered,
1934           "atomicrmw instructions cannot be unordered.", &RMWI);
1935   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1936   Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1937   Type *ElTy = PTy->getElementType();
1938   Assert2(ElTy->isIntegerTy(),
1939           "atomicrmw operand must have integer type!",
1940           &RMWI, ElTy);
1941   unsigned Size = ElTy->getPrimitiveSizeInBits();
1942   Assert2(Size >= 8 && !(Size & (Size - 1)),
1943           "atomicrmw operand must be power-of-two byte-sized integer",
1944           &RMWI, ElTy);
1945   Assert2(ElTy == RMWI.getOperand(1)->getType(),
1946           "Argument value type does not match pointer operand type!",
1947           &RMWI, ElTy);
1948   Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1949           RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1950           "Invalid binary operation!", &RMWI);
1951   visitInstruction(RMWI);
1952 }
1953
1954 void Verifier::visitFenceInst(FenceInst &FI) {
1955   const AtomicOrdering Ordering = FI.getOrdering();
1956   Assert1(Ordering == Acquire || Ordering == Release ||
1957           Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1958           "fence instructions may only have "
1959           "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1960   visitInstruction(FI);
1961 }
1962
1963 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1964   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1965                                            EVI.getIndices()) ==
1966           EVI.getType(),
1967           "Invalid ExtractValueInst operands!", &EVI);
1968
1969   visitInstruction(EVI);
1970 }
1971
1972 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1973   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1974                                            IVI.getIndices()) ==
1975           IVI.getOperand(1)->getType(),
1976           "Invalid InsertValueInst operands!", &IVI);
1977
1978   visitInstruction(IVI);
1979 }
1980
1981 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1982   BasicBlock *BB = LPI.getParent();
1983
1984   // The landingpad instruction is ill-formed if it doesn't have any clauses and
1985   // isn't a cleanup.
1986   Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1987           "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1988
1989   // The landingpad instruction defines its parent as a landing pad block. The
1990   // landing pad block may be branched to only by the unwind edge of an invoke.
1991   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1992     const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1993     Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1994             "Block containing LandingPadInst must be jumped to "
1995             "only by the unwind edge of an invoke.", &LPI);
1996   }
1997
1998   // The landingpad instruction must be the first non-PHI instruction in the
1999   // block.
2000   Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
2001           "LandingPadInst not the first non-PHI instruction in the block.",
2002           &LPI);
2003
2004   // The personality functions for all landingpad instructions within the same
2005   // function should match.
2006   if (PersonalityFn)
2007     Assert1(LPI.getPersonalityFn() == PersonalityFn,
2008             "Personality function doesn't match others in function", &LPI);
2009   PersonalityFn = LPI.getPersonalityFn();
2010
2011   // All operands must be constants.
2012   Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2013           &LPI);
2014   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2015     Value *Clause = LPI.getClause(i);
2016     Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
2017     if (LPI.isCatch(i)) {
2018       Assert1(isa<PointerType>(Clause->getType()),
2019               "Catch operand does not have pointer type!", &LPI);
2020     } else {
2021       Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2022       Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2023               "Filter operand is not an array of constants!", &LPI);
2024     }
2025   }
2026
2027   visitInstruction(LPI);
2028 }
2029
2030 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2031   Instruction *Op = cast<Instruction>(I.getOperand(i));
2032   // If the we have an invalid invoke, don't try to compute the dominance.
2033   // We already reject it in the invoke specific checks and the dominance
2034   // computation doesn't handle multiple edges.
2035   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2036     if (II->getNormalDest() == II->getUnwindDest())
2037       return;
2038   }
2039
2040   const Use &U = I.getOperandUse(i);
2041   Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
2042           "Instruction does not dominate all uses!", Op, &I);
2043 }
2044
2045 /// verifyInstruction - Verify that an instruction is well formed.
2046 ///
2047 void Verifier::visitInstruction(Instruction &I) {
2048   BasicBlock *BB = I.getParent();
2049   Assert1(BB, "Instruction not embedded in basic block!", &I);
2050
2051   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
2052     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
2053          UI != UE; ++UI)
2054       Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
2055               "Only PHI nodes may reference their own value!", &I);
2056   }
2057
2058   // Check that void typed values don't have names
2059   Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2060           "Instruction has a name, but provides a void value!", &I);
2061
2062   // Check that the return value of the instruction is either void or a legal
2063   // value type.
2064   Assert1(I.getType()->isVoidTy() ||
2065           I.getType()->isFirstClassType(),
2066           "Instruction returns a non-scalar type!", &I);
2067
2068   // Check that the instruction doesn't produce metadata. Calls are already
2069   // checked against the callee type.
2070   Assert1(!I.getType()->isMetadataTy() ||
2071           isa<CallInst>(I) || isa<InvokeInst>(I),
2072           "Invalid use of metadata!", &I);
2073
2074   // Check that all uses of the instruction, if they are instructions
2075   // themselves, actually have parent basic blocks.  If the use is not an
2076   // instruction, it is an error!
2077   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
2078        UI != UE; ++UI) {
2079     if (Instruction *Used = dyn_cast<Instruction>(*UI))
2080       Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
2081               " embedded in a basic block!", &I, Used);
2082     else {
2083       CheckFailed("Use of instruction is not an instruction!", *UI);
2084       return;
2085     }
2086   }
2087
2088   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2089     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
2090
2091     // Check to make sure that only first-class-values are operands to
2092     // instructions.
2093     if (!I.getOperand(i)->getType()->isFirstClassType()) {
2094       Assert1(0, "Instruction operands must be first-class values!", &I);
2095     }
2096
2097     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2098       // Check to make sure that the "address of" an intrinsic function is never
2099       // taken.
2100       Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
2101               "Cannot take the address of an intrinsic!", &I);
2102       Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2103               F->getIntrinsicID() == Intrinsic::donothing,
2104               "Cannot invoke an intrinsinc other than donothing", &I);
2105       Assert1(F->getParent() == Mod, "Referencing function in another module!",
2106               &I);
2107     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2108       Assert1(OpBB->getParent() == BB->getParent(),
2109               "Referring to a basic block in another function!", &I);
2110     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2111       Assert1(OpArg->getParent() == BB->getParent(),
2112               "Referring to an argument in another function!", &I);
2113     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2114       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
2115               &I);
2116     } else if (isa<Instruction>(I.getOperand(i))) {
2117       verifyDominatesUse(I, i);
2118     } else if (isa<InlineAsm>(I.getOperand(i))) {
2119       Assert1((i + 1 == e && isa<CallInst>(I)) ||
2120               (i + 3 == e && isa<InvokeInst>(I)),
2121               "Cannot take the address of an inline asm!", &I);
2122     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2123       if (CE->getType()->isPtrOrPtrVectorTy()) {
2124         // If we have a ConstantExpr pointer, we need to see if it came from an
2125         // illegal bitcast (inttoptr <constant int> )
2126         SmallVector<const ConstantExpr *, 4> Stack;
2127         SmallPtrSet<const ConstantExpr *, 4> Visited;
2128         Stack.push_back(CE);
2129
2130         while (!Stack.empty()) {
2131           const ConstantExpr *V = Stack.pop_back_val();
2132           if (!Visited.insert(V))
2133             continue;
2134
2135           VerifyConstantExprBitcastType(V);
2136
2137           for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2138             if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2139               Stack.push_back(Op);
2140           }
2141         }
2142       }
2143     }
2144   }
2145
2146   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2147     Assert1(I.getType()->isFPOrFPVectorTy(),
2148             "fpmath requires a floating point result!", &I);
2149     Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2150     Value *Op0 = MD->getOperand(0);
2151     if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
2152       APFloat Accuracy = CFP0->getValueAPF();
2153       Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2154               "fpmath accuracy not a positive number!", &I);
2155     } else {
2156       Assert1(false, "invalid fpmath accuracy!", &I);
2157     }
2158   }
2159
2160   MDNode *MD = I.getMetadata(LLVMContext::MD_range);
2161   Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
2162
2163   if (!DisableDebugInfoVerifier) {
2164     MD = I.getMetadata(LLVMContext::MD_dbg);
2165     Finder.processLocation(*Mod, DILocation(MD));
2166   }
2167
2168   InstsInThisBlock.insert(&I);
2169 }
2170
2171 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2172 /// intrinsic argument or return value) matches the type constraints specified
2173 /// by the .td file (e.g. an "any integer" argument really is an integer).
2174 ///
2175 /// This return true on error but does not print a message.
2176 bool Verifier::VerifyIntrinsicType(Type *Ty,
2177                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
2178                                    SmallVectorImpl<Type*> &ArgTys) {
2179   using namespace Intrinsic;
2180
2181   // If we ran out of descriptors, there are too many arguments.
2182   if (Infos.empty()) return true;
2183   IITDescriptor D = Infos.front();
2184   Infos = Infos.slice(1);
2185
2186   switch (D.Kind) {
2187   case IITDescriptor::Void: return !Ty->isVoidTy();
2188   case IITDescriptor::VarArg: return true;
2189   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
2190   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2191   case IITDescriptor::Half: return !Ty->isHalfTy();
2192   case IITDescriptor::Float: return !Ty->isFloatTy();
2193   case IITDescriptor::Double: return !Ty->isDoubleTy();
2194   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2195   case IITDescriptor::Vector: {
2196     VectorType *VT = dyn_cast<VectorType>(Ty);
2197     return VT == 0 || VT->getNumElements() != D.Vector_Width ||
2198            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2199   }
2200   case IITDescriptor::Pointer: {
2201     PointerType *PT = dyn_cast<PointerType>(Ty);
2202     return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2203            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2204   }
2205
2206   case IITDescriptor::Struct: {
2207     StructType *ST = dyn_cast<StructType>(Ty);
2208     if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
2209       return true;
2210
2211     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2212       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2213         return true;
2214     return false;
2215   }
2216
2217   case IITDescriptor::Argument:
2218     // Two cases here - If this is the second occurrence of an argument, verify
2219     // that the later instance matches the previous instance.
2220     if (D.getArgumentNumber() < ArgTys.size())
2221       return Ty != ArgTys[D.getArgumentNumber()];
2222
2223     // Otherwise, if this is the first instance of an argument, record it and
2224     // verify the "Any" kind.
2225     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2226     ArgTys.push_back(Ty);
2227
2228     switch (D.getArgumentKind()) {
2229     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2230     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
2231     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
2232     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2233     }
2234     llvm_unreachable("all argument kinds not covered");
2235
2236   case IITDescriptor::ExtendVecArgument:
2237     // This may only be used when referring to a previous vector argument.
2238     return D.getArgumentNumber() >= ArgTys.size() ||
2239            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2240            VectorType::getExtendedElementVectorType(
2241                        cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2242
2243   case IITDescriptor::TruncVecArgument:
2244     // This may only be used when referring to a previous vector argument.
2245     return D.getArgumentNumber() >= ArgTys.size() ||
2246            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2247            VectorType::getTruncatedElementVectorType(
2248                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2249   }
2250   llvm_unreachable("unhandled");
2251 }
2252
2253 /// \brief Verify if the intrinsic has variable arguments.
2254 /// This method is intended to be called after all the fixed arguments have been
2255 /// verified first.
2256 ///
2257 /// This method returns true on error and does not print an error message.
2258 bool
2259 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2260                                   ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2261   using namespace Intrinsic;
2262
2263   // If there are no descriptors left, then it can't be a vararg.
2264   if (Infos.empty())
2265     return isVarArg ? true : false;
2266
2267   // There should be only one descriptor remaining at this point.
2268   if (Infos.size() != 1)
2269     return true;
2270
2271   // Check and verify the descriptor.
2272   IITDescriptor D = Infos.front();
2273   Infos = Infos.slice(1);
2274   if (D.Kind == IITDescriptor::VarArg)
2275     return isVarArg ? false : true;
2276
2277   return true;
2278 }
2279
2280 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2281 ///
2282 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2283   Function *IF = CI.getCalledFunction();
2284   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2285           IF);
2286
2287   // Verify that the intrinsic prototype lines up with what the .td files
2288   // describe.
2289   FunctionType *IFTy = IF->getFunctionType();
2290   bool IsVarArg = IFTy->isVarArg();
2291
2292   SmallVector<Intrinsic::IITDescriptor, 8> Table;
2293   getIntrinsicInfoTableEntries(ID, Table);
2294   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2295
2296   SmallVector<Type *, 4> ArgTys;
2297   Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2298           "Intrinsic has incorrect return type!", IF);
2299   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2300     Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2301             "Intrinsic has incorrect argument type!", IF);
2302
2303   // Verify if the intrinsic call matches the vararg property.
2304   if (IsVarArg)
2305     Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2306             "Intrinsic was not defined with variable arguments!", IF);
2307   else
2308     Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2309             "Callsite was not defined with variable arguments!", IF);
2310
2311   // All descriptors should be absorbed by now.
2312   Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2313
2314   // Now that we have the intrinsic ID and the actual argument types (and we
2315   // know they are legal for the intrinsic!) get the intrinsic name through the
2316   // usual means.  This allows us to verify the mangling of argument types into
2317   // the name.
2318   Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
2319           "Intrinsic name not mangled correctly for type arguments!", IF);
2320
2321   // If the intrinsic takes MDNode arguments, verify that they are either global
2322   // or are local to *this* function.
2323   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2324     if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
2325       visitMDNode(*MD, CI.getParent()->getParent());
2326
2327   switch (ID) {
2328   default:
2329     break;
2330   case Intrinsic::ctlz:  // llvm.ctlz
2331   case Intrinsic::cttz:  // llvm.cttz
2332     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2333             "is_zero_undef argument of bit counting intrinsics must be a "
2334             "constant int", &CI);
2335     break;
2336   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
2337     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2338                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2339     MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
2340     Assert1(MD->getNumOperands() == 1,
2341                 "invalid llvm.dbg.declare intrinsic call 2", &CI);
2342     if (!DisableDebugInfoVerifier)
2343       Finder.processDeclare(*Mod, cast<DbgDeclareInst>(&CI));
2344   } break;
2345   case Intrinsic::dbg_value: { //llvm.dbg.value
2346     if (!DisableDebugInfoVerifier) {
2347       Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
2348               "invalid llvm.dbg.value intrinsic call 1", &CI);
2349       Finder.processValue(*Mod, cast<DbgValueInst>(&CI));
2350     }
2351     break;
2352   }
2353   case Intrinsic::memcpy:
2354   case Intrinsic::memmove:
2355   case Intrinsic::memset:
2356     Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
2357             "alignment argument of memory intrinsics must be a constant int",
2358             &CI);
2359     Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2360             "isvolatile argument of memory intrinsics must be a constant int",
2361             &CI);
2362     break;
2363   case Intrinsic::gcroot:
2364   case Intrinsic::gcwrite:
2365   case Intrinsic::gcread:
2366     if (ID == Intrinsic::gcroot) {
2367       AllocaInst *AI =
2368         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2369       Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2370       Assert1(isa<Constant>(CI.getArgOperand(1)),
2371               "llvm.gcroot parameter #2 must be a constant.", &CI);
2372       if (!AI->getType()->getElementType()->isPointerTy()) {
2373         Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2374                 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2375                 "or argument #2 must be a non-null constant.", &CI);
2376       }
2377     }
2378
2379     Assert1(CI.getParent()->getParent()->hasGC(),
2380             "Enclosing function does not use GC.", &CI);
2381     break;
2382   case Intrinsic::init_trampoline:
2383     Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2384             "llvm.init_trampoline parameter #2 must resolve to a function.",
2385             &CI);
2386     break;
2387   case Intrinsic::prefetch:
2388     Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2389             isa<ConstantInt>(CI.getArgOperand(2)) &&
2390             cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2391             cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2392             "invalid arguments to llvm.prefetch",
2393             &CI);
2394     break;
2395   case Intrinsic::stackprotector:
2396     Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2397             "llvm.stackprotector parameter #2 must resolve to an alloca.",
2398             &CI);
2399     break;
2400   case Intrinsic::lifetime_start:
2401   case Intrinsic::lifetime_end:
2402   case Intrinsic::invariant_start:
2403     Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2404             "size argument of memory use markers must be a constant integer",
2405             &CI);
2406     break;
2407   case Intrinsic::invariant_end:
2408     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2409             "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2410     break;
2411   }
2412 }
2413
2414 void Verifier::verifyDebugInfo() {
2415   // Verify Debug Info.
2416   if (!DisableDebugInfoVerifier) {
2417     for (DebugInfoFinder::iterator I = Finder.compile_unit_begin(),
2418          E = Finder.compile_unit_end(); I != E; ++I)
2419       Assert1(DICompileUnit(*I).Verify(), "DICompileUnit does not Verify!", *I);
2420     for (DebugInfoFinder::iterator I = Finder.subprogram_begin(),
2421          E = Finder.subprogram_end(); I != E; ++I)
2422       Assert1(DISubprogram(*I).Verify(), "DISubprogram does not Verify!", *I);
2423     for (DebugInfoFinder::iterator I = Finder.global_variable_begin(),
2424          E = Finder.global_variable_end(); I != E; ++I)
2425       Assert1(DIGlobalVariable(*I).Verify(),
2426               "DIGlobalVariable does not Verify!", *I);
2427     for (DebugInfoFinder::iterator I = Finder.type_begin(),
2428          E = Finder.type_end(); I != E; ++I)
2429       Assert1(DIType(*I).Verify(), "DIType does not Verify!", *I);
2430     for (DebugInfoFinder::iterator I = Finder.scope_begin(),
2431          E = Finder.scope_end(); I != E; ++I)
2432       Assert1(DIScope(*I).Verify(), "DIScope does not Verify!", *I);
2433   }
2434 }
2435
2436 //===----------------------------------------------------------------------===//
2437 //  Implement the public interfaces to this file...
2438 //===----------------------------------------------------------------------===//
2439
2440 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2441   return new Verifier(action);
2442 }
2443
2444
2445 /// verifyFunction - Check a function for errors, printing messages on stderr.
2446 /// Return true if the function is corrupt.
2447 ///
2448 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2449   Function &F = const_cast<Function&>(f);
2450   assert(!F.isDeclaration() && "Cannot verify external functions");
2451
2452   FunctionPassManager FPM(F.getParent());
2453   Verifier *V = new Verifier(action);
2454   FPM.add(V);
2455   FPM.doInitialization();
2456   FPM.run(F);
2457   return V->Broken;
2458 }
2459
2460 /// verifyModule - Check a module for errors, printing messages on stderr.
2461 /// Return true if the module is corrupt.
2462 ///
2463 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2464                         std::string *ErrorInfo) {
2465   PassManager PM;
2466   Verifier *V = new Verifier(action);
2467   PM.add(V);
2468   PM.run(const_cast<Module&>(M));
2469
2470   if (ErrorInfo && V->Broken)
2471     *ErrorInfo = V->MessagesStr.str();
2472   return V->Broken;
2473 }