LLVM API Documentation

Verifier.cpp
Go to the documentation of this file.
00001 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the function verifier interface, that can be used for some
00011 // sanity checking of input to the system.
00012 //
00013 // Note that this does not provide full `Java style' security and verifications,
00014 // instead it just tries to ensure that code is well-formed.
00015 //
00016 //  * Both of a binary operator's parameters are of the same type
00017 //  * Verify that the indices of mem access instructions match other operands
00018 //  * Verify that arithmetic and other things are only performed on first-class
00019 //    types.  Verify that shifts & logicals only happen on integrals f.e.
00020 //  * All of the constants in a switch statement are of the correct type
00021 //  * The code is in valid SSA form
00022 //  * It should be illegal to put a label into any other type (like a structure)
00023 //    or to return one. [except constant arrays!]
00024 //  * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
00025 //  * PHI nodes must have an entry for each predecessor, with no extras.
00026 //  * PHI nodes must be the first thing in a basic block, all grouped together
00027 //  * PHI nodes must have at least one entry
00028 //  * All basic blocks should only end with terminator insts, not contain them
00029 //  * The entry node to a function must not have predecessors
00030 //  * All Instructions must be embedded into a basic block
00031 //  * Functions cannot take a void-typed parameter
00032 //  * Verify that a function's argument list agrees with it's declared type.
00033 //  * It is illegal to specify a name for a void value.
00034 //  * It is illegal to have a internal global value with no initializer
00035 //  * It is illegal to have a ret instruction that returns a value that does not
00036 //    agree with the function return value type.
00037 //  * Function call argument types match the function prototype
00038 //  * A landing pad is defined by a landingpad instruction, and can be jumped to
00039 //    only by the unwind edge of an invoke instruction.
00040 //  * A landingpad instruction must be the first non-PHI instruction in the
00041 //    block.
00042 //  * All landingpad instructions must use the same personality function with
00043 //    the same function.
00044 //  * All other things that are tested by asserts spread about the code...
00045 //
00046 //===----------------------------------------------------------------------===//
00047 
00048 #include "llvm/Analysis/Verifier.h"
00049 #include "llvm/ADT/STLExtras.h"
00050 #include "llvm/ADT/SetVector.h"
00051 #include "llvm/ADT/SmallPtrSet.h"
00052 #include "llvm/ADT/SmallVector.h"
00053 #include "llvm/ADT/StringExtras.h"
00054 #include "llvm/Analysis/Dominators.h"
00055 #include "llvm/Assembly/Writer.h"
00056 #include "llvm/IR/CallingConv.h"
00057 #include "llvm/IR/Constants.h"
00058 #include "llvm/IR/DerivedTypes.h"
00059 #include "llvm/IR/InlineAsm.h"
00060 #include "llvm/IR/IntrinsicInst.h"
00061 #include "llvm/IR/LLVMContext.h"
00062 #include "llvm/IR/Metadata.h"
00063 #include "llvm/IR/Module.h"
00064 #include "llvm/InstVisitor.h"
00065 #include "llvm/Pass.h"
00066 #include "llvm/PassManager.h"
00067 #include "llvm/Support/CFG.h"
00068 #include "llvm/Support/CallSite.h"
00069 #include "llvm/Support/ConstantRange.h"
00070 #include "llvm/Support/Debug.h"
00071 #include "llvm/Support/ErrorHandling.h"
00072 #include "llvm/Support/raw_ostream.h"
00073 #include <algorithm>
00074 #include <cstdarg>
00075 using namespace llvm;
00076 
00077 namespace {  // Anonymous namespace for class
00078   struct PreVerifier : public FunctionPass {
00079     static char ID; // Pass ID, replacement for typeid
00080 
00081     PreVerifier() : FunctionPass(ID) {
00082       initializePreVerifierPass(*PassRegistry::getPassRegistry());
00083     }
00084 
00085     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00086       AU.setPreservesAll();
00087     }
00088 
00089     // Check that the prerequisites for successful DominatorTree construction
00090     // are satisfied.
00091     bool runOnFunction(Function &F) {
00092       bool Broken = false;
00093 
00094       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
00095         if (I->empty() || !I->back().isTerminator()) {
00096           dbgs() << "Basic Block in function '" << F.getName() 
00097                  << "' does not have terminator!\n";
00098           WriteAsOperand(dbgs(), I, true);
00099           dbgs() << "\n";
00100           Broken = true;
00101         }
00102       }
00103 
00104       if (Broken)
00105         report_fatal_error("Broken module, no Basic Block terminator!");
00106 
00107       return false;
00108     }
00109   };
00110 }
00111 
00112 char PreVerifier::ID = 0;
00113 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification", 
00114                 false, false)
00115 static char &PreVerifyID = PreVerifier::ID;
00116 
00117 namespace {
00118   struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
00119     static char ID; // Pass ID, replacement for typeid
00120     bool Broken;          // Is this module found to be broken?
00121     VerifierFailureAction action;
00122                           // What to do if verification fails.
00123     Module *Mod;          // Module we are verifying right now
00124     LLVMContext *Context; // Context within which we are verifying
00125     DominatorTree *DT;    // Dominator Tree, caution can be null!
00126 
00127     std::string Messages;
00128     raw_string_ostream MessagesStr;
00129 
00130     /// InstInThisBlock - when verifying a basic block, keep track of all of the
00131     /// instructions we have seen so far.  This allows us to do efficient
00132     /// dominance checks for the case when an instruction has an operand that is
00133     /// an instruction in the same block.
00134     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
00135 
00136     /// MDNodes - keep track of the metadata nodes that have been checked
00137     /// already.
00138     SmallPtrSet<MDNode *, 32> MDNodes;
00139 
00140     /// PersonalityFn - The personality function referenced by the
00141     /// LandingPadInsts. All LandingPadInsts within the same function must use
00142     /// the same personality function.
00143     const Value *PersonalityFn;
00144 
00145     Verifier()
00146       : FunctionPass(ID), Broken(false),
00147         action(AbortProcessAction), Mod(0), Context(0), DT(0),
00148         MessagesStr(Messages), PersonalityFn(0) {
00149       initializeVerifierPass(*PassRegistry::getPassRegistry());
00150     }
00151     explicit Verifier(VerifierFailureAction ctn)
00152       : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
00153         Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
00154       initializeVerifierPass(*PassRegistry::getPassRegistry());
00155     }
00156 
00157     bool doInitialization(Module &M) {
00158       Mod = &M;
00159       Context = &M.getContext();
00160 
00161       // We must abort before returning back to the pass manager, or else the
00162       // pass manager may try to run other passes on the broken module.
00163       return abortIfBroken();
00164     }
00165 
00166     bool runOnFunction(Function &F) {
00167       // Get dominator information if we are being run by PassManager
00168       DT = &getAnalysis<DominatorTree>();
00169 
00170       Mod = F.getParent();
00171       if (!Context) Context = &F.getContext();
00172 
00173       visit(F);
00174       InstsInThisBlock.clear();
00175       PersonalityFn = 0;
00176 
00177       // We must abort before returning back to the pass manager, or else the
00178       // pass manager may try to run other passes on the broken module.
00179       return abortIfBroken();
00180     }
00181 
00182     bool doFinalization(Module &M) {
00183       // Scan through, checking all of the external function's linkage now...
00184       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00185         visitGlobalValue(*I);
00186 
00187         // Check to make sure function prototypes are okay.
00188         if (I->isDeclaration()) visitFunction(*I);
00189       }
00190 
00191       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
00192            I != E; ++I)
00193         visitGlobalVariable(*I);
00194 
00195       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 
00196            I != E; ++I)
00197         visitGlobalAlias(*I);
00198 
00199       for (Module::named_metadata_iterator I = M.named_metadata_begin(),
00200            E = M.named_metadata_end(); I != E; ++I)
00201         visitNamedMDNode(*I);
00202 
00203       visitModuleFlags(M);
00204 
00205       // If the module is broken, abort at this time.
00206       return abortIfBroken();
00207     }
00208 
00209     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00210       AU.setPreservesAll();
00211       AU.addRequiredID(PreVerifyID);
00212       AU.addRequired<DominatorTree>();
00213     }
00214 
00215     /// abortIfBroken - If the module is broken and we are supposed to abort on
00216     /// this condition, do so.
00217     ///
00218     bool abortIfBroken() {
00219       if (!Broken) return false;
00220       MessagesStr << "Broken module found, ";
00221       switch (action) {
00222       case AbortProcessAction:
00223         MessagesStr << "compilation aborted!\n";
00224         dbgs() << MessagesStr.str();
00225         // Client should choose different reaction if abort is not desired
00226         abort();
00227       case PrintMessageAction:
00228         MessagesStr << "verification continues.\n";
00229         dbgs() << MessagesStr.str();
00230         return false;
00231       case ReturnStatusAction:
00232         MessagesStr << "compilation terminated.\n";
00233         return true;
00234       }
00235       llvm_unreachable("Invalid action");
00236     }
00237 
00238 
00239     // Verification methods...
00240     void visitGlobalValue(GlobalValue &GV);
00241     void visitGlobalVariable(GlobalVariable &GV);
00242     void visitGlobalAlias(GlobalAlias &GA);
00243     void visitNamedMDNode(NamedMDNode &NMD);
00244     void visitMDNode(MDNode &MD, Function *F);
00245     void visitModuleFlags(Module &M);
00246     void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
00247                          SmallVectorImpl<MDNode*> &Requirements);
00248     void visitFunction(Function &F);
00249     void visitBasicBlock(BasicBlock &BB);
00250     using InstVisitor<Verifier>::visit;
00251 
00252     void visit(Instruction &I);
00253 
00254     void visitTruncInst(TruncInst &I);
00255     void visitZExtInst(ZExtInst &I);
00256     void visitSExtInst(SExtInst &I);
00257     void visitFPTruncInst(FPTruncInst &I);
00258     void visitFPExtInst(FPExtInst &I);
00259     void visitFPToUIInst(FPToUIInst &I);
00260     void visitFPToSIInst(FPToSIInst &I);
00261     void visitUIToFPInst(UIToFPInst &I);
00262     void visitSIToFPInst(SIToFPInst &I);
00263     void visitIntToPtrInst(IntToPtrInst &I);
00264     void visitPtrToIntInst(PtrToIntInst &I);
00265     void visitBitCastInst(BitCastInst &I);
00266     void visitPHINode(PHINode &PN);
00267     void visitBinaryOperator(BinaryOperator &B);
00268     void visitICmpInst(ICmpInst &IC);
00269     void visitFCmpInst(FCmpInst &FC);
00270     void visitExtractElementInst(ExtractElementInst &EI);
00271     void visitInsertElementInst(InsertElementInst &EI);
00272     void visitShuffleVectorInst(ShuffleVectorInst &EI);
00273     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
00274     void visitCallInst(CallInst &CI);
00275     void visitInvokeInst(InvokeInst &II);
00276     void visitGetElementPtrInst(GetElementPtrInst &GEP);
00277     void visitLoadInst(LoadInst &LI);
00278     void visitStoreInst(StoreInst &SI);
00279     void verifyDominatesUse(Instruction &I, unsigned i);
00280     void visitInstruction(Instruction &I);
00281     void visitTerminatorInst(TerminatorInst &I);
00282     void visitBranchInst(BranchInst &BI);
00283     void visitReturnInst(ReturnInst &RI);
00284     void visitSwitchInst(SwitchInst &SI);
00285     void visitIndirectBrInst(IndirectBrInst &BI);
00286     void visitSelectInst(SelectInst &SI);
00287     void visitUserOp1(Instruction &I);
00288     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
00289     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
00290     void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
00291     void visitAtomicRMWInst(AtomicRMWInst &RMWI);
00292     void visitFenceInst(FenceInst &FI);
00293     void visitAllocaInst(AllocaInst &AI);
00294     void visitExtractValueInst(ExtractValueInst &EVI);
00295     void visitInsertValueInst(InsertValueInst &IVI);
00296     void visitLandingPadInst(LandingPadInst &LPI);
00297 
00298     void VerifyCallSite(CallSite CS);
00299     bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
00300                           int VT, unsigned ArgNo, std::string &Suffix);
00301     bool VerifyIntrinsicType(Type *Ty,
00302                              ArrayRef<Intrinsic::IITDescriptor> &Infos,
00303                              SmallVectorImpl<Type*> &ArgTys);
00304     bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
00305     void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
00306                               bool isFunction, const Value *V);
00307     void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
00308                               bool isReturnValue, const Value *V);
00309     void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
00310                              const Value *V);
00311 
00312     void WriteValue(const Value *V) {
00313       if (!V) return;
00314       if (isa<Instruction>(V)) {
00315         MessagesStr << *V << '\n';
00316       } else {
00317         WriteAsOperand(MessagesStr, V, true, Mod);
00318         MessagesStr << '\n';
00319       }
00320     }
00321 
00322     void WriteType(Type *T) {
00323       if (!T) return;
00324       MessagesStr << ' ' << *T;
00325     }
00326 
00327 
00328     // CheckFailed - A check failed, so print out the condition and the message
00329     // that failed.  This provides a nice place to put a breakpoint if you want
00330     // to see why something is not correct.
00331     void CheckFailed(const Twine &Message,
00332                      const Value *V1 = 0, const Value *V2 = 0,
00333                      const Value *V3 = 0, const Value *V4 = 0) {
00334       MessagesStr << Message.str() << "\n";
00335       WriteValue(V1);
00336       WriteValue(V2);
00337       WriteValue(V3);
00338       WriteValue(V4);
00339       Broken = true;
00340     }
00341 
00342     void CheckFailed(const Twine &Message, const Value *V1,
00343                      Type *T2, const Value *V3 = 0) {
00344       MessagesStr << Message.str() << "\n";
00345       WriteValue(V1);
00346       WriteType(T2);
00347       WriteValue(V3);
00348       Broken = true;
00349     }
00350 
00351     void CheckFailed(const Twine &Message, Type *T1,
00352                      Type *T2 = 0, Type *T3 = 0) {
00353       MessagesStr << Message.str() << "\n";
00354       WriteType(T1);
00355       WriteType(T2);
00356       WriteType(T3);
00357       Broken = true;
00358     }
00359   };
00360 } // End anonymous namespace
00361 
00362 char Verifier::ID = 0;
00363 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
00364 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
00365 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
00366 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
00367 
00368 // Assert - We know that cond should be true, if not print an error message.
00369 #define Assert(C, M) \
00370   do { if (!(C)) { CheckFailed(M); return; } } while (0)
00371 #define Assert1(C, M, V1) \
00372   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
00373 #define Assert2(C, M, V1, V2) \
00374   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
00375 #define Assert3(C, M, V1, V2, V3) \
00376   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
00377 #define Assert4(C, M, V1, V2, V3, V4) \
00378   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
00379 
00380 void Verifier::visit(Instruction &I) {
00381   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00382     Assert1(I.getOperand(i) != 0, "Operand is null", &I);
00383   InstVisitor<Verifier>::visit(I);
00384 }
00385 
00386 
00387 void Verifier::visitGlobalValue(GlobalValue &GV) {
00388   Assert1(!GV.isDeclaration() ||
00389           GV.isMaterializable() ||
00390           GV.hasExternalLinkage() ||
00391           GV.hasDLLImportLinkage() ||
00392           GV.hasExternalWeakLinkage() ||
00393           (isa<GlobalAlias>(GV) &&
00394            (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
00395   "Global is external, but doesn't have external or dllimport or weak linkage!",
00396           &GV);
00397 
00398   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
00399           "Global is marked as dllimport, but not external", &GV);
00400 
00401   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
00402           "Only global variables can have appending linkage!", &GV);
00403 
00404   if (GV.hasAppendingLinkage()) {
00405     GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
00406     Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
00407             "Only global arrays can have appending linkage!", GVar);
00408   }
00409 
00410   Assert1(!GV.hasLinkOnceODRAutoHideLinkage() || GV.hasDefaultVisibility(),
00411           "linkonce_odr_auto_hide can only have default visibility!",
00412           &GV);
00413 }
00414 
00415 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
00416   if (GV.hasInitializer()) {
00417     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
00418             "Global variable initializer type does not match global "
00419             "variable type!", &GV);
00420 
00421     // If the global has common linkage, it must have a zero initializer and
00422     // cannot be constant.
00423     if (GV.hasCommonLinkage()) {
00424       Assert1(GV.getInitializer()->isNullValue(),
00425               "'common' global must have a zero initializer!", &GV);
00426       Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
00427               &GV);
00428     }
00429   } else {
00430     Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
00431             GV.hasExternalWeakLinkage(),
00432             "invalid linkage type for global declaration", &GV);
00433   }
00434 
00435   if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
00436                        GV.getName() == "llvm.global_dtors")) {
00437     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
00438             "invalid linkage for intrinsic global variable", &GV);
00439     // Don't worry about emitting an error for it not being an array,
00440     // visitGlobalValue will complain on appending non-array.
00441     if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
00442       StructType *STy = dyn_cast<StructType>(ATy->getElementType());
00443       PointerType *FuncPtrTy =
00444           FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
00445       Assert1(STy && STy->getNumElements() == 2 &&
00446               STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
00447               STy->getTypeAtIndex(1) == FuncPtrTy,
00448               "wrong type for intrinsic global variable", &GV);
00449     }
00450   }
00451 
00452   if (GV.hasName() && (GV.getName() == "llvm.used" ||
00453                        GV.getName() == "llvm.compiler_used")) {
00454     Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
00455             "invalid linkage for intrinsic global variable", &GV);
00456     Type *GVType = GV.getType()->getElementType();
00457     if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
00458       PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
00459       Assert1(PTy, "wrong type for intrinsic global variable", &GV);
00460       if (GV.hasInitializer()) {
00461         Constant *Init = GV.getInitializer();
00462         ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
00463         Assert1(InitArray, "wrong initalizer for intrinsic global variable",
00464                 Init);
00465         for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
00466           Value *V = Init->getOperand(i)->stripPointerCasts();
00467           // stripPointerCasts strips aliases, so we only need to check for
00468           // variables and functions.
00469           Assert1(isa<GlobalVariable>(V) || isa<Function>(V),
00470                   "invalid llvm.used member", V);
00471         }
00472       }
00473     }
00474   }
00475 
00476   visitGlobalValue(GV);
00477 }
00478 
00479 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
00480   Assert1(!GA.getName().empty(),
00481           "Alias name cannot be empty!", &GA);
00482   Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
00483           GA.hasWeakLinkage(),
00484           "Alias should have external or external weak linkage!", &GA);
00485   Assert1(GA.getAliasee(),
00486           "Aliasee cannot be NULL!", &GA);
00487   Assert1(GA.getType() == GA.getAliasee()->getType(),
00488           "Alias and aliasee types should match!", &GA);
00489   Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
00490 
00491   if (!isa<GlobalValue>(GA.getAliasee())) {
00492     const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
00493     Assert1(CE && 
00494             (CE->getOpcode() == Instruction::BitCast ||
00495              CE->getOpcode() == Instruction::GetElementPtr) &&
00496             isa<GlobalValue>(CE->getOperand(0)),
00497             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
00498             &GA);
00499   }
00500 
00501   const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
00502   Assert1(Aliasee,
00503           "Aliasing chain should end with function or global variable", &GA);
00504 
00505   visitGlobalValue(GA);
00506 }
00507 
00508 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
00509   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
00510     MDNode *MD = NMD.getOperand(i);
00511     if (!MD)
00512       continue;
00513 
00514     Assert1(!MD->isFunctionLocal(),
00515             "Named metadata operand cannot be function local!", MD);
00516     visitMDNode(*MD, 0);
00517   }
00518 }
00519 
00520 void Verifier::visitMDNode(MDNode &MD, Function *F) {
00521   // Only visit each node once.  Metadata can be mutually recursive, so this
00522   // avoids infinite recursion here, as well as being an optimization.
00523   if (!MDNodes.insert(&MD))
00524     return;
00525 
00526   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
00527     Value *Op = MD.getOperand(i);
00528     if (!Op)
00529       continue;
00530     if (isa<Constant>(Op) || isa<MDString>(Op))
00531       continue;
00532     if (MDNode *N = dyn_cast<MDNode>(Op)) {
00533       Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
00534               "Global metadata operand cannot be function local!", &MD, N);
00535       visitMDNode(*N, F);
00536       continue;
00537     }
00538     Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
00539 
00540     // If this was an instruction, bb, or argument, verify that it is in the
00541     // function that we expect.
00542     Function *ActualF = 0;
00543     if (Instruction *I = dyn_cast<Instruction>(Op))
00544       ActualF = I->getParent()->getParent();
00545     else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
00546       ActualF = BB->getParent();
00547     else if (Argument *A = dyn_cast<Argument>(Op))
00548       ActualF = A->getParent();
00549     assert(ActualF && "Unimplemented function local metadata case!");
00550 
00551     Assert2(ActualF == F, "function-local metadata used in wrong function",
00552             &MD, Op);
00553   }
00554 }
00555 
00556 void Verifier::visitModuleFlags(Module &M) {
00557   const NamedMDNode *Flags = M.getModuleFlagsMetadata();
00558   if (!Flags) return;
00559 
00560   // Scan each flag, and track the flags and requirements.
00561   DenseMap<MDString*, MDNode*> SeenIDs;
00562   SmallVector<MDNode*, 16> Requirements;
00563   for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
00564     visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
00565   }
00566 
00567   // Validate that the requirements in the module are valid.
00568   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
00569     MDNode *Requirement = Requirements[I];
00570     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
00571     Value *ReqValue = Requirement->getOperand(1);
00572 
00573     MDNode *Op = SeenIDs.lookup(Flag);
00574     if (!Op) {
00575       CheckFailed("invalid requirement on flag, flag is not present in module",
00576                   Flag);
00577       continue;
00578     }
00579 
00580     if (Op->getOperand(2) != ReqValue) {
00581       CheckFailed(("invalid requirement on flag, "
00582                    "flag does not have the required value"),
00583                   Flag);
00584       continue;
00585     }
00586   }
00587 }
00588 
00589 void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
00590                                SmallVectorImpl<MDNode*> &Requirements) {
00591   // Each module flag should have three arguments, the merge behavior (a
00592   // constant int), the flag ID (an MDString), and the value.
00593   Assert1(Op->getNumOperands() == 3,
00594           "incorrect number of operands in module flag", Op);
00595   ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
00596   MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
00597   Assert1(Behavior,
00598           "invalid behavior operand in module flag (expected constant integer)",
00599           Op->getOperand(0));
00600   unsigned BehaviorValue = Behavior->getZExtValue();
00601   Assert1(ID,
00602           "invalid ID operand in module flag (expected metadata string)",
00603           Op->getOperand(1));
00604 
00605   // Sanity check the values for behaviors with additional requirements.
00606   switch (BehaviorValue) {
00607   default:
00608     Assert1(false,
00609             "invalid behavior operand in module flag (unexpected constant)",
00610             Op->getOperand(0));
00611     break;
00612 
00613   case Module::Error:
00614   case Module::Warning:
00615   case Module::Override:
00616     // These behavior types accept any value.
00617     break;
00618 
00619   case Module::Require: {
00620     // The value should itself be an MDNode with two operands, a flag ID (an
00621     // MDString), and a value.
00622     MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
00623     Assert1(Value && Value->getNumOperands() == 2,
00624             "invalid value for 'require' module flag (expected metadata pair)",
00625             Op->getOperand(2));
00626     Assert1(isa<MDString>(Value->getOperand(0)),
00627             ("invalid value for 'require' module flag "
00628              "(first value operand should be a string)"),
00629             Value->getOperand(0));
00630 
00631     // Append it to the list of requirements, to check once all module flags are
00632     // scanned.
00633     Requirements.push_back(Value);
00634     break;
00635   }
00636 
00637   case Module::Append:
00638   case Module::AppendUnique: {
00639     // These behavior types require the operand be an MDNode.
00640     Assert1(isa<MDNode>(Op->getOperand(2)),
00641             "invalid value for 'append'-type module flag "
00642             "(expected a metadata node)", Op->getOperand(2));
00643     break;
00644   }
00645   }
00646 
00647   // Unless this is a "requires" flag, check the ID is unique.
00648   if (BehaviorValue != Module::Require) {
00649     bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
00650     Assert1(Inserted,
00651             "module flag identifiers must be unique (or of 'require' type)",
00652             ID);
00653   }
00654 }
00655 
00656 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
00657                                     bool isFunction, const Value* V) {
00658   unsigned Slot = ~0U;
00659   for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
00660     if (Attrs.getSlotIndex(I) == Idx) {
00661       Slot = I;
00662       break;
00663     }
00664 
00665   assert(Slot != ~0U && "Attribute set inconsistency!");
00666 
00667   for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
00668          I != E; ++I) {
00669     if (I->isStringAttribute())
00670       continue;
00671 
00672     if (I->getKindAsEnum() == Attribute::NoReturn ||
00673         I->getKindAsEnum() == Attribute::NoUnwind ||
00674         I->getKindAsEnum() == Attribute::ReadNone ||
00675         I->getKindAsEnum() == Attribute::ReadOnly ||
00676         I->getKindAsEnum() == Attribute::NoInline ||
00677         I->getKindAsEnum() == Attribute::AlwaysInline ||
00678         I->getKindAsEnum() == Attribute::OptimizeForSize ||
00679         I->getKindAsEnum() == Attribute::StackProtect ||
00680         I->getKindAsEnum() == Attribute::StackProtectReq ||
00681         I->getKindAsEnum() == Attribute::StackProtectStrong ||
00682         I->getKindAsEnum() == Attribute::NoRedZone ||
00683         I->getKindAsEnum() == Attribute::NoImplicitFloat ||
00684         I->getKindAsEnum() == Attribute::Naked ||
00685         I->getKindAsEnum() == Attribute::InlineHint ||
00686         I->getKindAsEnum() == Attribute::StackAlignment ||
00687         I->getKindAsEnum() == Attribute::UWTable ||
00688         I->getKindAsEnum() == Attribute::NonLazyBind ||
00689         I->getKindAsEnum() == Attribute::ReturnsTwice ||
00690         I->getKindAsEnum() == Attribute::SanitizeAddress ||
00691         I->getKindAsEnum() == Attribute::SanitizeThread ||
00692         I->getKindAsEnum() == Attribute::SanitizeMemory ||
00693         I->getKindAsEnum() == Attribute::MinSize ||
00694         I->getKindAsEnum() == Attribute::NoDuplicate ||
00695         I->getKindAsEnum() == Attribute::NoBuiltin) {
00696       if (!isFunction)
00697           CheckFailed("Attribute '" + I->getKindAsString() +
00698                       "' only applies to functions!", V);
00699           return;
00700     } else if (isFunction) {
00701         CheckFailed("Attribute '" + I->getKindAsString() +
00702                     "' does not apply to functions!", V);
00703         return;
00704     }
00705   }
00706 }
00707 
00708 // VerifyParameterAttrs - Check the given attributes for an argument or return
00709 // value of the specified type.  The value V is printed in error messages.
00710 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
00711                                     bool isReturnValue, const Value *V) {
00712   if (!Attrs.hasAttributes(Idx))
00713     return;
00714 
00715   VerifyAttributeTypes(Attrs, Idx, false, V);
00716 
00717   if (isReturnValue)
00718     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
00719             !Attrs.hasAttribute(Idx, Attribute::Nest) &&
00720             !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
00721             !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
00722             !Attrs.hasAttribute(Idx, Attribute::Returned),
00723             "Attribute 'byval', 'nest', 'sret', 'nocapture', and 'returned' "
00724             "do not apply to return values!", V);
00725 
00726   // Check for mutually incompatible attributes.
00727   Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
00728              Attrs.hasAttribute(Idx, Attribute::Nest)) ||
00729             (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
00730              Attrs.hasAttribute(Idx, Attribute::StructRet)) ||
00731             (Attrs.hasAttribute(Idx, Attribute::Nest) &&
00732              Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes "
00733           "'byval, nest, and sret' are incompatible!", V);
00734 
00735   Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) &&
00736              Attrs.hasAttribute(Idx, Attribute::Nest)) ||
00737             (Attrs.hasAttribute(Idx, Attribute::ByVal) &&
00738              Attrs.hasAttribute(Idx, Attribute::InReg)) ||
00739             (Attrs.hasAttribute(Idx, Attribute::Nest) &&
00740              Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes "
00741           "'byval, nest, and inreg' are incompatible!", V);
00742 
00743   Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
00744             Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
00745           "'sret and returned' are incompatible!", V);
00746 
00747   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
00748             Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
00749           "'zeroext and signext' are incompatible!", V);
00750 
00751   Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
00752             Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
00753           "'readnone and readonly' are incompatible!", V);
00754 
00755   Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
00756             Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
00757           "'noinline and alwaysinline' are incompatible!", V);
00758 
00759   Assert1(!AttrBuilder(Attrs, Idx).
00760             hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
00761           "Wrong types for attribute: " +
00762           AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
00763 
00764   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
00765     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) ||
00766             PTy->getElementType()->isSized(),
00767             "Attribute 'byval' does not support unsized types!", V);
00768   else
00769     Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
00770             "Attribute 'byval' only applies to parameters with pointer type!",
00771             V);
00772 }
00773 
00774 // VerifyFunctionAttrs - Check parameter attributes against a function type.
00775 // The value V is printed in error messages.
00776 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
00777                                    const Value *V) {
00778   if (Attrs.isEmpty())
00779     return;
00780 
00781   bool SawNest = false;
00782   bool SawReturned = false;
00783 
00784   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
00785     unsigned Idx = Attrs.getSlotIndex(i);
00786 
00787     Type *Ty;
00788     if (Idx == 0)
00789       Ty = FT->getReturnType();
00790     else if (Idx-1 < FT->getNumParams())
00791       Ty = FT->getParamType(Idx-1);
00792     else
00793       break;  // VarArgs attributes, verified elsewhere.
00794 
00795     VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
00796 
00797     if (Idx == 0)
00798       continue;
00799 
00800     if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
00801       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
00802       SawNest = true;
00803     }
00804 
00805     if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
00806       Assert1(!SawReturned, "More than one parameter has attribute returned!",
00807               V);
00808       Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
00809               "argument and return types for 'returned' attribute", V);
00810       SawReturned = true;
00811     }
00812 
00813     if (Attrs.hasAttribute(Idx, Attribute::StructRet))
00814       Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
00815   }
00816 
00817   if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
00818     return;
00819 
00820   VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
00821 
00822   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
00823                                Attribute::ReadNone) &&
00824             Attrs.hasAttribute(AttributeSet::FunctionIndex,
00825                                Attribute::ReadOnly)),
00826           "Attributes 'readnone and readonly' are incompatible!", V);
00827 
00828   Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
00829                                Attribute::NoInline) &&
00830             Attrs.hasAttribute(AttributeSet::FunctionIndex,
00831                                Attribute::AlwaysInline)),
00832           "Attributes 'noinline and alwaysinline' are incompatible!", V);
00833 }
00834 
00835 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
00836   if (Attrs.getNumSlots() == 0)
00837     return true;
00838 
00839   unsigned LastSlot = Attrs.getNumSlots() - 1;
00840   unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
00841   if (LastIndex <= Params
00842       || (LastIndex == AttributeSet::FunctionIndex
00843           && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
00844     return true;
00845  
00846   return false;
00847 }
00848 
00849 // visitFunction - Verify that a function is ok.
00850 //
00851 void Verifier::visitFunction(Function &F) {
00852   // Check function arguments.
00853   FunctionType *FT = F.getFunctionType();
00854   unsigned NumArgs = F.arg_size();
00855 
00856   Assert1(Context == &F.getContext(),
00857           "Function context does not match Module context!", &F);
00858 
00859   Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
00860   Assert2(FT->getNumParams() == NumArgs,
00861           "# formal arguments must match # of arguments for function type!",
00862           &F, FT);
00863   Assert1(F.getReturnType()->isFirstClassType() ||
00864           F.getReturnType()->isVoidTy() || 
00865           F.getReturnType()->isStructTy(),
00866           "Functions cannot return aggregate values!", &F);
00867 
00868   Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
00869           "Invalid struct return type!", &F);
00870 
00871   AttributeSet Attrs = F.getAttributes();
00872 
00873   Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
00874           "Attribute after last parameter!", &F);
00875 
00876   // Check function attributes.
00877   VerifyFunctionAttrs(FT, Attrs, &F);
00878 
00879   // Check that this function meets the restrictions on this calling convention.
00880   switch (F.getCallingConv()) {
00881   default:
00882     break;
00883   case CallingConv::C:
00884     break;
00885   case CallingConv::Fast:
00886   case CallingConv::Cold:
00887   case CallingConv::X86_FastCall:
00888   case CallingConv::X86_ThisCall:
00889   case CallingConv::Intel_OCL_BI:
00890   case CallingConv::PTX_Kernel:
00891   case CallingConv::PTX_Device:
00892     Assert1(!F.isVarArg(),
00893             "Varargs functions must have C calling conventions!", &F);
00894     break;
00895   }
00896 
00897   bool isLLVMdotName = F.getName().size() >= 5 &&
00898                        F.getName().substr(0, 5) == "llvm.";
00899 
00900   // Check that the argument values match the function type for this function...
00901   unsigned i = 0;
00902   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
00903        I != E; ++I, ++i) {
00904     Assert2(I->getType() == FT->getParamType(i),
00905             "Argument value does not match function argument type!",
00906             I, FT->getParamType(i));
00907     Assert1(I->getType()->isFirstClassType(),
00908             "Function arguments must have first-class types!", I);
00909     if (!isLLVMdotName)
00910       Assert2(!I->getType()->isMetadataTy(),
00911               "Function takes metadata but isn't an intrinsic", I, &F);
00912   }
00913 
00914   if (F.isMaterializable()) {
00915     // Function has a body somewhere we can't see.
00916   } else if (F.isDeclaration()) {
00917     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
00918             F.hasExternalWeakLinkage(),
00919             "invalid linkage type for function declaration", &F);
00920   } else {
00921     // Verify that this function (which has a body) is not named "llvm.*".  It
00922     // is not legal to define intrinsics.
00923     Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
00924     
00925     // Check the entry node
00926     BasicBlock *Entry = &F.getEntryBlock();
00927     Assert1(pred_begin(Entry) == pred_end(Entry),
00928             "Entry block to function must not have predecessors!", Entry);
00929     
00930     // The address of the entry block cannot be taken, unless it is dead.
00931     if (Entry->hasAddressTaken()) {
00932       Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
00933               "blockaddress may not be used with the entry block!", Entry);
00934     }
00935   }
00936  
00937   // If this function is actually an intrinsic, verify that it is only used in
00938   // direct call/invokes, never having its "address taken".
00939   if (F.getIntrinsicID()) {
00940     const User *U;
00941     if (F.hasAddressTaken(&U))
00942       Assert1(0, "Invalid user of intrinsic instruction!", U); 
00943   }
00944 }
00945 
00946 // verifyBasicBlock - Verify that a basic block is well formed...
00947 //
00948 void Verifier::visitBasicBlock(BasicBlock &BB) {
00949   InstsInThisBlock.clear();
00950 
00951   // Ensure that basic blocks have terminators!
00952   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
00953 
00954   // Check constraints that this basic block imposes on all of the PHI nodes in
00955   // it.
00956   if (isa<PHINode>(BB.front())) {
00957     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
00958     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
00959     std::sort(Preds.begin(), Preds.end());
00960     PHINode *PN;
00961     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
00962       // Ensure that PHI nodes have at least one entry!
00963       Assert1(PN->getNumIncomingValues() != 0,
00964               "PHI nodes must have at least one entry.  If the block is dead, "
00965               "the PHI should be removed!", PN);
00966       Assert1(PN->getNumIncomingValues() == Preds.size(),
00967               "PHINode should have one entry for each predecessor of its "
00968               "parent basic block!", PN);
00969 
00970       // Get and sort all incoming values in the PHI node...
00971       Values.clear();
00972       Values.reserve(PN->getNumIncomingValues());
00973       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00974         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
00975                                         PN->getIncomingValue(i)));
00976       std::sort(Values.begin(), Values.end());
00977 
00978       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
00979         // Check to make sure that if there is more than one entry for a
00980         // particular basic block in this PHI node, that the incoming values are
00981         // all identical.
00982         //
00983         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
00984                 Values[i].second == Values[i-1].second,
00985                 "PHI node has multiple entries for the same basic block with "
00986                 "different incoming values!", PN, Values[i].first,
00987                 Values[i].second, Values[i-1].second);
00988 
00989         // Check to make sure that the predecessors and PHI node entries are
00990         // matched up.
00991         Assert3(Values[i].first == Preds[i],
00992                 "PHI node entries do not match predecessors!", PN,
00993                 Values[i].first, Preds[i]);
00994       }
00995     }
00996   }
00997 }
00998 
00999 void Verifier::visitTerminatorInst(TerminatorInst &I) {
01000   // Ensure that terminators only exist at the end of the basic block.
01001   Assert1(&I == I.getParent()->getTerminator(),
01002           "Terminator found in the middle of a basic block!", I.getParent());
01003   visitInstruction(I);
01004 }
01005 
01006 void Verifier::visitBranchInst(BranchInst &BI) {
01007   if (BI.isConditional()) {
01008     Assert2(BI.getCondition()->getType()->isIntegerTy(1),
01009             "Branch condition is not 'i1' type!", &BI, BI.getCondition());
01010   }
01011   visitTerminatorInst(BI);
01012 }
01013 
01014 void Verifier::visitReturnInst(ReturnInst &RI) {
01015   Function *F = RI.getParent()->getParent();
01016   unsigned N = RI.getNumOperands();
01017   if (F->getReturnType()->isVoidTy()) 
01018     Assert2(N == 0,
01019             "Found return instr that returns non-void in Function of void "
01020             "return type!", &RI, F->getReturnType());
01021   else
01022     Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
01023             "Function return type does not match operand "
01024             "type of return inst!", &RI, F->getReturnType());
01025 
01026   // Check to make sure that the return value has necessary properties for
01027   // terminators...
01028   visitTerminatorInst(RI);
01029 }
01030 
01031 void Verifier::visitSwitchInst(SwitchInst &SI) {
01032   // Check to make sure that all of the constants in the switch instruction
01033   // have the same type as the switched-on value.
01034   Type *SwitchTy = SI.getCondition()->getType();
01035   IntegerType *IntTy = cast<IntegerType>(SwitchTy);
01036   IntegersSubsetToBB Mapping;
01037   std::map<IntegersSubset::Range, unsigned> RangeSetMap;
01038   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
01039     IntegersSubset CaseRanges = i.getCaseValueEx();
01040     for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
01041       IntegersSubset::Range r = CaseRanges.getItem(ri);
01042       Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
01043               "Switch constants must all be same type as switch value!", &SI);
01044       Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
01045               "Switch constants must all be same type as switch value!", &SI);
01046       Mapping.add(r);
01047       RangeSetMap[r] = i.getCaseIndex();
01048     }
01049   }
01050   
01051   IntegersSubsetToBB::RangeIterator errItem;
01052   if (!Mapping.verify(errItem)) {
01053     unsigned CaseIndex = RangeSetMap[errItem->first];
01054     SwitchInst::CaseIt i(&SI, CaseIndex);
01055     Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
01056   }
01057   
01058   visitTerminatorInst(SI);
01059 }
01060 
01061 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
01062   Assert1(BI.getAddress()->getType()->isPointerTy(),
01063           "Indirectbr operand must have pointer type!", &BI);
01064   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
01065     Assert1(BI.getDestination(i)->getType()->isLabelTy(),
01066             "Indirectbr destinations must all have pointer type!", &BI);
01067 
01068   visitTerminatorInst(BI);
01069 }
01070 
01071 void Verifier::visitSelectInst(SelectInst &SI) {
01072   Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
01073                                           SI.getOperand(2)),
01074           "Invalid operands for select instruction!", &SI);
01075 
01076   Assert1(SI.getTrueValue()->getType() == SI.getType(),
01077           "Select values must have same type as select instruction!", &SI);
01078   visitInstruction(SI);
01079 }
01080 
01081 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
01082 /// a pass, if any exist, it's an error.
01083 ///
01084 void Verifier::visitUserOp1(Instruction &I) {
01085   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
01086 }
01087 
01088 void Verifier::visitTruncInst(TruncInst &I) {
01089   // Get the source and destination types
01090   Type *SrcTy = I.getOperand(0)->getType();
01091   Type *DestTy = I.getType();
01092 
01093   // Get the size of the types in bits, we'll need this later
01094   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
01095   unsigned DestBitSize = DestTy->getScalarSizeInBits();
01096 
01097   Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
01098   Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
01099   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
01100           "trunc source and destination must both be a vector or neither", &I);
01101   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
01102 
01103   visitInstruction(I);
01104 }
01105 
01106 void Verifier::visitZExtInst(ZExtInst &I) {
01107   // Get the source and destination types
01108   Type *SrcTy = I.getOperand(0)->getType();
01109   Type *DestTy = I.getType();
01110 
01111   // Get the size of the types in bits, we'll need this later
01112   Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
01113   Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
01114   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
01115           "zext source and destination must both be a vector or neither", &I);
01116   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
01117   unsigned DestBitSize = DestTy->getScalarSizeInBits();
01118 
01119   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
01120 
01121   visitInstruction(I);
01122 }
01123 
01124 void Verifier::visitSExtInst(SExtInst &I) {
01125   // Get the source and destination types
01126   Type *SrcTy = I.getOperand(0)->getType();
01127   Type *DestTy = I.getType();
01128 
01129   // Get the size of the types in bits, we'll need this later
01130   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
01131   unsigned DestBitSize = DestTy->getScalarSizeInBits();
01132 
01133   Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
01134   Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
01135   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
01136           "sext source and destination must both be a vector or neither", &I);
01137   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
01138 
01139   visitInstruction(I);
01140 }
01141 
01142 void Verifier::visitFPTruncInst(FPTruncInst &I) {
01143   // Get the source and destination types
01144   Type *SrcTy = I.getOperand(0)->getType();
01145   Type *DestTy = I.getType();
01146   // Get the size of the types in bits, we'll need this later
01147   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
01148   unsigned DestBitSize = DestTy->getScalarSizeInBits();
01149 
01150   Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
01151   Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
01152   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
01153           "fptrunc source and destination must both be a vector or neither",&I);
01154   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
01155 
01156   visitInstruction(I);
01157 }
01158 
01159 void Verifier::visitFPExtInst(FPExtInst &I) {
01160   // Get the source and destination types
01161   Type *SrcTy = I.getOperand(0)->getType();
01162   Type *DestTy = I.getType();
01163 
01164   // Get the size of the types in bits, we'll need this later
01165   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
01166   unsigned DestBitSize = DestTy->getScalarSizeInBits();
01167 
01168   Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
01169   Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
01170   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
01171           "fpext source and destination must both be a vector or neither", &I);
01172   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
01173 
01174   visitInstruction(I);
01175 }
01176 
01177 void Verifier::visitUIToFPInst(UIToFPInst &I) {
01178   // Get the source and destination types
01179   Type *SrcTy = I.getOperand(0)->getType();
01180   Type *DestTy = I.getType();
01181 
01182   bool SrcVec = SrcTy->isVectorTy();
01183   bool DstVec = DestTy->isVectorTy();
01184 
01185   Assert1(SrcVec == DstVec,
01186           "UIToFP source and dest must both be vector or scalar", &I);
01187   Assert1(SrcTy->isIntOrIntVectorTy(),
01188           "UIToFP source must be integer or integer vector", &I);
01189   Assert1(DestTy->isFPOrFPVectorTy(),
01190           "UIToFP result must be FP or FP vector", &I);
01191 
01192   if (SrcVec && DstVec)
01193     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
01194             cast<VectorType>(DestTy)->getNumElements(),
01195             "UIToFP source and dest vector length mismatch", &I);
01196 
01197   visitInstruction(I);
01198 }
01199 
01200 void Verifier::visitSIToFPInst(SIToFPInst &I) {
01201   // Get the source and destination types
01202   Type *SrcTy = I.getOperand(0)->getType();
01203   Type *DestTy = I.getType();
01204 
01205   bool SrcVec = SrcTy->isVectorTy();
01206   bool DstVec = DestTy->isVectorTy();
01207 
01208   Assert1(SrcVec == DstVec,
01209           "SIToFP source and dest must both be vector or scalar", &I);
01210   Assert1(SrcTy->isIntOrIntVectorTy(),
01211           "SIToFP source must be integer or integer vector", &I);
01212   Assert1(DestTy->isFPOrFPVectorTy(),
01213           "SIToFP result must be FP or FP vector", &I);
01214 
01215   if (SrcVec && DstVec)
01216     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
01217             cast<VectorType>(DestTy)->getNumElements(),
01218             "SIToFP source and dest vector length mismatch", &I);
01219 
01220   visitInstruction(I);
01221 }
01222 
01223 void Verifier::visitFPToUIInst(FPToUIInst &I) {
01224   // Get the source and destination types
01225   Type *SrcTy = I.getOperand(0)->getType();
01226   Type *DestTy = I.getType();
01227 
01228   bool SrcVec = SrcTy->isVectorTy();
01229   bool DstVec = DestTy->isVectorTy();
01230 
01231   Assert1(SrcVec == DstVec,
01232           "FPToUI source and dest must both be vector or scalar", &I);
01233   Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
01234           &I);
01235   Assert1(DestTy->isIntOrIntVectorTy(),
01236           "FPToUI result must be integer or integer vector", &I);
01237 
01238   if (SrcVec && DstVec)
01239     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
01240             cast<VectorType>(DestTy)->getNumElements(),
01241             "FPToUI source and dest vector length mismatch", &I);
01242 
01243   visitInstruction(I);
01244 }
01245 
01246 void Verifier::visitFPToSIInst(FPToSIInst &I) {
01247   // Get the source and destination types
01248   Type *SrcTy = I.getOperand(0)->getType();
01249   Type *DestTy = I.getType();
01250 
01251   bool SrcVec = SrcTy->isVectorTy();
01252   bool DstVec = DestTy->isVectorTy();
01253 
01254   Assert1(SrcVec == DstVec,
01255           "FPToSI source and dest must both be vector or scalar", &I);
01256   Assert1(SrcTy->isFPOrFPVectorTy(),
01257           "FPToSI source must be FP or FP vector", &I);
01258   Assert1(DestTy->isIntOrIntVectorTy(),
01259           "FPToSI result must be integer or integer vector", &I);
01260 
01261   if (SrcVec && DstVec)
01262     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
01263             cast<VectorType>(DestTy)->getNumElements(),
01264             "FPToSI source and dest vector length mismatch", &I);
01265 
01266   visitInstruction(I);
01267 }
01268 
01269 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
01270   // Get the source and destination types
01271   Type *SrcTy = I.getOperand(0)->getType();
01272   Type *DestTy = I.getType();
01273 
01274   Assert1(SrcTy->getScalarType()->isPointerTy(),
01275           "PtrToInt source must be pointer", &I);
01276   Assert1(DestTy->getScalarType()->isIntegerTy(),
01277           "PtrToInt result must be integral", &I);
01278   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
01279           "PtrToInt type mismatch", &I);
01280 
01281   if (SrcTy->isVectorTy()) {
01282     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
01283     VectorType *VDest = dyn_cast<VectorType>(DestTy);
01284     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
01285           "PtrToInt Vector width mismatch", &I);
01286   }
01287 
01288   visitInstruction(I);
01289 }
01290 
01291 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
01292   // Get the source and destination types
01293   Type *SrcTy = I.getOperand(0)->getType();
01294   Type *DestTy = I.getType();
01295 
01296   Assert1(SrcTy->getScalarType()->isIntegerTy(),
01297           "IntToPtr source must be an integral", &I);
01298   Assert1(DestTy->getScalarType()->isPointerTy(),
01299           "IntToPtr result must be a pointer",&I);
01300   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
01301           "IntToPtr type mismatch", &I);
01302   if (SrcTy->isVectorTy()) {
01303     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
01304     VectorType *VDest = dyn_cast<VectorType>(DestTy);
01305     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
01306           "IntToPtr Vector width mismatch", &I);
01307   }
01308   visitInstruction(I);
01309 }
01310 
01311 void Verifier::visitBitCastInst(BitCastInst &I) {
01312   // Get the source and destination types
01313   Type *SrcTy = I.getOperand(0)->getType();
01314   Type *DestTy = I.getType();
01315 
01316   // Get the size of the types in bits, we'll need this later
01317   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
01318   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
01319 
01320   // BitCast implies a no-op cast of type only. No bits change.
01321   // However, you can't cast pointers to anything but pointers.
01322   Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
01323           "Bitcast requires both operands to be pointer or neither", &I);
01324   Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
01325 
01326   // Disallow aggregates.
01327   Assert1(!SrcTy->isAggregateType(),
01328           "Bitcast operand must not be aggregate", &I);
01329   Assert1(!DestTy->isAggregateType(),
01330           "Bitcast type must not be aggregate", &I);
01331 
01332   visitInstruction(I);
01333 }
01334 
01335 /// visitPHINode - Ensure that a PHI node is well formed.
01336 ///
01337 void Verifier::visitPHINode(PHINode &PN) {
01338   // Ensure that the PHI nodes are all grouped together at the top of the block.
01339   // This can be tested by checking whether the instruction before this is
01340   // either nonexistent (because this is begin()) or is a PHI node.  If not,
01341   // then there is some other instruction before a PHI.
01342   Assert2(&PN == &PN.getParent()->front() || 
01343           isa<PHINode>(--BasicBlock::iterator(&PN)),
01344           "PHI nodes not grouped at top of basic block!",
01345           &PN, PN.getParent());
01346 
01347   // Check that all of the values of the PHI node have the same type as the
01348   // result, and that the incoming blocks are really basic blocks.
01349   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
01350     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
01351             "PHI node operands are not the same type as the result!", &PN);
01352   }
01353 
01354   // All other PHI node constraints are checked in the visitBasicBlock method.
01355 
01356   visitInstruction(PN);
01357 }
01358 
01359 void Verifier::VerifyCallSite(CallSite CS) {
01360   Instruction *I = CS.getInstruction();
01361 
01362   Assert1(CS.getCalledValue()->getType()->isPointerTy(),
01363           "Called function must be a pointer!", I);
01364   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
01365 
01366   Assert1(FPTy->getElementType()->isFunctionTy(),
01367           "Called function is not pointer to function type!", I);
01368   FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
01369 
01370   // Verify that the correct number of arguments are being passed
01371   if (FTy->isVarArg())
01372     Assert1(CS.arg_size() >= FTy->getNumParams(),
01373             "Called function requires more parameters than were provided!",I);
01374   else
01375     Assert1(CS.arg_size() == FTy->getNumParams(),
01376             "Incorrect number of arguments passed to called function!", I);
01377 
01378   // Verify that all arguments to the call match the function type.
01379   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
01380     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
01381             "Call parameter type does not match function signature!",
01382             CS.getArgument(i), FTy->getParamType(i), I);
01383 
01384   AttributeSet Attrs = CS.getAttributes();
01385 
01386   Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
01387           "Attribute after last parameter!", I);
01388 
01389   // Verify call attributes.
01390   VerifyFunctionAttrs(FTy, Attrs, I);
01391 
01392   if (FTy->isVarArg()) {
01393     // FIXME? is 'nest' even legal here?
01394     bool SawNest = false;
01395     bool SawReturned = false;
01396 
01397     for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
01398       if (Attrs.hasAttribute(Idx, Attribute::Nest))
01399         SawNest = true;
01400       if (Attrs.hasAttribute(Idx, Attribute::Returned))
01401         SawReturned = true;
01402     }
01403 
01404     // Check attributes on the varargs part.
01405     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
01406       Type *Ty = CS.getArgument(Idx-1)->getType(); 
01407       VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
01408       
01409       if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
01410         Assert1(!SawNest, "More than one parameter has attribute nest!", I);
01411         SawNest = true;
01412       }
01413 
01414       if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
01415         Assert1(!SawReturned, "More than one parameter has attribute returned!",
01416                 I);
01417         Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
01418                 "Incompatible argument and return types for 'returned' "
01419                 "attribute", I);
01420         SawReturned = true;
01421       }
01422 
01423       Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
01424               "Attribute 'sret' cannot be used for vararg call arguments!", I);
01425     }
01426   }
01427 
01428   // Verify that there's no metadata unless it's a direct call to an intrinsic.
01429   if (CS.getCalledFunction() == 0 ||
01430       !CS.getCalledFunction()->getName().startswith("llvm.")) {
01431     for (FunctionType::param_iterator PI = FTy->param_begin(),
01432            PE = FTy->param_end(); PI != PE; ++PI)
01433       Assert1(!(*PI)->isMetadataTy(),
01434               "Function has metadata parameter but isn't an intrinsic", I);
01435   }
01436 
01437   visitInstruction(*I);
01438 }
01439 
01440 void Verifier::visitCallInst(CallInst &CI) {
01441   VerifyCallSite(&CI);
01442 
01443   if (Function *F = CI.getCalledFunction())
01444     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
01445       visitIntrinsicFunctionCall(ID, CI);
01446 }
01447 
01448 void Verifier::visitInvokeInst(InvokeInst &II) {
01449   VerifyCallSite(&II);
01450 
01451   // Verify that there is a landingpad instruction as the first non-PHI
01452   // instruction of the 'unwind' destination.
01453   Assert1(II.getUnwindDest()->isLandingPad(),
01454           "The unwind destination does not have a landingpad instruction!",&II);
01455 
01456   visitTerminatorInst(II);
01457 }
01458 
01459 /// visitBinaryOperator - Check that both arguments to the binary operator are
01460 /// of the same type!
01461 ///
01462 void Verifier::visitBinaryOperator(BinaryOperator &B) {
01463   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
01464           "Both operands to a binary operator are not of the same type!", &B);
01465 
01466   switch (B.getOpcode()) {
01467   // Check that integer arithmetic operators are only used with
01468   // integral operands.
01469   case Instruction::Add:
01470   case Instruction::Sub:
01471   case Instruction::Mul:
01472   case Instruction::SDiv:
01473   case Instruction::UDiv:
01474   case Instruction::SRem:
01475   case Instruction::URem:
01476     Assert1(B.getType()->isIntOrIntVectorTy(),
01477             "Integer arithmetic operators only work with integral types!", &B);
01478     Assert1(B.getType() == B.getOperand(0)->getType(),
01479             "Integer arithmetic operators must have same type "
01480             "for operands and result!", &B);
01481     break;
01482   // Check that floating-point arithmetic operators are only used with
01483   // floating-point operands.
01484   case Instruction::FAdd:
01485   case Instruction::FSub:
01486   case Instruction::FMul:
01487   case Instruction::FDiv:
01488   case Instruction::FRem:
01489     Assert1(B.getType()->isFPOrFPVectorTy(),
01490             "Floating-point arithmetic operators only work with "
01491             "floating-point types!", &B);
01492     Assert1(B.getType() == B.getOperand(0)->getType(),
01493             "Floating-point arithmetic operators must have same type "
01494             "for operands and result!", &B);
01495     break;
01496   // Check that logical operators are only used with integral operands.
01497   case Instruction::And:
01498   case Instruction::Or:
01499   case Instruction::Xor:
01500     Assert1(B.getType()->isIntOrIntVectorTy(),
01501             "Logical operators only work with integral types!", &B);
01502     Assert1(B.getType() == B.getOperand(0)->getType(),
01503             "Logical operators must have same type for operands and result!",
01504             &B);
01505     break;
01506   case Instruction::Shl:
01507   case Instruction::LShr:
01508   case Instruction::AShr:
01509     Assert1(B.getType()->isIntOrIntVectorTy(),
01510             "Shifts only work with integral types!", &B);
01511     Assert1(B.getType() == B.getOperand(0)->getType(),
01512             "Shift return type must be same as operands!", &B);
01513     break;
01514   default:
01515     llvm_unreachable("Unknown BinaryOperator opcode!");
01516   }
01517 
01518   visitInstruction(B);
01519 }
01520 
01521 void Verifier::visitICmpInst(ICmpInst &IC) {
01522   // Check that the operands are the same type
01523   Type *Op0Ty = IC.getOperand(0)->getType();
01524   Type *Op1Ty = IC.getOperand(1)->getType();
01525   Assert1(Op0Ty == Op1Ty,
01526           "Both operands to ICmp instruction are not of the same type!", &IC);
01527   // Check that the operands are the right type
01528   Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
01529           "Invalid operand types for ICmp instruction", &IC);
01530   // Check that the predicate is valid.
01531   Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
01532           IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
01533           "Invalid predicate in ICmp instruction!", &IC);
01534 
01535   visitInstruction(IC);
01536 }
01537 
01538 void Verifier::visitFCmpInst(FCmpInst &FC) {
01539   // Check that the operands are the same type
01540   Type *Op0Ty = FC.getOperand(0)->getType();
01541   Type *Op1Ty = FC.getOperand(1)->getType();
01542   Assert1(Op0Ty == Op1Ty,
01543           "Both operands to FCmp instruction are not of the same type!", &FC);
01544   // Check that the operands are the right type
01545   Assert1(Op0Ty->isFPOrFPVectorTy(),
01546           "Invalid operand types for FCmp instruction", &FC);
01547   // Check that the predicate is valid.
01548   Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
01549           FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
01550           "Invalid predicate in FCmp instruction!", &FC);
01551 
01552   visitInstruction(FC);
01553 }
01554 
01555 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
01556   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
01557                                               EI.getOperand(1)),
01558           "Invalid extractelement operands!", &EI);
01559   visitInstruction(EI);
01560 }
01561 
01562 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
01563   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
01564                                              IE.getOperand(1),
01565                                              IE.getOperand(2)),
01566           "Invalid insertelement operands!", &IE);
01567   visitInstruction(IE);
01568 }
01569 
01570 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
01571   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
01572                                              SV.getOperand(2)),
01573           "Invalid shufflevector operands!", &SV);
01574   visitInstruction(SV);
01575 }
01576 
01577 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
01578   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
01579 
01580   Assert1(isa<PointerType>(TargetTy),
01581     "GEP base pointer is not a vector or a vector of pointers", &GEP);
01582   Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
01583           "GEP into unsized type!", &GEP);
01584   Assert1(GEP.getPointerOperandType()->isVectorTy() ==
01585           GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
01586           &GEP);
01587 
01588   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
01589   Type *ElTy =
01590     GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
01591   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
01592 
01593   Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
01594           cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
01595           == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
01596 
01597   if (GEP.getPointerOperandType()->isVectorTy()) {
01598     // Additional checks for vector GEPs.
01599     unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
01600     Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
01601             "Vector GEP result width doesn't match operand's", &GEP);
01602     for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
01603       Type *IndexTy = Idxs[i]->getType();
01604       Assert1(IndexTy->isVectorTy(),
01605               "Vector GEP must have vector indices!", &GEP);
01606       unsigned IndexWidth = IndexTy->getVectorNumElements();
01607       Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
01608     }
01609   }
01610   visitInstruction(GEP);
01611 }
01612 
01613 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
01614   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
01615 }
01616 
01617 void Verifier::visitLoadInst(LoadInst &LI) {
01618   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
01619   Assert1(PTy, "Load operand must be a pointer.", &LI);
01620   Type *ElTy = PTy->getElementType();
01621   Assert2(ElTy == LI.getType(),
01622           "Load result type does not match pointer operand type!", &LI, ElTy);
01623   if (LI.isAtomic()) {
01624     Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
01625             "Load cannot have Release ordering", &LI);
01626     Assert1(LI.getAlignment() != 0,
01627             "Atomic load must specify explicit alignment", &LI);
01628     if (!ElTy->isPointerTy()) {
01629       Assert2(ElTy->isIntegerTy(),
01630               "atomic store operand must have integer type!",
01631               &LI, ElTy);
01632       unsigned Size = ElTy->getPrimitiveSizeInBits();
01633       Assert2(Size >= 8 && !(Size & (Size - 1)),
01634               "atomic store operand must be power-of-two byte-sized integer",
01635               &LI, ElTy);
01636     }
01637   } else {
01638     Assert1(LI.getSynchScope() == CrossThread,
01639             "Non-atomic load cannot have SynchronizationScope specified", &LI);
01640   }
01641 
01642   if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
01643     unsigned NumOperands = Range->getNumOperands();
01644     Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
01645     unsigned NumRanges = NumOperands / 2;
01646     Assert1(NumRanges >= 1, "It should have at least one range!", Range);
01647 
01648     ConstantRange LastRange(1); // Dummy initial value
01649     for (unsigned i = 0; i < NumRanges; ++i) {
01650       ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
01651       Assert1(Low, "The lower limit must be an integer!", Low);
01652       ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
01653       Assert1(High, "The upper limit must be an integer!", High);
01654       Assert1(High->getType() == Low->getType() &&
01655               High->getType() == ElTy, "Range types must match load type!",
01656               &LI);
01657 
01658       APInt HighV = High->getValue();
01659       APInt LowV = Low->getValue();
01660       ConstantRange CurRange(LowV, HighV);
01661       Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
01662               "Range must not be empty!", Range);
01663       if (i != 0) {
01664         Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
01665                 "Intervals are overlapping", Range);
01666         Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
01667                 Range);
01668         Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
01669                 Range);
01670       }
01671       LastRange = ConstantRange(LowV, HighV);
01672     }
01673     if (NumRanges > 2) {
01674       APInt FirstLow =
01675         dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
01676       APInt FirstHigh =
01677         dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
01678       ConstantRange FirstRange(FirstLow, FirstHigh);
01679       Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
01680               "Intervals are overlapping", Range);
01681       Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
01682               Range);
01683     }
01684 
01685 
01686   }
01687 
01688   visitInstruction(LI);
01689 }
01690 
01691 void Verifier::visitStoreInst(StoreInst &SI) {
01692   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
01693   Assert1(PTy, "Store operand must be a pointer.", &SI);
01694   Type *ElTy = PTy->getElementType();
01695   Assert2(ElTy == SI.getOperand(0)->getType(),
01696           "Stored value type does not match pointer operand type!",
01697           &SI, ElTy);
01698   if (SI.isAtomic()) {
01699     Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
01700             "Store cannot have Acquire ordering", &SI);
01701     Assert1(SI.getAlignment() != 0,
01702             "Atomic store must specify explicit alignment", &SI);
01703     if (!ElTy->isPointerTy()) {
01704       Assert2(ElTy->isIntegerTy(),
01705               "atomic store operand must have integer type!",
01706               &SI, ElTy);
01707       unsigned Size = ElTy->getPrimitiveSizeInBits();
01708       Assert2(Size >= 8 && !(Size & (Size - 1)),
01709               "atomic store operand must be power-of-two byte-sized integer",
01710               &SI, ElTy);
01711     }
01712   } else {
01713     Assert1(SI.getSynchScope() == CrossThread,
01714             "Non-atomic store cannot have SynchronizationScope specified", &SI);
01715   }
01716   visitInstruction(SI);
01717 }
01718 
01719 void Verifier::visitAllocaInst(AllocaInst &AI) {
01720   PointerType *PTy = AI.getType();
01721   Assert1(PTy->getAddressSpace() == 0, 
01722           "Allocation instruction pointer not in the generic address space!",
01723           &AI);
01724   Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
01725           &AI);
01726   Assert1(AI.getArraySize()->getType()->isIntegerTy(),
01727           "Alloca array size must have integer type", &AI);
01728   visitInstruction(AI);
01729 }
01730 
01731 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
01732   Assert1(CXI.getOrdering() != NotAtomic,
01733           "cmpxchg instructions must be atomic.", &CXI);
01734   Assert1(CXI.getOrdering() != Unordered,
01735           "cmpxchg instructions cannot be unordered.", &CXI);
01736   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
01737   Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
01738   Type *ElTy = PTy->getElementType();
01739   Assert2(ElTy->isIntegerTy(),
01740           "cmpxchg operand must have integer type!",
01741           &CXI, ElTy);
01742   unsigned Size = ElTy->getPrimitiveSizeInBits();
01743   Assert2(Size >= 8 && !(Size & (Size - 1)),
01744           "cmpxchg operand must be power-of-two byte-sized integer",
01745           &CXI, ElTy);
01746   Assert2(ElTy == CXI.getOperand(1)->getType(),
01747           "Expected value type does not match pointer operand type!",
01748           &CXI, ElTy);
01749   Assert2(ElTy == CXI.getOperand(2)->getType(),
01750           "Stored value type does not match pointer operand type!",
01751           &CXI, ElTy);
01752   visitInstruction(CXI);
01753 }
01754 
01755 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
01756   Assert1(RMWI.getOrdering() != NotAtomic,
01757           "atomicrmw instructions must be atomic.", &RMWI);
01758   Assert1(RMWI.getOrdering() != Unordered,
01759           "atomicrmw instructions cannot be unordered.", &RMWI);
01760   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
01761   Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
01762   Type *ElTy = PTy->getElementType();
01763   Assert2(ElTy->isIntegerTy(),
01764           "atomicrmw operand must have integer type!",
01765           &RMWI, ElTy);
01766   unsigned Size = ElTy->getPrimitiveSizeInBits();
01767   Assert2(Size >= 8 && !(Size & (Size - 1)),
01768           "atomicrmw operand must be power-of-two byte-sized integer",
01769           &RMWI, ElTy);
01770   Assert2(ElTy == RMWI.getOperand(1)->getType(),
01771           "Argument value type does not match pointer operand type!",
01772           &RMWI, ElTy);
01773   Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
01774           RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
01775           "Invalid binary operation!", &RMWI);
01776   visitInstruction(RMWI);
01777 }
01778 
01779 void Verifier::visitFenceInst(FenceInst &FI) {
01780   const AtomicOrdering Ordering = FI.getOrdering();
01781   Assert1(Ordering == Acquire || Ordering == Release ||
01782           Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
01783           "fence instructions may only have "
01784           "acquire, release, acq_rel, or seq_cst ordering.", &FI);
01785   visitInstruction(FI);
01786 }
01787 
01788 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
01789   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
01790                                            EVI.getIndices()) ==
01791           EVI.getType(),
01792           "Invalid ExtractValueInst operands!", &EVI);
01793   
01794   visitInstruction(EVI);
01795 }
01796 
01797 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
01798   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
01799                                            IVI.getIndices()) ==
01800           IVI.getOperand(1)->getType(),
01801           "Invalid InsertValueInst operands!", &IVI);
01802   
01803   visitInstruction(IVI);
01804 }
01805 
01806 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
01807   BasicBlock *BB = LPI.getParent();
01808 
01809   // The landingpad instruction is ill-formed if it doesn't have any clauses and
01810   // isn't a cleanup.
01811   Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
01812           "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
01813 
01814   // The landingpad instruction defines its parent as a landing pad block. The
01815   // landing pad block may be branched to only by the unwind edge of an invoke.
01816   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
01817     const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
01818     Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
01819             "Block containing LandingPadInst must be jumped to "
01820             "only by the unwind edge of an invoke.", &LPI);
01821   }
01822 
01823   // The landingpad instruction must be the first non-PHI instruction in the
01824   // block.
01825   Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
01826           "LandingPadInst not the first non-PHI instruction in the block.",
01827           &LPI);
01828 
01829   // The personality functions for all landingpad instructions within the same
01830   // function should match.
01831   if (PersonalityFn)
01832     Assert1(LPI.getPersonalityFn() == PersonalityFn,
01833             "Personality function doesn't match others in function", &LPI);
01834   PersonalityFn = LPI.getPersonalityFn();
01835 
01836   // All operands must be constants.
01837   Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
01838           &LPI);
01839   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
01840     Value *Clause = LPI.getClause(i);
01841     Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
01842     if (LPI.isCatch(i)) {
01843       Assert1(isa<PointerType>(Clause->getType()),
01844               "Catch operand does not have pointer type!", &LPI);
01845     } else {
01846       Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
01847       Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
01848               "Filter operand is not an array of constants!", &LPI);
01849     }
01850   }
01851 
01852   visitInstruction(LPI);
01853 }
01854 
01855 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
01856   Instruction *Op = cast<Instruction>(I.getOperand(i));
01857   // If the we have an invalid invoke, don't try to compute the dominance.
01858   // We already reject it in the invoke specific checks and the dominance
01859   // computation doesn't handle multiple edges.
01860   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
01861     if (II->getNormalDest() == II->getUnwindDest())
01862       return;
01863   }
01864 
01865   const Use &U = I.getOperandUse(i);
01866   Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
01867           "Instruction does not dominate all uses!", Op, &I);
01868 }
01869 
01870 /// verifyInstruction - Verify that an instruction is well formed.
01871 ///
01872 void Verifier::visitInstruction(Instruction &I) {
01873   BasicBlock *BB = I.getParent();
01874   Assert1(BB, "Instruction not embedded in basic block!", &I);
01875 
01876   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
01877     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
01878          UI != UE; ++UI)
01879       Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
01880               "Only PHI nodes may reference their own value!", &I);
01881   }
01882 
01883   // Check that void typed values don't have names
01884   Assert1(!I.getType()->isVoidTy() || !I.hasName(),
01885           "Instruction has a name, but provides a void value!", &I);
01886 
01887   // Check that the return value of the instruction is either void or a legal
01888   // value type.
01889   Assert1(I.getType()->isVoidTy() || 
01890           I.getType()->isFirstClassType(),
01891           "Instruction returns a non-scalar type!", &I);
01892 
01893   // Check that the instruction doesn't produce metadata. Calls are already
01894   // checked against the callee type.
01895   Assert1(!I.getType()->isMetadataTy() ||
01896           isa<CallInst>(I) || isa<InvokeInst>(I),
01897           "Invalid use of metadata!", &I);
01898 
01899   // Check that all uses of the instruction, if they are instructions
01900   // themselves, actually have parent basic blocks.  If the use is not an
01901   // instruction, it is an error!
01902   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
01903        UI != UE; ++UI) {
01904     if (Instruction *Used = dyn_cast<Instruction>(*UI))
01905       Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
01906               " embedded in a basic block!", &I, Used);
01907     else {
01908       CheckFailed("Use of instruction is not an instruction!", *UI);
01909       return;
01910     }
01911   }
01912 
01913   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
01914     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
01915 
01916     // Check to make sure that only first-class-values are operands to
01917     // instructions.
01918     if (!I.getOperand(i)->getType()->isFirstClassType()) {
01919       Assert1(0, "Instruction operands must be first-class values!", &I);
01920     }
01921 
01922     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
01923       // Check to make sure that the "address of" an intrinsic function is never
01924       // taken.
01925       Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
01926               "Cannot take the address of an intrinsic!", &I);
01927       Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
01928               F->getIntrinsicID() == Intrinsic::donothing,
01929               "Cannot invoke an intrinsinc other than donothing", &I);
01930       Assert1(F->getParent() == Mod, "Referencing function in another module!",
01931               &I);
01932     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
01933       Assert1(OpBB->getParent() == BB->getParent(),
01934               "Referring to a basic block in another function!", &I);
01935     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
01936       Assert1(OpArg->getParent() == BB->getParent(),
01937               "Referring to an argument in another function!", &I);
01938     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
01939       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
01940               &I);
01941     } else if (isa<Instruction>(I.getOperand(i))) {
01942       verifyDominatesUse(I, i);
01943     } else if (isa<InlineAsm>(I.getOperand(i))) {
01944       Assert1((i + 1 == e && isa<CallInst>(I)) ||
01945               (i + 3 == e && isa<InvokeInst>(I)),
01946               "Cannot take the address of an inline asm!", &I);
01947     }
01948   }
01949 
01950   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
01951     Assert1(I.getType()->isFPOrFPVectorTy(),
01952             "fpmath requires a floating point result!", &I);
01953     Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
01954     Value *Op0 = MD->getOperand(0);
01955     if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
01956       APFloat Accuracy = CFP0->getValueAPF();
01957       Assert1(Accuracy.isNormal() && !Accuracy.isNegative(),
01958               "fpmath accuracy not a positive number!", &I);
01959     } else {
01960       Assert1(false, "invalid fpmath accuracy!", &I);
01961     }
01962   }
01963 
01964   MDNode *MD = I.getMetadata(LLVMContext::MD_range);
01965   Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
01966 
01967   InstsInThisBlock.insert(&I);
01968 }
01969 
01970 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
01971 /// intrinsic argument or return value) matches the type constraints specified
01972 /// by the .td file (e.g. an "any integer" argument really is an integer).
01973 ///
01974 /// This return true on error but does not print a message.
01975 bool Verifier::VerifyIntrinsicType(Type *Ty,
01976                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
01977                                    SmallVectorImpl<Type*> &ArgTys) {
01978   using namespace Intrinsic;
01979 
01980   // If we ran out of descriptors, there are too many arguments.
01981   if (Infos.empty()) return true; 
01982   IITDescriptor D = Infos.front();
01983   Infos = Infos.slice(1);
01984   
01985   switch (D.Kind) {
01986   case IITDescriptor::Void: return !Ty->isVoidTy();
01987   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
01988   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
01989   case IITDescriptor::Half: return !Ty->isHalfTy();
01990   case IITDescriptor::Float: return !Ty->isFloatTy();
01991   case IITDescriptor::Double: return !Ty->isDoubleTy();
01992   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
01993   case IITDescriptor::Vector: {
01994     VectorType *VT = dyn_cast<VectorType>(Ty);
01995     return VT == 0 || VT->getNumElements() != D.Vector_Width ||
01996            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
01997   }
01998   case IITDescriptor::Pointer: {
01999     PointerType *PT = dyn_cast<PointerType>(Ty);
02000     return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
02001            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
02002   }
02003       
02004   case IITDescriptor::Struct: {
02005     StructType *ST = dyn_cast<StructType>(Ty);
02006     if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
02007       return true;
02008     
02009     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
02010       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
02011         return true;
02012     return false;
02013   }
02014       
02015   case IITDescriptor::Argument:
02016     // Two cases here - If this is the second occurrence of an argument, verify
02017     // that the later instance matches the previous instance. 
02018     if (D.getArgumentNumber() < ArgTys.size())
02019       return Ty != ArgTys[D.getArgumentNumber()];  
02020       
02021     // Otherwise, if this is the first instance of an argument, record it and
02022     // verify the "Any" kind.
02023     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
02024     ArgTys.push_back(Ty);
02025       
02026     switch (D.getArgumentKind()) {
02027     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
02028     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
02029     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
02030     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
02031     }
02032     llvm_unreachable("all argument kinds not covered");
02033       
02034   case IITDescriptor::ExtendVecArgument:
02035     // This may only be used when referring to a previous vector argument.
02036     return D.getArgumentNumber() >= ArgTys.size() ||
02037            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
02038            VectorType::getExtendedElementVectorType(
02039                        cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
02040 
02041   case IITDescriptor::TruncVecArgument:
02042     // This may only be used when referring to a previous vector argument.
02043     return D.getArgumentNumber() >= ArgTys.size() ||
02044            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
02045            VectorType::getTruncatedElementVectorType(
02046                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
02047   }
02048   llvm_unreachable("unhandled");
02049 }
02050 
02051 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
02052 ///
02053 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
02054   Function *IF = CI.getCalledFunction();
02055   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
02056           IF);
02057 
02058   // Verify that the intrinsic prototype lines up with what the .td files
02059   // describe.
02060   FunctionType *IFTy = IF->getFunctionType();
02061   Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
02062   
02063   SmallVector<Intrinsic::IITDescriptor, 8> Table;
02064   getIntrinsicInfoTableEntries(ID, Table);
02065   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
02066 
02067   SmallVector<Type *, 4> ArgTys;
02068   Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
02069           "Intrinsic has incorrect return type!", IF);
02070   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
02071     Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
02072             "Intrinsic has incorrect argument type!", IF);
02073   Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
02074 
02075   // Now that we have the intrinsic ID and the actual argument types (and we
02076   // know they are legal for the intrinsic!) get the intrinsic name through the
02077   // usual means.  This allows us to verify the mangling of argument types into
02078   // the name.
02079   Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
02080           "Intrinsic name not mangled correctly for type arguments!", IF);
02081   
02082   // If the intrinsic takes MDNode arguments, verify that they are either global
02083   // or are local to *this* function.
02084   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
02085     if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
02086       visitMDNode(*MD, CI.getParent()->getParent());
02087 
02088   switch (ID) {
02089   default:
02090     break;
02091   case Intrinsic::ctlz:  // llvm.ctlz
02092   case Intrinsic::cttz:  // llvm.cttz
02093     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
02094             "is_zero_undef argument of bit counting intrinsics must be a "
02095             "constant int", &CI);
02096     break;
02097   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
02098     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
02099                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
02100     MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
02101     Assert1(MD->getNumOperands() == 1,
02102                 "invalid llvm.dbg.declare intrinsic call 2", &CI);
02103   } break;
02104   case Intrinsic::memcpy:
02105   case Intrinsic::memmove:
02106   case Intrinsic::memset:
02107     Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
02108             "alignment argument of memory intrinsics must be a constant int",
02109             &CI);
02110     Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
02111             "isvolatile argument of memory intrinsics must be a constant int",
02112             &CI);
02113     break;
02114   case Intrinsic::gcroot:
02115   case Intrinsic::gcwrite:
02116   case Intrinsic::gcread:
02117     if (ID == Intrinsic::gcroot) {
02118       AllocaInst *AI =
02119         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
02120       Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
02121       Assert1(isa<Constant>(CI.getArgOperand(1)),
02122               "llvm.gcroot parameter #2 must be a constant.", &CI);
02123       if (!AI->getType()->getElementType()->isPointerTy()) {
02124         Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
02125                 "llvm.gcroot parameter #1 must either be a pointer alloca, "
02126                 "or argument #2 must be a non-null constant.", &CI);
02127       }
02128     }
02129 
02130     Assert1(CI.getParent()->getParent()->hasGC(),
02131             "Enclosing function does not use GC.", &CI);
02132     break;
02133   case Intrinsic::init_trampoline:
02134     Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
02135             "llvm.init_trampoline parameter #2 must resolve to a function.",
02136             &CI);
02137     break;
02138   case Intrinsic::prefetch:
02139     Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
02140             isa<ConstantInt>(CI.getArgOperand(2)) &&
02141             cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
02142             cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
02143             "invalid arguments to llvm.prefetch",
02144             &CI);
02145     break;
02146   case Intrinsic::stackprotector:
02147     Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
02148             "llvm.stackprotector parameter #2 must resolve to an alloca.",
02149             &CI);
02150     break;
02151   case Intrinsic::lifetime_start:
02152   case Intrinsic::lifetime_end:
02153   case Intrinsic::invariant_start:
02154     Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
02155             "size argument of memory use markers must be a constant integer",
02156             &CI);
02157     break;
02158   case Intrinsic::invariant_end:
02159     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
02160             "llvm.invariant.end parameter #2 must be a constant integer", &CI);
02161     break;
02162   }
02163 }
02164 
02165 //===----------------------------------------------------------------------===//
02166 //  Implement the public interfaces to this file...
02167 //===----------------------------------------------------------------------===//
02168 
02169 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
02170   return new Verifier(action);
02171 }
02172 
02173 
02174 /// verifyFunction - Check a function for errors, printing messages on stderr.
02175 /// Return true if the function is corrupt.
02176 ///
02177 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
02178   Function &F = const_cast<Function&>(f);
02179   assert(!F.isDeclaration() && "Cannot verify external functions");
02180 
02181   FunctionPassManager FPM(F.getParent());
02182   Verifier *V = new Verifier(action);
02183   FPM.add(V);
02184   FPM.run(F);
02185   return V->Broken;
02186 }
02187 
02188 /// verifyModule - Check a module for errors, printing messages on stderr.
02189 /// Return true if the module is corrupt.
02190 ///
02191 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
02192                         std::string *ErrorInfo) {
02193   PassManager PM;
02194   Verifier *V = new Verifier(action);
02195   PM.add(V);
02196   PM.run(const_cast<Module&>(M));
02197 
02198   if (ErrorInfo && V->Broken)
02199     *ErrorInfo = V->MessagesStr.str();
02200   return V->Broken;
02201 }