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