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