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