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