LLVM API Documentation
00001 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the function verifier interface, that can be used for some 00011 // sanity checking of input to the system. 00012 // 00013 // Note that this does not provide full `Java style' security and verifications, 00014 // instead it just tries to ensure that code is well-formed. 00015 // 00016 // * Both of a binary operator's parameters are of the same type 00017 // * Verify that the indices of mem access instructions match other operands 00018 // * Verify that arithmetic and other things are only performed on first-class 00019 // types. Verify that shifts & logicals only happen on integrals f.e. 00020 // * All of the constants in a switch statement are of the correct type 00021 // * The code is in valid SSA form 00022 // * It should be illegal to put a label into any other type (like a structure) 00023 // or to return one. [except constant arrays!] 00024 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad 00025 // * PHI nodes must have an entry for each predecessor, with no extras. 00026 // * PHI nodes must be the first thing in a basic block, all grouped together 00027 // * PHI nodes must have at least one entry 00028 // * All basic blocks should only end with terminator insts, not contain them 00029 // * The entry node to a function must not have predecessors 00030 // * All Instructions must be embedded into a basic block 00031 // * Functions cannot take a void-typed parameter 00032 // * Verify that a function's argument list agrees with it's declared type. 00033 // * It is illegal to specify a name for a void value. 00034 // * It is illegal to have a internal global value with no initializer 00035 // * It is illegal to have a ret instruction that returns a value that does not 00036 // agree with the function return value type. 00037 // * Function call argument types match the function prototype 00038 // * A landing pad is defined by a landingpad instruction, and can be jumped to 00039 // only by the unwind edge of an invoke instruction. 00040 // * A landingpad instruction must be the first non-PHI instruction in the 00041 // block. 00042 // * All landingpad instructions must use the same personality function with 00043 // the same function. 00044 // * All other things that are tested by asserts spread about the code... 00045 // 00046 //===----------------------------------------------------------------------===// 00047 00048 #include "llvm/IR/Verifier.h" 00049 #include "llvm/ADT/STLExtras.h" 00050 #include "llvm/ADT/SetVector.h" 00051 #include "llvm/ADT/SmallPtrSet.h" 00052 #include "llvm/ADT/SmallVector.h" 00053 #include "llvm/ADT/StringExtras.h" 00054 #include "llvm/IR/CFG.h" 00055 #include "llvm/IR/CallSite.h" 00056 #include "llvm/IR/CallingConv.h" 00057 #include "llvm/IR/ConstantRange.h" 00058 #include "llvm/IR/Constants.h" 00059 #include "llvm/IR/DataLayout.h" 00060 #include "llvm/IR/DebugInfo.h" 00061 #include "llvm/IR/DerivedTypes.h" 00062 #include "llvm/IR/Dominators.h" 00063 #include "llvm/IR/InlineAsm.h" 00064 #include "llvm/IR/InstIterator.h" 00065 #include "llvm/IR/InstVisitor.h" 00066 #include "llvm/IR/IntrinsicInst.h" 00067 #include "llvm/IR/LLVMContext.h" 00068 #include "llvm/IR/Metadata.h" 00069 #include "llvm/IR/Module.h" 00070 #include "llvm/IR/PassManager.h" 00071 #include "llvm/Pass.h" 00072 #include "llvm/Support/CommandLine.h" 00073 #include "llvm/Support/Debug.h" 00074 #include "llvm/Support/ErrorHandling.h" 00075 #include "llvm/Support/raw_ostream.h" 00076 #include <algorithm> 00077 #include <cstdarg> 00078 using namespace llvm; 00079 00080 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(false)); 00081 00082 namespace { 00083 struct VerifierSupport { 00084 raw_ostream &OS; 00085 const Module *M; 00086 00087 /// \brief Track the brokenness of the module while recursively visiting. 00088 bool Broken; 00089 00090 explicit VerifierSupport(raw_ostream &OS) 00091 : OS(OS), M(nullptr), Broken(false) {} 00092 00093 void WriteValue(const Value *V) { 00094 if (!V) 00095 return; 00096 if (isa<Instruction>(V)) { 00097 OS << *V << '\n'; 00098 } else { 00099 V->printAsOperand(OS, true, M); 00100 OS << '\n'; 00101 } 00102 } 00103 00104 void WriteType(Type *T) { 00105 if (!T) 00106 return; 00107 OS << ' ' << *T; 00108 } 00109 00110 void WriteComdat(const Comdat *C) { 00111 if (!C) 00112 return; 00113 OS << *C; 00114 } 00115 00116 // CheckFailed - A check failed, so print out the condition and the message 00117 // that failed. This provides a nice place to put a breakpoint if you want 00118 // to see why something is not correct. 00119 void CheckFailed(const Twine &Message, const Value *V1 = nullptr, 00120 const Value *V2 = nullptr, const Value *V3 = nullptr, 00121 const Value *V4 = nullptr) { 00122 OS << Message.str() << "\n"; 00123 WriteValue(V1); 00124 WriteValue(V2); 00125 WriteValue(V3); 00126 WriteValue(V4); 00127 Broken = true; 00128 } 00129 00130 void CheckFailed(const Twine &Message, const Value *V1, Type *T2, 00131 const Value *V3 = nullptr) { 00132 OS << Message.str() << "\n"; 00133 WriteValue(V1); 00134 WriteType(T2); 00135 WriteValue(V3); 00136 Broken = true; 00137 } 00138 00139 void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr, 00140 Type *T3 = nullptr) { 00141 OS << Message.str() << "\n"; 00142 WriteType(T1); 00143 WriteType(T2); 00144 WriteType(T3); 00145 Broken = true; 00146 } 00147 00148 void CheckFailed(const Twine &Message, const Comdat *C) { 00149 OS << Message.str() << "\n"; 00150 WriteComdat(C); 00151 Broken = true; 00152 } 00153 }; 00154 class Verifier : public InstVisitor<Verifier>, VerifierSupport { 00155 friend class InstVisitor<Verifier>; 00156 00157 LLVMContext *Context; 00158 const DataLayout *DL; 00159 DominatorTree DT; 00160 00161 /// \brief When verifying a basic block, keep track of all of the 00162 /// instructions we have seen so far. 00163 /// 00164 /// This allows us to do efficient dominance checks for the case when an 00165 /// instruction has an operand that is an instruction in the same block. 00166 SmallPtrSet<Instruction *, 16> InstsInThisBlock; 00167 00168 /// \brief Keep track of the metadata nodes that have been checked already. 00169 SmallPtrSet<MDNode *, 32> MDNodes; 00170 00171 /// \brief The personality function referenced by the LandingPadInsts. 00172 /// All LandingPadInsts within the same function must use the same 00173 /// personality function. 00174 const Value *PersonalityFn; 00175 00176 public: 00177 explicit Verifier(raw_ostream &OS = dbgs()) 00178 : VerifierSupport(OS), Context(nullptr), DL(nullptr), 00179 PersonalityFn(nullptr) {} 00180 00181 bool verify(const Function &F) { 00182 M = F.getParent(); 00183 Context = &M->getContext(); 00184 00185 // First ensure the function is well-enough formed to compute dominance 00186 // information. 00187 if (F.empty()) { 00188 OS << "Function '" << F.getName() 00189 << "' does not contain an entry block!\n"; 00190 return false; 00191 } 00192 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) { 00193 if (I->empty() || !I->back().isTerminator()) { 00194 OS << "Basic Block in function '" << F.getName() 00195 << "' does not have terminator!\n"; 00196 I->printAsOperand(OS, true); 00197 OS << "\n"; 00198 return false; 00199 } 00200 } 00201 00202 // Now directly compute a dominance tree. We don't rely on the pass 00203 // manager to provide this as it isolates us from a potentially 00204 // out-of-date dominator tree and makes it significantly more complex to 00205 // run this code outside of a pass manager. 00206 // FIXME: It's really gross that we have to cast away constness here. 00207 DT.recalculate(const_cast<Function &>(F)); 00208 00209 Broken = false; 00210 // FIXME: We strip const here because the inst visitor strips const. 00211 visit(const_cast<Function &>(F)); 00212 InstsInThisBlock.clear(); 00213 PersonalityFn = nullptr; 00214 00215 return !Broken; 00216 } 00217 00218 bool verify(const Module &M) { 00219 this->M = &M; 00220 Context = &M.getContext(); 00221 Broken = false; 00222 00223 // Scan through, checking all of the external function's linkage now... 00224 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 00225 visitGlobalValue(*I); 00226 00227 // Check to make sure function prototypes are okay. 00228 if (I->isDeclaration()) 00229 visitFunction(*I); 00230 } 00231 00232 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 00233 I != E; ++I) 00234 visitGlobalVariable(*I); 00235 00236 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 00237 I != E; ++I) 00238 visitGlobalAlias(*I); 00239 00240 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(), 00241 E = M.named_metadata_end(); 00242 I != E; ++I) 00243 visitNamedMDNode(*I); 00244 00245 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable()) 00246 visitComdat(SMEC.getValue()); 00247 00248 visitModuleFlags(M); 00249 visitModuleIdents(M); 00250 00251 return !Broken; 00252 } 00253 00254 private: 00255 // Verification methods... 00256 void visitGlobalValue(const GlobalValue &GV); 00257 void visitGlobalVariable(const GlobalVariable &GV); 00258 void visitGlobalAlias(const GlobalAlias &GA); 00259 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C); 00260 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited, 00261 const GlobalAlias &A, const Constant &C); 00262 void visitNamedMDNode(const NamedMDNode &NMD); 00263 void visitMDNode(MDNode &MD, Function *F); 00264 void visitComdat(const Comdat &C); 00265 void visitModuleIdents(const Module &M); 00266 void visitModuleFlags(const Module &M); 00267 void visitModuleFlag(const MDNode *Op, 00268 DenseMap<const MDString *, const MDNode *> &SeenIDs, 00269 SmallVectorImpl<const MDNode *> &Requirements); 00270 void visitFunction(const Function &F); 00271 void visitBasicBlock(BasicBlock &BB); 00272 00273 // InstVisitor overrides... 00274 using InstVisitor<Verifier>::visit; 00275 void visit(Instruction &I); 00276 00277 void visitTruncInst(TruncInst &I); 00278 void visitZExtInst(ZExtInst &I); 00279 void visitSExtInst(SExtInst &I); 00280 void visitFPTruncInst(FPTruncInst &I); 00281 void visitFPExtInst(FPExtInst &I); 00282 void visitFPToUIInst(FPToUIInst &I); 00283 void visitFPToSIInst(FPToSIInst &I); 00284 void visitUIToFPInst(UIToFPInst &I); 00285 void visitSIToFPInst(SIToFPInst &I); 00286 void visitIntToPtrInst(IntToPtrInst &I); 00287 void visitPtrToIntInst(PtrToIntInst &I); 00288 void visitBitCastInst(BitCastInst &I); 00289 void visitAddrSpaceCastInst(AddrSpaceCastInst &I); 00290 void visitPHINode(PHINode &PN); 00291 void visitBinaryOperator(BinaryOperator &B); 00292 void visitICmpInst(ICmpInst &IC); 00293 void visitFCmpInst(FCmpInst &FC); 00294 void visitExtractElementInst(ExtractElementInst &EI); 00295 void visitInsertElementInst(InsertElementInst &EI); 00296 void visitShuffleVectorInst(ShuffleVectorInst &EI); 00297 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 00298 void visitCallInst(CallInst &CI); 00299 void visitInvokeInst(InvokeInst &II); 00300 void visitGetElementPtrInst(GetElementPtrInst &GEP); 00301 void visitLoadInst(LoadInst &LI); 00302 void visitStoreInst(StoreInst &SI); 00303 void verifyDominatesUse(Instruction &I, unsigned i); 00304 void visitInstruction(Instruction &I); 00305 void visitTerminatorInst(TerminatorInst &I); 00306 void visitBranchInst(BranchInst &BI); 00307 void visitReturnInst(ReturnInst &RI); 00308 void visitSwitchInst(SwitchInst &SI); 00309 void visitIndirectBrInst(IndirectBrInst &BI); 00310 void visitSelectInst(SelectInst &SI); 00311 void visitUserOp1(Instruction &I); 00312 void visitUserOp2(Instruction &I) { visitUserOp1(I); } 00313 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI); 00314 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 00315 void visitAtomicRMWInst(AtomicRMWInst &RMWI); 00316 void visitFenceInst(FenceInst &FI); 00317 void visitAllocaInst(AllocaInst &AI); 00318 void visitExtractValueInst(ExtractValueInst &EVI); 00319 void visitInsertValueInst(InsertValueInst &IVI); 00320 void visitLandingPadInst(LandingPadInst &LPI); 00321 00322 void VerifyCallSite(CallSite CS); 00323 void verifyMustTailCall(CallInst &CI); 00324 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT, 00325 unsigned ArgNo, std::string &Suffix); 00326 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 00327 SmallVectorImpl<Type *> &ArgTys); 00328 bool VerifyIntrinsicIsVarArg(bool isVarArg, 00329 ArrayRef<Intrinsic::IITDescriptor> &Infos); 00330 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params); 00331 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction, 00332 const Value *V); 00333 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 00334 bool isReturnValue, const Value *V); 00335 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 00336 const Value *V); 00337 00338 void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy); 00339 void VerifyConstantExprBitcastType(const ConstantExpr *CE); 00340 }; 00341 class DebugInfoVerifier : public VerifierSupport { 00342 public: 00343 explicit DebugInfoVerifier(raw_ostream &OS = dbgs()) : VerifierSupport(OS) {} 00344 00345 bool verify(const Module &M) { 00346 this->M = &M; 00347 verifyDebugInfo(); 00348 return !Broken; 00349 } 00350 00351 private: 00352 void verifyDebugInfo(); 00353 void processInstructions(DebugInfoFinder &Finder); 00354 void processCallInst(DebugInfoFinder &Finder, const CallInst &CI); 00355 }; 00356 } // End anonymous namespace 00357 00358 // Assert - We know that cond should be true, if not print an error message. 00359 #define Assert(C, M) \ 00360 do { if (!(C)) { CheckFailed(M); return; } } while (0) 00361 #define Assert1(C, M, V1) \ 00362 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0) 00363 #define Assert2(C, M, V1, V2) \ 00364 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0) 00365 #define Assert3(C, M, V1, V2, V3) \ 00366 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0) 00367 #define Assert4(C, M, V1, V2, V3, V4) \ 00368 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0) 00369 00370 void Verifier::visit(Instruction &I) { 00371 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 00372 Assert1(I.getOperand(i) != nullptr, "Operand is null", &I); 00373 InstVisitor<Verifier>::visit(I); 00374 } 00375 00376 00377 void Verifier::visitGlobalValue(const GlobalValue &GV) { 00378 Assert1(!GV.isDeclaration() || GV.isMaterializable() || 00379 GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(), 00380 "Global is external, but doesn't have external or weak linkage!", 00381 &GV); 00382 00383 Assert1(GV.getAlignment() <= Value::MaximumAlignment, 00384 "huge alignment values are unsupported", &GV); 00385 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 00386 "Only global variables can have appending linkage!", &GV); 00387 00388 if (GV.hasAppendingLinkage()) { 00389 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 00390 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(), 00391 "Only global arrays can have appending linkage!", GVar); 00392 } 00393 } 00394 00395 void Verifier::visitGlobalVariable(const GlobalVariable &GV) { 00396 if (GV.hasInitializer()) { 00397 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(), 00398 "Global variable initializer type does not match global " 00399 "variable type!", &GV); 00400 00401 // If the global has common linkage, it must have a zero initializer and 00402 // cannot be constant. 00403 if (GV.hasCommonLinkage()) { 00404 Assert1(GV.getInitializer()->isNullValue(), 00405 "'common' global must have a zero initializer!", &GV); 00406 Assert1(!GV.isConstant(), "'common' global may not be marked constant!", 00407 &GV); 00408 Assert1(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV); 00409 } 00410 } else { 00411 Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(), 00412 "invalid linkage type for global declaration", &GV); 00413 } 00414 00415 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 00416 GV.getName() == "llvm.global_dtors")) { 00417 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(), 00418 "invalid linkage for intrinsic global variable", &GV); 00419 // Don't worry about emitting an error for it not being an array, 00420 // visitGlobalValue will complain on appending non-array. 00421 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) { 00422 StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 00423 PointerType *FuncPtrTy = 00424 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo(); 00425 // FIXME: Reject the 2-field form in LLVM 4.0. 00426 Assert1(STy && (STy->getNumElements() == 2 || 00427 STy->getNumElements() == 3) && 00428 STy->getTypeAtIndex(0u)->isIntegerTy(32) && 00429 STy->getTypeAtIndex(1) == FuncPtrTy, 00430 "wrong type for intrinsic global variable", &GV); 00431 if (STy->getNumElements() == 3) { 00432 Type *ETy = STy->getTypeAtIndex(2); 00433 Assert1(ETy->isPointerTy() && 00434 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8), 00435 "wrong type for intrinsic global variable", &GV); 00436 } 00437 } 00438 } 00439 00440 if (GV.hasName() && (GV.getName() == "llvm.used" || 00441 GV.getName() == "llvm.compiler.used")) { 00442 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(), 00443 "invalid linkage for intrinsic global variable", &GV); 00444 Type *GVType = GV.getType()->getElementType(); 00445 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) { 00446 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType()); 00447 Assert1(PTy, "wrong type for intrinsic global variable", &GV); 00448 if (GV.hasInitializer()) { 00449 const Constant *Init = GV.getInitializer(); 00450 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init); 00451 Assert1(InitArray, "wrong initalizer for intrinsic global variable", 00452 Init); 00453 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) { 00454 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases(); 00455 Assert1( 00456 isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V), 00457 "invalid llvm.used member", V); 00458 Assert1(V->hasName(), "members of llvm.used must be named", V); 00459 } 00460 } 00461 } 00462 } 00463 00464 Assert1(!GV.hasDLLImportStorageClass() || 00465 (GV.isDeclaration() && GV.hasExternalLinkage()) || 00466 GV.hasAvailableExternallyLinkage(), 00467 "Global is marked as dllimport, but not external", &GV); 00468 00469 if (!GV.hasInitializer()) { 00470 visitGlobalValue(GV); 00471 return; 00472 } 00473 00474 // Walk any aggregate initializers looking for bitcasts between address spaces 00475 SmallPtrSet<const Value *, 4> Visited; 00476 SmallVector<const Value *, 4> WorkStack; 00477 WorkStack.push_back(cast<Value>(GV.getInitializer())); 00478 00479 while (!WorkStack.empty()) { 00480 const Value *V = WorkStack.pop_back_val(); 00481 if (!Visited.insert(V)) 00482 continue; 00483 00484 if (const User *U = dyn_cast<User>(V)) { 00485 for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I) 00486 WorkStack.push_back(U->getOperand(I)); 00487 } 00488 00489 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 00490 VerifyConstantExprBitcastType(CE); 00491 if (Broken) 00492 return; 00493 } 00494 } 00495 00496 visitGlobalValue(GV); 00497 } 00498 00499 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) { 00500 SmallPtrSet<const GlobalAlias*, 4> Visited; 00501 Visited.insert(&GA); 00502 visitAliaseeSubExpr(Visited, GA, C); 00503 } 00504 00505 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited, 00506 const GlobalAlias &GA, const Constant &C) { 00507 if (const auto *GV = dyn_cast<GlobalValue>(&C)) { 00508 Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA); 00509 00510 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) { 00511 Assert1(Visited.insert(GA2), "Aliases cannot form a cycle", &GA); 00512 00513 Assert1(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias", 00514 &GA); 00515 } else { 00516 // Only continue verifying subexpressions of GlobalAliases. 00517 // Do not recurse into global initializers. 00518 return; 00519 } 00520 } 00521 00522 if (const auto *CE = dyn_cast<ConstantExpr>(&C)) 00523 VerifyConstantExprBitcastType(CE); 00524 00525 for (const Use &U : C.operands()) { 00526 Value *V = &*U; 00527 if (const auto *GA2 = dyn_cast<GlobalAlias>(V)) 00528 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee()); 00529 else if (const auto *C2 = dyn_cast<Constant>(V)) 00530 visitAliaseeSubExpr(Visited, GA, *C2); 00531 } 00532 } 00533 00534 void Verifier::visitGlobalAlias(const GlobalAlias &GA) { 00535 Assert1(!GA.getName().empty(), 00536 "Alias name cannot be empty!", &GA); 00537 Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()), 00538 "Alias should have private, internal, linkonce, weak, linkonce_odr, " 00539 "weak_odr, or external linkage!", 00540 &GA); 00541 const Constant *Aliasee = GA.getAliasee(); 00542 Assert1(Aliasee, "Aliasee cannot be NULL!", &GA); 00543 Assert1(GA.getType() == Aliasee->getType(), 00544 "Alias and aliasee types should match!", &GA); 00545 00546 Assert1(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee), 00547 "Aliasee should be either GlobalValue or ConstantExpr", &GA); 00548 00549 visitAliaseeSubExpr(GA, *Aliasee); 00550 00551 visitGlobalValue(GA); 00552 } 00553 00554 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) { 00555 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) { 00556 MDNode *MD = NMD.getOperand(i); 00557 if (!MD) 00558 continue; 00559 00560 Assert1(!MD->isFunctionLocal(), 00561 "Named metadata operand cannot be function local!", MD); 00562 visitMDNode(*MD, nullptr); 00563 } 00564 } 00565 00566 void Verifier::visitMDNode(MDNode &MD, Function *F) { 00567 // Only visit each node once. Metadata can be mutually recursive, so this 00568 // avoids infinite recursion here, as well as being an optimization. 00569 if (!MDNodes.insert(&MD)) 00570 return; 00571 00572 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) { 00573 Value *Op = MD.getOperand(i); 00574 if (!Op) 00575 continue; 00576 if (isa<Constant>(Op) || isa<MDString>(Op)) 00577 continue; 00578 if (MDNode *N = dyn_cast<MDNode>(Op)) { 00579 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(), 00580 "Global metadata operand cannot be function local!", &MD, N); 00581 visitMDNode(*N, F); 00582 continue; 00583 } 00584 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op); 00585 00586 // If this was an instruction, bb, or argument, verify that it is in the 00587 // function that we expect. 00588 Function *ActualF = nullptr; 00589 if (Instruction *I = dyn_cast<Instruction>(Op)) 00590 ActualF = I->getParent()->getParent(); 00591 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op)) 00592 ActualF = BB->getParent(); 00593 else if (Argument *A = dyn_cast<Argument>(Op)) 00594 ActualF = A->getParent(); 00595 assert(ActualF && "Unimplemented function local metadata case!"); 00596 00597 Assert2(ActualF == F, "function-local metadata used in wrong function", 00598 &MD, Op); 00599 } 00600 } 00601 00602 void Verifier::visitComdat(const Comdat &C) { 00603 // All Comdat::SelectionKind values other than Comdat::Any require a 00604 // GlobalValue with the same name as the Comdat. 00605 const GlobalValue *GV = M->getNamedValue(C.getName()); 00606 if (C.getSelectionKind() != Comdat::Any) 00607 Assert1(GV, 00608 "comdat selection kind requires a global value with the same name", 00609 &C); 00610 // The Module is invalid if the GlobalValue has private linkage. Entities 00611 // with private linkage don't have entries in the symbol table. 00612 if (GV) 00613 Assert1(!GV->hasPrivateLinkage(), "comdat global value has private linkage", 00614 GV); 00615 } 00616 00617 void Verifier::visitModuleIdents(const Module &M) { 00618 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident"); 00619 if (!Idents) 00620 return; 00621 00622 // llvm.ident takes a list of metadata entry. Each entry has only one string. 00623 // Scan each llvm.ident entry and make sure that this requirement is met. 00624 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) { 00625 const MDNode *N = Idents->getOperand(i); 00626 Assert1(N->getNumOperands() == 1, 00627 "incorrect number of operands in llvm.ident metadata", N); 00628 Assert1(isa<MDString>(N->getOperand(0)), 00629 ("invalid value for llvm.ident metadata entry operand" 00630 "(the operand should be a string)"), 00631 N->getOperand(0)); 00632 } 00633 } 00634 00635 void Verifier::visitModuleFlags(const Module &M) { 00636 const NamedMDNode *Flags = M.getModuleFlagsMetadata(); 00637 if (!Flags) return; 00638 00639 // Scan each flag, and track the flags and requirements. 00640 DenseMap<const MDString*, const MDNode*> SeenIDs; 00641 SmallVector<const MDNode*, 16> Requirements; 00642 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) { 00643 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements); 00644 } 00645 00646 // Validate that the requirements in the module are valid. 00647 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 00648 const MDNode *Requirement = Requirements[I]; 00649 const MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 00650 const Value *ReqValue = Requirement->getOperand(1); 00651 00652 const MDNode *Op = SeenIDs.lookup(Flag); 00653 if (!Op) { 00654 CheckFailed("invalid requirement on flag, flag is not present in module", 00655 Flag); 00656 continue; 00657 } 00658 00659 if (Op->getOperand(2) != ReqValue) { 00660 CheckFailed(("invalid requirement on flag, " 00661 "flag does not have the required value"), 00662 Flag); 00663 continue; 00664 } 00665 } 00666 } 00667 00668 void 00669 Verifier::visitModuleFlag(const MDNode *Op, 00670 DenseMap<const MDString *, const MDNode *> &SeenIDs, 00671 SmallVectorImpl<const MDNode *> &Requirements) { 00672 // Each module flag should have three arguments, the merge behavior (a 00673 // constant int), the flag ID (an MDString), and the value. 00674 Assert1(Op->getNumOperands() == 3, 00675 "incorrect number of operands in module flag", Op); 00676 Module::ModFlagBehavior MFB; 00677 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) { 00678 Assert1( 00679 dyn_cast<ConstantInt>(Op->getOperand(0)), 00680 "invalid behavior operand in module flag (expected constant integer)", 00681 Op->getOperand(0)); 00682 Assert1(false, 00683 "invalid behavior operand in module flag (unexpected constant)", 00684 Op->getOperand(0)); 00685 } 00686 MDString *ID = dyn_cast<MDString>(Op->getOperand(1)); 00687 Assert1(ID, 00688 "invalid ID operand in module flag (expected metadata string)", 00689 Op->getOperand(1)); 00690 00691 // Sanity check the values for behaviors with additional requirements. 00692 switch (MFB) { 00693 case Module::Error: 00694 case Module::Warning: 00695 case Module::Override: 00696 // These behavior types accept any value. 00697 break; 00698 00699 case Module::Require: { 00700 // The value should itself be an MDNode with two operands, a flag ID (an 00701 // MDString), and a value. 00702 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2)); 00703 Assert1(Value && Value->getNumOperands() == 2, 00704 "invalid value for 'require' module flag (expected metadata pair)", 00705 Op->getOperand(2)); 00706 Assert1(isa<MDString>(Value->getOperand(0)), 00707 ("invalid value for 'require' module flag " 00708 "(first value operand should be a string)"), 00709 Value->getOperand(0)); 00710 00711 // Append it to the list of requirements, to check once all module flags are 00712 // scanned. 00713 Requirements.push_back(Value); 00714 break; 00715 } 00716 00717 case Module::Append: 00718 case Module::AppendUnique: { 00719 // These behavior types require the operand be an MDNode. 00720 Assert1(isa<MDNode>(Op->getOperand(2)), 00721 "invalid value for 'append'-type module flag " 00722 "(expected a metadata node)", Op->getOperand(2)); 00723 break; 00724 } 00725 } 00726 00727 // Unless this is a "requires" flag, check the ID is unique. 00728 if (MFB != Module::Require) { 00729 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second; 00730 Assert1(Inserted, 00731 "module flag identifiers must be unique (or of 'require' type)", 00732 ID); 00733 } 00734 } 00735 00736 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, 00737 bool isFunction, const Value *V) { 00738 unsigned Slot = ~0U; 00739 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I) 00740 if (Attrs.getSlotIndex(I) == Idx) { 00741 Slot = I; 00742 break; 00743 } 00744 00745 assert(Slot != ~0U && "Attribute set inconsistency!"); 00746 00747 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot); 00748 I != E; ++I) { 00749 if (I->isStringAttribute()) 00750 continue; 00751 00752 if (I->getKindAsEnum() == Attribute::NoReturn || 00753 I->getKindAsEnum() == Attribute::NoUnwind || 00754 I->getKindAsEnum() == Attribute::NoInline || 00755 I->getKindAsEnum() == Attribute::AlwaysInline || 00756 I->getKindAsEnum() == Attribute::OptimizeForSize || 00757 I->getKindAsEnum() == Attribute::StackProtect || 00758 I->getKindAsEnum() == Attribute::StackProtectReq || 00759 I->getKindAsEnum() == Attribute::StackProtectStrong || 00760 I->getKindAsEnum() == Attribute::NoRedZone || 00761 I->getKindAsEnum() == Attribute::NoImplicitFloat || 00762 I->getKindAsEnum() == Attribute::Naked || 00763 I->getKindAsEnum() == Attribute::InlineHint || 00764 I->getKindAsEnum() == Attribute::StackAlignment || 00765 I->getKindAsEnum() == Attribute::UWTable || 00766 I->getKindAsEnum() == Attribute::NonLazyBind || 00767 I->getKindAsEnum() == Attribute::ReturnsTwice || 00768 I->getKindAsEnum() == Attribute::SanitizeAddress || 00769 I->getKindAsEnum() == Attribute::SanitizeThread || 00770 I->getKindAsEnum() == Attribute::SanitizeMemory || 00771 I->getKindAsEnum() == Attribute::MinSize || 00772 I->getKindAsEnum() == Attribute::NoDuplicate || 00773 I->getKindAsEnum() == Attribute::Builtin || 00774 I->getKindAsEnum() == Attribute::NoBuiltin || 00775 I->getKindAsEnum() == Attribute::Cold || 00776 I->getKindAsEnum() == Attribute::OptimizeNone || 00777 I->getKindAsEnum() == Attribute::JumpTable) { 00778 if (!isFunction) { 00779 CheckFailed("Attribute '" + I->getAsString() + 00780 "' only applies to functions!", V); 00781 return; 00782 } 00783 } else if (I->getKindAsEnum() == Attribute::ReadOnly || 00784 I->getKindAsEnum() == Attribute::ReadNone) { 00785 if (Idx == 0) { 00786 CheckFailed("Attribute '" + I->getAsString() + 00787 "' does not apply to function returns"); 00788 return; 00789 } 00790 } else if (isFunction) { 00791 CheckFailed("Attribute '" + I->getAsString() + 00792 "' does not apply to functions!", V); 00793 return; 00794 } 00795 } 00796 } 00797 00798 // VerifyParameterAttrs - Check the given attributes for an argument or return 00799 // value of the specified type. The value V is printed in error messages. 00800 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 00801 bool isReturnValue, const Value *V) { 00802 if (!Attrs.hasAttributes(Idx)) 00803 return; 00804 00805 VerifyAttributeTypes(Attrs, Idx, false, V); 00806 00807 if (isReturnValue) 00808 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 00809 !Attrs.hasAttribute(Idx, Attribute::Nest) && 00810 !Attrs.hasAttribute(Idx, Attribute::StructRet) && 00811 !Attrs.hasAttribute(Idx, Attribute::NoCapture) && 00812 !Attrs.hasAttribute(Idx, Attribute::Returned) && 00813 !Attrs.hasAttribute(Idx, Attribute::InAlloca), 00814 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and " 00815 "'returned' do not apply to return values!", V); 00816 00817 // Check for mutually incompatible attributes. Only inreg is compatible with 00818 // sret. 00819 unsigned AttrCount = 0; 00820 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal); 00821 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca); 00822 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) || 00823 Attrs.hasAttribute(Idx, Attribute::InReg); 00824 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest); 00825 Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', " 00826 "and 'sret' are incompatible!", V); 00827 00828 Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) && 00829 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes " 00830 "'inalloca and readonly' are incompatible!", V); 00831 00832 Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) && 00833 Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes " 00834 "'sret and returned' are incompatible!", V); 00835 00836 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) && 00837 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes " 00838 "'zeroext and signext' are incompatible!", V); 00839 00840 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) && 00841 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes " 00842 "'readnone and readonly' are incompatible!", V); 00843 00844 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) && 00845 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes " 00846 "'noinline and alwaysinline' are incompatible!", V); 00847 00848 Assert1(!AttrBuilder(Attrs, Idx). 00849 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx), 00850 "Wrong types for attribute: " + 00851 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V); 00852 00853 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) { 00854 if (!PTy->getElementType()->isSized()) { 00855 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 00856 !Attrs.hasAttribute(Idx, Attribute::InAlloca), 00857 "Attributes 'byval' and 'inalloca' do not support unsized types!", 00858 V); 00859 } 00860 } else { 00861 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal), 00862 "Attribute 'byval' only applies to parameters with pointer type!", 00863 V); 00864 } 00865 } 00866 00867 // VerifyFunctionAttrs - Check parameter attributes against a function type. 00868 // The value V is printed in error messages. 00869 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 00870 const Value *V) { 00871 if (Attrs.isEmpty()) 00872 return; 00873 00874 bool SawNest = false; 00875 bool SawReturned = false; 00876 bool SawSRet = false; 00877 00878 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) { 00879 unsigned Idx = Attrs.getSlotIndex(i); 00880 00881 Type *Ty; 00882 if (Idx == 0) 00883 Ty = FT->getReturnType(); 00884 else if (Idx-1 < FT->getNumParams()) 00885 Ty = FT->getParamType(Idx-1); 00886 else 00887 break; // VarArgs attributes, verified elsewhere. 00888 00889 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V); 00890 00891 if (Idx == 0) 00892 continue; 00893 00894 if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 00895 Assert1(!SawNest, "More than one parameter has attribute nest!", V); 00896 SawNest = true; 00897 } 00898 00899 if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 00900 Assert1(!SawReturned, "More than one parameter has attribute returned!", 00901 V); 00902 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible " 00903 "argument and return types for 'returned' attribute", V); 00904 SawReturned = true; 00905 } 00906 00907 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) { 00908 Assert1(!SawSRet, "Cannot have multiple 'sret' parameters!", V); 00909 Assert1(Idx == 1 || Idx == 2, 00910 "Attribute 'sret' is not on first or second parameter!", V); 00911 SawSRet = true; 00912 } 00913 00914 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) { 00915 Assert1(Idx == FT->getNumParams(), 00916 "inalloca isn't on the last parameter!", V); 00917 } 00918 } 00919 00920 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex)) 00921 return; 00922 00923 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V); 00924 00925 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex, 00926 Attribute::ReadNone) && 00927 Attrs.hasAttribute(AttributeSet::FunctionIndex, 00928 Attribute::ReadOnly)), 00929 "Attributes 'readnone and readonly' are incompatible!", V); 00930 00931 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex, 00932 Attribute::NoInline) && 00933 Attrs.hasAttribute(AttributeSet::FunctionIndex, 00934 Attribute::AlwaysInline)), 00935 "Attributes 'noinline and alwaysinline' are incompatible!", V); 00936 00937 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 00938 Attribute::OptimizeNone)) { 00939 Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex, 00940 Attribute::NoInline), 00941 "Attribute 'optnone' requires 'noinline'!", V); 00942 00943 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 00944 Attribute::OptimizeForSize), 00945 "Attributes 'optsize and optnone' are incompatible!", V); 00946 00947 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 00948 Attribute::MinSize), 00949 "Attributes 'minsize and optnone' are incompatible!", V); 00950 } 00951 00952 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 00953 Attribute::JumpTable)) { 00954 const GlobalValue *GV = cast<GlobalValue>(V); 00955 Assert1(GV->hasUnnamedAddr(), 00956 "Attribute 'jumptable' requires 'unnamed_addr'", V); 00957 00958 } 00959 } 00960 00961 void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) { 00962 // Get the size of the types in bits, we'll need this later 00963 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits(); 00964 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits(); 00965 00966 // BitCast implies a no-op cast of type only. No bits change. 00967 // However, you can't cast pointers to anything but pointers. 00968 Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(), 00969 "Bitcast requires both operands to be pointer or neither", V); 00970 Assert1(SrcBitSize == DestBitSize, 00971 "Bitcast requires types of same width", V); 00972 00973 // Disallow aggregates. 00974 Assert1(!SrcTy->isAggregateType(), 00975 "Bitcast operand must not be aggregate", V); 00976 Assert1(!DestTy->isAggregateType(), 00977 "Bitcast type must not be aggregate", V); 00978 00979 // Without datalayout, assume all address spaces are the same size. 00980 // Don't check if both types are not pointers. 00981 // Skip casts between scalars and vectors. 00982 if (!DL || 00983 !SrcTy->isPtrOrPtrVectorTy() || 00984 !DestTy->isPtrOrPtrVectorTy() || 00985 SrcTy->isVectorTy() != DestTy->isVectorTy()) { 00986 return; 00987 } 00988 00989 unsigned SrcAS = SrcTy->getPointerAddressSpace(); 00990 unsigned DstAS = DestTy->getPointerAddressSpace(); 00991 00992 Assert1(SrcAS == DstAS, 00993 "Bitcasts between pointers of different address spaces is not legal." 00994 "Use AddrSpaceCast instead.", V); 00995 } 00996 00997 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) { 00998 if (CE->getOpcode() == Instruction::BitCast) { 00999 Type *SrcTy = CE->getOperand(0)->getType(); 01000 Type *DstTy = CE->getType(); 01001 VerifyBitcastType(CE, DstTy, SrcTy); 01002 } 01003 } 01004 01005 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) { 01006 if (Attrs.getNumSlots() == 0) 01007 return true; 01008 01009 unsigned LastSlot = Attrs.getNumSlots() - 1; 01010 unsigned LastIndex = Attrs.getSlotIndex(LastSlot); 01011 if (LastIndex <= Params 01012 || (LastIndex == AttributeSet::FunctionIndex 01013 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params))) 01014 return true; 01015 01016 return false; 01017 } 01018 01019 // visitFunction - Verify that a function is ok. 01020 // 01021 void Verifier::visitFunction(const Function &F) { 01022 // Check function arguments. 01023 FunctionType *FT = F.getFunctionType(); 01024 unsigned NumArgs = F.arg_size(); 01025 01026 Assert1(Context == &F.getContext(), 01027 "Function context does not match Module context!", &F); 01028 01029 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 01030 Assert2(FT->getNumParams() == NumArgs, 01031 "# formal arguments must match # of arguments for function type!", 01032 &F, FT); 01033 Assert1(F.getReturnType()->isFirstClassType() || 01034 F.getReturnType()->isVoidTy() || 01035 F.getReturnType()->isStructTy(), 01036 "Functions cannot return aggregate values!", &F); 01037 01038 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 01039 "Invalid struct return type!", &F); 01040 01041 AttributeSet Attrs = F.getAttributes(); 01042 01043 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()), 01044 "Attribute after last parameter!", &F); 01045 01046 // Check function attributes. 01047 VerifyFunctionAttrs(FT, Attrs, &F); 01048 01049 // On function declarations/definitions, we do not support the builtin 01050 // attribute. We do not check this in VerifyFunctionAttrs since that is 01051 // checking for Attributes that can/can not ever be on functions. 01052 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 01053 Attribute::Builtin), 01054 "Attribute 'builtin' can only be applied to a callsite.", &F); 01055 01056 // Check that this function meets the restrictions on this calling convention. 01057 // Sometimes varargs is used for perfectly forwarding thunks, so some of these 01058 // restrictions can be lifted. 01059 switch (F.getCallingConv()) { 01060 default: 01061 case CallingConv::C: 01062 break; 01063 case CallingConv::Fast: 01064 case CallingConv::Cold: 01065 case CallingConv::Intel_OCL_BI: 01066 case CallingConv::PTX_Kernel: 01067 case CallingConv::PTX_Device: 01068 Assert1(!F.isVarArg(), "Calling convention does not support varargs or " 01069 "perfect forwarding!", &F); 01070 break; 01071 } 01072 01073 bool isLLVMdotName = F.getName().size() >= 5 && 01074 F.getName().substr(0, 5) == "llvm."; 01075 01076 // Check that the argument values match the function type for this function... 01077 unsigned i = 0; 01078 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 01079 ++I, ++i) { 01080 Assert2(I->getType() == FT->getParamType(i), 01081 "Argument value does not match function argument type!", 01082 I, FT->getParamType(i)); 01083 Assert1(I->getType()->isFirstClassType(), 01084 "Function arguments must have first-class types!", I); 01085 if (!isLLVMdotName) 01086 Assert2(!I->getType()->isMetadataTy(), 01087 "Function takes metadata but isn't an intrinsic", I, &F); 01088 } 01089 01090 if (F.isMaterializable()) { 01091 // Function has a body somewhere we can't see. 01092 } else if (F.isDeclaration()) { 01093 Assert1(F.hasExternalLinkage() || F.hasExternalWeakLinkage(), 01094 "invalid linkage type for function declaration", &F); 01095 } else { 01096 // Verify that this function (which has a body) is not named "llvm.*". It 01097 // is not legal to define intrinsics. 01098 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 01099 01100 // Check the entry node 01101 const BasicBlock *Entry = &F.getEntryBlock(); 01102 Assert1(pred_begin(Entry) == pred_end(Entry), 01103 "Entry block to function must not have predecessors!", Entry); 01104 01105 // The address of the entry block cannot be taken, unless it is dead. 01106 if (Entry->hasAddressTaken()) { 01107 Assert1(!BlockAddress::lookup(Entry)->isConstantUsed(), 01108 "blockaddress may not be used with the entry block!", Entry); 01109 } 01110 } 01111 01112 // If this function is actually an intrinsic, verify that it is only used in 01113 // direct call/invokes, never having its "address taken". 01114 if (F.getIntrinsicID()) { 01115 const User *U; 01116 if (F.hasAddressTaken(&U)) 01117 Assert1(0, "Invalid user of intrinsic instruction!", U); 01118 } 01119 01120 Assert1(!F.hasDLLImportStorageClass() || 01121 (F.isDeclaration() && F.hasExternalLinkage()) || 01122 F.hasAvailableExternallyLinkage(), 01123 "Function is marked as dllimport, but not external.", &F); 01124 } 01125 01126 // verifyBasicBlock - Verify that a basic block is well formed... 01127 // 01128 void Verifier::visitBasicBlock(BasicBlock &BB) { 01129 InstsInThisBlock.clear(); 01130 01131 // Ensure that basic blocks have terminators! 01132 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 01133 01134 // Check constraints that this basic block imposes on all of the PHI nodes in 01135 // it. 01136 if (isa<PHINode>(BB.front())) { 01137 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB)); 01138 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 01139 std::sort(Preds.begin(), Preds.end()); 01140 PHINode *PN; 01141 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) { 01142 // Ensure that PHI nodes have at least one entry! 01143 Assert1(PN->getNumIncomingValues() != 0, 01144 "PHI nodes must have at least one entry. If the block is dead, " 01145 "the PHI should be removed!", PN); 01146 Assert1(PN->getNumIncomingValues() == Preds.size(), 01147 "PHINode should have one entry for each predecessor of its " 01148 "parent basic block!", PN); 01149 01150 // Get and sort all incoming values in the PHI node... 01151 Values.clear(); 01152 Values.reserve(PN->getNumIncomingValues()); 01153 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 01154 Values.push_back(std::make_pair(PN->getIncomingBlock(i), 01155 PN->getIncomingValue(i))); 01156 std::sort(Values.begin(), Values.end()); 01157 01158 for (unsigned i = 0, e = Values.size(); i != e; ++i) { 01159 // Check to make sure that if there is more than one entry for a 01160 // particular basic block in this PHI node, that the incoming values are 01161 // all identical. 01162 // 01163 Assert4(i == 0 || Values[i].first != Values[i-1].first || 01164 Values[i].second == Values[i-1].second, 01165 "PHI node has multiple entries for the same basic block with " 01166 "different incoming values!", PN, Values[i].first, 01167 Values[i].second, Values[i-1].second); 01168 01169 // Check to make sure that the predecessors and PHI node entries are 01170 // matched up. 01171 Assert3(Values[i].first == Preds[i], 01172 "PHI node entries do not match predecessors!", PN, 01173 Values[i].first, Preds[i]); 01174 } 01175 } 01176 } 01177 } 01178 01179 void Verifier::visitTerminatorInst(TerminatorInst &I) { 01180 // Ensure that terminators only exist at the end of the basic block. 01181 Assert1(&I == I.getParent()->getTerminator(), 01182 "Terminator found in the middle of a basic block!", I.getParent()); 01183 visitInstruction(I); 01184 } 01185 01186 void Verifier::visitBranchInst(BranchInst &BI) { 01187 if (BI.isConditional()) { 01188 Assert2(BI.getCondition()->getType()->isIntegerTy(1), 01189 "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 01190 } 01191 visitTerminatorInst(BI); 01192 } 01193 01194 void Verifier::visitReturnInst(ReturnInst &RI) { 01195 Function *F = RI.getParent()->getParent(); 01196 unsigned N = RI.getNumOperands(); 01197 if (F->getReturnType()->isVoidTy()) 01198 Assert2(N == 0, 01199 "Found return instr that returns non-void in Function of void " 01200 "return type!", &RI, F->getReturnType()); 01201 else 01202 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 01203 "Function return type does not match operand " 01204 "type of return inst!", &RI, F->getReturnType()); 01205 01206 // Check to make sure that the return value has necessary properties for 01207 // terminators... 01208 visitTerminatorInst(RI); 01209 } 01210 01211 void Verifier::visitSwitchInst(SwitchInst &SI) { 01212 // Check to make sure that all of the constants in the switch instruction 01213 // have the same type as the switched-on value. 01214 Type *SwitchTy = SI.getCondition()->getType(); 01215 SmallPtrSet<ConstantInt*, 32> Constants; 01216 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) { 01217 Assert1(i.getCaseValue()->getType() == SwitchTy, 01218 "Switch constants must all be same type as switch value!", &SI); 01219 Assert2(Constants.insert(i.getCaseValue()), 01220 "Duplicate integer as switch case", &SI, i.getCaseValue()); 01221 } 01222 01223 visitTerminatorInst(SI); 01224 } 01225 01226 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 01227 Assert1(BI.getAddress()->getType()->isPointerTy(), 01228 "Indirectbr operand must have pointer type!", &BI); 01229 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 01230 Assert1(BI.getDestination(i)->getType()->isLabelTy(), 01231 "Indirectbr destinations must all have pointer type!", &BI); 01232 01233 visitTerminatorInst(BI); 01234 } 01235 01236 void Verifier::visitSelectInst(SelectInst &SI) { 01237 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 01238 SI.getOperand(2)), 01239 "Invalid operands for select instruction!", &SI); 01240 01241 Assert1(SI.getTrueValue()->getType() == SI.getType(), 01242 "Select values must have same type as select instruction!", &SI); 01243 visitInstruction(SI); 01244 } 01245 01246 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 01247 /// a pass, if any exist, it's an error. 01248 /// 01249 void Verifier::visitUserOp1(Instruction &I) { 01250 Assert1(0, "User-defined operators should not live outside of a pass!", &I); 01251 } 01252 01253 void Verifier::visitTruncInst(TruncInst &I) { 01254 // Get the source and destination types 01255 Type *SrcTy = I.getOperand(0)->getType(); 01256 Type *DestTy = I.getType(); 01257 01258 // Get the size of the types in bits, we'll need this later 01259 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 01260 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 01261 01262 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 01263 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 01264 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 01265 "trunc source and destination must both be a vector or neither", &I); 01266 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I); 01267 01268 visitInstruction(I); 01269 } 01270 01271 void Verifier::visitZExtInst(ZExtInst &I) { 01272 // Get the source and destination types 01273 Type *SrcTy = I.getOperand(0)->getType(); 01274 Type *DestTy = I.getType(); 01275 01276 // Get the size of the types in bits, we'll need this later 01277 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 01278 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 01279 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 01280 "zext source and destination must both be a vector or neither", &I); 01281 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 01282 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 01283 01284 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I); 01285 01286 visitInstruction(I); 01287 } 01288 01289 void Verifier::visitSExtInst(SExtInst &I) { 01290 // Get the source and destination types 01291 Type *SrcTy = I.getOperand(0)->getType(); 01292 Type *DestTy = I.getType(); 01293 01294 // Get the size of the types in bits, we'll need this later 01295 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 01296 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 01297 01298 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 01299 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 01300 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 01301 "sext source and destination must both be a vector or neither", &I); 01302 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I); 01303 01304 visitInstruction(I); 01305 } 01306 01307 void Verifier::visitFPTruncInst(FPTruncInst &I) { 01308 // Get the source and destination types 01309 Type *SrcTy = I.getOperand(0)->getType(); 01310 Type *DestTy = I.getType(); 01311 // Get the size of the types in bits, we'll need this later 01312 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 01313 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 01314 01315 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I); 01316 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I); 01317 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 01318 "fptrunc source and destination must both be a vector or neither",&I); 01319 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I); 01320 01321 visitInstruction(I); 01322 } 01323 01324 void Verifier::visitFPExtInst(FPExtInst &I) { 01325 // Get the source and destination types 01326 Type *SrcTy = I.getOperand(0)->getType(); 01327 Type *DestTy = I.getType(); 01328 01329 // Get the size of the types in bits, we'll need this later 01330 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 01331 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 01332 01333 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I); 01334 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I); 01335 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 01336 "fpext source and destination must both be a vector or neither", &I); 01337 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I); 01338 01339 visitInstruction(I); 01340 } 01341 01342 void Verifier::visitUIToFPInst(UIToFPInst &I) { 01343 // Get the source and destination types 01344 Type *SrcTy = I.getOperand(0)->getType(); 01345 Type *DestTy = I.getType(); 01346 01347 bool SrcVec = SrcTy->isVectorTy(); 01348 bool DstVec = DestTy->isVectorTy(); 01349 01350 Assert1(SrcVec == DstVec, 01351 "UIToFP source and dest must both be vector or scalar", &I); 01352 Assert1(SrcTy->isIntOrIntVectorTy(), 01353 "UIToFP source must be integer or integer vector", &I); 01354 Assert1(DestTy->isFPOrFPVectorTy(), 01355 "UIToFP result must be FP or FP vector", &I); 01356 01357 if (SrcVec && DstVec) 01358 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 01359 cast<VectorType>(DestTy)->getNumElements(), 01360 "UIToFP source and dest vector length mismatch", &I); 01361 01362 visitInstruction(I); 01363 } 01364 01365 void Verifier::visitSIToFPInst(SIToFPInst &I) { 01366 // Get the source and destination types 01367 Type *SrcTy = I.getOperand(0)->getType(); 01368 Type *DestTy = I.getType(); 01369 01370 bool SrcVec = SrcTy->isVectorTy(); 01371 bool DstVec = DestTy->isVectorTy(); 01372 01373 Assert1(SrcVec == DstVec, 01374 "SIToFP source and dest must both be vector or scalar", &I); 01375 Assert1(SrcTy->isIntOrIntVectorTy(), 01376 "SIToFP source must be integer or integer vector", &I); 01377 Assert1(DestTy->isFPOrFPVectorTy(), 01378 "SIToFP result must be FP or FP vector", &I); 01379 01380 if (SrcVec && DstVec) 01381 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 01382 cast<VectorType>(DestTy)->getNumElements(), 01383 "SIToFP source and dest vector length mismatch", &I); 01384 01385 visitInstruction(I); 01386 } 01387 01388 void Verifier::visitFPToUIInst(FPToUIInst &I) { 01389 // Get the source and destination types 01390 Type *SrcTy = I.getOperand(0)->getType(); 01391 Type *DestTy = I.getType(); 01392 01393 bool SrcVec = SrcTy->isVectorTy(); 01394 bool DstVec = DestTy->isVectorTy(); 01395 01396 Assert1(SrcVec == DstVec, 01397 "FPToUI source and dest must both be vector or scalar", &I); 01398 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 01399 &I); 01400 Assert1(DestTy->isIntOrIntVectorTy(), 01401 "FPToUI result must be integer or integer vector", &I); 01402 01403 if (SrcVec && DstVec) 01404 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 01405 cast<VectorType>(DestTy)->getNumElements(), 01406 "FPToUI source and dest vector length mismatch", &I); 01407 01408 visitInstruction(I); 01409 } 01410 01411 void Verifier::visitFPToSIInst(FPToSIInst &I) { 01412 // Get the source and destination types 01413 Type *SrcTy = I.getOperand(0)->getType(); 01414 Type *DestTy = I.getType(); 01415 01416 bool SrcVec = SrcTy->isVectorTy(); 01417 bool DstVec = DestTy->isVectorTy(); 01418 01419 Assert1(SrcVec == DstVec, 01420 "FPToSI source and dest must both be vector or scalar", &I); 01421 Assert1(SrcTy->isFPOrFPVectorTy(), 01422 "FPToSI source must be FP or FP vector", &I); 01423 Assert1(DestTy->isIntOrIntVectorTy(), 01424 "FPToSI result must be integer or integer vector", &I); 01425 01426 if (SrcVec && DstVec) 01427 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 01428 cast<VectorType>(DestTy)->getNumElements(), 01429 "FPToSI source and dest vector length mismatch", &I); 01430 01431 visitInstruction(I); 01432 } 01433 01434 void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 01435 // Get the source and destination types 01436 Type *SrcTy = I.getOperand(0)->getType(); 01437 Type *DestTy = I.getType(); 01438 01439 Assert1(SrcTy->getScalarType()->isPointerTy(), 01440 "PtrToInt source must be pointer", &I); 01441 Assert1(DestTy->getScalarType()->isIntegerTy(), 01442 "PtrToInt result must be integral", &I); 01443 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 01444 "PtrToInt type mismatch", &I); 01445 01446 if (SrcTy->isVectorTy()) { 01447 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 01448 VectorType *VDest = dyn_cast<VectorType>(DestTy); 01449 Assert1(VSrc->getNumElements() == VDest->getNumElements(), 01450 "PtrToInt Vector width mismatch", &I); 01451 } 01452 01453 visitInstruction(I); 01454 } 01455 01456 void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 01457 // Get the source and destination types 01458 Type *SrcTy = I.getOperand(0)->getType(); 01459 Type *DestTy = I.getType(); 01460 01461 Assert1(SrcTy->getScalarType()->isIntegerTy(), 01462 "IntToPtr source must be an integral", &I); 01463 Assert1(DestTy->getScalarType()->isPointerTy(), 01464 "IntToPtr result must be a pointer",&I); 01465 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 01466 "IntToPtr type mismatch", &I); 01467 if (SrcTy->isVectorTy()) { 01468 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 01469 VectorType *VDest = dyn_cast<VectorType>(DestTy); 01470 Assert1(VSrc->getNumElements() == VDest->getNumElements(), 01471 "IntToPtr Vector width mismatch", &I); 01472 } 01473 visitInstruction(I); 01474 } 01475 01476 void Verifier::visitBitCastInst(BitCastInst &I) { 01477 Type *SrcTy = I.getOperand(0)->getType(); 01478 Type *DestTy = I.getType(); 01479 VerifyBitcastType(&I, DestTy, SrcTy); 01480 visitInstruction(I); 01481 } 01482 01483 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 01484 Type *SrcTy = I.getOperand(0)->getType(); 01485 Type *DestTy = I.getType(); 01486 01487 Assert1(SrcTy->isPtrOrPtrVectorTy(), 01488 "AddrSpaceCast source must be a pointer", &I); 01489 Assert1(DestTy->isPtrOrPtrVectorTy(), 01490 "AddrSpaceCast result must be a pointer", &I); 01491 Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 01492 "AddrSpaceCast must be between different address spaces", &I); 01493 if (SrcTy->isVectorTy()) 01494 Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(), 01495 "AddrSpaceCast vector pointer number of elements mismatch", &I); 01496 visitInstruction(I); 01497 } 01498 01499 /// visitPHINode - Ensure that a PHI node is well formed. 01500 /// 01501 void Verifier::visitPHINode(PHINode &PN) { 01502 // Ensure that the PHI nodes are all grouped together at the top of the block. 01503 // This can be tested by checking whether the instruction before this is 01504 // either nonexistent (because this is begin()) or is a PHI node. If not, 01505 // then there is some other instruction before a PHI. 01506 Assert2(&PN == &PN.getParent()->front() || 01507 isa<PHINode>(--BasicBlock::iterator(&PN)), 01508 "PHI nodes not grouped at top of basic block!", 01509 &PN, PN.getParent()); 01510 01511 // Check that all of the values of the PHI node have the same type as the 01512 // result, and that the incoming blocks are really basic blocks. 01513 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 01514 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(), 01515 "PHI node operands are not the same type as the result!", &PN); 01516 } 01517 01518 // All other PHI node constraints are checked in the visitBasicBlock method. 01519 01520 visitInstruction(PN); 01521 } 01522 01523 void Verifier::VerifyCallSite(CallSite CS) { 01524 Instruction *I = CS.getInstruction(); 01525 01526 Assert1(CS.getCalledValue()->getType()->isPointerTy(), 01527 "Called function must be a pointer!", I); 01528 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType()); 01529 01530 Assert1(FPTy->getElementType()->isFunctionTy(), 01531 "Called function is not pointer to function type!", I); 01532 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType()); 01533 01534 // Verify that the correct number of arguments are being passed 01535 if (FTy->isVarArg()) 01536 Assert1(CS.arg_size() >= FTy->getNumParams(), 01537 "Called function requires more parameters than were provided!",I); 01538 else 01539 Assert1(CS.arg_size() == FTy->getNumParams(), 01540 "Incorrect number of arguments passed to called function!", I); 01541 01542 // Verify that all arguments to the call match the function type. 01543 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 01544 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i), 01545 "Call parameter type does not match function signature!", 01546 CS.getArgument(i), FTy->getParamType(i), I); 01547 01548 AttributeSet Attrs = CS.getAttributes(); 01549 01550 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()), 01551 "Attribute after last parameter!", I); 01552 01553 // Verify call attributes. 01554 VerifyFunctionAttrs(FTy, Attrs, I); 01555 01556 // Conservatively check the inalloca argument. 01557 // We have a bug if we can find that there is an underlying alloca without 01558 // inalloca. 01559 if (CS.hasInAllocaArgument()) { 01560 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1); 01561 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets())) 01562 Assert2(AI->isUsedWithInAlloca(), 01563 "inalloca argument for call has mismatched alloca", AI, I); 01564 } 01565 01566 if (FTy->isVarArg()) { 01567 // FIXME? is 'nest' even legal here? 01568 bool SawNest = false; 01569 bool SawReturned = false; 01570 01571 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) { 01572 if (Attrs.hasAttribute(Idx, Attribute::Nest)) 01573 SawNest = true; 01574 if (Attrs.hasAttribute(Idx, Attribute::Returned)) 01575 SawReturned = true; 01576 } 01577 01578 // Check attributes on the varargs part. 01579 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) { 01580 Type *Ty = CS.getArgument(Idx-1)->getType(); 01581 VerifyParameterAttrs(Attrs, Idx, Ty, false, I); 01582 01583 if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 01584 Assert1(!SawNest, "More than one parameter has attribute nest!", I); 01585 SawNest = true; 01586 } 01587 01588 if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 01589 Assert1(!SawReturned, "More than one parameter has attribute returned!", 01590 I); 01591 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 01592 "Incompatible argument and return types for 'returned' " 01593 "attribute", I); 01594 SawReturned = true; 01595 } 01596 01597 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet), 01598 "Attribute 'sret' cannot be used for vararg call arguments!", I); 01599 01600 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) 01601 Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!", 01602 I); 01603 } 01604 } 01605 01606 // Verify that there's no metadata unless it's a direct call to an intrinsic. 01607 if (CS.getCalledFunction() == nullptr || 01608 !CS.getCalledFunction()->getName().startswith("llvm.")) { 01609 for (FunctionType::param_iterator PI = FTy->param_begin(), 01610 PE = FTy->param_end(); PI != PE; ++PI) 01611 Assert1(!(*PI)->isMetadataTy(), 01612 "Function has metadata parameter but isn't an intrinsic", I); 01613 } 01614 01615 visitInstruction(*I); 01616 } 01617 01618 /// Two types are "congruent" if they are identical, or if they are both pointer 01619 /// types with different pointee types and the same address space. 01620 static bool isTypeCongruent(Type *L, Type *R) { 01621 if (L == R) 01622 return true; 01623 PointerType *PL = dyn_cast<PointerType>(L); 01624 PointerType *PR = dyn_cast<PointerType>(R); 01625 if (!PL || !PR) 01626 return false; 01627 return PL->getAddressSpace() == PR->getAddressSpace(); 01628 } 01629 01630 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) { 01631 static const Attribute::AttrKind ABIAttrs[] = { 01632 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 01633 Attribute::InReg, Attribute::Returned}; 01634 AttrBuilder Copy; 01635 for (auto AK : ABIAttrs) { 01636 if (Attrs.hasAttribute(I + 1, AK)) 01637 Copy.addAttribute(AK); 01638 } 01639 if (Attrs.hasAttribute(I + 1, Attribute::Alignment)) 01640 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1)); 01641 return Copy; 01642 } 01643 01644 void Verifier::verifyMustTailCall(CallInst &CI) { 01645 Assert1(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI); 01646 01647 // - The caller and callee prototypes must match. Pointer types of 01648 // parameters or return types may differ in pointee type, but not 01649 // address space. 01650 Function *F = CI.getParent()->getParent(); 01651 auto GetFnTy = [](Value *V) { 01652 return cast<FunctionType>( 01653 cast<PointerType>(V->getType())->getElementType()); 01654 }; 01655 FunctionType *CallerTy = GetFnTy(F); 01656 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue()); 01657 Assert1(CallerTy->getNumParams() == CalleeTy->getNumParams(), 01658 "cannot guarantee tail call due to mismatched parameter counts", &CI); 01659 Assert1(CallerTy->isVarArg() == CalleeTy->isVarArg(), 01660 "cannot guarantee tail call due to mismatched varargs", &CI); 01661 Assert1(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()), 01662 "cannot guarantee tail call due to mismatched return types", &CI); 01663 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 01664 Assert1( 01665 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)), 01666 "cannot guarantee tail call due to mismatched parameter types", &CI); 01667 } 01668 01669 // - The calling conventions of the caller and callee must match. 01670 Assert1(F->getCallingConv() == CI.getCallingConv(), 01671 "cannot guarantee tail call due to mismatched calling conv", &CI); 01672 01673 // - All ABI-impacting function attributes, such as sret, byval, inreg, 01674 // returned, and inalloca, must match. 01675 AttributeSet CallerAttrs = F->getAttributes(); 01676 AttributeSet CalleeAttrs = CI.getAttributes(); 01677 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 01678 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs); 01679 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 01680 Assert2(CallerABIAttrs == CalleeABIAttrs, 01681 "cannot guarantee tail call due to mismatched ABI impacting " 01682 "function attributes", &CI, CI.getOperand(I)); 01683 } 01684 01685 // - The call must immediately precede a :ref:`ret <i_ret>` instruction, 01686 // or a pointer bitcast followed by a ret instruction. 01687 // - The ret instruction must return the (possibly bitcasted) value 01688 // produced by the call or void. 01689 Value *RetVal = &CI; 01690 Instruction *Next = CI.getNextNode(); 01691 01692 // Handle the optional bitcast. 01693 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) { 01694 Assert1(BI->getOperand(0) == RetVal, 01695 "bitcast following musttail call must use the call", BI); 01696 RetVal = BI; 01697 Next = BI->getNextNode(); 01698 } 01699 01700 // Check the return. 01701 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 01702 Assert1(Ret, "musttail call must be precede a ret with an optional bitcast", 01703 &CI); 01704 Assert1(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal, 01705 "musttail call result must be returned", Ret); 01706 } 01707 01708 void Verifier::visitCallInst(CallInst &CI) { 01709 VerifyCallSite(&CI); 01710 01711 if (CI.isMustTailCall()) 01712 verifyMustTailCall(CI); 01713 01714 if (Function *F = CI.getCalledFunction()) 01715 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 01716 visitIntrinsicFunctionCall(ID, CI); 01717 } 01718 01719 void Verifier::visitInvokeInst(InvokeInst &II) { 01720 VerifyCallSite(&II); 01721 01722 // Verify that there is a landingpad instruction as the first non-PHI 01723 // instruction of the 'unwind' destination. 01724 Assert1(II.getUnwindDest()->isLandingPad(), 01725 "The unwind destination does not have a landingpad instruction!",&II); 01726 01727 visitTerminatorInst(II); 01728 } 01729 01730 /// visitBinaryOperator - Check that both arguments to the binary operator are 01731 /// of the same type! 01732 /// 01733 void Verifier::visitBinaryOperator(BinaryOperator &B) { 01734 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 01735 "Both operands to a binary operator are not of the same type!", &B); 01736 01737 switch (B.getOpcode()) { 01738 // Check that integer arithmetic operators are only used with 01739 // integral operands. 01740 case Instruction::Add: 01741 case Instruction::Sub: 01742 case Instruction::Mul: 01743 case Instruction::SDiv: 01744 case Instruction::UDiv: 01745 case Instruction::SRem: 01746 case Instruction::URem: 01747 Assert1(B.getType()->isIntOrIntVectorTy(), 01748 "Integer arithmetic operators only work with integral types!", &B); 01749 Assert1(B.getType() == B.getOperand(0)->getType(), 01750 "Integer arithmetic operators must have same type " 01751 "for operands and result!", &B); 01752 break; 01753 // Check that floating-point arithmetic operators are only used with 01754 // floating-point operands. 01755 case Instruction::FAdd: 01756 case Instruction::FSub: 01757 case Instruction::FMul: 01758 case Instruction::FDiv: 01759 case Instruction::FRem: 01760 Assert1(B.getType()->isFPOrFPVectorTy(), 01761 "Floating-point arithmetic operators only work with " 01762 "floating-point types!", &B); 01763 Assert1(B.getType() == B.getOperand(0)->getType(), 01764 "Floating-point arithmetic operators must have same type " 01765 "for operands and result!", &B); 01766 break; 01767 // Check that logical operators are only used with integral operands. 01768 case Instruction::And: 01769 case Instruction::Or: 01770 case Instruction::Xor: 01771 Assert1(B.getType()->isIntOrIntVectorTy(), 01772 "Logical operators only work with integral types!", &B); 01773 Assert1(B.getType() == B.getOperand(0)->getType(), 01774 "Logical operators must have same type for operands and result!", 01775 &B); 01776 break; 01777 case Instruction::Shl: 01778 case Instruction::LShr: 01779 case Instruction::AShr: 01780 Assert1(B.getType()->isIntOrIntVectorTy(), 01781 "Shifts only work with integral types!", &B); 01782 Assert1(B.getType() == B.getOperand(0)->getType(), 01783 "Shift return type must be same as operands!", &B); 01784 break; 01785 default: 01786 llvm_unreachable("Unknown BinaryOperator opcode!"); 01787 } 01788 01789 visitInstruction(B); 01790 } 01791 01792 void Verifier::visitICmpInst(ICmpInst &IC) { 01793 // Check that the operands are the same type 01794 Type *Op0Ty = IC.getOperand(0)->getType(); 01795 Type *Op1Ty = IC.getOperand(1)->getType(); 01796 Assert1(Op0Ty == Op1Ty, 01797 "Both operands to ICmp instruction are not of the same type!", &IC); 01798 // Check that the operands are the right type 01799 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(), 01800 "Invalid operand types for ICmp instruction", &IC); 01801 // Check that the predicate is valid. 01802 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE && 01803 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE, 01804 "Invalid predicate in ICmp instruction!", &IC); 01805 01806 visitInstruction(IC); 01807 } 01808 01809 void Verifier::visitFCmpInst(FCmpInst &FC) { 01810 // Check that the operands are the same type 01811 Type *Op0Ty = FC.getOperand(0)->getType(); 01812 Type *Op1Ty = FC.getOperand(1)->getType(); 01813 Assert1(Op0Ty == Op1Ty, 01814 "Both operands to FCmp instruction are not of the same type!", &FC); 01815 // Check that the operands are the right type 01816 Assert1(Op0Ty->isFPOrFPVectorTy(), 01817 "Invalid operand types for FCmp instruction", &FC); 01818 // Check that the predicate is valid. 01819 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE && 01820 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE, 01821 "Invalid predicate in FCmp instruction!", &FC); 01822 01823 visitInstruction(FC); 01824 } 01825 01826 void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 01827 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0), 01828 EI.getOperand(1)), 01829 "Invalid extractelement operands!", &EI); 01830 visitInstruction(EI); 01831 } 01832 01833 void Verifier::visitInsertElementInst(InsertElementInst &IE) { 01834 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0), 01835 IE.getOperand(1), 01836 IE.getOperand(2)), 01837 "Invalid insertelement operands!", &IE); 01838 visitInstruction(IE); 01839 } 01840 01841 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 01842 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 01843 SV.getOperand(2)), 01844 "Invalid shufflevector operands!", &SV); 01845 visitInstruction(SV); 01846 } 01847 01848 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 01849 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 01850 01851 Assert1(isa<PointerType>(TargetTy), 01852 "GEP base pointer is not a vector or a vector of pointers", &GEP); 01853 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(), 01854 "GEP into unsized type!", &GEP); 01855 Assert1(GEP.getPointerOperandType()->isVectorTy() == 01856 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value", 01857 &GEP); 01858 01859 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end()); 01860 Type *ElTy = 01861 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs); 01862 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP); 01863 01864 Assert2(GEP.getType()->getScalarType()->isPointerTy() && 01865 cast<PointerType>(GEP.getType()->getScalarType())->getElementType() 01866 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy); 01867 01868 if (GEP.getPointerOperandType()->isVectorTy()) { 01869 // Additional checks for vector GEPs. 01870 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements(); 01871 Assert1(GepWidth == GEP.getType()->getVectorNumElements(), 01872 "Vector GEP result width doesn't match operand's", &GEP); 01873 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) { 01874 Type *IndexTy = Idxs[i]->getType(); 01875 Assert1(IndexTy->isVectorTy(), 01876 "Vector GEP must have vector indices!", &GEP); 01877 unsigned IndexWidth = IndexTy->getVectorNumElements(); 01878 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP); 01879 } 01880 } 01881 visitInstruction(GEP); 01882 } 01883 01884 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 01885 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 01886 } 01887 01888 void Verifier::visitLoadInst(LoadInst &LI) { 01889 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 01890 Assert1(PTy, "Load operand must be a pointer.", &LI); 01891 Type *ElTy = PTy->getElementType(); 01892 Assert2(ElTy == LI.getType(), 01893 "Load result type does not match pointer operand type!", &LI, ElTy); 01894 Assert1(LI.getAlignment() <= Value::MaximumAlignment, 01895 "huge alignment values are unsupported", &LI); 01896 if (LI.isAtomic()) { 01897 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease, 01898 "Load cannot have Release ordering", &LI); 01899 Assert1(LI.getAlignment() != 0, 01900 "Atomic load must specify explicit alignment", &LI); 01901 if (!ElTy->isPointerTy()) { 01902 Assert2(ElTy->isIntegerTy(), 01903 "atomic load operand must have integer type!", 01904 &LI, ElTy); 01905 unsigned Size = ElTy->getPrimitiveSizeInBits(); 01906 Assert2(Size >= 8 && !(Size & (Size - 1)), 01907 "atomic load operand must be power-of-two byte-sized integer", 01908 &LI, ElTy); 01909 } 01910 } else { 01911 Assert1(LI.getSynchScope() == CrossThread, 01912 "Non-atomic load cannot have SynchronizationScope specified", &LI); 01913 } 01914 01915 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) { 01916 unsigned NumOperands = Range->getNumOperands(); 01917 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range); 01918 unsigned NumRanges = NumOperands / 2; 01919 Assert1(NumRanges >= 1, "It should have at least one range!", Range); 01920 01921 ConstantRange LastRange(1); // Dummy initial value 01922 for (unsigned i = 0; i < NumRanges; ++i) { 01923 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i)); 01924 Assert1(Low, "The lower limit must be an integer!", Low); 01925 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1)); 01926 Assert1(High, "The upper limit must be an integer!", High); 01927 Assert1(High->getType() == Low->getType() && 01928 High->getType() == ElTy, "Range types must match load type!", 01929 &LI); 01930 01931 APInt HighV = High->getValue(); 01932 APInt LowV = Low->getValue(); 01933 ConstantRange CurRange(LowV, HighV); 01934 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(), 01935 "Range must not be empty!", Range); 01936 if (i != 0) { 01937 Assert1(CurRange.intersectWith(LastRange).isEmptySet(), 01938 "Intervals are overlapping", Range); 01939 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 01940 Range); 01941 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 01942 Range); 01943 } 01944 LastRange = ConstantRange(LowV, HighV); 01945 } 01946 if (NumRanges > 2) { 01947 APInt FirstLow = 01948 dyn_cast<ConstantInt>(Range->getOperand(0))->getValue(); 01949 APInt FirstHigh = 01950 dyn_cast<ConstantInt>(Range->getOperand(1))->getValue(); 01951 ConstantRange FirstRange(FirstLow, FirstHigh); 01952 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(), 01953 "Intervals are overlapping", Range); 01954 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 01955 Range); 01956 } 01957 01958 01959 } 01960 01961 visitInstruction(LI); 01962 } 01963 01964 void Verifier::visitStoreInst(StoreInst &SI) { 01965 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 01966 Assert1(PTy, "Store operand must be a pointer.", &SI); 01967 Type *ElTy = PTy->getElementType(); 01968 Assert2(ElTy == SI.getOperand(0)->getType(), 01969 "Stored value type does not match pointer operand type!", 01970 &SI, ElTy); 01971 Assert1(SI.getAlignment() <= Value::MaximumAlignment, 01972 "huge alignment values are unsupported", &SI); 01973 if (SI.isAtomic()) { 01974 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease, 01975 "Store cannot have Acquire ordering", &SI); 01976 Assert1(SI.getAlignment() != 0, 01977 "Atomic store must specify explicit alignment", &SI); 01978 if (!ElTy->isPointerTy()) { 01979 Assert2(ElTy->isIntegerTy(), 01980 "atomic store operand must have integer type!", 01981 &SI, ElTy); 01982 unsigned Size = ElTy->getPrimitiveSizeInBits(); 01983 Assert2(Size >= 8 && !(Size & (Size - 1)), 01984 "atomic store operand must be power-of-two byte-sized integer", 01985 &SI, ElTy); 01986 } 01987 } else { 01988 Assert1(SI.getSynchScope() == CrossThread, 01989 "Non-atomic store cannot have SynchronizationScope specified", &SI); 01990 } 01991 visitInstruction(SI); 01992 } 01993 01994 void Verifier::visitAllocaInst(AllocaInst &AI) { 01995 SmallPtrSet<const Type*, 4> Visited; 01996 PointerType *PTy = AI.getType(); 01997 Assert1(PTy->getAddressSpace() == 0, 01998 "Allocation instruction pointer not in the generic address space!", 01999 &AI); 02000 Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type", 02001 &AI); 02002 Assert1(AI.getArraySize()->getType()->isIntegerTy(), 02003 "Alloca array size must have integer type", &AI); 02004 Assert1(AI.getAlignment() <= Value::MaximumAlignment, 02005 "huge alignment values are unsupported", &AI); 02006 02007 visitInstruction(AI); 02008 } 02009 02010 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 02011 02012 // FIXME: more conditions??? 02013 Assert1(CXI.getSuccessOrdering() != NotAtomic, 02014 "cmpxchg instructions must be atomic.", &CXI); 02015 Assert1(CXI.getFailureOrdering() != NotAtomic, 02016 "cmpxchg instructions must be atomic.", &CXI); 02017 Assert1(CXI.getSuccessOrdering() != Unordered, 02018 "cmpxchg instructions cannot be unordered.", &CXI); 02019 Assert1(CXI.getFailureOrdering() != Unordered, 02020 "cmpxchg instructions cannot be unordered.", &CXI); 02021 Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(), 02022 "cmpxchg instructions be at least as constrained on success as fail", 02023 &CXI); 02024 Assert1(CXI.getFailureOrdering() != Release && 02025 CXI.getFailureOrdering() != AcquireRelease, 02026 "cmpxchg failure ordering cannot include release semantics", &CXI); 02027 02028 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType()); 02029 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI); 02030 Type *ElTy = PTy->getElementType(); 02031 Assert2(ElTy->isIntegerTy(), 02032 "cmpxchg operand must have integer type!", 02033 &CXI, ElTy); 02034 unsigned Size = ElTy->getPrimitiveSizeInBits(); 02035 Assert2(Size >= 8 && !(Size & (Size - 1)), 02036 "cmpxchg operand must be power-of-two byte-sized integer", 02037 &CXI, ElTy); 02038 Assert2(ElTy == CXI.getOperand(1)->getType(), 02039 "Expected value type does not match pointer operand type!", 02040 &CXI, ElTy); 02041 Assert2(ElTy == CXI.getOperand(2)->getType(), 02042 "Stored value type does not match pointer operand type!", 02043 &CXI, ElTy); 02044 visitInstruction(CXI); 02045 } 02046 02047 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 02048 Assert1(RMWI.getOrdering() != NotAtomic, 02049 "atomicrmw instructions must be atomic.", &RMWI); 02050 Assert1(RMWI.getOrdering() != Unordered, 02051 "atomicrmw instructions cannot be unordered.", &RMWI); 02052 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType()); 02053 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI); 02054 Type *ElTy = PTy->getElementType(); 02055 Assert2(ElTy->isIntegerTy(), 02056 "atomicrmw operand must have integer type!", 02057 &RMWI, ElTy); 02058 unsigned Size = ElTy->getPrimitiveSizeInBits(); 02059 Assert2(Size >= 8 && !(Size & (Size - 1)), 02060 "atomicrmw operand must be power-of-two byte-sized integer", 02061 &RMWI, ElTy); 02062 Assert2(ElTy == RMWI.getOperand(1)->getType(), 02063 "Argument value type does not match pointer operand type!", 02064 &RMWI, ElTy); 02065 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() && 02066 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP, 02067 "Invalid binary operation!", &RMWI); 02068 visitInstruction(RMWI); 02069 } 02070 02071 void Verifier::visitFenceInst(FenceInst &FI) { 02072 const AtomicOrdering Ordering = FI.getOrdering(); 02073 Assert1(Ordering == Acquire || Ordering == Release || 02074 Ordering == AcquireRelease || Ordering == SequentiallyConsistent, 02075 "fence instructions may only have " 02076 "acquire, release, acq_rel, or seq_cst ordering.", &FI); 02077 visitInstruction(FI); 02078 } 02079 02080 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 02081 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 02082 EVI.getIndices()) == 02083 EVI.getType(), 02084 "Invalid ExtractValueInst operands!", &EVI); 02085 02086 visitInstruction(EVI); 02087 } 02088 02089 void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 02090 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 02091 IVI.getIndices()) == 02092 IVI.getOperand(1)->getType(), 02093 "Invalid InsertValueInst operands!", &IVI); 02094 02095 visitInstruction(IVI); 02096 } 02097 02098 void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 02099 BasicBlock *BB = LPI.getParent(); 02100 02101 // The landingpad instruction is ill-formed if it doesn't have any clauses and 02102 // isn't a cleanup. 02103 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(), 02104 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 02105 02106 // The landingpad instruction defines its parent as a landing pad block. The 02107 // landing pad block may be branched to only by the unwind edge of an invoke. 02108 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 02109 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()); 02110 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 02111 "Block containing LandingPadInst must be jumped to " 02112 "only by the unwind edge of an invoke.", &LPI); 02113 } 02114 02115 // The landingpad instruction must be the first non-PHI instruction in the 02116 // block. 02117 Assert1(LPI.getParent()->getLandingPadInst() == &LPI, 02118 "LandingPadInst not the first non-PHI instruction in the block.", 02119 &LPI); 02120 02121 // The personality functions for all landingpad instructions within the same 02122 // function should match. 02123 if (PersonalityFn) 02124 Assert1(LPI.getPersonalityFn() == PersonalityFn, 02125 "Personality function doesn't match others in function", &LPI); 02126 PersonalityFn = LPI.getPersonalityFn(); 02127 02128 // All operands must be constants. 02129 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!", 02130 &LPI); 02131 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 02132 Constant *Clause = LPI.getClause(i); 02133 if (LPI.isCatch(i)) { 02134 Assert1(isa<PointerType>(Clause->getType()), 02135 "Catch operand does not have pointer type!", &LPI); 02136 } else { 02137 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 02138 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 02139 "Filter operand is not an array of constants!", &LPI); 02140 } 02141 } 02142 02143 visitInstruction(LPI); 02144 } 02145 02146 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 02147 Instruction *Op = cast<Instruction>(I.getOperand(i)); 02148 // If the we have an invalid invoke, don't try to compute the dominance. 02149 // We already reject it in the invoke specific checks and the dominance 02150 // computation doesn't handle multiple edges. 02151 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 02152 if (II->getNormalDest() == II->getUnwindDest()) 02153 return; 02154 } 02155 02156 const Use &U = I.getOperandUse(i); 02157 Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U), 02158 "Instruction does not dominate all uses!", Op, &I); 02159 } 02160 02161 /// verifyInstruction - Verify that an instruction is well formed. 02162 /// 02163 void Verifier::visitInstruction(Instruction &I) { 02164 BasicBlock *BB = I.getParent(); 02165 Assert1(BB, "Instruction not embedded in basic block!", &I); 02166 02167 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 02168 for (User *U : I.users()) { 02169 Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB), 02170 "Only PHI nodes may reference their own value!", &I); 02171 } 02172 } 02173 02174 // Check that void typed values don't have names 02175 Assert1(!I.getType()->isVoidTy() || !I.hasName(), 02176 "Instruction has a name, but provides a void value!", &I); 02177 02178 // Check that the return value of the instruction is either void or a legal 02179 // value type. 02180 Assert1(I.getType()->isVoidTy() || 02181 I.getType()->isFirstClassType(), 02182 "Instruction returns a non-scalar type!", &I); 02183 02184 // Check that the instruction doesn't produce metadata. Calls are already 02185 // checked against the callee type. 02186 Assert1(!I.getType()->isMetadataTy() || 02187 isa<CallInst>(I) || isa<InvokeInst>(I), 02188 "Invalid use of metadata!", &I); 02189 02190 // Check that all uses of the instruction, if they are instructions 02191 // themselves, actually have parent basic blocks. If the use is not an 02192 // instruction, it is an error! 02193 for (Use &U : I.uses()) { 02194 if (Instruction *Used = dyn_cast<Instruction>(U.getUser())) 02195 Assert2(Used->getParent() != nullptr, "Instruction referencing" 02196 " instruction not embedded in a basic block!", &I, Used); 02197 else { 02198 CheckFailed("Use of instruction is not an instruction!", U); 02199 return; 02200 } 02201 } 02202 02203 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 02204 Assert1(I.getOperand(i) != nullptr, "Instruction has null operand!", &I); 02205 02206 // Check to make sure that only first-class-values are operands to 02207 // instructions. 02208 if (!I.getOperand(i)->getType()->isFirstClassType()) { 02209 Assert1(0, "Instruction operands must be first-class values!", &I); 02210 } 02211 02212 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 02213 // Check to make sure that the "address of" an intrinsic function is never 02214 // taken. 02215 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0), 02216 "Cannot take the address of an intrinsic!", &I); 02217 Assert1(!F->isIntrinsic() || isa<CallInst>(I) || 02218 F->getIntrinsicID() == Intrinsic::donothing, 02219 "Cannot invoke an intrinsinc other than donothing", &I); 02220 Assert1(F->getParent() == M, "Referencing function in another module!", 02221 &I); 02222 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 02223 Assert1(OpBB->getParent() == BB->getParent(), 02224 "Referring to a basic block in another function!", &I); 02225 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 02226 Assert1(OpArg->getParent() == BB->getParent(), 02227 "Referring to an argument in another function!", &I); 02228 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 02229 Assert1(GV->getParent() == M, "Referencing global in another module!", 02230 &I); 02231 } else if (isa<Instruction>(I.getOperand(i))) { 02232 verifyDominatesUse(I, i); 02233 } else if (isa<InlineAsm>(I.getOperand(i))) { 02234 Assert1((i + 1 == e && isa<CallInst>(I)) || 02235 (i + 3 == e && isa<InvokeInst>(I)), 02236 "Cannot take the address of an inline asm!", &I); 02237 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 02238 if (CE->getType()->isPtrOrPtrVectorTy()) { 02239 // If we have a ConstantExpr pointer, we need to see if it came from an 02240 // illegal bitcast (inttoptr <constant int> ) 02241 SmallVector<const ConstantExpr *, 4> Stack; 02242 SmallPtrSet<const ConstantExpr *, 4> Visited; 02243 Stack.push_back(CE); 02244 02245 while (!Stack.empty()) { 02246 const ConstantExpr *V = Stack.pop_back_val(); 02247 if (!Visited.insert(V)) 02248 continue; 02249 02250 VerifyConstantExprBitcastType(V); 02251 02252 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) { 02253 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I))) 02254 Stack.push_back(Op); 02255 } 02256 } 02257 } 02258 } 02259 } 02260 02261 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 02262 Assert1(I.getType()->isFPOrFPVectorTy(), 02263 "fpmath requires a floating point result!", &I); 02264 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 02265 Value *Op0 = MD->getOperand(0); 02266 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) { 02267 APFloat Accuracy = CFP0->getValueAPF(); 02268 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 02269 "fpmath accuracy not a positive number!", &I); 02270 } else { 02271 Assert1(false, "invalid fpmath accuracy!", &I); 02272 } 02273 } 02274 02275 MDNode *MD = I.getMetadata(LLVMContext::MD_range); 02276 Assert1(!MD || isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I), 02277 "Ranges are only for loads, calls and invokes!", &I); 02278 02279 InstsInThisBlock.insert(&I); 02280 } 02281 02282 /// VerifyIntrinsicType - Verify that the specified type (which comes from an 02283 /// intrinsic argument or return value) matches the type constraints specified 02284 /// by the .td file (e.g. an "any integer" argument really is an integer). 02285 /// 02286 /// This return true on error but does not print a message. 02287 bool Verifier::VerifyIntrinsicType(Type *Ty, 02288 ArrayRef<Intrinsic::IITDescriptor> &Infos, 02289 SmallVectorImpl<Type*> &ArgTys) { 02290 using namespace Intrinsic; 02291 02292 // If we ran out of descriptors, there are too many arguments. 02293 if (Infos.empty()) return true; 02294 IITDescriptor D = Infos.front(); 02295 Infos = Infos.slice(1); 02296 02297 switch (D.Kind) { 02298 case IITDescriptor::Void: return !Ty->isVoidTy(); 02299 case IITDescriptor::VarArg: return true; 02300 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 02301 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 02302 case IITDescriptor::Half: return !Ty->isHalfTy(); 02303 case IITDescriptor::Float: return !Ty->isFloatTy(); 02304 case IITDescriptor::Double: return !Ty->isDoubleTy(); 02305 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 02306 case IITDescriptor::Vector: { 02307 VectorType *VT = dyn_cast<VectorType>(Ty); 02308 return !VT || VT->getNumElements() != D.Vector_Width || 02309 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys); 02310 } 02311 case IITDescriptor::Pointer: { 02312 PointerType *PT = dyn_cast<PointerType>(Ty); 02313 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 02314 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys); 02315 } 02316 02317 case IITDescriptor::Struct: { 02318 StructType *ST = dyn_cast<StructType>(Ty); 02319 if (!ST || ST->getNumElements() != D.Struct_NumElements) 02320 return true; 02321 02322 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 02323 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys)) 02324 return true; 02325 return false; 02326 } 02327 02328 case IITDescriptor::Argument: 02329 // Two cases here - If this is the second occurrence of an argument, verify 02330 // that the later instance matches the previous instance. 02331 if (D.getArgumentNumber() < ArgTys.size()) 02332 return Ty != ArgTys[D.getArgumentNumber()]; 02333 02334 // Otherwise, if this is the first instance of an argument, record it and 02335 // verify the "Any" kind. 02336 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error"); 02337 ArgTys.push_back(Ty); 02338 02339 switch (D.getArgumentKind()) { 02340 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 02341 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 02342 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 02343 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 02344 } 02345 llvm_unreachable("all argument kinds not covered"); 02346 02347 case IITDescriptor::ExtendArgument: { 02348 // This may only be used when referring to a previous vector argument. 02349 if (D.getArgumentNumber() >= ArgTys.size()) 02350 return true; 02351 02352 Type *NewTy = ArgTys[D.getArgumentNumber()]; 02353 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 02354 NewTy = VectorType::getExtendedElementVectorType(VTy); 02355 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 02356 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 02357 else 02358 return true; 02359 02360 return Ty != NewTy; 02361 } 02362 case IITDescriptor::TruncArgument: { 02363 // This may only be used when referring to a previous vector argument. 02364 if (D.getArgumentNumber() >= ArgTys.size()) 02365 return true; 02366 02367 Type *NewTy = ArgTys[D.getArgumentNumber()]; 02368 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 02369 NewTy = VectorType::getTruncatedElementVectorType(VTy); 02370 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 02371 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 02372 else 02373 return true; 02374 02375 return Ty != NewTy; 02376 } 02377 case IITDescriptor::HalfVecArgument: 02378 // This may only be used when referring to a previous vector argument. 02379 return D.getArgumentNumber() >= ArgTys.size() || 02380 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 02381 VectorType::getHalfElementsVectorType( 02382 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 02383 } 02384 llvm_unreachable("unhandled"); 02385 } 02386 02387 /// \brief Verify if the intrinsic has variable arguments. 02388 /// This method is intended to be called after all the fixed arguments have been 02389 /// verified first. 02390 /// 02391 /// This method returns true on error and does not print an error message. 02392 bool 02393 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg, 02394 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 02395 using namespace Intrinsic; 02396 02397 // If there are no descriptors left, then it can't be a vararg. 02398 if (Infos.empty()) 02399 return isVarArg ? true : false; 02400 02401 // There should be only one descriptor remaining at this point. 02402 if (Infos.size() != 1) 02403 return true; 02404 02405 // Check and verify the descriptor. 02406 IITDescriptor D = Infos.front(); 02407 Infos = Infos.slice(1); 02408 if (D.Kind == IITDescriptor::VarArg) 02409 return isVarArg ? false : true; 02410 02411 return true; 02412 } 02413 02414 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways. 02415 /// 02416 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) { 02417 Function *IF = CI.getCalledFunction(); 02418 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!", 02419 IF); 02420 02421 // Verify that the intrinsic prototype lines up with what the .td files 02422 // describe. 02423 FunctionType *IFTy = IF->getFunctionType(); 02424 bool IsVarArg = IFTy->isVarArg(); 02425 02426 SmallVector<Intrinsic::IITDescriptor, 8> Table; 02427 getIntrinsicInfoTableEntries(ID, Table); 02428 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 02429 02430 SmallVector<Type *, 4> ArgTys; 02431 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys), 02432 "Intrinsic has incorrect return type!", IF); 02433 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i) 02434 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys), 02435 "Intrinsic has incorrect argument type!", IF); 02436 02437 // Verify if the intrinsic call matches the vararg property. 02438 if (IsVarArg) 02439 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef), 02440 "Intrinsic was not defined with variable arguments!", IF); 02441 else 02442 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef), 02443 "Callsite was not defined with variable arguments!", IF); 02444 02445 // All descriptors should be absorbed by now. 02446 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF); 02447 02448 // Now that we have the intrinsic ID and the actual argument types (and we 02449 // know they are legal for the intrinsic!) get the intrinsic name through the 02450 // usual means. This allows us to verify the mangling of argument types into 02451 // the name. 02452 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys); 02453 Assert1(ExpectedName == IF->getName(), 02454 "Intrinsic name not mangled correctly for type arguments! " 02455 "Should be: " + ExpectedName, IF); 02456 02457 // If the intrinsic takes MDNode arguments, verify that they are either global 02458 // or are local to *this* function. 02459 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i) 02460 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i))) 02461 visitMDNode(*MD, CI.getParent()->getParent()); 02462 02463 switch (ID) { 02464 default: 02465 break; 02466 case Intrinsic::ctlz: // llvm.ctlz 02467 case Intrinsic::cttz: // llvm.cttz 02468 Assert1(isa<ConstantInt>(CI.getArgOperand(1)), 02469 "is_zero_undef argument of bit counting intrinsics must be a " 02470 "constant int", &CI); 02471 break; 02472 case Intrinsic::dbg_declare: { // llvm.dbg.declare 02473 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)), 02474 "invalid llvm.dbg.declare intrinsic call 1", &CI); 02475 MDNode *MD = cast<MDNode>(CI.getArgOperand(0)); 02476 Assert1(MD->getNumOperands() == 1, 02477 "invalid llvm.dbg.declare intrinsic call 2", &CI); 02478 } break; 02479 case Intrinsic::memcpy: 02480 case Intrinsic::memmove: 02481 case Intrinsic::memset: 02482 Assert1(isa<ConstantInt>(CI.getArgOperand(3)), 02483 "alignment argument of memory intrinsics must be a constant int", 02484 &CI); 02485 Assert1(isa<ConstantInt>(CI.getArgOperand(4)), 02486 "isvolatile argument of memory intrinsics must be a constant int", 02487 &CI); 02488 break; 02489 case Intrinsic::gcroot: 02490 case Intrinsic::gcwrite: 02491 case Intrinsic::gcread: 02492 if (ID == Intrinsic::gcroot) { 02493 AllocaInst *AI = 02494 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts()); 02495 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI); 02496 Assert1(isa<Constant>(CI.getArgOperand(1)), 02497 "llvm.gcroot parameter #2 must be a constant.", &CI); 02498 if (!AI->getType()->getElementType()->isPointerTy()) { 02499 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)), 02500 "llvm.gcroot parameter #1 must either be a pointer alloca, " 02501 "or argument #2 must be a non-null constant.", &CI); 02502 } 02503 } 02504 02505 Assert1(CI.getParent()->getParent()->hasGC(), 02506 "Enclosing function does not use GC.", &CI); 02507 break; 02508 case Intrinsic::init_trampoline: 02509 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()), 02510 "llvm.init_trampoline parameter #2 must resolve to a function.", 02511 &CI); 02512 break; 02513 case Intrinsic::prefetch: 02514 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) && 02515 isa<ConstantInt>(CI.getArgOperand(2)) && 02516 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 && 02517 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4, 02518 "invalid arguments to llvm.prefetch", 02519 &CI); 02520 break; 02521 case Intrinsic::stackprotector: 02522 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()), 02523 "llvm.stackprotector parameter #2 must resolve to an alloca.", 02524 &CI); 02525 break; 02526 case Intrinsic::lifetime_start: 02527 case Intrinsic::lifetime_end: 02528 case Intrinsic::invariant_start: 02529 Assert1(isa<ConstantInt>(CI.getArgOperand(0)), 02530 "size argument of memory use markers must be a constant integer", 02531 &CI); 02532 break; 02533 case Intrinsic::invariant_end: 02534 Assert1(isa<ConstantInt>(CI.getArgOperand(1)), 02535 "llvm.invariant.end parameter #2 must be a constant integer", &CI); 02536 break; 02537 } 02538 } 02539 02540 void DebugInfoVerifier::verifyDebugInfo() { 02541 if (!VerifyDebugInfo) 02542 return; 02543 02544 DebugInfoFinder Finder; 02545 Finder.processModule(*M); 02546 processInstructions(Finder); 02547 02548 // Verify Debug Info. 02549 // 02550 // NOTE: The loud braces are necessary for MSVC compatibility. 02551 for (DICompileUnit CU : Finder.compile_units()) { 02552 Assert1(CU.Verify(), "DICompileUnit does not Verify!", CU); 02553 } 02554 for (DISubprogram S : Finder.subprograms()) { 02555 Assert1(S.Verify(), "DISubprogram does not Verify!", S); 02556 } 02557 for (DIGlobalVariable GV : Finder.global_variables()) { 02558 Assert1(GV.Verify(), "DIGlobalVariable does not Verify!", GV); 02559 } 02560 for (DIType T : Finder.types()) { 02561 Assert1(T.Verify(), "DIType does not Verify!", T); 02562 } 02563 for (DIScope S : Finder.scopes()) { 02564 Assert1(S.Verify(), "DIScope does not Verify!", S); 02565 } 02566 } 02567 02568 void DebugInfoVerifier::processInstructions(DebugInfoFinder &Finder) { 02569 for (const Function &F : *M) 02570 for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) { 02571 if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg)) 02572 Finder.processLocation(*M, DILocation(MD)); 02573 if (const CallInst *CI = dyn_cast<CallInst>(&*I)) 02574 processCallInst(Finder, *CI); 02575 } 02576 } 02577 02578 void DebugInfoVerifier::processCallInst(DebugInfoFinder &Finder, 02579 const CallInst &CI) { 02580 if (Function *F = CI.getCalledFunction()) 02581 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 02582 switch (ID) { 02583 case Intrinsic::dbg_declare: 02584 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI)); 02585 break; 02586 case Intrinsic::dbg_value: 02587 Finder.processValue(*M, cast<DbgValueInst>(&CI)); 02588 break; 02589 default: 02590 break; 02591 } 02592 } 02593 02594 //===----------------------------------------------------------------------===// 02595 // Implement the public interfaces to this file... 02596 //===----------------------------------------------------------------------===// 02597 02598 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) { 02599 Function &F = const_cast<Function &>(f); 02600 assert(!F.isDeclaration() && "Cannot verify external functions"); 02601 02602 raw_null_ostream NullStr; 02603 Verifier V(OS ? *OS : NullStr); 02604 02605 // Note that this function's return value is inverted from what you would 02606 // expect of a function called "verify". 02607 return !V.verify(F); 02608 } 02609 02610 bool llvm::verifyModule(const Module &M, raw_ostream *OS) { 02611 raw_null_ostream NullStr; 02612 Verifier V(OS ? *OS : NullStr); 02613 02614 bool Broken = false; 02615 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) 02616 if (!I->isDeclaration()) 02617 Broken |= !V.verify(*I); 02618 02619 // Note that this function's return value is inverted from what you would 02620 // expect of a function called "verify". 02621 DebugInfoVerifier DIV(OS ? *OS : NullStr); 02622 return !V.verify(M) || !DIV.verify(M) || Broken; 02623 } 02624 02625 namespace { 02626 struct VerifierLegacyPass : public FunctionPass { 02627 static char ID; 02628 02629 Verifier V; 02630 bool FatalErrors; 02631 02632 VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) { 02633 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 02634 } 02635 explicit VerifierLegacyPass(bool FatalErrors) 02636 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) { 02637 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 02638 } 02639 02640 bool runOnFunction(Function &F) override { 02641 if (!V.verify(F) && FatalErrors) 02642 report_fatal_error("Broken function found, compilation aborted!"); 02643 02644 return false; 02645 } 02646 02647 bool doFinalization(Module &M) override { 02648 if (!V.verify(M) && FatalErrors) 02649 report_fatal_error("Broken module found, compilation aborted!"); 02650 02651 return false; 02652 } 02653 02654 void getAnalysisUsage(AnalysisUsage &AU) const override { 02655 AU.setPreservesAll(); 02656 } 02657 }; 02658 struct DebugInfoVerifierLegacyPass : public ModulePass { 02659 static char ID; 02660 02661 DebugInfoVerifier V; 02662 bool FatalErrors; 02663 02664 DebugInfoVerifierLegacyPass() : ModulePass(ID), FatalErrors(true) { 02665 initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 02666 } 02667 explicit DebugInfoVerifierLegacyPass(bool FatalErrors) 02668 : ModulePass(ID), V(dbgs()), FatalErrors(FatalErrors) { 02669 initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 02670 } 02671 02672 bool runOnModule(Module &M) override { 02673 if (!V.verify(M) && FatalErrors) 02674 report_fatal_error("Broken debug info found, compilation aborted!"); 02675 02676 return false; 02677 } 02678 02679 void getAnalysisUsage(AnalysisUsage &AU) const override { 02680 AU.setPreservesAll(); 02681 } 02682 }; 02683 } 02684 02685 char VerifierLegacyPass::ID = 0; 02686 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false) 02687 02688 char DebugInfoVerifierLegacyPass::ID = 0; 02689 INITIALIZE_PASS(DebugInfoVerifierLegacyPass, "verify-di", "Debug Info Verifier", 02690 false, false) 02691 02692 FunctionPass *llvm::createVerifierPass(bool FatalErrors) { 02693 return new VerifierLegacyPass(FatalErrors); 02694 } 02695 02696 ModulePass *llvm::createDebugInfoVerifierPass(bool FatalErrors) { 02697 return new DebugInfoVerifierLegacyPass(FatalErrors); 02698 } 02699 02700 PreservedAnalyses VerifierPass::run(Module *M) { 02701 if (verifyModule(*M, &dbgs()) && FatalErrors) 02702 report_fatal_error("Broken module found, compilation aborted!"); 02703 02704 return PreservedAnalyses::all(); 02705 } 02706 02707 PreservedAnalyses VerifierPass::run(Function *F) { 02708 if (verifyFunction(*F, &dbgs()) && FatalErrors) 02709 report_fatal_error("Broken function found, compilation aborted!"); 02710 02711 return PreservedAnalyses::all(); 02712 }