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