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