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