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