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