Verifier.cpp revision 261991
1254721Semaste//===-- Verifier.cpp - Implement the Module Verifier -----------------------==// 2254721Semaste// 3254721Semaste// The LLVM Compiler Infrastructure 4254721Semaste// 5254721Semaste// This file is distributed under the University of Illinois Open Source 6254721Semaste// License. See LICENSE.TXT for details. 7254721Semaste// 8254721Semaste//===----------------------------------------------------------------------===// 9254721Semaste// 10254721Semaste// This file defines the function verifier interface, that can be used for some 11254721Semaste// sanity checking of input to the system. 12254721Semaste// 13254721Semaste// Note that this does not provide full `Java style' security and verifications, 14254721Semaste// instead it just tries to ensure that code is well-formed. 15254721Semaste// 16254721Semaste// * Both of a binary operator's parameters are of the same type 17254721Semaste// * Verify that the indices of mem access instructions match other operands 18254721Semaste// * Verify that arithmetic and other things are only performed on first-class 19288943Sdim// types. Verify that shifts & logicals only happen on integrals f.e. 20254721Semaste// * All of the constants in a switch statement are of the correct type 21254721Semaste// * The code is in valid SSA form 22254721Semaste// * It should be illegal to put a label into any other type (like a structure) 23254721Semaste// or to return one. [except constant arrays!] 24254721Semaste// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad 25254721Semaste// * PHI nodes must have an entry for each predecessor, with no extras. 26254721Semaste// * PHI nodes must be the first thing in a basic block, all grouped together 27254721Semaste// * PHI nodes must have at least one entry 28254721Semaste// * All basic blocks should only end with terminator insts, not contain them 29254721Semaste// * The entry node to a function must not have predecessors 30254721Semaste// * All Instructions must be embedded into a basic block 31254721Semaste// * Functions cannot take a void-typed parameter 32254721Semaste// * Verify that a function's argument list agrees with it's declared type. 33254721Semaste// * It is illegal to specify a name for a void value. 34254721Semaste// * It is illegal to have a internal global value with no initializer 35254721Semaste// * It is illegal to have a ret instruction that returns a value that does not 36254721Semaste// agree with the function return value type. 37254721Semaste// * Function call argument types match the function prototype 38254721Semaste// * A landing pad is defined by a landingpad instruction, and can be jumped to 39254721Semaste// only by the unwind edge of an invoke instruction. 40254721Semaste// * A landingpad instruction must be the first non-PHI instruction in the 41254721Semaste// block. 42254721Semaste// * All landingpad instructions must use the same personality function with 43254721Semaste// the same function. 44254721Semaste// * All other things that are tested by asserts spread about the code... 45254721Semaste// 46254721Semaste//===----------------------------------------------------------------------===// 47254721Semaste 48254721Semaste#include "llvm/Analysis/Verifier.h" 49254721Semaste#include "llvm/ADT/STLExtras.h" 50254721Semaste#include "llvm/ADT/SetVector.h" 51254721Semaste#include "llvm/ADT/SmallPtrSet.h" 52254721Semaste#include "llvm/ADT/SmallVector.h" 53254721Semaste#include "llvm/ADT/StringExtras.h" 54254721Semaste#include "llvm/Analysis/Dominators.h" 55254721Semaste#include "llvm/Assembly/Writer.h" 56254721Semaste#include "llvm/DebugInfo.h" 57254721Semaste#include "llvm/IR/CallingConv.h" 58254721Semaste#include "llvm/IR/Constants.h" 59254721Semaste#include "llvm/IR/DataLayout.h" 60254721Semaste#include "llvm/IR/DerivedTypes.h" 61254721Semaste#include "llvm/IR/InlineAsm.h" 62254721Semaste#include "llvm/IR/IntrinsicInst.h" 63288943Sdim#include "llvm/IR/LLVMContext.h" 64288943Sdim#include "llvm/IR/Metadata.h" 65254721Semaste#include "llvm/IR/Module.h" 66288943Sdim#include "llvm/InstVisitor.h" 67288943Sdim#include "llvm/Pass.h" 68288943Sdim#include "llvm/PassManager.h" 69288943Sdim#include "llvm/Support/CFG.h" 70288943Sdim#include "llvm/Support/CallSite.h" 71288943Sdim#include "llvm/Support/CommandLine.h" 72288943Sdim#include "llvm/Support/ConstantRange.h" 73288943Sdim#include "llvm/Support/Debug.h" 74288943Sdim#include "llvm/Support/ErrorHandling.h" 75288943Sdim#include "llvm/Support/raw_ostream.h" 76288943Sdim#include <algorithm> 77288943Sdim#include <cstdarg> 78288943Sdimusing namespace llvm; 79288943Sdim 80288943Sdimstatic cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier", 81288943Sdim cl::init(true)); 82288943Sdim 83254721Semastenamespace { // Anonymous namespace for class 84254721Semaste struct PreVerifier : public FunctionPass { 85254721Semaste static char ID; // Pass ID, replacement for typeid 86296417Sdim 87254721Semaste PreVerifier() : FunctionPass(ID) { 88254721Semaste initializePreVerifierPass(*PassRegistry::getPassRegistry()); 89296417Sdim } 90296417Sdim 91254721Semaste virtual void getAnalysisUsage(AnalysisUsage &AU) const { 92296417Sdim AU.setPreservesAll(); 93296417Sdim } 94254721Semaste 95254721Semaste // Check that the prerequisites for successful DominatorTree construction 96254721Semaste // are satisfied. 97254721Semaste bool runOnFunction(Function &F) { 98254721Semaste bool Broken = false; 99254721Semaste 100254721Semaste for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { 101254721Semaste if (I->empty() || !I->back().isTerminator()) { 102254721Semaste dbgs() << "Basic Block in function '" << F.getName() 103254721Semaste << "' does not have terminator!\n"; 104254721Semaste WriteAsOperand(dbgs(), I, true); 105254721Semaste dbgs() << "\n"; 106254721Semaste Broken = true; 107254721Semaste } 108296417Sdim } 109254721Semaste 110296417Sdim if (Broken) 111296417Sdim report_fatal_error("Broken module, no Basic Block terminator!"); 112254721Semaste 113254721Semaste return false; 114254721Semaste } 115254721Semaste }; 116254721Semaste} 117254721Semaste 118254721Semastechar PreVerifier::ID = 0; 119254721SemasteINITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification", 120254721Semaste false, false) 121254721Semastestatic char &PreVerifyID = PreVerifier::ID; 122254721Semaste 123254721Semastenamespace { 124254721Semaste struct Verifier : public FunctionPass, public InstVisitor<Verifier> { 125254721Semaste static char ID; // Pass ID, replacement for typeid 126254721Semaste bool Broken; // Is this module found to be broken? 127254721Semaste VerifierFailureAction action; 128254721Semaste // What to do if verification fails. 129254721Semaste Module *Mod; // Module we are verifying right now 130296417Sdim LLVMContext *Context; // Context within which we are verifying 131254721Semaste DominatorTree *DT; // Dominator Tree, caution can be null! 132254721Semaste const DataLayout *DL; 133254721Semaste 134254721Semaste std::string Messages; 135254721Semaste raw_string_ostream MessagesStr; 136296417Sdim 137254721Semaste /// InstInThisBlock - when verifying a basic block, keep track of all of the 138254721Semaste /// instructions we have seen so far. This allows us to do efficient 139254721Semaste /// dominance checks for the case when an instruction has an operand that is 140254721Semaste /// an instruction in the same block. 141254721Semaste SmallPtrSet<Instruction*, 16> InstsInThisBlock; 142254721Semaste 143254721Semaste /// MDNodes - keep track of the metadata nodes that have been checked 144254721Semaste /// already. 145254721Semaste SmallPtrSet<MDNode *, 32> MDNodes; 146254721Semaste 147254721Semaste /// PersonalityFn - The personality function referenced by the 148254721Semaste /// LandingPadInsts. All LandingPadInsts within the same function must use 149254721Semaste /// the same personality function. 150296417Sdim const Value *PersonalityFn; 151254721Semaste 152254721Semaste /// Finder keeps track of all debug info MDNodes in a Module. 153254721Semaste DebugInfoFinder Finder; 154254721Semaste 155254721Semaste Verifier() 156254721Semaste : FunctionPass(ID), Broken(false), 157254721Semaste action(AbortProcessAction), Mod(0), Context(0), DT(0), DL(0), 158296417Sdim MessagesStr(Messages), PersonalityFn(0) { 159254721Semaste initializeVerifierPass(*PassRegistry::getPassRegistry()); 160254721Semaste } 161254721Semaste explicit Verifier(VerifierFailureAction ctn) 162254721Semaste : FunctionPass(ID), Broken(false), action(ctn), Mod(0), 163254721Semaste Context(0), DT(0), DL(0), MessagesStr(Messages), PersonalityFn(0) { 164254721Semaste initializeVerifierPass(*PassRegistry::getPassRegistry()); 165276479Sdim } 166276479Sdim 167254721Semaste bool doInitialization(Module &M) { 168254721Semaste Mod = &M; 169254721Semaste Context = &M.getContext(); 170254721Semaste 171254721Semaste DL = getAnalysisIfAvailable<DataLayout>(); 172254721Semaste 173254721Semaste // We must abort before returning back to the pass manager, or else the 174254721Semaste // pass manager may try to run other passes on the broken module. 175254721Semaste return abortIfBroken(); 176254721Semaste } 177254721Semaste 178254721Semaste bool runOnFunction(Function &F) { 179254721Semaste // Get dominator information if we are being run by PassManager 180254721Semaste DT = &getAnalysis<DominatorTree>(); 181254721Semaste 182254721Semaste Mod = F.getParent(); 183254721Semaste if (!Context) Context = &F.getContext(); 184254721Semaste 185254721Semaste Finder.reset(); 186254721Semaste visit(F); 187254721Semaste InstsInThisBlock.clear(); 188254721Semaste PersonalityFn = 0; 189254721Semaste 190254721Semaste if (!DisableDebugInfoVerifier) 191254721Semaste // Verify Debug Info. 192254721Semaste verifyDebugInfo(); 193254721Semaste 194254721Semaste // We must abort before returning back to the pass manager, or else the 195254721Semaste // pass manager may try to run other passes on the broken module. 196254721Semaste return abortIfBroken(); 197254721Semaste } 198254721Semaste 199254721Semaste bool doFinalization(Module &M) { 200254721Semaste // Scan through, checking all of the external function's linkage now... 201254721Semaste for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 202254721Semaste visitGlobalValue(*I); 203254721Semaste 204254721Semaste // Check to make sure function prototypes are okay. 205254721Semaste if (I->isDeclaration()) visitFunction(*I); 206254721Semaste } 207254721Semaste 208254721Semaste for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 209254721Semaste I != E; ++I) 210254721Semaste visitGlobalVariable(*I); 211254721Semaste 212254721Semaste for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 213254721Semaste I != E; ++I) 214254721Semaste visitGlobalAlias(*I); 215254721Semaste 216296417Sdim for (Module::named_metadata_iterator I = M.named_metadata_begin(), 217296417Sdim E = M.named_metadata_end(); I != E; ++I) 218254721Semaste visitNamedMDNode(*I); 219254721Semaste 220254721Semaste visitModuleFlags(M); 221254721Semaste visitModuleIdents(M); 222254721Semaste 223254721Semaste if (!DisableDebugInfoVerifier) { 224254721Semaste Finder.reset(); 225254721Semaste Finder.processModule(M); 226254721Semaste // Verify Debug Info. 227254721Semaste verifyDebugInfo(); 228254721Semaste } 229254721Semaste 230254721Semaste // If the module is broken, abort at this time. 231254721Semaste return abortIfBroken(); 232254721Semaste } 233254721Semaste 234254721Semaste virtual void getAnalysisUsage(AnalysisUsage &AU) const { 235254721Semaste AU.setPreservesAll(); 236254721Semaste AU.addRequiredID(PreVerifyID); 237254721Semaste AU.addRequired<DominatorTree>(); 238254721Semaste } 239254721Semaste 240254721Semaste /// abortIfBroken - If the module is broken and we are supposed to abort on 241254721Semaste /// this condition, do so. 242254721Semaste /// 243254721Semaste bool abortIfBroken() { 244288943Sdim if (!Broken) return false; 245254721Semaste MessagesStr << "Broken module found, "; 246254721Semaste switch (action) { 247254721Semaste case AbortProcessAction: 248254721Semaste MessagesStr << "compilation aborted!\n"; 249254721Semaste dbgs() << MessagesStr.str(); 250254721Semaste // Client should choose different reaction if abort is not desired 251254721Semaste abort(); 252254721Semaste case PrintMessageAction: 253254721Semaste MessagesStr << "verification continues.\n"; 254254721Semaste dbgs() << MessagesStr.str(); 255254721Semaste return false; 256254721Semaste case ReturnStatusAction: 257254721Semaste MessagesStr << "compilation terminated.\n"; 258254721Semaste return true; 259254721Semaste } 260254721Semaste llvm_unreachable("Invalid action"); 261254721Semaste } 262254721Semaste 263254721Semaste 264254721Semaste // Verification methods... 265254721Semaste void visitGlobalValue(GlobalValue &GV); 266254721Semaste void visitGlobalVariable(GlobalVariable &GV); 267254721Semaste void visitGlobalAlias(GlobalAlias &GA); 268254721Semaste void visitNamedMDNode(NamedMDNode &NMD); 269254721Semaste void visitMDNode(MDNode &MD, Function *F); 270254721Semaste void visitModuleIdents(Module &M); 271254721Semaste void visitModuleFlags(Module &M); 272254721Semaste void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs, 273254721Semaste SmallVectorImpl<MDNode*> &Requirements); 274254721Semaste void visitFunction(Function &F); 275254721Semaste void visitBasicBlock(BasicBlock &BB); 276254721Semaste using InstVisitor<Verifier>::visit; 277254721Semaste 278254721Semaste void visit(Instruction &I); 279254721Semaste 280254721Semaste void visitTruncInst(TruncInst &I); 281254721Semaste void visitZExtInst(ZExtInst &I); 282254721Semaste void visitSExtInst(SExtInst &I); 283254721Semaste void visitFPTruncInst(FPTruncInst &I); 284254721Semaste void visitFPExtInst(FPExtInst &I); 285254721Semaste void visitFPToUIInst(FPToUIInst &I); 286254721Semaste void visitFPToSIInst(FPToSIInst &I); 287254721Semaste void visitUIToFPInst(UIToFPInst &I); 288254721Semaste void visitSIToFPInst(SIToFPInst &I); 289254721Semaste void visitIntToPtrInst(IntToPtrInst &I); 290276479Sdim void visitPtrToIntInst(PtrToIntInst &I); 291276479Sdim void visitBitCastInst(BitCastInst &I); 292254721Semaste void visitAddrSpaceCastInst(AddrSpaceCastInst &I); 293254721Semaste void visitPHINode(PHINode &PN); 294254721Semaste void visitBinaryOperator(BinaryOperator &B); 295254721Semaste void visitICmpInst(ICmpInst &IC); 296254721Semaste void visitFCmpInst(FCmpInst &FC); 297254721Semaste void visitExtractElementInst(ExtractElementInst &EI); 298254721Semaste void visitInsertElementInst(InsertElementInst &EI); 299254721Semaste void visitShuffleVectorInst(ShuffleVectorInst &EI); 300254721Semaste void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 301254721Semaste void visitCallInst(CallInst &CI); 302254721Semaste void visitInvokeInst(InvokeInst &II); 303254721Semaste void visitGetElementPtrInst(GetElementPtrInst &GEP); 304254721Semaste void visitLoadInst(LoadInst &LI); 305254721Semaste void visitStoreInst(StoreInst &SI); 306254721Semaste void verifyDominatesUse(Instruction &I, unsigned i); 307254721Semaste void visitInstruction(Instruction &I); 308254721Semaste void visitTerminatorInst(TerminatorInst &I); 309254721Semaste void visitBranchInst(BranchInst &BI); 310254721Semaste void visitReturnInst(ReturnInst &RI); 311254721Semaste void visitSwitchInst(SwitchInst &SI); 312254721Semaste void visitIndirectBrInst(IndirectBrInst &BI); 313254721Semaste void visitSelectInst(SelectInst &SI); 314254721Semaste void visitUserOp1(Instruction &I); 315254721Semaste void visitUserOp2(Instruction &I) { visitUserOp1(I); } 316254721Semaste void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI); 317254721Semaste void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 318254721Semaste void visitAtomicRMWInst(AtomicRMWInst &RMWI); 319254721Semaste void visitFenceInst(FenceInst &FI); 320254721Semaste void visitAllocaInst(AllocaInst &AI); 321254721Semaste void visitExtractValueInst(ExtractValueInst &EVI); 322296417Sdim void visitInsertValueInst(InsertValueInst &IVI); 323254721Semaste void visitLandingPadInst(LandingPadInst &LPI); 324254721Semaste 325296417Sdim void VerifyCallSite(CallSite CS); 326254721Semaste bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, 327254721Semaste int VT, unsigned ArgNo, std::string &Suffix); 328254721Semaste bool VerifyIntrinsicType(Type *Ty, 329254721Semaste ArrayRef<Intrinsic::IITDescriptor> &Infos, 330254721Semaste SmallVectorImpl<Type*> &ArgTys); 331254721Semaste bool VerifyIntrinsicIsVarArg(bool isVarArg, 332254721Semaste ArrayRef<Intrinsic::IITDescriptor> &Infos); 333296417Sdim bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params); 334254721Semaste void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, 335254721Semaste bool isFunction, const Value *V); 336254721Semaste void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 337254721Semaste bool isReturnValue, const Value *V); 338254721Semaste void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 339254721Semaste const Value *V); 340254721Semaste 341254721Semaste void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy); 342254721Semaste void VerifyConstantExprBitcastType(const ConstantExpr *CE); 343254721Semaste 344254721Semaste void verifyDebugInfo(); 345254721Semaste 346254721Semaste void WriteValue(const Value *V) { 347254721Semaste if (!V) return; 348254721Semaste if (isa<Instruction>(V)) { 349296417Sdim MessagesStr << *V << '\n'; 350296417Sdim } else { 351254721Semaste WriteAsOperand(MessagesStr, V, true, Mod); 352254721Semaste MessagesStr << '\n'; 353254721Semaste } 354254721Semaste } 355254721Semaste 356254721Semaste void WriteType(Type *T) { 357254721Semaste if (!T) return; 358254721Semaste MessagesStr << ' ' << *T; 359254721Semaste } 360254721Semaste 361254721Semaste 362254721Semaste // CheckFailed - A check failed, so print out the condition and the message 363254721Semaste // that failed. This provides a nice place to put a breakpoint if you want 364254721Semaste // to see why something is not correct. 365254721Semaste void CheckFailed(const Twine &Message, 366254721Semaste const Value *V1 = 0, const Value *V2 = 0, 367254721Semaste const Value *V3 = 0, const Value *V4 = 0) { 368254721Semaste MessagesStr << Message.str() << "\n"; 369254721Semaste WriteValue(V1); 370254721Semaste WriteValue(V2); 371254721Semaste WriteValue(V3); 372254721Semaste WriteValue(V4); 373254721Semaste Broken = true; 374254721Semaste } 375254721Semaste 376254721Semaste void CheckFailed(const Twine &Message, const Value *V1, 377254721Semaste Type *T2, const Value *V3 = 0) { 378254721Semaste MessagesStr << Message.str() << "\n"; 379254721Semaste WriteValue(V1); 380254721Semaste WriteType(T2); 381254721Semaste WriteValue(V3); 382254721Semaste Broken = true; 383254721Semaste } 384254721Semaste 385254721Semaste void CheckFailed(const Twine &Message, Type *T1, 386254721Semaste Type *T2 = 0, Type *T3 = 0) { 387254721Semaste MessagesStr << Message.str() << "\n"; 388254721Semaste WriteType(T1); 389254721Semaste WriteType(T2); 390254721Semaste WriteType(T3); 391254721Semaste Broken = true; 392254721Semaste } 393254721Semaste }; 394254721Semaste} // End anonymous namespace 395254721Semaste 396254721Semastechar Verifier::ID = 0; 397254721SemasteINITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false) 398254721SemasteINITIALIZE_PASS_DEPENDENCY(PreVerifier) 399254721SemasteINITIALIZE_PASS_DEPENDENCY(DominatorTree) 400254721SemasteINITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false) 401254721Semaste 402254721Semaste// Assert - We know that cond should be true, if not print an error message. 403254721Semaste#define Assert(C, M) \ 404254721Semaste do { if (!(C)) { CheckFailed(M); return; } } while (0) 405254721Semaste#define Assert1(C, M, V1) \ 406254721Semaste do { if (!(C)) { CheckFailed(M, V1); return; } } while (0) 407254721Semaste#define Assert2(C, M, V1, V2) \ 408254721Semaste do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0) 409254721Semaste#define Assert3(C, M, V1, V2, V3) \ 410254721Semaste do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0) 411254721Semaste#define Assert4(C, M, V1, V2, V3, V4) \ 412254721Semaste do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0) 413254721Semaste 414296417Sdimvoid Verifier::visit(Instruction &I) { 415254721Semaste for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 416296417Sdim Assert1(I.getOperand(i) != 0, "Operand is null", &I); 417254721Semaste InstVisitor<Verifier>::visit(I); 418254721Semaste} 419254721Semaste 420254721Semaste 421254721Semastevoid Verifier::visitGlobalValue(GlobalValue &GV) { 422254721Semaste Assert1(!GV.isDeclaration() || 423254721Semaste GV.isMaterializable() || 424296417Sdim GV.hasExternalLinkage() || 425254721Semaste GV.hasDLLImportLinkage() || 426254721Semaste GV.hasExternalWeakLinkage() || 427254721Semaste (isa<GlobalAlias>(GV) && 428254721Semaste (GV.hasLocalLinkage() || GV.hasWeakLinkage())), 429254721Semaste "Global is external, but doesn't have external or dllimport or weak linkage!", 430254721Semaste &GV); 431254721Semaste 432254721Semaste Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(), 433254721Semaste "Global is marked as dllimport, but not external", &GV); 434254721Semaste 435254721Semaste Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 436254721Semaste "Only global variables can have appending linkage!", &GV); 437254721Semaste 438254721Semaste if (GV.hasAppendingLinkage()) { 439254721Semaste GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 440296417Sdim Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(), 441296417Sdim "Only global arrays can have appending linkage!", GVar); 442254721Semaste } 443254721Semaste} 444254721Semaste 445254721Semastevoid Verifier::visitGlobalVariable(GlobalVariable &GV) { 446254721Semaste if (GV.hasInitializer()) { 447254721Semaste Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(), 448254721Semaste "Global variable initializer type does not match global " 449254721Semaste "variable type!", &GV); 450254721Semaste 451254721Semaste // If the global has common linkage, it must have a zero initializer and 452254721Semaste // cannot be constant. 453254721Semaste if (GV.hasCommonLinkage()) { 454254721Semaste Assert1(GV.getInitializer()->isNullValue(), 455254721Semaste "'common' global must have a zero initializer!", &GV); 456254721Semaste Assert1(!GV.isConstant(), "'common' global may not be marked constant!", 457254721Semaste &GV); 458254721Semaste } 459254721Semaste } else { 460254721Semaste Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() || 461254721Semaste GV.hasExternalWeakLinkage(), 462254721Semaste "invalid linkage type for global declaration", &GV); 463254721Semaste } 464254721Semaste 465254721Semaste if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 466254721Semaste GV.getName() == "llvm.global_dtors")) { 467254721Semaste Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(), 468254721Semaste "invalid linkage for intrinsic global variable", &GV); 469254721Semaste // Don't worry about emitting an error for it not being an array, 470254721Semaste // visitGlobalValue will complain on appending non-array. 471254721Semaste if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) { 472254721Semaste StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 473254721Semaste PointerType *FuncPtrTy = 474254721Semaste FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo(); 475254721Semaste Assert1(STy && STy->getNumElements() == 2 && 476254721Semaste STy->getTypeAtIndex(0u)->isIntegerTy(32) && 477254721Semaste STy->getTypeAtIndex(1) == FuncPtrTy, 478254721Semaste "wrong type for intrinsic global variable", &GV); 479254721Semaste } 480254721Semaste } 481254721Semaste 482254721Semaste if (GV.hasName() && (GV.getName() == "llvm.used" || 483254721Semaste GV.getName() == "llvm.compiler.used")) { 484254721Semaste Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(), 485254721Semaste "invalid linkage for intrinsic global variable", &GV); 486254721Semaste Type *GVType = GV.getType()->getElementType(); 487254721Semaste if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) { 488254721Semaste PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType()); 489254721Semaste Assert1(PTy, "wrong type for intrinsic global variable", &GV); 490254721Semaste if (GV.hasInitializer()) { 491254721Semaste Constant *Init = GV.getInitializer(); 492254721Semaste ConstantArray *InitArray = dyn_cast<ConstantArray>(Init); 493254721Semaste Assert1(InitArray, "wrong initalizer for intrinsic global variable", 494254721Semaste Init); 495254721Semaste for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) { 496254721Semaste Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases(); 497254721Semaste Assert1( 498254721Semaste isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V), 499254721Semaste "invalid llvm.used member", V); 500254721Semaste Assert1(V->hasName(), "members of llvm.used must be named", V); 501254721Semaste } 502254721Semaste } 503254721Semaste } 504254721Semaste } 505254721Semaste 506254721Semaste if (!GV.hasInitializer()) { 507254721Semaste visitGlobalValue(GV); 508254721Semaste return; 509254721Semaste } 510254721Semaste 511254721Semaste // Walk any aggregate initializers looking for bitcasts between address spaces 512254721Semaste SmallPtrSet<const Value *, 4> Visited; 513254721Semaste SmallVector<const Value *, 4> WorkStack; 514254721Semaste WorkStack.push_back(cast<Value>(GV.getInitializer())); 515254721Semaste 516254721Semaste while (!WorkStack.empty()) { 517254721Semaste const Value *V = WorkStack.pop_back_val(); 518254721Semaste if (!Visited.insert(V)) 519254721Semaste continue; 520296417Sdim 521254721Semaste if (const User *U = dyn_cast<User>(V)) { 522296417Sdim for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I) 523254721Semaste WorkStack.push_back(U->getOperand(I)); 524254721Semaste } 525254721Semaste 526254721Semaste if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 527254721Semaste VerifyConstantExprBitcastType(CE); 528254721Semaste if (Broken) 529254721Semaste return; 530296417Sdim } 531254721Semaste } 532254721Semaste 533254721Semaste visitGlobalValue(GV); 534254721Semaste} 535254721Semaste 536254721Semastevoid Verifier::visitGlobalAlias(GlobalAlias &GA) { 537254721Semaste Assert1(!GA.getName().empty(), 538254721Semaste "Alias name cannot be empty!", &GA); 539254721Semaste Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()), 540254721Semaste "Alias should have external or external weak linkage!", &GA); 541254721Semaste Assert1(GA.getAliasee(), 542254721Semaste "Aliasee cannot be NULL!", &GA); 543254721Semaste Assert1(GA.getType() == GA.getAliasee()->getType(), 544254721Semaste "Alias and aliasee types should match!", &GA); 545254721Semaste Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA); 546254721Semaste 547254721Semaste Constant *Aliasee = GA.getAliasee(); 548254721Semaste 549296417Sdim if (!isa<GlobalValue>(Aliasee)) { 550296417Sdim ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee); 551254721Semaste Assert1(CE && 552254721Semaste (CE->getOpcode() == Instruction::BitCast || 553254721Semaste CE->getOpcode() == Instruction::GetElementPtr) && 554254721Semaste isa<GlobalValue>(CE->getOperand(0)), 555254721Semaste "Aliasee should be either GlobalValue or bitcast of GlobalValue", 556254721Semaste &GA); 557254721Semaste 558254721Semaste if (CE->getOpcode() == Instruction::BitCast) { 559254721Semaste unsigned SrcAS = CE->getOperand(0)->getType()->getPointerAddressSpace(); 560254721Semaste unsigned DstAS = CE->getType()->getPointerAddressSpace(); 561254721Semaste 562254721Semaste Assert1(SrcAS == DstAS, 563254721Semaste "Alias bitcasts cannot be between different address spaces", 564254721Semaste &GA); 565254721Semaste } 566254721Semaste } 567254721Semaste 568254721Semaste const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false); 569254721Semaste Assert1(Resolved, 570254721Semaste "Aliasing chain should end with function or global variable", &GA); 571254721Semaste 572254721Semaste visitGlobalValue(GA); 573254721Semaste} 574254721Semaste 575254721Semastevoid Verifier::visitNamedMDNode(NamedMDNode &NMD) { 576254721Semaste for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) { 577254721Semaste MDNode *MD = NMD.getOperand(i); 578254721Semaste if (!MD) 579254721Semaste continue; 580254721Semaste 581254721Semaste Assert1(!MD->isFunctionLocal(), 582254721Semaste "Named metadata operand cannot be function local!", MD); 583254721Semaste visitMDNode(*MD, 0); 584254721Semaste } 585254721Semaste} 586254721Semaste 587254721Semastevoid Verifier::visitMDNode(MDNode &MD, Function *F) { 588254721Semaste // Only visit each node once. Metadata can be mutually recursive, so this 589254721Semaste // avoids infinite recursion here, as well as being an optimization. 590254721Semaste if (!MDNodes.insert(&MD)) 591254721Semaste return; 592254721Semaste 593254721Semaste for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) { 594254721Semaste Value *Op = MD.getOperand(i); 595254721Semaste if (!Op) 596254721Semaste continue; 597254721Semaste if (isa<Constant>(Op) || isa<MDString>(Op)) 598254721Semaste continue; 599254721Semaste if (MDNode *N = dyn_cast<MDNode>(Op)) { 600254721Semaste Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(), 601254721Semaste "Global metadata operand cannot be function local!", &MD, N); 602254721Semaste visitMDNode(*N, F); 603254721Semaste continue; 604254721Semaste } 605254721Semaste Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op); 606254721Semaste 607254721Semaste // If this was an instruction, bb, or argument, verify that it is in the 608254721Semaste // function that we expect. 609254721Semaste Function *ActualF = 0; 610254721Semaste if (Instruction *I = dyn_cast<Instruction>(Op)) 611254721Semaste ActualF = I->getParent()->getParent(); 612254721Semaste else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op)) 613254721Semaste ActualF = BB->getParent(); 614254721Semaste else if (Argument *A = dyn_cast<Argument>(Op)) 615254721Semaste ActualF = A->getParent(); 616254721Semaste assert(ActualF && "Unimplemented function local metadata case!"); 617254721Semaste 618254721Semaste Assert2(ActualF == F, "function-local metadata used in wrong function", 619254721Semaste &MD, Op); 620254721Semaste } 621254721Semaste} 622254721Semaste 623254721Semastevoid Verifier::visitModuleIdents(Module &M) { 624254721Semaste const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident"); 625254721Semaste if (!Idents) 626254721Semaste return; 627254721Semaste 628254721Semaste // llvm.ident takes a list of metadata entry. Each entry has only one string. 629254721Semaste // Scan each llvm.ident entry and make sure that this requirement is met. 630254721Semaste for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) { 631254721Semaste const MDNode *N = Idents->getOperand(i); 632254721Semaste Assert1(N->getNumOperands() == 1, 633254721Semaste "incorrect number of operands in llvm.ident metadata", N); 634254721Semaste Assert1(isa<MDString>(N->getOperand(0)), 635254721Semaste ("invalid value for llvm.ident metadata entry operand" 636254721Semaste "(the operand should be a string)"), 637254721Semaste N->getOperand(0)); 638254721Semaste } 639254721Semaste} 640254721Semaste 641254721Semastevoid Verifier::visitModuleFlags(Module &M) { 642254721Semaste const NamedMDNode *Flags = M.getModuleFlagsMetadata(); 643254721Semaste if (!Flags) return; 644254721Semaste 645254721Semaste // Scan each flag, and track the flags and requirements. 646254721Semaste DenseMap<MDString*, MDNode*> SeenIDs; 647254721Semaste SmallVector<MDNode*, 16> Requirements; 648254721Semaste for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) { 649254721Semaste visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements); 650296417Sdim } 651254721Semaste 652254721Semaste // Validate that the requirements in the module are valid. 653296417Sdim for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 654296417Sdim MDNode *Requirement = Requirements[I]; 655254721Semaste MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 656296417Sdim Value *ReqValue = Requirement->getOperand(1); 657254721Semaste 658254721Semaste MDNode *Op = SeenIDs.lookup(Flag); 659254721Semaste if (!Op) { 660254721Semaste CheckFailed("invalid requirement on flag, flag is not present in module", 661254721Semaste Flag); 662254721Semaste continue; 663254721Semaste } 664296417Sdim 665254721Semaste if (Op->getOperand(2) != ReqValue) { 666254721Semaste CheckFailed(("invalid requirement on flag, " 667254721Semaste "flag does not have the required value"), 668254721Semaste Flag); 669254721Semaste continue; 670254721Semaste } 671254721Semaste } 672254721Semaste} 673254721Semaste 674254721Semastevoid Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs, 675254721Semaste SmallVectorImpl<MDNode*> &Requirements) { 676254721Semaste // Each module flag should have three arguments, the merge behavior (a 677254721Semaste // constant int), the flag ID (an MDString), and the value. 678254721Semaste Assert1(Op->getNumOperands() == 3, 679254721Semaste "incorrect number of operands in module flag", Op); 680254721Semaste ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0)); 681254721Semaste MDString *ID = dyn_cast<MDString>(Op->getOperand(1)); 682254721Semaste Assert1(Behavior, 683296417Sdim "invalid behavior operand in module flag (expected constant integer)", 684296417Sdim Op->getOperand(0)); 685254721Semaste unsigned BehaviorValue = Behavior->getZExtValue(); 686254721Semaste Assert1(ID, 687254721Semaste "invalid ID operand in module flag (expected metadata string)", 688254721Semaste Op->getOperand(1)); 689254721Semaste 690254721Semaste // Sanity check the values for behaviors with additional requirements. 691254721Semaste switch (BehaviorValue) { 692254721Semaste default: 693254721Semaste Assert1(false, 694254721Semaste "invalid behavior operand in module flag (unexpected constant)", 695254721Semaste Op->getOperand(0)); 696254721Semaste break; 697254721Semaste 698254721Semaste case Module::Error: 699254721Semaste case Module::Warning: 700254721Semaste case Module::Override: 701254721Semaste // These behavior types accept any value. 702254721Semaste break; 703254721Semaste 704254721Semaste case Module::Require: { 705254721Semaste // The value should itself be an MDNode with two operands, a flag ID (an 706254721Semaste // MDString), and a value. 707254721Semaste MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2)); 708254721Semaste Assert1(Value && Value->getNumOperands() == 2, 709254721Semaste "invalid value for 'require' module flag (expected metadata pair)", 710254721Semaste Op->getOperand(2)); 711254721Semaste Assert1(isa<MDString>(Value->getOperand(0)), 712254721Semaste ("invalid value for 'require' module flag " 713254721Semaste "(first value operand should be a string)"), 714254721Semaste Value->getOperand(0)); 715254721Semaste 716254721Semaste // Append it to the list of requirements, to check once all module flags are 717254721Semaste // scanned. 718254721Semaste Requirements.push_back(Value); 719254721Semaste break; 720254721Semaste } 721254721Semaste 722254721Semaste case Module::Append: 723254721Semaste case Module::AppendUnique: { 724254721Semaste // These behavior types require the operand be an MDNode. 725254721Semaste Assert1(isa<MDNode>(Op->getOperand(2)), 726254721Semaste "invalid value for 'append'-type module flag " 727254721Semaste "(expected a metadata node)", Op->getOperand(2)); 728254721Semaste break; 729254721Semaste } 730254721Semaste } 731254721Semaste 732254721Semaste // Unless this is a "requires" flag, check the ID is unique. 733254721Semaste if (BehaviorValue != Module::Require) { 734254721Semaste bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second; 735254721Semaste Assert1(Inserted, 736254721Semaste "module flag identifiers must be unique (or of 'require' type)", 737254721Semaste ID); 738254721Semaste } 739254721Semaste} 740254721Semaste 741254721Semastevoid Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, 742254721Semaste bool isFunction, const Value *V) { 743254721Semaste unsigned Slot = ~0U; 744254721Semaste for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I) 745254721Semaste if (Attrs.getSlotIndex(I) == Idx) { 746254721Semaste Slot = I; 747254721Semaste break; 748254721Semaste } 749254721Semaste 750254721Semaste assert(Slot != ~0U && "Attribute set inconsistency!"); 751254721Semaste 752254721Semaste for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot); 753254721Semaste I != E; ++I) { 754254721Semaste if (I->isStringAttribute()) 755254721Semaste continue; 756254721Semaste 757254721Semaste if (I->getKindAsEnum() == Attribute::NoReturn || 758254721Semaste I->getKindAsEnum() == Attribute::NoUnwind || 759254721Semaste I->getKindAsEnum() == Attribute::NoInline || 760254721Semaste I->getKindAsEnum() == Attribute::AlwaysInline || 761254721Semaste I->getKindAsEnum() == Attribute::OptimizeForSize || 762254721Semaste I->getKindAsEnum() == Attribute::StackProtect || 763254721Semaste I->getKindAsEnum() == Attribute::StackProtectReq || 764254721Semaste I->getKindAsEnum() == Attribute::StackProtectStrong || 765254721Semaste I->getKindAsEnum() == Attribute::NoRedZone || 766254721Semaste I->getKindAsEnum() == Attribute::NoImplicitFloat || 767254721Semaste I->getKindAsEnum() == Attribute::Naked || 768254721Semaste I->getKindAsEnum() == Attribute::InlineHint || 769254721Semaste I->getKindAsEnum() == Attribute::StackAlignment || 770296417Sdim I->getKindAsEnum() == Attribute::UWTable || 771254721Semaste I->getKindAsEnum() == Attribute::NonLazyBind || 772254721Semaste I->getKindAsEnum() == Attribute::ReturnsTwice || 773296417Sdim I->getKindAsEnum() == Attribute::SanitizeAddress || 774296417Sdim I->getKindAsEnum() == Attribute::SanitizeThread || 775254721Semaste I->getKindAsEnum() == Attribute::SanitizeMemory || 776296417Sdim I->getKindAsEnum() == Attribute::MinSize || 777254721Semaste I->getKindAsEnum() == Attribute::NoDuplicate || 778254721Semaste I->getKindAsEnum() == Attribute::Builtin || 779254721Semaste I->getKindAsEnum() == Attribute::NoBuiltin || 780254721Semaste I->getKindAsEnum() == Attribute::Cold || 781254721Semaste I->getKindAsEnum() == Attribute::OptimizeNone) { 782254721Semaste if (!isFunction) { 783254721Semaste CheckFailed("Attribute '" + I->getAsString() + 784296417Sdim "' only applies to functions!", V); 785254721Semaste return; 786254721Semaste } 787254721Semaste } else if (I->getKindAsEnum() == Attribute::ReadOnly || 788254721Semaste I->getKindAsEnum() == Attribute::ReadNone) { 789254721Semaste if (Idx == 0) { 790254721Semaste CheckFailed("Attribute '" + I->getAsString() + 791254721Semaste "' does not apply to function returns"); 792254721Semaste return; 793254721Semaste } 794254721Semaste } else if (isFunction) { 795254721Semaste CheckFailed("Attribute '" + I->getAsString() + 796254721Semaste "' does not apply to functions!", V); 797254721Semaste return; 798254721Semaste } 799254721Semaste } 800254721Semaste} 801254721Semaste 802254721Semaste// VerifyParameterAttrs - Check the given attributes for an argument or return 803296417Sdim// value of the specified type. The value V is printed in error messages. 804296417Sdimvoid Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 805254721Semaste bool isReturnValue, const Value *V) { 806254721Semaste if (!Attrs.hasAttributes(Idx)) 807254721Semaste return; 808254721Semaste 809254721Semaste VerifyAttributeTypes(Attrs, Idx, false, V); 810254721Semaste 811254721Semaste if (isReturnValue) 812254721Semaste Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 813254721Semaste !Attrs.hasAttribute(Idx, Attribute::Nest) && 814254721Semaste !Attrs.hasAttribute(Idx, Attribute::StructRet) && 815254721Semaste !Attrs.hasAttribute(Idx, Attribute::NoCapture) && 816254721Semaste !Attrs.hasAttribute(Idx, Attribute::Returned), 817254721Semaste "Attribute 'byval', 'nest', 'sret', 'nocapture', and 'returned' " 818254721Semaste "do not apply to return values!", V); 819254721Semaste 820254721Semaste // Check for mutually incompatible attributes. 821254721Semaste Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) && 822254721Semaste Attrs.hasAttribute(Idx, Attribute::Nest)) || 823254721Semaste (Attrs.hasAttribute(Idx, Attribute::ByVal) && 824254721Semaste Attrs.hasAttribute(Idx, Attribute::StructRet)) || 825254721Semaste (Attrs.hasAttribute(Idx, Attribute::Nest) && 826254721Semaste Attrs.hasAttribute(Idx, Attribute::StructRet))), "Attributes " 827254721Semaste "'byval, nest, and sret' are incompatible!", V); 828254721Semaste 829254721Semaste Assert1(!((Attrs.hasAttribute(Idx, Attribute::ByVal) && 830254721Semaste Attrs.hasAttribute(Idx, Attribute::Nest)) || 831254721Semaste (Attrs.hasAttribute(Idx, Attribute::ByVal) && 832254721Semaste Attrs.hasAttribute(Idx, Attribute::InReg)) || 833254721Semaste (Attrs.hasAttribute(Idx, Attribute::Nest) && 834254721Semaste Attrs.hasAttribute(Idx, Attribute::InReg))), "Attributes " 835254721Semaste "'byval, nest, and inreg' are incompatible!", V); 836254721Semaste 837254721Semaste Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) && 838254721Semaste Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes " 839254721Semaste "'sret and returned' are incompatible!", V); 840254721Semaste 841254721Semaste Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) && 842254721Semaste Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes " 843254721Semaste "'zeroext and signext' are incompatible!", V); 844254721Semaste 845254721Semaste Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) && 846254721Semaste Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes " 847254721Semaste "'readnone and readonly' are incompatible!", V); 848254721Semaste 849254721Semaste Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) && 850254721Semaste Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes " 851254721Semaste "'noinline and alwaysinline' are incompatible!", V); 852254721Semaste 853254721Semaste Assert1(!AttrBuilder(Attrs, Idx). 854254721Semaste hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx), 855254721Semaste "Wrong types for attribute: " + 856254721Semaste AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V); 857254721Semaste 858254721Semaste if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 859254721Semaste Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) || 860254721Semaste PTy->getElementType()->isSized(), 861254721Semaste "Attribute 'byval' does not support unsized types!", V); 862254721Semaste else 863254721Semaste Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal), 864254721Semaste "Attribute 'byval' only applies to parameters with pointer type!", 865254721Semaste V); 866254721Semaste} 867254721Semaste 868254721Semaste// VerifyFunctionAttrs - Check parameter attributes against a function type. 869254721Semaste// The value V is printed in error messages. 870254721Semastevoid Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 871254721Semaste const Value *V) { 872254721Semaste if (Attrs.isEmpty()) 873254721Semaste return; 874254721Semaste 875254721Semaste bool SawNest = false; 876254721Semaste bool SawReturned = false; 877254721Semaste 878254721Semaste for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) { 879254721Semaste unsigned Idx = Attrs.getSlotIndex(i); 880254721Semaste 881254721Semaste Type *Ty; 882254721Semaste if (Idx == 0) 883254721Semaste Ty = FT->getReturnType(); 884254721Semaste else if (Idx-1 < FT->getNumParams()) 885254721Semaste Ty = FT->getParamType(Idx-1); 886254721Semaste else 887254721Semaste break; // VarArgs attributes, verified elsewhere. 888254721Semaste 889254721Semaste VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V); 890254721Semaste 891254721Semaste if (Idx == 0) 892254721Semaste continue; 893296417Sdim 894254721Semaste if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 895254721Semaste Assert1(!SawNest, "More than one parameter has attribute nest!", V); 896296417Sdim SawNest = true; 897296417Sdim } 898254721Semaste 899296417Sdim if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 900254721Semaste Assert1(!SawReturned, "More than one parameter has attribute returned!", 901254721Semaste V); 902254721Semaste Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible " 903254721Semaste "argument and return types for 'returned' attribute", V); 904254721Semaste SawReturned = true; 905254721Semaste } 906254721Semaste 907296417Sdim if (Attrs.hasAttribute(Idx, Attribute::StructRet)) 908254721Semaste Assert1(Idx == 1, "Attribute sret is not on first parameter!", V); 909254721Semaste } 910254721Semaste 911254721Semaste if (!Attrs.hasAttributes(AttributeSet::FunctionIndex)) 912254721Semaste return; 913254721Semaste 914254721Semaste VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V); 915254721Semaste 916254721Semaste Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex, 917254721Semaste Attribute::ReadNone) && 918254721Semaste Attrs.hasAttribute(AttributeSet::FunctionIndex, 919254721Semaste Attribute::ReadOnly)), 920254721Semaste "Attributes 'readnone and readonly' are incompatible!", V); 921254721Semaste 922254721Semaste Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex, 923254721Semaste Attribute::NoInline) && 924254721Semaste Attrs.hasAttribute(AttributeSet::FunctionIndex, 925254721Semaste Attribute::AlwaysInline)), 926296417Sdim "Attributes 'noinline and alwaysinline' are incompatible!", V); 927296417Sdim 928254721Semaste if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 929254721Semaste Attribute::OptimizeNone)) { 930254721Semaste Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex, 931254721Semaste Attribute::NoInline), 932254721Semaste "Attribute 'optnone' requires 'noinline'!", V); 933254721Semaste 934254721Semaste Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 935254721Semaste Attribute::OptimizeForSize), 936254721Semaste "Attributes 'optsize and optnone' are incompatible!", V); 937254721Semaste 938254721Semaste Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 939254721Semaste Attribute::MinSize), 940254721Semaste "Attributes 'minsize and optnone' are incompatible!", V); 941254721Semaste } 942254721Semaste} 943254721Semaste 944254721Semastevoid Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) { 945254721Semaste // Get the size of the types in bits, we'll need this later 946254721Semaste unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits(); 947254721Semaste unsigned DestBitSize = DestTy->getPrimitiveSizeInBits(); 948254721Semaste 949254721Semaste // BitCast implies a no-op cast of type only. No bits change. 950254721Semaste // However, you can't cast pointers to anything but pointers. 951254721Semaste Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(), 952254721Semaste "Bitcast requires both operands to be pointer or neither", V); 953254721Semaste Assert1(SrcBitSize == DestBitSize, 954254721Semaste "Bitcast requires types of same width", V); 955254721Semaste 956254721Semaste // Disallow aggregates. 957254721Semaste Assert1(!SrcTy->isAggregateType(), 958254721Semaste "Bitcast operand must not be aggregate", V); 959254721Semaste Assert1(!DestTy->isAggregateType(), 960254721Semaste "Bitcast type must not be aggregate", V); 961254721Semaste 962254721Semaste // Without datalayout, assume all address spaces are the same size. 963254721Semaste // Don't check if both types are not pointers. 964254721Semaste // Skip casts between scalars and vectors. 965254721Semaste if (!DL || 966254721Semaste !SrcTy->isPtrOrPtrVectorTy() || 967254721Semaste !DestTy->isPtrOrPtrVectorTy() || 968254721Semaste SrcTy->isVectorTy() != DestTy->isVectorTy()) { 969254721Semaste return; 970254721Semaste } 971254721Semaste 972254721Semaste unsigned SrcAS = SrcTy->getPointerAddressSpace(); 973254721Semaste unsigned DstAS = DestTy->getPointerAddressSpace(); 974254721Semaste 975254721Semaste Assert1(SrcAS == DstAS, 976254721Semaste "Bitcasts between pointers of different address spaces is not legal." 977254721Semaste "Use AddrSpaceCast instead.", V); 978254721Semaste} 979254721Semaste 980254721Semastevoid Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) { 981254721Semaste if (CE->getOpcode() == Instruction::BitCast) { 982254721Semaste Type *SrcTy = CE->getOperand(0)->getType(); 983254721Semaste Type *DstTy = CE->getType(); 984254721Semaste VerifyBitcastType(CE, DstTy, SrcTy); 985254721Semaste } 986254721Semaste} 987254721Semaste 988254721Semastebool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) { 989254721Semaste if (Attrs.getNumSlots() == 0) 990254721Semaste return true; 991254721Semaste 992254721Semaste unsigned LastSlot = Attrs.getNumSlots() - 1; 993254721Semaste unsigned LastIndex = Attrs.getSlotIndex(LastSlot); 994254721Semaste if (LastIndex <= Params 995254721Semaste || (LastIndex == AttributeSet::FunctionIndex 996254721Semaste && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params))) 997254721Semaste return true; 998254721Semaste 999254721Semaste return false; 1000254721Semaste} 1001254721Semaste 1002254721Semaste// visitFunction - Verify that a function is ok. 1003254721Semaste// 1004254721Semastevoid Verifier::visitFunction(Function &F) { 1005254721Semaste // Check function arguments. 1006296417Sdim FunctionType *FT = F.getFunctionType(); 1007254721Semaste unsigned NumArgs = F.arg_size(); 1008254721Semaste 1009296417Sdim Assert1(Context == &F.getContext(), 1010296417Sdim "Function context does not match Module context!", &F); 1011254721Semaste 1012296417Sdim Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 1013254721Semaste Assert2(FT->getNumParams() == NumArgs, 1014254721Semaste "# formal arguments must match # of arguments for function type!", 1015254721Semaste &F, FT); 1016254721Semaste Assert1(F.getReturnType()->isFirstClassType() || 1017254721Semaste F.getReturnType()->isVoidTy() || 1018254721Semaste F.getReturnType()->isStructTy(), 1019254721Semaste "Functions cannot return aggregate values!", &F); 1020296417Sdim 1021254721Semaste Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 1022254721Semaste "Invalid struct return type!", &F); 1023254721Semaste 1024254721Semaste AttributeSet Attrs = F.getAttributes(); 1025254721Semaste 1026254721Semaste Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()), 1027254721Semaste "Attribute after last parameter!", &F); 1028254721Semaste 1029254721Semaste // Check function attributes. 1030254721Semaste VerifyFunctionAttrs(FT, Attrs, &F); 1031254721Semaste 1032254721Semaste // On function declarations/definitions, we do not support the builtin 1033254721Semaste // attribute. We do not check this in VerifyFunctionAttrs since that is 1034254721Semaste // checking for Attributes that can/can not ever be on functions. 1035254721Semaste Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 1036254721Semaste Attribute::Builtin), 1037254721Semaste "Attribute 'builtin' can only be applied to a callsite.", &F); 1038254721Semaste 1039296417Sdim // Check that this function meets the restrictions on this calling convention. 1040296417Sdim switch (F.getCallingConv()) { 1041254721Semaste default: 1042254721Semaste break; 1043254721Semaste case CallingConv::C: 1044254721Semaste break; 1045254721Semaste case CallingConv::Fast: 1046254721Semaste case CallingConv::Cold: 1047254721Semaste case CallingConv::X86_FastCall: 1048254721Semaste case CallingConv::X86_ThisCall: 1049254721Semaste case CallingConv::Intel_OCL_BI: 1050254721Semaste case CallingConv::PTX_Kernel: 1051254721Semaste case CallingConv::PTX_Device: 1052254721Semaste Assert1(!F.isVarArg(), 1053254721Semaste "Varargs functions must have C calling conventions!", &F); 1054254721Semaste break; 1055254721Semaste } 1056254721Semaste 1057254721Semaste bool isLLVMdotName = F.getName().size() >= 5 && 1058254721Semaste F.getName().substr(0, 5) == "llvm."; 1059254721Semaste 1060254721Semaste // Check that the argument values match the function type for this function... 1061254721Semaste unsigned i = 0; 1062254721Semaste for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); 1063254721Semaste I != E; ++I, ++i) { 1064254721Semaste Assert2(I->getType() == FT->getParamType(i), 1065254721Semaste "Argument value does not match function argument type!", 1066254721Semaste I, FT->getParamType(i)); 1067254721Semaste Assert1(I->getType()->isFirstClassType(), 1068254721Semaste "Function arguments must have first-class types!", I); 1069254721Semaste if (!isLLVMdotName) 1070254721Semaste Assert2(!I->getType()->isMetadataTy(), 1071254721Semaste "Function takes metadata but isn't an intrinsic", I, &F); 1072254721Semaste } 1073254721Semaste 1074254721Semaste if (F.isMaterializable()) { 1075254721Semaste // Function has a body somewhere we can't see. 1076254721Semaste } else if (F.isDeclaration()) { 1077254721Semaste Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() || 1078254721Semaste F.hasExternalWeakLinkage(), 1079254721Semaste "invalid linkage type for function declaration", &F); 1080254721Semaste } else { 1081254721Semaste // Verify that this function (which has a body) is not named "llvm.*". It 1082254721Semaste // is not legal to define intrinsics. 1083254721Semaste Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 1084254721Semaste 1085254721Semaste // Check the entry node 1086254721Semaste BasicBlock *Entry = &F.getEntryBlock(); 1087254721Semaste Assert1(pred_begin(Entry) == pred_end(Entry), 1088254721Semaste "Entry block to function must not have predecessors!", Entry); 1089254721Semaste 1090254721Semaste // The address of the entry block cannot be taken, unless it is dead. 1091254721Semaste if (Entry->hasAddressTaken()) { 1092254721Semaste Assert1(!BlockAddress::get(Entry)->isConstantUsed(), 1093254721Semaste "blockaddress may not be used with the entry block!", Entry); 1094254721Semaste } 1095254721Semaste } 1096254721Semaste 1097254721Semaste // If this function is actually an intrinsic, verify that it is only used in 1098254721Semaste // direct call/invokes, never having its "address taken". 1099254721Semaste if (F.getIntrinsicID()) { 1100254721Semaste const User *U; 1101254721Semaste if (F.hasAddressTaken(&U)) 1102254721Semaste Assert1(0, "Invalid user of intrinsic instruction!", U); 1103254721Semaste } 1104254721Semaste} 1105254721Semaste 1106254721Semaste// verifyBasicBlock - Verify that a basic block is well formed... 1107254721Semaste// 1108254721Semastevoid Verifier::visitBasicBlock(BasicBlock &BB) { 1109254721Semaste InstsInThisBlock.clear(); 1110254721Semaste 1111296417Sdim // Ensure that basic blocks have terminators! 1112254721Semaste Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 1113296417Sdim 1114254721Semaste // Check constraints that this basic block imposes on all of the PHI nodes in 1115254721Semaste // it. 1116254721Semaste if (isa<PHINode>(BB.front())) { 1117254721Semaste SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB)); 1118254721Semaste SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 1119254721Semaste std::sort(Preds.begin(), Preds.end()); 1120254721Semaste PHINode *PN; 1121296417Sdim for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) { 1122254721Semaste // Ensure that PHI nodes have at least one entry! 1123254721Semaste Assert1(PN->getNumIncomingValues() != 0, 1124254721Semaste "PHI nodes must have at least one entry. If the block is dead, " 1125254721Semaste "the PHI should be removed!", PN); 1126254721Semaste Assert1(PN->getNumIncomingValues() == Preds.size(), 1127254721Semaste "PHINode should have one entry for each predecessor of its " 1128254721Semaste "parent basic block!", PN); 1129254721Semaste 1130254721Semaste // Get and sort all incoming values in the PHI node... 1131254721Semaste Values.clear(); 1132254721Semaste Values.reserve(PN->getNumIncomingValues()); 1133254721Semaste for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1134254721Semaste Values.push_back(std::make_pair(PN->getIncomingBlock(i), 1135254721Semaste PN->getIncomingValue(i))); 1136254721Semaste std::sort(Values.begin(), Values.end()); 1137254721Semaste 1138254721Semaste for (unsigned i = 0, e = Values.size(); i != e; ++i) { 1139254721Semaste // Check to make sure that if there is more than one entry for a 1140296417Sdim // particular basic block in this PHI node, that the incoming values are 1141296417Sdim // all identical. 1142254721Semaste // 1143254721Semaste Assert4(i == 0 || Values[i].first != Values[i-1].first || 1144254721Semaste Values[i].second == Values[i-1].second, 1145254721Semaste "PHI node has multiple entries for the same basic block with " 1146254721Semaste "different incoming values!", PN, Values[i].first, 1147254721Semaste Values[i].second, Values[i-1].second); 1148276479Sdim 1149254721Semaste // Check to make sure that the predecessors and PHI node entries are 1150254721Semaste // matched up. 1151254721Semaste Assert3(Values[i].first == Preds[i], 1152254721Semaste "PHI node entries do not match predecessors!", PN, 1153254721Semaste Values[i].first, Preds[i]); 1154254721Semaste } 1155254721Semaste } 1156254721Semaste } 1157254721Semaste} 1158254721Semaste 1159254721Semastevoid Verifier::visitTerminatorInst(TerminatorInst &I) { 1160254721Semaste // Ensure that terminators only exist at the end of the basic block. 1161254721Semaste Assert1(&I == I.getParent()->getTerminator(), 1162254721Semaste "Terminator found in the middle of a basic block!", I.getParent()); 1163254721Semaste visitInstruction(I); 1164254721Semaste} 1165254721Semaste 1166254721Semastevoid Verifier::visitBranchInst(BranchInst &BI) { 1167254721Semaste if (BI.isConditional()) { 1168254721Semaste Assert2(BI.getCondition()->getType()->isIntegerTy(1), 1169254721Semaste "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 1170254721Semaste } 1171254721Semaste visitTerminatorInst(BI); 1172254721Semaste} 1173254721Semaste 1174254721Semastevoid Verifier::visitReturnInst(ReturnInst &RI) { 1175254721Semaste Function *F = RI.getParent()->getParent(); 1176254721Semaste unsigned N = RI.getNumOperands(); 1177254721Semaste if (F->getReturnType()->isVoidTy()) 1178254721Semaste Assert2(N == 0, 1179254721Semaste "Found return instr that returns non-void in Function of void " 1180254721Semaste "return type!", &RI, F->getReturnType()); 1181254721Semaste else 1182254721Semaste Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 1183254721Semaste "Function return type does not match operand " 1184254721Semaste "type of return inst!", &RI, F->getReturnType()); 1185254721Semaste 1186254721Semaste // Check to make sure that the return value has necessary properties for 1187254721Semaste // terminators... 1188254721Semaste visitTerminatorInst(RI); 1189254721Semaste} 1190254721Semaste 1191254721Semastevoid Verifier::visitSwitchInst(SwitchInst &SI) { 1192254721Semaste // Check to make sure that all of the constants in the switch instruction 1193254721Semaste // have the same type as the switched-on value. 1194254721Semaste Type *SwitchTy = SI.getCondition()->getType(); 1195254721Semaste SmallPtrSet<ConstantInt*, 32> Constants; 1196254721Semaste for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) { 1197254721Semaste Assert1(i.getCaseValue()->getType() == SwitchTy, 1198254721Semaste "Switch constants must all be same type as switch value!", &SI); 1199254721Semaste Assert2(Constants.insert(i.getCaseValue()), 1200 "Duplicate integer as switch case", &SI, i.getCaseValue()); 1201 } 1202 1203 visitTerminatorInst(SI); 1204} 1205 1206void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 1207 Assert1(BI.getAddress()->getType()->isPointerTy(), 1208 "Indirectbr operand must have pointer type!", &BI); 1209 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 1210 Assert1(BI.getDestination(i)->getType()->isLabelTy(), 1211 "Indirectbr destinations must all have pointer type!", &BI); 1212 1213 visitTerminatorInst(BI); 1214} 1215 1216void Verifier::visitSelectInst(SelectInst &SI) { 1217 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 1218 SI.getOperand(2)), 1219 "Invalid operands for select instruction!", &SI); 1220 1221 Assert1(SI.getTrueValue()->getType() == SI.getType(), 1222 "Select values must have same type as select instruction!", &SI); 1223 visitInstruction(SI); 1224} 1225 1226/// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 1227/// a pass, if any exist, it's an error. 1228/// 1229void Verifier::visitUserOp1(Instruction &I) { 1230 Assert1(0, "User-defined operators should not live outside of a pass!", &I); 1231} 1232 1233void Verifier::visitTruncInst(TruncInst &I) { 1234 // Get the source and destination types 1235 Type *SrcTy = I.getOperand(0)->getType(); 1236 Type *DestTy = I.getType(); 1237 1238 // Get the size of the types in bits, we'll need this later 1239 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 1240 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 1241 1242 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 1243 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 1244 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1245 "trunc source and destination must both be a vector or neither", &I); 1246 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I); 1247 1248 visitInstruction(I); 1249} 1250 1251void Verifier::visitZExtInst(ZExtInst &I) { 1252 // Get the source and destination types 1253 Type *SrcTy = I.getOperand(0)->getType(); 1254 Type *DestTy = I.getType(); 1255 1256 // Get the size of the types in bits, we'll need this later 1257 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 1258 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 1259 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1260 "zext source and destination must both be a vector or neither", &I); 1261 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 1262 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 1263 1264 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I); 1265 1266 visitInstruction(I); 1267} 1268 1269void Verifier::visitSExtInst(SExtInst &I) { 1270 // Get the source and destination types 1271 Type *SrcTy = I.getOperand(0)->getType(); 1272 Type *DestTy = I.getType(); 1273 1274 // Get the size of the types in bits, we'll need this later 1275 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 1276 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 1277 1278 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 1279 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 1280 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1281 "sext source and destination must both be a vector or neither", &I); 1282 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I); 1283 1284 visitInstruction(I); 1285} 1286 1287void Verifier::visitFPTruncInst(FPTruncInst &I) { 1288 // Get the source and destination types 1289 Type *SrcTy = I.getOperand(0)->getType(); 1290 Type *DestTy = I.getType(); 1291 // Get the size of the types in bits, we'll need this later 1292 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 1293 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 1294 1295 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I); 1296 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I); 1297 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1298 "fptrunc source and destination must both be a vector or neither",&I); 1299 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I); 1300 1301 visitInstruction(I); 1302} 1303 1304void Verifier::visitFPExtInst(FPExtInst &I) { 1305 // Get the source and destination types 1306 Type *SrcTy = I.getOperand(0)->getType(); 1307 Type *DestTy = I.getType(); 1308 1309 // Get the size of the types in bits, we'll need this later 1310 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 1311 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 1312 1313 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I); 1314 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I); 1315 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1316 "fpext source and destination must both be a vector or neither", &I); 1317 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I); 1318 1319 visitInstruction(I); 1320} 1321 1322void Verifier::visitUIToFPInst(UIToFPInst &I) { 1323 // Get the source and destination types 1324 Type *SrcTy = I.getOperand(0)->getType(); 1325 Type *DestTy = I.getType(); 1326 1327 bool SrcVec = SrcTy->isVectorTy(); 1328 bool DstVec = DestTy->isVectorTy(); 1329 1330 Assert1(SrcVec == DstVec, 1331 "UIToFP source and dest must both be vector or scalar", &I); 1332 Assert1(SrcTy->isIntOrIntVectorTy(), 1333 "UIToFP source must be integer or integer vector", &I); 1334 Assert1(DestTy->isFPOrFPVectorTy(), 1335 "UIToFP result must be FP or FP vector", &I); 1336 1337 if (SrcVec && DstVec) 1338 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 1339 cast<VectorType>(DestTy)->getNumElements(), 1340 "UIToFP source and dest vector length mismatch", &I); 1341 1342 visitInstruction(I); 1343} 1344 1345void Verifier::visitSIToFPInst(SIToFPInst &I) { 1346 // Get the source and destination types 1347 Type *SrcTy = I.getOperand(0)->getType(); 1348 Type *DestTy = I.getType(); 1349 1350 bool SrcVec = SrcTy->isVectorTy(); 1351 bool DstVec = DestTy->isVectorTy(); 1352 1353 Assert1(SrcVec == DstVec, 1354 "SIToFP source and dest must both be vector or scalar", &I); 1355 Assert1(SrcTy->isIntOrIntVectorTy(), 1356 "SIToFP source must be integer or integer vector", &I); 1357 Assert1(DestTy->isFPOrFPVectorTy(), 1358 "SIToFP result must be FP or FP vector", &I); 1359 1360 if (SrcVec && DstVec) 1361 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 1362 cast<VectorType>(DestTy)->getNumElements(), 1363 "SIToFP source and dest vector length mismatch", &I); 1364 1365 visitInstruction(I); 1366} 1367 1368void Verifier::visitFPToUIInst(FPToUIInst &I) { 1369 // Get the source and destination types 1370 Type *SrcTy = I.getOperand(0)->getType(); 1371 Type *DestTy = I.getType(); 1372 1373 bool SrcVec = SrcTy->isVectorTy(); 1374 bool DstVec = DestTy->isVectorTy(); 1375 1376 Assert1(SrcVec == DstVec, 1377 "FPToUI source and dest must both be vector or scalar", &I); 1378 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 1379 &I); 1380 Assert1(DestTy->isIntOrIntVectorTy(), 1381 "FPToUI result must be integer or integer vector", &I); 1382 1383 if (SrcVec && DstVec) 1384 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 1385 cast<VectorType>(DestTy)->getNumElements(), 1386 "FPToUI source and dest vector length mismatch", &I); 1387 1388 visitInstruction(I); 1389} 1390 1391void Verifier::visitFPToSIInst(FPToSIInst &I) { 1392 // Get the source and destination types 1393 Type *SrcTy = I.getOperand(0)->getType(); 1394 Type *DestTy = I.getType(); 1395 1396 bool SrcVec = SrcTy->isVectorTy(); 1397 bool DstVec = DestTy->isVectorTy(); 1398 1399 Assert1(SrcVec == DstVec, 1400 "FPToSI source and dest must both be vector or scalar", &I); 1401 Assert1(SrcTy->isFPOrFPVectorTy(), 1402 "FPToSI source must be FP or FP vector", &I); 1403 Assert1(DestTy->isIntOrIntVectorTy(), 1404 "FPToSI result must be integer or integer vector", &I); 1405 1406 if (SrcVec && DstVec) 1407 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 1408 cast<VectorType>(DestTy)->getNumElements(), 1409 "FPToSI source and dest vector length mismatch", &I); 1410 1411 visitInstruction(I); 1412} 1413 1414void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 1415 // Get the source and destination types 1416 Type *SrcTy = I.getOperand(0)->getType(); 1417 Type *DestTy = I.getType(); 1418 1419 Assert1(SrcTy->getScalarType()->isPointerTy(), 1420 "PtrToInt source must be pointer", &I); 1421 Assert1(DestTy->getScalarType()->isIntegerTy(), 1422 "PtrToInt result must be integral", &I); 1423 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1424 "PtrToInt type mismatch", &I); 1425 1426 if (SrcTy->isVectorTy()) { 1427 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 1428 VectorType *VDest = dyn_cast<VectorType>(DestTy); 1429 Assert1(VSrc->getNumElements() == VDest->getNumElements(), 1430 "PtrToInt Vector width mismatch", &I); 1431 } 1432 1433 visitInstruction(I); 1434} 1435 1436void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 1437 // Get the source and destination types 1438 Type *SrcTy = I.getOperand(0)->getType(); 1439 Type *DestTy = I.getType(); 1440 1441 Assert1(SrcTy->getScalarType()->isIntegerTy(), 1442 "IntToPtr source must be an integral", &I); 1443 Assert1(DestTy->getScalarType()->isPointerTy(), 1444 "IntToPtr result must be a pointer",&I); 1445 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1446 "IntToPtr type mismatch", &I); 1447 if (SrcTy->isVectorTy()) { 1448 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 1449 VectorType *VDest = dyn_cast<VectorType>(DestTy); 1450 Assert1(VSrc->getNumElements() == VDest->getNumElements(), 1451 "IntToPtr Vector width mismatch", &I); 1452 } 1453 visitInstruction(I); 1454} 1455 1456void Verifier::visitBitCastInst(BitCastInst &I) { 1457 Type *SrcTy = I.getOperand(0)->getType(); 1458 Type *DestTy = I.getType(); 1459 VerifyBitcastType(&I, DestTy, SrcTy); 1460 visitInstruction(I); 1461} 1462 1463void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 1464 Type *SrcTy = I.getOperand(0)->getType(); 1465 Type *DestTy = I.getType(); 1466 1467 Assert1(SrcTy->isPtrOrPtrVectorTy(), 1468 "AddrSpaceCast source must be a pointer", &I); 1469 Assert1(DestTy->isPtrOrPtrVectorTy(), 1470 "AddrSpaceCast result must be a pointer", &I); 1471 Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 1472 "AddrSpaceCast must be between different address spaces", &I); 1473 if (SrcTy->isVectorTy()) 1474 Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(), 1475 "AddrSpaceCast vector pointer number of elements mismatch", &I); 1476 visitInstruction(I); 1477} 1478 1479/// visitPHINode - Ensure that a PHI node is well formed. 1480/// 1481void Verifier::visitPHINode(PHINode &PN) { 1482 // Ensure that the PHI nodes are all grouped together at the top of the block. 1483 // This can be tested by checking whether the instruction before this is 1484 // either nonexistent (because this is begin()) or is a PHI node. If not, 1485 // then there is some other instruction before a PHI. 1486 Assert2(&PN == &PN.getParent()->front() || 1487 isa<PHINode>(--BasicBlock::iterator(&PN)), 1488 "PHI nodes not grouped at top of basic block!", 1489 &PN, PN.getParent()); 1490 1491 // Check that all of the values of the PHI node have the same type as the 1492 // result, and that the incoming blocks are really basic blocks. 1493 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1494 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(), 1495 "PHI node operands are not the same type as the result!", &PN); 1496 } 1497 1498 // All other PHI node constraints are checked in the visitBasicBlock method. 1499 1500 visitInstruction(PN); 1501} 1502 1503void Verifier::VerifyCallSite(CallSite CS) { 1504 Instruction *I = CS.getInstruction(); 1505 1506 Assert1(CS.getCalledValue()->getType()->isPointerTy(), 1507 "Called function must be a pointer!", I); 1508 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType()); 1509 1510 Assert1(FPTy->getElementType()->isFunctionTy(), 1511 "Called function is not pointer to function type!", I); 1512 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType()); 1513 1514 // Verify that the correct number of arguments are being passed 1515 if (FTy->isVarArg()) 1516 Assert1(CS.arg_size() >= FTy->getNumParams(), 1517 "Called function requires more parameters than were provided!",I); 1518 else 1519 Assert1(CS.arg_size() == FTy->getNumParams(), 1520 "Incorrect number of arguments passed to called function!", I); 1521 1522 // Verify that all arguments to the call match the function type. 1523 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 1524 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i), 1525 "Call parameter type does not match function signature!", 1526 CS.getArgument(i), FTy->getParamType(i), I); 1527 1528 AttributeSet Attrs = CS.getAttributes(); 1529 1530 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()), 1531 "Attribute after last parameter!", I); 1532 1533 // Verify call attributes. 1534 VerifyFunctionAttrs(FTy, Attrs, I); 1535 1536 if (FTy->isVarArg()) { 1537 // FIXME? is 'nest' even legal here? 1538 bool SawNest = false; 1539 bool SawReturned = false; 1540 1541 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) { 1542 if (Attrs.hasAttribute(Idx, Attribute::Nest)) 1543 SawNest = true; 1544 if (Attrs.hasAttribute(Idx, Attribute::Returned)) 1545 SawReturned = true; 1546 } 1547 1548 // Check attributes on the varargs part. 1549 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) { 1550 Type *Ty = CS.getArgument(Idx-1)->getType(); 1551 VerifyParameterAttrs(Attrs, Idx, Ty, false, I); 1552 1553 if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 1554 Assert1(!SawNest, "More than one parameter has attribute nest!", I); 1555 SawNest = true; 1556 } 1557 1558 if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 1559 Assert1(!SawReturned, "More than one parameter has attribute returned!", 1560 I); 1561 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 1562 "Incompatible argument and return types for 'returned' " 1563 "attribute", I); 1564 SawReturned = true; 1565 } 1566 1567 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet), 1568 "Attribute 'sret' cannot be used for vararg call arguments!", I); 1569 } 1570 } 1571 1572 // Verify that there's no metadata unless it's a direct call to an intrinsic. 1573 if (CS.getCalledFunction() == 0 || 1574 !CS.getCalledFunction()->getName().startswith("llvm.")) { 1575 for (FunctionType::param_iterator PI = FTy->param_begin(), 1576 PE = FTy->param_end(); PI != PE; ++PI) 1577 Assert1(!(*PI)->isMetadataTy(), 1578 "Function has metadata parameter but isn't an intrinsic", I); 1579 } 1580 1581 visitInstruction(*I); 1582} 1583 1584void Verifier::visitCallInst(CallInst &CI) { 1585 VerifyCallSite(&CI); 1586 1587 if (Function *F = CI.getCalledFunction()) 1588 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 1589 visitIntrinsicFunctionCall(ID, CI); 1590} 1591 1592void Verifier::visitInvokeInst(InvokeInst &II) { 1593 VerifyCallSite(&II); 1594 1595 // Verify that there is a landingpad instruction as the first non-PHI 1596 // instruction of the 'unwind' destination. 1597 Assert1(II.getUnwindDest()->isLandingPad(), 1598 "The unwind destination does not have a landingpad instruction!",&II); 1599 1600 visitTerminatorInst(II); 1601} 1602 1603/// visitBinaryOperator - Check that both arguments to the binary operator are 1604/// of the same type! 1605/// 1606void Verifier::visitBinaryOperator(BinaryOperator &B) { 1607 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 1608 "Both operands to a binary operator are not of the same type!", &B); 1609 1610 switch (B.getOpcode()) { 1611 // Check that integer arithmetic operators are only used with 1612 // integral operands. 1613 case Instruction::Add: 1614 case Instruction::Sub: 1615 case Instruction::Mul: 1616 case Instruction::SDiv: 1617 case Instruction::UDiv: 1618 case Instruction::SRem: 1619 case Instruction::URem: 1620 Assert1(B.getType()->isIntOrIntVectorTy(), 1621 "Integer arithmetic operators only work with integral types!", &B); 1622 Assert1(B.getType() == B.getOperand(0)->getType(), 1623 "Integer arithmetic operators must have same type " 1624 "for operands and result!", &B); 1625 break; 1626 // Check that floating-point arithmetic operators are only used with 1627 // floating-point operands. 1628 case Instruction::FAdd: 1629 case Instruction::FSub: 1630 case Instruction::FMul: 1631 case Instruction::FDiv: 1632 case Instruction::FRem: 1633 Assert1(B.getType()->isFPOrFPVectorTy(), 1634 "Floating-point arithmetic operators only work with " 1635 "floating-point types!", &B); 1636 Assert1(B.getType() == B.getOperand(0)->getType(), 1637 "Floating-point arithmetic operators must have same type " 1638 "for operands and result!", &B); 1639 break; 1640 // Check that logical operators are only used with integral operands. 1641 case Instruction::And: 1642 case Instruction::Or: 1643 case Instruction::Xor: 1644 Assert1(B.getType()->isIntOrIntVectorTy(), 1645 "Logical operators only work with integral types!", &B); 1646 Assert1(B.getType() == B.getOperand(0)->getType(), 1647 "Logical operators must have same type for operands and result!", 1648 &B); 1649 break; 1650 case Instruction::Shl: 1651 case Instruction::LShr: 1652 case Instruction::AShr: 1653 Assert1(B.getType()->isIntOrIntVectorTy(), 1654 "Shifts only work with integral types!", &B); 1655 Assert1(B.getType() == B.getOperand(0)->getType(), 1656 "Shift return type must be same as operands!", &B); 1657 break; 1658 default: 1659 llvm_unreachable("Unknown BinaryOperator opcode!"); 1660 } 1661 1662 visitInstruction(B); 1663} 1664 1665void Verifier::visitICmpInst(ICmpInst &IC) { 1666 // Check that the operands are the same type 1667 Type *Op0Ty = IC.getOperand(0)->getType(); 1668 Type *Op1Ty = IC.getOperand(1)->getType(); 1669 Assert1(Op0Ty == Op1Ty, 1670 "Both operands to ICmp instruction are not of the same type!", &IC); 1671 // Check that the operands are the right type 1672 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(), 1673 "Invalid operand types for ICmp instruction", &IC); 1674 // Check that the predicate is valid. 1675 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE && 1676 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE, 1677 "Invalid predicate in ICmp instruction!", &IC); 1678 1679 visitInstruction(IC); 1680} 1681 1682void Verifier::visitFCmpInst(FCmpInst &FC) { 1683 // Check that the operands are the same type 1684 Type *Op0Ty = FC.getOperand(0)->getType(); 1685 Type *Op1Ty = FC.getOperand(1)->getType(); 1686 Assert1(Op0Ty == Op1Ty, 1687 "Both operands to FCmp instruction are not of the same type!", &FC); 1688 // Check that the operands are the right type 1689 Assert1(Op0Ty->isFPOrFPVectorTy(), 1690 "Invalid operand types for FCmp instruction", &FC); 1691 // Check that the predicate is valid. 1692 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE && 1693 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE, 1694 "Invalid predicate in FCmp instruction!", &FC); 1695 1696 visitInstruction(FC); 1697} 1698 1699void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 1700 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0), 1701 EI.getOperand(1)), 1702 "Invalid extractelement operands!", &EI); 1703 visitInstruction(EI); 1704} 1705 1706void Verifier::visitInsertElementInst(InsertElementInst &IE) { 1707 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0), 1708 IE.getOperand(1), 1709 IE.getOperand(2)), 1710 "Invalid insertelement operands!", &IE); 1711 visitInstruction(IE); 1712} 1713 1714void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 1715 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 1716 SV.getOperand(2)), 1717 "Invalid shufflevector operands!", &SV); 1718 visitInstruction(SV); 1719} 1720 1721void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 1722 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 1723 1724 Assert1(isa<PointerType>(TargetTy), 1725 "GEP base pointer is not a vector or a vector of pointers", &GEP); 1726 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(), 1727 "GEP into unsized type!", &GEP); 1728 Assert1(GEP.getPointerOperandType()->isVectorTy() == 1729 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value", 1730 &GEP); 1731 1732 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end()); 1733 Type *ElTy = 1734 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs); 1735 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP); 1736 1737 Assert2(GEP.getType()->getScalarType()->isPointerTy() && 1738 cast<PointerType>(GEP.getType()->getScalarType())->getElementType() 1739 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy); 1740 1741 if (GEP.getPointerOperandType()->isVectorTy()) { 1742 // Additional checks for vector GEPs. 1743 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements(); 1744 Assert1(GepWidth == GEP.getType()->getVectorNumElements(), 1745 "Vector GEP result width doesn't match operand's", &GEP); 1746 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) { 1747 Type *IndexTy = Idxs[i]->getType(); 1748 Assert1(IndexTy->isVectorTy(), 1749 "Vector GEP must have vector indices!", &GEP); 1750 unsigned IndexWidth = IndexTy->getVectorNumElements(); 1751 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP); 1752 } 1753 } 1754 visitInstruction(GEP); 1755} 1756 1757static bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 1758 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 1759} 1760 1761void Verifier::visitLoadInst(LoadInst &LI) { 1762 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 1763 Assert1(PTy, "Load operand must be a pointer.", &LI); 1764 Type *ElTy = PTy->getElementType(); 1765 Assert2(ElTy == LI.getType(), 1766 "Load result type does not match pointer operand type!", &LI, ElTy); 1767 if (LI.isAtomic()) { 1768 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease, 1769 "Load cannot have Release ordering", &LI); 1770 Assert1(LI.getAlignment() != 0, 1771 "Atomic load must specify explicit alignment", &LI); 1772 if (!ElTy->isPointerTy()) { 1773 Assert2(ElTy->isIntegerTy(), 1774 "atomic store operand must have integer type!", 1775 &LI, ElTy); 1776 unsigned Size = ElTy->getPrimitiveSizeInBits(); 1777 Assert2(Size >= 8 && !(Size & (Size - 1)), 1778 "atomic store operand must be power-of-two byte-sized integer", 1779 &LI, ElTy); 1780 } 1781 } else { 1782 Assert1(LI.getSynchScope() == CrossThread, 1783 "Non-atomic load cannot have SynchronizationScope specified", &LI); 1784 } 1785 1786 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) { 1787 unsigned NumOperands = Range->getNumOperands(); 1788 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range); 1789 unsigned NumRanges = NumOperands / 2; 1790 Assert1(NumRanges >= 1, "It should have at least one range!", Range); 1791 1792 ConstantRange LastRange(1); // Dummy initial value 1793 for (unsigned i = 0; i < NumRanges; ++i) { 1794 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i)); 1795 Assert1(Low, "The lower limit must be an integer!", Low); 1796 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1)); 1797 Assert1(High, "The upper limit must be an integer!", High); 1798 Assert1(High->getType() == Low->getType() && 1799 High->getType() == ElTy, "Range types must match load type!", 1800 &LI); 1801 1802 APInt HighV = High->getValue(); 1803 APInt LowV = Low->getValue(); 1804 ConstantRange CurRange(LowV, HighV); 1805 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(), 1806 "Range must not be empty!", Range); 1807 if (i != 0) { 1808 Assert1(CurRange.intersectWith(LastRange).isEmptySet(), 1809 "Intervals are overlapping", Range); 1810 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 1811 Range); 1812 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 1813 Range); 1814 } 1815 LastRange = ConstantRange(LowV, HighV); 1816 } 1817 if (NumRanges > 2) { 1818 APInt FirstLow = 1819 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue(); 1820 APInt FirstHigh = 1821 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue(); 1822 ConstantRange FirstRange(FirstLow, FirstHigh); 1823 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(), 1824 "Intervals are overlapping", Range); 1825 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 1826 Range); 1827 } 1828 1829 1830 } 1831 1832 visitInstruction(LI); 1833} 1834 1835void Verifier::visitStoreInst(StoreInst &SI) { 1836 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 1837 Assert1(PTy, "Store operand must be a pointer.", &SI); 1838 Type *ElTy = PTy->getElementType(); 1839 Assert2(ElTy == SI.getOperand(0)->getType(), 1840 "Stored value type does not match pointer operand type!", 1841 &SI, ElTy); 1842 if (SI.isAtomic()) { 1843 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease, 1844 "Store cannot have Acquire ordering", &SI); 1845 Assert1(SI.getAlignment() != 0, 1846 "Atomic store must specify explicit alignment", &SI); 1847 if (!ElTy->isPointerTy()) { 1848 Assert2(ElTy->isIntegerTy(), 1849 "atomic store operand must have integer type!", 1850 &SI, ElTy); 1851 unsigned Size = ElTy->getPrimitiveSizeInBits(); 1852 Assert2(Size >= 8 && !(Size & (Size - 1)), 1853 "atomic store operand must be power-of-two byte-sized integer", 1854 &SI, ElTy); 1855 } 1856 } else { 1857 Assert1(SI.getSynchScope() == CrossThread, 1858 "Non-atomic store cannot have SynchronizationScope specified", &SI); 1859 } 1860 visitInstruction(SI); 1861} 1862 1863void Verifier::visitAllocaInst(AllocaInst &AI) { 1864 PointerType *PTy = AI.getType(); 1865 Assert1(PTy->getAddressSpace() == 0, 1866 "Allocation instruction pointer not in the generic address space!", 1867 &AI); 1868 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type", 1869 &AI); 1870 Assert1(AI.getArraySize()->getType()->isIntegerTy(), 1871 "Alloca array size must have integer type", &AI); 1872 visitInstruction(AI); 1873} 1874 1875void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 1876 Assert1(CXI.getOrdering() != NotAtomic, 1877 "cmpxchg instructions must be atomic.", &CXI); 1878 Assert1(CXI.getOrdering() != Unordered, 1879 "cmpxchg instructions cannot be unordered.", &CXI); 1880 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType()); 1881 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI); 1882 Type *ElTy = PTy->getElementType(); 1883 Assert2(ElTy->isIntegerTy(), 1884 "cmpxchg operand must have integer type!", 1885 &CXI, ElTy); 1886 unsigned Size = ElTy->getPrimitiveSizeInBits(); 1887 Assert2(Size >= 8 && !(Size & (Size - 1)), 1888 "cmpxchg operand must be power-of-two byte-sized integer", 1889 &CXI, ElTy); 1890 Assert2(ElTy == CXI.getOperand(1)->getType(), 1891 "Expected value type does not match pointer operand type!", 1892 &CXI, ElTy); 1893 Assert2(ElTy == CXI.getOperand(2)->getType(), 1894 "Stored value type does not match pointer operand type!", 1895 &CXI, ElTy); 1896 visitInstruction(CXI); 1897} 1898 1899void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 1900 Assert1(RMWI.getOrdering() != NotAtomic, 1901 "atomicrmw instructions must be atomic.", &RMWI); 1902 Assert1(RMWI.getOrdering() != Unordered, 1903 "atomicrmw instructions cannot be unordered.", &RMWI); 1904 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType()); 1905 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI); 1906 Type *ElTy = PTy->getElementType(); 1907 Assert2(ElTy->isIntegerTy(), 1908 "atomicrmw operand must have integer type!", 1909 &RMWI, ElTy); 1910 unsigned Size = ElTy->getPrimitiveSizeInBits(); 1911 Assert2(Size >= 8 && !(Size & (Size - 1)), 1912 "atomicrmw operand must be power-of-two byte-sized integer", 1913 &RMWI, ElTy); 1914 Assert2(ElTy == RMWI.getOperand(1)->getType(), 1915 "Argument value type does not match pointer operand type!", 1916 &RMWI, ElTy); 1917 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() && 1918 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP, 1919 "Invalid binary operation!", &RMWI); 1920 visitInstruction(RMWI); 1921} 1922 1923void Verifier::visitFenceInst(FenceInst &FI) { 1924 const AtomicOrdering Ordering = FI.getOrdering(); 1925 Assert1(Ordering == Acquire || Ordering == Release || 1926 Ordering == AcquireRelease || Ordering == SequentiallyConsistent, 1927 "fence instructions may only have " 1928 "acquire, release, acq_rel, or seq_cst ordering.", &FI); 1929 visitInstruction(FI); 1930} 1931 1932void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 1933 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 1934 EVI.getIndices()) == 1935 EVI.getType(), 1936 "Invalid ExtractValueInst operands!", &EVI); 1937 1938 visitInstruction(EVI); 1939} 1940 1941void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 1942 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 1943 IVI.getIndices()) == 1944 IVI.getOperand(1)->getType(), 1945 "Invalid InsertValueInst operands!", &IVI); 1946 1947 visitInstruction(IVI); 1948} 1949 1950void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 1951 BasicBlock *BB = LPI.getParent(); 1952 1953 // The landingpad instruction is ill-formed if it doesn't have any clauses and 1954 // isn't a cleanup. 1955 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(), 1956 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 1957 1958 // The landingpad instruction defines its parent as a landing pad block. The 1959 // landing pad block may be branched to only by the unwind edge of an invoke. 1960 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 1961 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()); 1962 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 1963 "Block containing LandingPadInst must be jumped to " 1964 "only by the unwind edge of an invoke.", &LPI); 1965 } 1966 1967 // The landingpad instruction must be the first non-PHI instruction in the 1968 // block. 1969 Assert1(LPI.getParent()->getLandingPadInst() == &LPI, 1970 "LandingPadInst not the first non-PHI instruction in the block.", 1971 &LPI); 1972 1973 // The personality functions for all landingpad instructions within the same 1974 // function should match. 1975 if (PersonalityFn) 1976 Assert1(LPI.getPersonalityFn() == PersonalityFn, 1977 "Personality function doesn't match others in function", &LPI); 1978 PersonalityFn = LPI.getPersonalityFn(); 1979 1980 // All operands must be constants. 1981 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!", 1982 &LPI); 1983 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 1984 Value *Clause = LPI.getClause(i); 1985 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI); 1986 if (LPI.isCatch(i)) { 1987 Assert1(isa<PointerType>(Clause->getType()), 1988 "Catch operand does not have pointer type!", &LPI); 1989 } else { 1990 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 1991 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 1992 "Filter operand is not an array of constants!", &LPI); 1993 } 1994 } 1995 1996 visitInstruction(LPI); 1997} 1998 1999void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 2000 Instruction *Op = cast<Instruction>(I.getOperand(i)); 2001 // If the we have an invalid invoke, don't try to compute the dominance. 2002 // We already reject it in the invoke specific checks and the dominance 2003 // computation doesn't handle multiple edges. 2004 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 2005 if (II->getNormalDest() == II->getUnwindDest()) 2006 return; 2007 } 2008 2009 const Use &U = I.getOperandUse(i); 2010 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U), 2011 "Instruction does not dominate all uses!", Op, &I); 2012} 2013 2014/// verifyInstruction - Verify that an instruction is well formed. 2015/// 2016void Verifier::visitInstruction(Instruction &I) { 2017 BasicBlock *BB = I.getParent(); 2018 Assert1(BB, "Instruction not embedded in basic block!", &I); 2019 2020 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 2021 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); 2022 UI != UE; ++UI) 2023 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB), 2024 "Only PHI nodes may reference their own value!", &I); 2025 } 2026 2027 // Check that void typed values don't have names 2028 Assert1(!I.getType()->isVoidTy() || !I.hasName(), 2029 "Instruction has a name, but provides a void value!", &I); 2030 2031 // Check that the return value of the instruction is either void or a legal 2032 // value type. 2033 Assert1(I.getType()->isVoidTy() || 2034 I.getType()->isFirstClassType(), 2035 "Instruction returns a non-scalar type!", &I); 2036 2037 // Check that the instruction doesn't produce metadata. Calls are already 2038 // checked against the callee type. 2039 Assert1(!I.getType()->isMetadataTy() || 2040 isa<CallInst>(I) || isa<InvokeInst>(I), 2041 "Invalid use of metadata!", &I); 2042 2043 // Check that all uses of the instruction, if they are instructions 2044 // themselves, actually have parent basic blocks. If the use is not an 2045 // instruction, it is an error! 2046 for (User::use_iterator UI = I.use_begin(), UE = I.use_end(); 2047 UI != UE; ++UI) { 2048 if (Instruction *Used = dyn_cast<Instruction>(*UI)) 2049 Assert2(Used->getParent() != 0, "Instruction referencing instruction not" 2050 " embedded in a basic block!", &I, Used); 2051 else { 2052 CheckFailed("Use of instruction is not an instruction!", *UI); 2053 return; 2054 } 2055 } 2056 2057 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 2058 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I); 2059 2060 // Check to make sure that only first-class-values are operands to 2061 // instructions. 2062 if (!I.getOperand(i)->getType()->isFirstClassType()) { 2063 Assert1(0, "Instruction operands must be first-class values!", &I); 2064 } 2065 2066 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 2067 // Check to make sure that the "address of" an intrinsic function is never 2068 // taken. 2069 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0), 2070 "Cannot take the address of an intrinsic!", &I); 2071 Assert1(!F->isIntrinsic() || isa<CallInst>(I) || 2072 F->getIntrinsicID() == Intrinsic::donothing, 2073 "Cannot invoke an intrinsinc other than donothing", &I); 2074 Assert1(F->getParent() == Mod, "Referencing function in another module!", 2075 &I); 2076 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 2077 Assert1(OpBB->getParent() == BB->getParent(), 2078 "Referring to a basic block in another function!", &I); 2079 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 2080 Assert1(OpArg->getParent() == BB->getParent(), 2081 "Referring to an argument in another function!", &I); 2082 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 2083 Assert1(GV->getParent() == Mod, "Referencing global in another module!", 2084 &I); 2085 } else if (isa<Instruction>(I.getOperand(i))) { 2086 verifyDominatesUse(I, i); 2087 } else if (isa<InlineAsm>(I.getOperand(i))) { 2088 Assert1((i + 1 == e && isa<CallInst>(I)) || 2089 (i + 3 == e && isa<InvokeInst>(I)), 2090 "Cannot take the address of an inline asm!", &I); 2091 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 2092 if (CE->getType()->isPtrOrPtrVectorTy()) { 2093 // If we have a ConstantExpr pointer, we need to see if it came from an 2094 // illegal bitcast (inttoptr <constant int> ) 2095 SmallVector<const ConstantExpr *, 4> Stack; 2096 SmallPtrSet<const ConstantExpr *, 4> Visited; 2097 Stack.push_back(CE); 2098 2099 while (!Stack.empty()) { 2100 const ConstantExpr *V = Stack.pop_back_val(); 2101 if (!Visited.insert(V)) 2102 continue; 2103 2104 VerifyConstantExprBitcastType(V); 2105 2106 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) { 2107 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I))) 2108 Stack.push_back(Op); 2109 } 2110 } 2111 } 2112 } 2113 } 2114 2115 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 2116 Assert1(I.getType()->isFPOrFPVectorTy(), 2117 "fpmath requires a floating point result!", &I); 2118 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 2119 Value *Op0 = MD->getOperand(0); 2120 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) { 2121 APFloat Accuracy = CFP0->getValueAPF(); 2122 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 2123 "fpmath accuracy not a positive number!", &I); 2124 } else { 2125 Assert1(false, "invalid fpmath accuracy!", &I); 2126 } 2127 } 2128 2129 MDNode *MD = I.getMetadata(LLVMContext::MD_range); 2130 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I); 2131 2132 if (!DisableDebugInfoVerifier) { 2133 MD = I.getMetadata(LLVMContext::MD_dbg); 2134 Finder.processLocation(*Mod, DILocation(MD)); 2135 } 2136 2137 InstsInThisBlock.insert(&I); 2138} 2139 2140/// VerifyIntrinsicType - Verify that the specified type (which comes from an 2141/// intrinsic argument or return value) matches the type constraints specified 2142/// by the .td file (e.g. an "any integer" argument really is an integer). 2143/// 2144/// This return true on error but does not print a message. 2145bool Verifier::VerifyIntrinsicType(Type *Ty, 2146 ArrayRef<Intrinsic::IITDescriptor> &Infos, 2147 SmallVectorImpl<Type*> &ArgTys) { 2148 using namespace Intrinsic; 2149 2150 // If we ran out of descriptors, there are too many arguments. 2151 if (Infos.empty()) return true; 2152 IITDescriptor D = Infos.front(); 2153 Infos = Infos.slice(1); 2154 2155 switch (D.Kind) { 2156 case IITDescriptor::Void: return !Ty->isVoidTy(); 2157 case IITDescriptor::VarArg: return true; 2158 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 2159 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 2160 case IITDescriptor::Half: return !Ty->isHalfTy(); 2161 case IITDescriptor::Float: return !Ty->isFloatTy(); 2162 case IITDescriptor::Double: return !Ty->isDoubleTy(); 2163 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 2164 case IITDescriptor::Vector: { 2165 VectorType *VT = dyn_cast<VectorType>(Ty); 2166 return VT == 0 || VT->getNumElements() != D.Vector_Width || 2167 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys); 2168 } 2169 case IITDescriptor::Pointer: { 2170 PointerType *PT = dyn_cast<PointerType>(Ty); 2171 return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace || 2172 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys); 2173 } 2174 2175 case IITDescriptor::Struct: { 2176 StructType *ST = dyn_cast<StructType>(Ty); 2177 if (ST == 0 || ST->getNumElements() != D.Struct_NumElements) 2178 return true; 2179 2180 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 2181 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys)) 2182 return true; 2183 return false; 2184 } 2185 2186 case IITDescriptor::Argument: 2187 // Two cases here - If this is the second occurrence of an argument, verify 2188 // that the later instance matches the previous instance. 2189 if (D.getArgumentNumber() < ArgTys.size()) 2190 return Ty != ArgTys[D.getArgumentNumber()]; 2191 2192 // Otherwise, if this is the first instance of an argument, record it and 2193 // verify the "Any" kind. 2194 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error"); 2195 ArgTys.push_back(Ty); 2196 2197 switch (D.getArgumentKind()) { 2198 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 2199 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 2200 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 2201 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 2202 } 2203 llvm_unreachable("all argument kinds not covered"); 2204 2205 case IITDescriptor::ExtendVecArgument: 2206 // This may only be used when referring to a previous vector argument. 2207 return D.getArgumentNumber() >= ArgTys.size() || 2208 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 2209 VectorType::getExtendedElementVectorType( 2210 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 2211 2212 case IITDescriptor::TruncVecArgument: 2213 // This may only be used when referring to a previous vector argument. 2214 return D.getArgumentNumber() >= ArgTys.size() || 2215 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 2216 VectorType::getTruncatedElementVectorType( 2217 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 2218 } 2219 llvm_unreachable("unhandled"); 2220} 2221 2222/// \brief Verify if the intrinsic has variable arguments. 2223/// This method is intended to be called after all the fixed arguments have been 2224/// verified first. 2225/// 2226/// This method returns true on error and does not print an error message. 2227bool 2228Verifier::VerifyIntrinsicIsVarArg(bool isVarArg, 2229 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 2230 using namespace Intrinsic; 2231 2232 // If there are no descriptors left, then it can't be a vararg. 2233 if (Infos.empty()) 2234 return isVarArg ? true : false; 2235 2236 // There should be only one descriptor remaining at this point. 2237 if (Infos.size() != 1) 2238 return true; 2239 2240 // Check and verify the descriptor. 2241 IITDescriptor D = Infos.front(); 2242 Infos = Infos.slice(1); 2243 if (D.Kind == IITDescriptor::VarArg) 2244 return isVarArg ? false : true; 2245 2246 return true; 2247} 2248 2249/// visitIntrinsicFunction - Allow intrinsics to be verified in different ways. 2250/// 2251void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) { 2252 Function *IF = CI.getCalledFunction(); 2253 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!", 2254 IF); 2255 2256 // Verify that the intrinsic prototype lines up with what the .td files 2257 // describe. 2258 FunctionType *IFTy = IF->getFunctionType(); 2259 bool IsVarArg = IFTy->isVarArg(); 2260 2261 SmallVector<Intrinsic::IITDescriptor, 8> Table; 2262 getIntrinsicInfoTableEntries(ID, Table); 2263 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 2264 2265 SmallVector<Type *, 4> ArgTys; 2266 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys), 2267 "Intrinsic has incorrect return type!", IF); 2268 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i) 2269 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys), 2270 "Intrinsic has incorrect argument type!", IF); 2271 2272 // Verify if the intrinsic call matches the vararg property. 2273 if (IsVarArg) 2274 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef), 2275 "Intrinsic was not defined with variable arguments!", IF); 2276 else 2277 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef), 2278 "Callsite was not defined with variable arguments!", IF); 2279 2280 // All descriptors should be absorbed by now. 2281 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF); 2282 2283 // Now that we have the intrinsic ID and the actual argument types (and we 2284 // know they are legal for the intrinsic!) get the intrinsic name through the 2285 // usual means. This allows us to verify the mangling of argument types into 2286 // the name. 2287 Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(), 2288 "Intrinsic name not mangled correctly for type arguments!", IF); 2289 2290 // If the intrinsic takes MDNode arguments, verify that they are either global 2291 // or are local to *this* function. 2292 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i) 2293 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i))) 2294 visitMDNode(*MD, CI.getParent()->getParent()); 2295 2296 switch (ID) { 2297 default: 2298 break; 2299 case Intrinsic::ctlz: // llvm.ctlz 2300 case Intrinsic::cttz: // llvm.cttz 2301 Assert1(isa<ConstantInt>(CI.getArgOperand(1)), 2302 "is_zero_undef argument of bit counting intrinsics must be a " 2303 "constant int", &CI); 2304 break; 2305 case Intrinsic::dbg_declare: { // llvm.dbg.declare 2306 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)), 2307 "invalid llvm.dbg.declare intrinsic call 1", &CI); 2308 MDNode *MD = cast<MDNode>(CI.getArgOperand(0)); 2309 Assert1(MD->getNumOperands() == 1, 2310 "invalid llvm.dbg.declare intrinsic call 2", &CI); 2311 if (!DisableDebugInfoVerifier) 2312 Finder.processDeclare(*Mod, cast<DbgDeclareInst>(&CI)); 2313 } break; 2314 case Intrinsic::dbg_value: { //llvm.dbg.value 2315 if (!DisableDebugInfoVerifier) { 2316 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)), 2317 "invalid llvm.dbg.value intrinsic call 1", &CI); 2318 Finder.processValue(*Mod, cast<DbgValueInst>(&CI)); 2319 } 2320 break; 2321 } 2322 case Intrinsic::memcpy: 2323 case Intrinsic::memmove: 2324 case Intrinsic::memset: 2325 Assert1(isa<ConstantInt>(CI.getArgOperand(3)), 2326 "alignment argument of memory intrinsics must be a constant int", 2327 &CI); 2328 Assert1(isa<ConstantInt>(CI.getArgOperand(4)), 2329 "isvolatile argument of memory intrinsics must be a constant int", 2330 &CI); 2331 break; 2332 case Intrinsic::gcroot: 2333 case Intrinsic::gcwrite: 2334 case Intrinsic::gcread: 2335 if (ID == Intrinsic::gcroot) { 2336 AllocaInst *AI = 2337 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts()); 2338 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI); 2339 Assert1(isa<Constant>(CI.getArgOperand(1)), 2340 "llvm.gcroot parameter #2 must be a constant.", &CI); 2341 if (!AI->getType()->getElementType()->isPointerTy()) { 2342 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)), 2343 "llvm.gcroot parameter #1 must either be a pointer alloca, " 2344 "or argument #2 must be a non-null constant.", &CI); 2345 } 2346 } 2347 2348 Assert1(CI.getParent()->getParent()->hasGC(), 2349 "Enclosing function does not use GC.", &CI); 2350 break; 2351 case Intrinsic::init_trampoline: 2352 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()), 2353 "llvm.init_trampoline parameter #2 must resolve to a function.", 2354 &CI); 2355 break; 2356 case Intrinsic::prefetch: 2357 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) && 2358 isa<ConstantInt>(CI.getArgOperand(2)) && 2359 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 && 2360 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4, 2361 "invalid arguments to llvm.prefetch", 2362 &CI); 2363 break; 2364 case Intrinsic::stackprotector: 2365 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()), 2366 "llvm.stackprotector parameter #2 must resolve to an alloca.", 2367 &CI); 2368 break; 2369 case Intrinsic::lifetime_start: 2370 case Intrinsic::lifetime_end: 2371 case Intrinsic::invariant_start: 2372 Assert1(isa<ConstantInt>(CI.getArgOperand(0)), 2373 "size argument of memory use markers must be a constant integer", 2374 &CI); 2375 break; 2376 case Intrinsic::invariant_end: 2377 Assert1(isa<ConstantInt>(CI.getArgOperand(1)), 2378 "llvm.invariant.end parameter #2 must be a constant integer", &CI); 2379 break; 2380 } 2381} 2382 2383void Verifier::verifyDebugInfo() { 2384 // Verify Debug Info. 2385 if (!DisableDebugInfoVerifier) { 2386 for (DebugInfoFinder::iterator I = Finder.compile_unit_begin(), 2387 E = Finder.compile_unit_end(); I != E; ++I) 2388 Assert1(DICompileUnit(*I).Verify(), "DICompileUnit does not Verify!", *I); 2389 for (DebugInfoFinder::iterator I = Finder.subprogram_begin(), 2390 E = Finder.subprogram_end(); I != E; ++I) 2391 Assert1(DISubprogram(*I).Verify(), "DISubprogram does not Verify!", *I); 2392 for (DebugInfoFinder::iterator I = Finder.global_variable_begin(), 2393 E = Finder.global_variable_end(); I != E; ++I) 2394 Assert1(DIGlobalVariable(*I).Verify(), 2395 "DIGlobalVariable does not Verify!", *I); 2396 for (DebugInfoFinder::iterator I = Finder.type_begin(), 2397 E = Finder.type_end(); I != E; ++I) 2398 Assert1(DIType(*I).Verify(), "DIType does not Verify!", *I); 2399 for (DebugInfoFinder::iterator I = Finder.scope_begin(), 2400 E = Finder.scope_end(); I != E; ++I) 2401 Assert1(DIScope(*I).Verify(), "DIScope does not Verify!", *I); 2402 } 2403} 2404 2405//===----------------------------------------------------------------------===// 2406// Implement the public interfaces to this file... 2407//===----------------------------------------------------------------------===// 2408 2409FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) { 2410 return new Verifier(action); 2411} 2412 2413 2414/// verifyFunction - Check a function for errors, printing messages on stderr. 2415/// Return true if the function is corrupt. 2416/// 2417bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) { 2418 Function &F = const_cast<Function&>(f); 2419 assert(!F.isDeclaration() && "Cannot verify external functions"); 2420 2421 FunctionPassManager FPM(F.getParent()); 2422 Verifier *V = new Verifier(action); 2423 FPM.add(V); 2424 FPM.doInitialization(); 2425 FPM.run(F); 2426 return V->Broken; 2427} 2428 2429/// verifyModule - Check a module for errors, printing messages on stderr. 2430/// Return true if the module is corrupt. 2431/// 2432bool llvm::verifyModule(const Module &M, VerifierFailureAction action, 2433 std::string *ErrorInfo) { 2434 PassManager PM; 2435 Verifier *V = new Verifier(action); 2436 PM.add(V); 2437 PM.run(const_cast<Module&>(M)); 2438 2439 if (ErrorInfo && V->Broken) 2440 *ErrorInfo = V->MessagesStr.str(); 2441 return V->Broken; 2442} 2443