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