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