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/CallingConv.h" 50 #include "llvm/Constants.h" 51 #include "llvm/DerivedTypes.h" 52 #include "llvm/InlineAsm.h" 53 #include "llvm/IntrinsicInst.h" 54 #include "llvm/LLVMContext.h" 55 #include "llvm/Metadata.h" 56 #include "llvm/Module.h" 57 #include "llvm/Pass.h" 58 #include "llvm/PassManager.h" 59 #include "llvm/Analysis/Dominators.h" 60 #include "llvm/Assembly/Writer.h" 61 #include "llvm/CodeGen/ValueTypes.h" 62 #include "llvm/Support/CallSite.h" 63 #include "llvm/Support/CFG.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/InstVisitor.h" 66 #include "llvm/ADT/SetVector.h" 67 #include "llvm/ADT/SmallPtrSet.h" 68 #include "llvm/ADT/SmallVector.h" 69 #include "llvm/ADT/StringExtras.h" 70 #include "llvm/ADT/STLExtras.h" 71 #include "llvm/Support/ErrorHandling.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include <algorithm> 74 #include <cstdarg> 75 using namespace llvm; 76 77 namespace { // Anonymous namespace for class 78 struct PreVerifier : public FunctionPass { 79 static char ID; // Pass ID, replacement for typeid 80 81 PreVerifier() : FunctionPass(ID) { 82 initializePreVerifierPass(*PassRegistry::getPassRegistry()); 83 } 84 85 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 86 AU.setPreservesAll(); 87 } 88 89 // Check that the prerequisites for successful DominatorTree construction 90 // are satisfied. 91 bool runOnFunction(Function &F) { 92 bool Broken = false; 93 94 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { 95 if (I->empty() || !I->back().isTerminator()) { 96 dbgs() << "Basic Block in function '" << F.getName() 97 << "' does not have terminator!\n"; 98 WriteAsOperand(dbgs(), I, true); 99 dbgs() << "\n"; 100 Broken = true; 101 } 102 } 103 104 if (Broken) 105 report_fatal_error("Broken module, no Basic Block terminator!"); 106 107 return false; 108 } 109 }; 110 } 111 112 char PreVerifier::ID = 0; 113 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification", 114 false, false) 115 static char &PreVerifyID = PreVerifier::ID; 116 117 namespace { 118 struct Verifier : public FunctionPass, public InstVisitor<Verifier> { 119 static char ID; // Pass ID, replacement for typeid 120 bool Broken; // Is this module found to be broken? 121 VerifierFailureAction action; 122 // What to do if verification fails. 123 Module *Mod; // Module we are verifying right now 124 LLVMContext *Context; // Context within which we are verifying 125 DominatorTree *DT; // Dominator Tree, caution can be null! 126 127 std::string Messages; 128 raw_string_ostream MessagesStr; 129 130 /// InstInThisBlock - when verifying a basic block, keep track of all of the 131 /// instructions we have seen so far. This allows us to do efficient 132 /// dominance checks for the case when an instruction has an operand that is 133 /// an instruction in the same block. 134 SmallPtrSet<Instruction*, 16> InstsInThisBlock; 135 136 /// MDNodes - keep track of the metadata nodes that have been checked 137 /// already. 138 SmallPtrSet<MDNode *, 32> MDNodes; 139 140 /// PersonalityFn - The personality function referenced by the 141 /// LandingPadInsts. All LandingPadInsts within the same function must use 142 /// the same personality function. 143 const Value *PersonalityFn; 144 145 Verifier() 146 : FunctionPass(ID), Broken(false), 147 action(AbortProcessAction), Mod(0), Context(0), DT(0), 148 MessagesStr(Messages), PersonalityFn(0) { 149 initializeVerifierPass(*PassRegistry::getPassRegistry()); 150 } 151 explicit Verifier(VerifierFailureAction ctn) 152 : FunctionPass(ID), Broken(false), action(ctn), Mod(0), 153 Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) { 154 initializeVerifierPass(*PassRegistry::getPassRegistry()); 155 } 156 157 bool doInitialization(Module &M) { 158 Mod = &M; 159 Context = &M.getContext(); 160 161 // We must abort before returning back to the pass manager, or else the 162 // pass manager may try to run other passes on the broken module. 163 return abortIfBroken(); 164 } 165 166 bool runOnFunction(Function &F) { 167 // Get dominator information if we are being run by PassManager 168 DT = &getAnalysis<DominatorTree>(); 169 170 Mod = F.getParent(); 171 if (!Context) Context = &F.getContext(); 172 173 visit(F); 174 InstsInThisBlock.clear(); 175 PersonalityFn = 0; 176 177 // We must abort before returning back to the pass manager, or else the 178 // pass manager may try to run other passes on the broken module. 179 return abortIfBroken(); 180 } 181 182 bool doFinalization(Module &M) { 183 // Scan through, checking all of the external function's linkage now... 184 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 185 visitGlobalValue(*I); 186 187 // Check to make sure function prototypes are okay. 188 if (I->isDeclaration()) visitFunction(*I); 189 } 190 191 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 192 I != E; ++I) 193 visitGlobalVariable(*I); 194 195 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 196 I != E; ++I) 197 visitGlobalAlias(*I); 198 199 for (Module::named_metadata_iterator I = M.named_metadata_begin(), 200 E = M.named_metadata_end(); I != E; ++I) 201 visitNamedMDNode(*I); 202 203 // If the module is broken, abort at this time. 204 return abortIfBroken(); 205 } 206 207 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 208 AU.setPreservesAll(); 209 AU.addRequiredID(PreVerifyID); 210 AU.addRequired<DominatorTree>(); 211 } 212 213 /// abortIfBroken - If the module is broken and we are supposed to abort on 214 /// this condition, do so. 215 /// 216 bool abortIfBroken() { 217 if (!Broken) return false; 218 MessagesStr << "Broken module found, "; 219 switch (action) { 220 case AbortProcessAction: 221 MessagesStr << "compilation aborted!\n"; 222 dbgs() << MessagesStr.str(); 223 // Client should choose different reaction if abort is not desired 224 abort(); 225 case PrintMessageAction: 226 MessagesStr << "verification continues.\n"; 227 dbgs() << MessagesStr.str(); 228 return false; 229 case ReturnStatusAction: 230 MessagesStr << "compilation terminated.\n"; 231 return true; 232 } 233 llvm_unreachable("Invalid action"); 234 } 235 236 237 // Verification methods... 238 void visitGlobalValue(GlobalValue &GV); 239 void visitGlobalVariable(GlobalVariable &GV); 240 void visitGlobalAlias(GlobalAlias &GA); 241 void visitNamedMDNode(NamedMDNode &NMD); 242 void visitMDNode(MDNode &MD, Function *F); 243 void visitFunction(Function &F); 244 void visitBasicBlock(BasicBlock &BB); 245 using InstVisitor<Verifier>::visit; 246 247 void visit(Instruction &I); 248 249 void visitTruncInst(TruncInst &I); 250 void visitZExtInst(ZExtInst &I); 251 void visitSExtInst(SExtInst &I); 252 void visitFPTruncInst(FPTruncInst &I); 253 void visitFPExtInst(FPExtInst &I); 254 void visitFPToUIInst(FPToUIInst &I); 255 void visitFPToSIInst(FPToSIInst &I); 256 void visitUIToFPInst(UIToFPInst &I); 257 void visitSIToFPInst(SIToFPInst &I); 258 void visitIntToPtrInst(IntToPtrInst &I); 259 void visitPtrToIntInst(PtrToIntInst &I); 260 void visitBitCastInst(BitCastInst &I); 261 void visitPHINode(PHINode &PN); 262 void visitBinaryOperator(BinaryOperator &B); 263 void visitICmpInst(ICmpInst &IC); 264 void visitFCmpInst(FCmpInst &FC); 265 void visitExtractElementInst(ExtractElementInst &EI); 266 void visitInsertElementInst(InsertElementInst &EI); 267 void visitShuffleVectorInst(ShuffleVectorInst &EI); 268 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 269 void visitCallInst(CallInst &CI); 270 void visitInvokeInst(InvokeInst &II); 271 void visitGetElementPtrInst(GetElementPtrInst &GEP); 272 void visitLoadInst(LoadInst &LI); 273 void visitStoreInst(StoreInst &SI); 274 void verifyDominatesUse(Instruction &I, unsigned i); 275 void visitInstruction(Instruction &I); 276 void visitTerminatorInst(TerminatorInst &I); 277 void visitBranchInst(BranchInst &BI); 278 void visitReturnInst(ReturnInst &RI); 279 void visitSwitchInst(SwitchInst &SI); 280 void visitIndirectBrInst(IndirectBrInst &BI); 281 void visitSelectInst(SelectInst &SI); 282 void visitUserOp1(Instruction &I); 283 void visitUserOp2(Instruction &I) { visitUserOp1(I); } 284 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI); 285 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 286 void visitAtomicRMWInst(AtomicRMWInst &RMWI); 287 void visitFenceInst(FenceInst &FI); 288 void visitAllocaInst(AllocaInst &AI); 289 void visitExtractValueInst(ExtractValueInst &EVI); 290 void visitInsertValueInst(InsertValueInst &IVI); 291 void visitLandingPadInst(LandingPadInst &LPI); 292 293 void VerifyCallSite(CallSite CS); 294 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, 295 int VT, unsigned ArgNo, std::string &Suffix); 296 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F, 297 unsigned RetNum, unsigned ParamNum, ...); 298 void VerifyParameterAttrs(Attributes Attrs, Type *Ty, 299 bool isReturnValue, const Value *V); 300 void VerifyFunctionAttrs(FunctionType *FT, const AttrListPtr &Attrs, 301 const Value *V); 302 303 void WriteValue(const Value *V) { 304 if (!V) return; 305 if (isa<Instruction>(V)) { 306 MessagesStr << *V << '\n'; 307 } else { 308 WriteAsOperand(MessagesStr, V, true, Mod); 309 MessagesStr << '\n'; 310 } 311 } 312 313 void WriteType(Type *T) { 314 if (!T) return; 315 MessagesStr << ' ' << *T; 316 } 317 318 319 // CheckFailed - A check failed, so print out the condition and the message 320 // that failed. This provides a nice place to put a breakpoint if you want 321 // to see why something is not correct. 322 void CheckFailed(const Twine &Message, 323 const Value *V1 = 0, const Value *V2 = 0, 324 const Value *V3 = 0, const Value *V4 = 0) { 325 MessagesStr << Message.str() << "\n"; 326 WriteValue(V1); 327 WriteValue(V2); 328 WriteValue(V3); 329 WriteValue(V4); 330 Broken = true; 331 } 332 333 void CheckFailed(const Twine &Message, const Value *V1, 334 Type *T2, const Value *V3 = 0) { 335 MessagesStr << Message.str() << "\n"; 336 WriteValue(V1); 337 WriteType(T2); 338 WriteValue(V3); 339 Broken = true; 340 } 341 342 void CheckFailed(const Twine &Message, Type *T1, 343 Type *T2 = 0, Type *T3 = 0) { 344 MessagesStr << Message.str() << "\n"; 345 WriteType(T1); 346 WriteType(T2); 347 WriteType(T3); 348 Broken = true; 349 } 350 }; 351 } // End anonymous namespace 352 353 char Verifier::ID = 0; 354 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false) 355 INITIALIZE_PASS_DEPENDENCY(PreVerifier) 356 INITIALIZE_PASS_DEPENDENCY(DominatorTree) 357 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false) 358 359 // Assert - We know that cond should be true, if not print an error message. 360 #define Assert(C, M) \ 361 do { if (!(C)) { CheckFailed(M); return; } } while (0) 362 #define Assert1(C, M, V1) \ 363 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0) 364 #define Assert2(C, M, V1, V2) \ 365 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0) 366 #define Assert3(C, M, V1, V2, V3) \ 367 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0) 368 #define Assert4(C, M, V1, V2, V3, V4) \ 369 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0) 370 371 void Verifier::visit(Instruction &I) { 372 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 373 Assert1(I.getOperand(i) != 0, "Operand is null", &I); 374 InstVisitor<Verifier>::visit(I); 375 } 376 377 378 void Verifier::visitGlobalValue(GlobalValue &GV) { 379 Assert1(!GV.isDeclaration() || 380 GV.isMaterializable() || 381 GV.hasExternalLinkage() || 382 GV.hasDLLImportLinkage() || 383 GV.hasExternalWeakLinkage() || 384 (isa<GlobalAlias>(GV) && 385 (GV.hasLocalLinkage() || GV.hasWeakLinkage())), 386 "Global is external, but doesn't have external or dllimport or weak linkage!", 387 &GV); 388 389 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(), 390 "Global is marked as dllimport, but not external", &GV); 391 392 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 393 "Only global variables can have appending linkage!", &GV); 394 395 if (GV.hasAppendingLinkage()) { 396 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 397 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(), 398 "Only global arrays can have appending linkage!", GVar); 399 } 400 401 Assert1(!GV.hasLinkerPrivateWeakDefAutoLinkage() || GV.hasDefaultVisibility(), 402 "linker_private_weak_def_auto can only have default visibility!", 403 &GV); 404 } 405 406 void Verifier::visitGlobalVariable(GlobalVariable &GV) { 407 if (GV.hasInitializer()) { 408 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(), 409 "Global variable initializer type does not match global " 410 "variable type!", &GV); 411 412 // If the global has common linkage, it must have a zero initializer and 413 // cannot be constant. 414 if (GV.hasCommonLinkage()) { 415 Assert1(GV.getInitializer()->isNullValue(), 416 "'common' global must have a zero initializer!", &GV); 417 Assert1(!GV.isConstant(), "'common' global may not be marked constant!", 418 &GV); 419 } 420 } else { 421 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() || 422 GV.hasExternalWeakLinkage(), 423 "invalid linkage type for global declaration", &GV); 424 } 425 426 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 427 GV.getName() == "llvm.global_dtors")) { 428 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(), 429 "invalid linkage for intrinsic global variable", &GV); 430 // Don't worry about emitting an error for it not being an array, 431 // visitGlobalValue will complain on appending non-array. 432 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) { 433 StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 434 PointerType *FuncPtrTy = 435 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo(); 436 Assert1(STy && STy->getNumElements() == 2 && 437 STy->getTypeAtIndex(0u)->isIntegerTy(32) && 438 STy->getTypeAtIndex(1) == FuncPtrTy, 439 "wrong type for intrinsic global variable", &GV); 440 } 441 } 442 443 visitGlobalValue(GV); 444 } 445 446 void Verifier::visitGlobalAlias(GlobalAlias &GA) { 447 Assert1(!GA.getName().empty(), 448 "Alias name cannot be empty!", &GA); 449 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() || 450 GA.hasWeakLinkage(), 451 "Alias should have external or external weak linkage!", &GA); 452 Assert1(GA.getAliasee(), 453 "Aliasee cannot be NULL!", &GA); 454 Assert1(GA.getType() == GA.getAliasee()->getType(), 455 "Alias and aliasee types should match!", &GA); 456 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA); 457 458 if (!isa<GlobalValue>(GA.getAliasee())) { 459 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee()); 460 Assert1(CE && 461 (CE->getOpcode() == Instruction::BitCast || 462 CE->getOpcode() == Instruction::GetElementPtr) && 463 isa<GlobalValue>(CE->getOperand(0)), 464 "Aliasee should be either GlobalValue or bitcast of GlobalValue", 465 &GA); 466 } 467 468 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false); 469 Assert1(Aliasee, 470 "Aliasing chain should end with function or global variable", &GA); 471 472 visitGlobalValue(GA); 473 } 474 475 void Verifier::visitNamedMDNode(NamedMDNode &NMD) { 476 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) { 477 MDNode *MD = NMD.getOperand(i); 478 if (!MD) 479 continue; 480 481 Assert1(!MD->isFunctionLocal(), 482 "Named metadata operand cannot be function local!", MD); 483 visitMDNode(*MD, 0); 484 } 485 } 486 487 void Verifier::visitMDNode(MDNode &MD, Function *F) { 488 // Only visit each node once. Metadata can be mutually recursive, so this 489 // avoids infinite recursion here, as well as being an optimization. 490 if (!MDNodes.insert(&MD)) 491 return; 492 493 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) { 494 Value *Op = MD.getOperand(i); 495 if (!Op) 496 continue; 497 if (isa<Constant>(Op) || isa<MDString>(Op)) 498 continue; 499 if (MDNode *N = dyn_cast<MDNode>(Op)) { 500 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(), 501 "Global metadata operand cannot be function local!", &MD, N); 502 visitMDNode(*N, F); 503 continue; 504 } 505 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op); 506 507 // If this was an instruction, bb, or argument, verify that it is in the 508 // function that we expect. 509 Function *ActualF = 0; 510 if (Instruction *I = dyn_cast<Instruction>(Op)) 511 ActualF = I->getParent()->getParent(); 512 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op)) 513 ActualF = BB->getParent(); 514 else if (Argument *A = dyn_cast<Argument>(Op)) 515 ActualF = A->getParent(); 516 assert(ActualF && "Unimplemented function local metadata case!"); 517 518 Assert2(ActualF == F, "function-local metadata used in wrong function", 519 &MD, Op); 520 } 521 } 522 523 // VerifyParameterAttrs - Check the given attributes for an argument or return 524 // value of the specified type. The value V is printed in error messages. 525 void Verifier::VerifyParameterAttrs(Attributes Attrs, Type *Ty, 526 bool isReturnValue, const Value *V) { 527 if (Attrs == Attribute::None) 528 return; 529 530 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly; 531 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) + 532 " only applies to the function!", V); 533 534 if (isReturnValue) { 535 Attributes RetI = Attrs & Attribute::ParameterOnly; 536 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) + 537 " does not apply to return values!", V); 538 } 539 540 for (unsigned i = 0; 541 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) { 542 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i]; 543 Assert1(MutI.isEmptyOrSingleton(), "Attributes " + 544 Attribute::getAsString(MutI) + " are incompatible!", V); 545 } 546 547 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty); 548 Assert1(!TypeI, "Wrong type for attribute " + 549 Attribute::getAsString(TypeI), V); 550 551 Attributes ByValI = Attrs & Attribute::ByVal; 552 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) { 553 Assert1(!ByValI || PTy->getElementType()->isSized(), 554 "Attribute " + Attribute::getAsString(ByValI) + 555 " does not support unsized types!", V); 556 } else { 557 Assert1(!ByValI, 558 "Attribute " + Attribute::getAsString(ByValI) + 559 " only applies to parameters with pointer type!", V); 560 } 561 } 562 563 // VerifyFunctionAttrs - Check parameter attributes against a function type. 564 // The value V is printed in error messages. 565 void Verifier::VerifyFunctionAttrs(FunctionType *FT, 566 const AttrListPtr &Attrs, 567 const Value *V) { 568 if (Attrs.isEmpty()) 569 return; 570 571 bool SawNest = false; 572 573 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) { 574 const AttributeWithIndex &Attr = Attrs.getSlot(i); 575 576 Type *Ty; 577 if (Attr.Index == 0) 578 Ty = FT->getReturnType(); 579 else if (Attr.Index-1 < FT->getNumParams()) 580 Ty = FT->getParamType(Attr.Index-1); 581 else 582 break; // VarArgs attributes, verified elsewhere. 583 584 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V); 585 586 if (Attr.Attrs & Attribute::Nest) { 587 Assert1(!SawNest, "More than one parameter has attribute nest!", V); 588 SawNest = true; 589 } 590 591 if (Attr.Attrs & Attribute::StructRet) 592 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V); 593 } 594 595 Attributes FAttrs = Attrs.getFnAttributes(); 596 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly); 597 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) + 598 " does not apply to the function!", V); 599 600 for (unsigned i = 0; 601 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) { 602 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i]; 603 Assert1(MutI.isEmptyOrSingleton(), "Attributes " + 604 Attribute::getAsString(MutI) + " are incompatible!", V); 605 } 606 } 607 608 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) { 609 if (Attrs.isEmpty()) 610 return true; 611 612 unsigned LastSlot = Attrs.getNumSlots() - 1; 613 unsigned LastIndex = Attrs.getSlot(LastSlot).Index; 614 if (LastIndex <= Params 615 || (LastIndex == (unsigned)~0 616 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params))) 617 return true; 618 619 return false; 620 } 621 622 // visitFunction - Verify that a function is ok. 623 // 624 void Verifier::visitFunction(Function &F) { 625 // Check function arguments. 626 FunctionType *FT = F.getFunctionType(); 627 unsigned NumArgs = F.arg_size(); 628 629 Assert1(Context == &F.getContext(), 630 "Function context does not match Module context!", &F); 631 632 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 633 Assert2(FT->getNumParams() == NumArgs, 634 "# formal arguments must match # of arguments for function type!", 635 &F, FT); 636 Assert1(F.getReturnType()->isFirstClassType() || 637 F.getReturnType()->isVoidTy() || 638 F.getReturnType()->isStructTy(), 639 "Functions cannot return aggregate values!", &F); 640 641 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 642 "Invalid struct return type!", &F); 643 644 const AttrListPtr &Attrs = F.getAttributes(); 645 646 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()), 647 "Attributes after last parameter!", &F); 648 649 // Check function attributes. 650 VerifyFunctionAttrs(FT, Attrs, &F); 651 652 // Check that this function meets the restrictions on this calling convention. 653 switch (F.getCallingConv()) { 654 default: 655 break; 656 case CallingConv::C: 657 break; 658 case CallingConv::Fast: 659 case CallingConv::Cold: 660 case CallingConv::X86_FastCall: 661 case CallingConv::X86_ThisCall: 662 case CallingConv::PTX_Kernel: 663 case CallingConv::PTX_Device: 664 Assert1(!F.isVarArg(), 665 "Varargs functions must have C calling conventions!", &F); 666 break; 667 } 668 669 bool isLLVMdotName = F.getName().size() >= 5 && 670 F.getName().substr(0, 5) == "llvm."; 671 672 // Check that the argument values match the function type for this function... 673 unsigned i = 0; 674 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); 675 I != E; ++I, ++i) { 676 Assert2(I->getType() == FT->getParamType(i), 677 "Argument value does not match function argument type!", 678 I, FT->getParamType(i)); 679 Assert1(I->getType()->isFirstClassType(), 680 "Function arguments must have first-class types!", I); 681 if (!isLLVMdotName) 682 Assert2(!I->getType()->isMetadataTy(), 683 "Function takes metadata but isn't an intrinsic", I, &F); 684 } 685 686 if (F.isMaterializable()) { 687 // Function has a body somewhere we can't see. 688 } else if (F.isDeclaration()) { 689 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() || 690 F.hasExternalWeakLinkage(), 691 "invalid linkage type for function declaration", &F); 692 } else { 693 // Verify that this function (which has a body) is not named "llvm.*". It 694 // is not legal to define intrinsics. 695 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 696 697 // Check the entry node 698 BasicBlock *Entry = &F.getEntryBlock(); 699 Assert1(pred_begin(Entry) == pred_end(Entry), 700 "Entry block to function must not have predecessors!", Entry); 701 702 // The address of the entry block cannot be taken, unless it is dead. 703 if (Entry->hasAddressTaken()) { 704 Assert1(!BlockAddress::get(Entry)->isConstantUsed(), 705 "blockaddress may not be used with the entry block!", Entry); 706 } 707 } 708 709 // If this function is actually an intrinsic, verify that it is only used in 710 // direct call/invokes, never having its "address taken". 711 if (F.getIntrinsicID()) { 712 const User *U; 713 if (F.hasAddressTaken(&U)) 714 Assert1(0, "Invalid user of intrinsic instruction!", U); 715 } 716 } 717 718 // verifyBasicBlock - Verify that a basic block is well formed... 719 // 720 void Verifier::visitBasicBlock(BasicBlock &BB) { 721 InstsInThisBlock.clear(); 722 723 // Ensure that basic blocks have terminators! 724 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 725 726 // Check constraints that this basic block imposes on all of the PHI nodes in 727 // it. 728 if (isa<PHINode>(BB.front())) { 729 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB)); 730 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 731 std::sort(Preds.begin(), Preds.end()); 732 PHINode *PN; 733 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) { 734 // Ensure that PHI nodes have at least one entry! 735 Assert1(PN->getNumIncomingValues() != 0, 736 "PHI nodes must have at least one entry. If the block is dead, " 737 "the PHI should be removed!", PN); 738 Assert1(PN->getNumIncomingValues() == Preds.size(), 739 "PHINode should have one entry for each predecessor of its " 740 "parent basic block!", PN); 741 742 // Get and sort all incoming values in the PHI node... 743 Values.clear(); 744 Values.reserve(PN->getNumIncomingValues()); 745 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 746 Values.push_back(std::make_pair(PN->getIncomingBlock(i), 747 PN->getIncomingValue(i))); 748 std::sort(Values.begin(), Values.end()); 749 750 for (unsigned i = 0, e = Values.size(); i != e; ++i) { 751 // Check to make sure that if there is more than one entry for a 752 // particular basic block in this PHI node, that the incoming values are 753 // all identical. 754 // 755 Assert4(i == 0 || Values[i].first != Values[i-1].first || 756 Values[i].second == Values[i-1].second, 757 "PHI node has multiple entries for the same basic block with " 758 "different incoming values!", PN, Values[i].first, 759 Values[i].second, Values[i-1].second); 760 761 // Check to make sure that the predecessors and PHI node entries are 762 // matched up. 763 Assert3(Values[i].first == Preds[i], 764 "PHI node entries do not match predecessors!", PN, 765 Values[i].first, Preds[i]); 766 } 767 } 768 } 769 } 770 771 void Verifier::visitTerminatorInst(TerminatorInst &I) { 772 // Ensure that terminators only exist at the end of the basic block. 773 Assert1(&I == I.getParent()->getTerminator(), 774 "Terminator found in the middle of a basic block!", I.getParent()); 775 visitInstruction(I); 776 } 777 778 void Verifier::visitBranchInst(BranchInst &BI) { 779 if (BI.isConditional()) { 780 Assert2(BI.getCondition()->getType()->isIntegerTy(1), 781 "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 782 } 783 visitTerminatorInst(BI); 784 } 785 786 void Verifier::visitReturnInst(ReturnInst &RI) { 787 Function *F = RI.getParent()->getParent(); 788 unsigned N = RI.getNumOperands(); 789 if (F->getReturnType()->isVoidTy()) 790 Assert2(N == 0, 791 "Found return instr that returns non-void in Function of void " 792 "return type!", &RI, F->getReturnType()); 793 else 794 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 795 "Function return type does not match operand " 796 "type of return inst!", &RI, F->getReturnType()); 797 798 // Check to make sure that the return value has necessary properties for 799 // terminators... 800 visitTerminatorInst(RI); 801 } 802 803 void Verifier::visitSwitchInst(SwitchInst &SI) { 804 // Check to make sure that all of the constants in the switch instruction 805 // have the same type as the switched-on value. 806 Type *SwitchTy = SI.getCondition()->getType(); 807 SmallPtrSet<ConstantInt*, 32> Constants; 808 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) { 809 Assert1(i.getCaseValue()->getType() == SwitchTy, 810 "Switch constants must all be same type as switch value!", &SI); 811 Assert2(Constants.insert(i.getCaseValue()), 812 "Duplicate integer as switch case", &SI, i.getCaseValue()); 813 } 814 815 visitTerminatorInst(SI); 816 } 817 818 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 819 Assert1(BI.getAddress()->getType()->isPointerTy(), 820 "Indirectbr operand must have pointer type!", &BI); 821 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 822 Assert1(BI.getDestination(i)->getType()->isLabelTy(), 823 "Indirectbr destinations must all have pointer type!", &BI); 824 825 visitTerminatorInst(BI); 826 } 827 828 void Verifier::visitSelectInst(SelectInst &SI) { 829 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 830 SI.getOperand(2)), 831 "Invalid operands for select instruction!", &SI); 832 833 Assert1(SI.getTrueValue()->getType() == SI.getType(), 834 "Select values must have same type as select instruction!", &SI); 835 visitInstruction(SI); 836 } 837 838 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 839 /// a pass, if any exist, it's an error. 840 /// 841 void Verifier::visitUserOp1(Instruction &I) { 842 Assert1(0, "User-defined operators should not live outside of a pass!", &I); 843 } 844 845 void Verifier::visitTruncInst(TruncInst &I) { 846 // Get the source and destination types 847 Type *SrcTy = I.getOperand(0)->getType(); 848 Type *DestTy = I.getType(); 849 850 // Get the size of the types in bits, we'll need this later 851 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 852 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 853 854 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 855 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 856 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 857 "trunc source and destination must both be a vector or neither", &I); 858 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I); 859 860 visitInstruction(I); 861 } 862 863 void Verifier::visitZExtInst(ZExtInst &I) { 864 // Get the source and destination types 865 Type *SrcTy = I.getOperand(0)->getType(); 866 Type *DestTy = I.getType(); 867 868 // Get the size of the types in bits, we'll need this later 869 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 870 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 871 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 872 "zext source and destination must both be a vector or neither", &I); 873 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 874 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 875 876 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I); 877 878 visitInstruction(I); 879 } 880 881 void Verifier::visitSExtInst(SExtInst &I) { 882 // Get the source and destination types 883 Type *SrcTy = I.getOperand(0)->getType(); 884 Type *DestTy = I.getType(); 885 886 // Get the size of the types in bits, we'll need this later 887 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 888 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 889 890 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 891 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 892 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 893 "sext source and destination must both be a vector or neither", &I); 894 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I); 895 896 visitInstruction(I); 897 } 898 899 void Verifier::visitFPTruncInst(FPTruncInst &I) { 900 // Get the source and destination types 901 Type *SrcTy = I.getOperand(0)->getType(); 902 Type *DestTy = I.getType(); 903 // Get the size of the types in bits, we'll need this later 904 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 905 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 906 907 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I); 908 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I); 909 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 910 "fptrunc source and destination must both be a vector or neither",&I); 911 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I); 912 913 visitInstruction(I); 914 } 915 916 void Verifier::visitFPExtInst(FPExtInst &I) { 917 // Get the source and destination types 918 Type *SrcTy = I.getOperand(0)->getType(); 919 Type *DestTy = I.getType(); 920 921 // Get the size of the types in bits, we'll need this later 922 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 923 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 924 925 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I); 926 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I); 927 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 928 "fpext source and destination must both be a vector or neither", &I); 929 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I); 930 931 visitInstruction(I); 932 } 933 934 void Verifier::visitUIToFPInst(UIToFPInst &I) { 935 // Get the source and destination types 936 Type *SrcTy = I.getOperand(0)->getType(); 937 Type *DestTy = I.getType(); 938 939 bool SrcVec = SrcTy->isVectorTy(); 940 bool DstVec = DestTy->isVectorTy(); 941 942 Assert1(SrcVec == DstVec, 943 "UIToFP source and dest must both be vector or scalar", &I); 944 Assert1(SrcTy->isIntOrIntVectorTy(), 945 "UIToFP source must be integer or integer vector", &I); 946 Assert1(DestTy->isFPOrFPVectorTy(), 947 "UIToFP result must be FP or FP vector", &I); 948 949 if (SrcVec && DstVec) 950 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 951 cast<VectorType>(DestTy)->getNumElements(), 952 "UIToFP source and dest vector length mismatch", &I); 953 954 visitInstruction(I); 955 } 956 957 void Verifier::visitSIToFPInst(SIToFPInst &I) { 958 // Get the source and destination types 959 Type *SrcTy = I.getOperand(0)->getType(); 960 Type *DestTy = I.getType(); 961 962 bool SrcVec = SrcTy->isVectorTy(); 963 bool DstVec = DestTy->isVectorTy(); 964 965 Assert1(SrcVec == DstVec, 966 "SIToFP source and dest must both be vector or scalar", &I); 967 Assert1(SrcTy->isIntOrIntVectorTy(), 968 "SIToFP source must be integer or integer vector", &I); 969 Assert1(DestTy->isFPOrFPVectorTy(), 970 "SIToFP result must be FP or FP vector", &I); 971 972 if (SrcVec && DstVec) 973 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 974 cast<VectorType>(DestTy)->getNumElements(), 975 "SIToFP source and dest vector length mismatch", &I); 976 977 visitInstruction(I); 978 } 979 980 void Verifier::visitFPToUIInst(FPToUIInst &I) { 981 // Get the source and destination types 982 Type *SrcTy = I.getOperand(0)->getType(); 983 Type *DestTy = I.getType(); 984 985 bool SrcVec = SrcTy->isVectorTy(); 986 bool DstVec = DestTy->isVectorTy(); 987 988 Assert1(SrcVec == DstVec, 989 "FPToUI source and dest must both be vector or scalar", &I); 990 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 991 &I); 992 Assert1(DestTy->isIntOrIntVectorTy(), 993 "FPToUI result must be integer or integer vector", &I); 994 995 if (SrcVec && DstVec) 996 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 997 cast<VectorType>(DestTy)->getNumElements(), 998 "FPToUI source and dest vector length mismatch", &I); 999 1000 visitInstruction(I); 1001 } 1002 1003 void Verifier::visitFPToSIInst(FPToSIInst &I) { 1004 // Get the source and destination types 1005 Type *SrcTy = I.getOperand(0)->getType(); 1006 Type *DestTy = I.getType(); 1007 1008 bool SrcVec = SrcTy->isVectorTy(); 1009 bool DstVec = DestTy->isVectorTy(); 1010 1011 Assert1(SrcVec == DstVec, 1012 "FPToSI source and dest must both be vector or scalar", &I); 1013 Assert1(SrcTy->isFPOrFPVectorTy(), 1014 "FPToSI source must be FP or FP vector", &I); 1015 Assert1(DestTy->isIntOrIntVectorTy(), 1016 "FPToSI result must be integer or integer vector", &I); 1017 1018 if (SrcVec && DstVec) 1019 Assert1(cast<VectorType>(SrcTy)->getNumElements() == 1020 cast<VectorType>(DestTy)->getNumElements(), 1021 "FPToSI source and dest vector length mismatch", &I); 1022 1023 visitInstruction(I); 1024 } 1025 1026 void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 1027 // Get the source and destination types 1028 Type *SrcTy = I.getOperand(0)->getType(); 1029 Type *DestTy = I.getType(); 1030 1031 Assert1(SrcTy->getScalarType()->isPointerTy(), 1032 "PtrToInt source must be pointer", &I); 1033 Assert1(DestTy->getScalarType()->isIntegerTy(), 1034 "PtrToInt result must be integral", &I); 1035 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1036 "PtrToInt type mismatch", &I); 1037 1038 if (SrcTy->isVectorTy()) { 1039 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 1040 VectorType *VDest = dyn_cast<VectorType>(DestTy); 1041 Assert1(VSrc->getNumElements() == VDest->getNumElements(), 1042 "PtrToInt Vector width mismatch", &I); 1043 } 1044 1045 visitInstruction(I); 1046 } 1047 1048 void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 1049 // Get the source and destination types 1050 Type *SrcTy = I.getOperand(0)->getType(); 1051 Type *DestTy = I.getType(); 1052 1053 Assert1(SrcTy->getScalarType()->isIntegerTy(), 1054 "IntToPtr source must be an integral", &I); 1055 Assert1(DestTy->getScalarType()->isPointerTy(), 1056 "IntToPtr result must be a pointer",&I); 1057 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(), 1058 "IntToPtr type mismatch", &I); 1059 if (SrcTy->isVectorTy()) { 1060 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 1061 VectorType *VDest = dyn_cast<VectorType>(DestTy); 1062 Assert1(VSrc->getNumElements() == VDest->getNumElements(), 1063 "IntToPtr Vector width mismatch", &I); 1064 } 1065 visitInstruction(I); 1066 } 1067 1068 void Verifier::visitBitCastInst(BitCastInst &I) { 1069 // Get the source and destination types 1070 Type *SrcTy = I.getOperand(0)->getType(); 1071 Type *DestTy = I.getType(); 1072 1073 // Get the size of the types in bits, we'll need this later 1074 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits(); 1075 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits(); 1076 1077 // BitCast implies a no-op cast of type only. No bits change. 1078 // However, you can't cast pointers to anything but pointers. 1079 Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(), 1080 "Bitcast requires both operands to be pointer or neither", &I); 1081 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I); 1082 1083 // Disallow aggregates. 1084 Assert1(!SrcTy->isAggregateType(), 1085 "Bitcast operand must not be aggregate", &I); 1086 Assert1(!DestTy->isAggregateType(), 1087 "Bitcast type must not be aggregate", &I); 1088 1089 visitInstruction(I); 1090 } 1091 1092 /// visitPHINode - Ensure that a PHI node is well formed. 1093 /// 1094 void Verifier::visitPHINode(PHINode &PN) { 1095 // Ensure that the PHI nodes are all grouped together at the top of the block. 1096 // This can be tested by checking whether the instruction before this is 1097 // either nonexistent (because this is begin()) or is a PHI node. If not, 1098 // then there is some other instruction before a PHI. 1099 Assert2(&PN == &PN.getParent()->front() || 1100 isa<PHINode>(--BasicBlock::iterator(&PN)), 1101 "PHI nodes not grouped at top of basic block!", 1102 &PN, PN.getParent()); 1103 1104 // Check that all of the values of the PHI node have the same type as the 1105 // result, and that the incoming blocks are really basic blocks. 1106 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1107 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(), 1108 "PHI node operands are not the same type as the result!", &PN); 1109 } 1110 1111 // All other PHI node constraints are checked in the visitBasicBlock method. 1112 1113 visitInstruction(PN); 1114 } 1115 1116 void Verifier::VerifyCallSite(CallSite CS) { 1117 Instruction *I = CS.getInstruction(); 1118 1119 Assert1(CS.getCalledValue()->getType()->isPointerTy(), 1120 "Called function must be a pointer!", I); 1121 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType()); 1122 1123 Assert1(FPTy->getElementType()->isFunctionTy(), 1124 "Called function is not pointer to function type!", I); 1125 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType()); 1126 1127 // Verify that the correct number of arguments are being passed 1128 if (FTy->isVarArg()) 1129 Assert1(CS.arg_size() >= FTy->getNumParams(), 1130 "Called function requires more parameters than were provided!",I); 1131 else 1132 Assert1(CS.arg_size() == FTy->getNumParams(), 1133 "Incorrect number of arguments passed to called function!", I); 1134 1135 // Verify that all arguments to the call match the function type. 1136 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 1137 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i), 1138 "Call parameter type does not match function signature!", 1139 CS.getArgument(i), FTy->getParamType(i), I); 1140 1141 const AttrListPtr &Attrs = CS.getAttributes(); 1142 1143 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()), 1144 "Attributes after last parameter!", I); 1145 1146 // Verify call attributes. 1147 VerifyFunctionAttrs(FTy, Attrs, I); 1148 1149 if (FTy->isVarArg()) 1150 // Check attributes on the varargs part. 1151 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) { 1152 Attributes Attr = Attrs.getParamAttributes(Idx); 1153 1154 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I); 1155 1156 Attributes VArgI = Attr & Attribute::VarArgsIncompatible; 1157 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) + 1158 " cannot be used for vararg call arguments!", I); 1159 } 1160 1161 // Verify that there's no metadata unless it's a direct call to an intrinsic. 1162 if (CS.getCalledFunction() == 0 || 1163 !CS.getCalledFunction()->getName().startswith("llvm.")) { 1164 for (FunctionType::param_iterator PI = FTy->param_begin(), 1165 PE = FTy->param_end(); PI != PE; ++PI) 1166 Assert1(!(*PI)->isMetadataTy(), 1167 "Function has metadata parameter but isn't an intrinsic", I); 1168 } 1169 1170 visitInstruction(*I); 1171 } 1172 1173 void Verifier::visitCallInst(CallInst &CI) { 1174 VerifyCallSite(&CI); 1175 1176 if (Function *F = CI.getCalledFunction()) 1177 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 1178 visitIntrinsicFunctionCall(ID, CI); 1179 } 1180 1181 void Verifier::visitInvokeInst(InvokeInst &II) { 1182 VerifyCallSite(&II); 1183 1184 // Verify that there is a landingpad instruction as the first non-PHI 1185 // instruction of the 'unwind' destination. 1186 Assert1(II.getUnwindDest()->isLandingPad(), 1187 "The unwind destination does not have a landingpad instruction!",&II); 1188 1189 visitTerminatorInst(II); 1190 } 1191 1192 /// visitBinaryOperator - Check that both arguments to the binary operator are 1193 /// of the same type! 1194 /// 1195 void Verifier::visitBinaryOperator(BinaryOperator &B) { 1196 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 1197 "Both operands to a binary operator are not of the same type!", &B); 1198 1199 switch (B.getOpcode()) { 1200 // Check that integer arithmetic operators are only used with 1201 // integral operands. 1202 case Instruction::Add: 1203 case Instruction::Sub: 1204 case Instruction::Mul: 1205 case Instruction::SDiv: 1206 case Instruction::UDiv: 1207 case Instruction::SRem: 1208 case Instruction::URem: 1209 Assert1(B.getType()->isIntOrIntVectorTy(), 1210 "Integer arithmetic operators only work with integral types!", &B); 1211 Assert1(B.getType() == B.getOperand(0)->getType(), 1212 "Integer arithmetic operators must have same type " 1213 "for operands and result!", &B); 1214 break; 1215 // Check that floating-point arithmetic operators are only used with 1216 // floating-point operands. 1217 case Instruction::FAdd: 1218 case Instruction::FSub: 1219 case Instruction::FMul: 1220 case Instruction::FDiv: 1221 case Instruction::FRem: 1222 Assert1(B.getType()->isFPOrFPVectorTy(), 1223 "Floating-point arithmetic operators only work with " 1224 "floating-point types!", &B); 1225 Assert1(B.getType() == B.getOperand(0)->getType(), 1226 "Floating-point arithmetic operators must have same type " 1227 "for operands and result!", &B); 1228 break; 1229 // Check that logical operators are only used with integral operands. 1230 case Instruction::And: 1231 case Instruction::Or: 1232 case Instruction::Xor: 1233 Assert1(B.getType()->isIntOrIntVectorTy(), 1234 "Logical operators only work with integral types!", &B); 1235 Assert1(B.getType() == B.getOperand(0)->getType(), 1236 "Logical operators must have same type for operands and result!", 1237 &B); 1238 break; 1239 case Instruction::Shl: 1240 case Instruction::LShr: 1241 case Instruction::AShr: 1242 Assert1(B.getType()->isIntOrIntVectorTy(), 1243 "Shifts only work with integral types!", &B); 1244 Assert1(B.getType() == B.getOperand(0)->getType(), 1245 "Shift return type must be same as operands!", &B); 1246 break; 1247 default: 1248 llvm_unreachable("Unknown BinaryOperator opcode!"); 1249 } 1250 1251 visitInstruction(B); 1252 } 1253 1254 void Verifier::visitICmpInst(ICmpInst &IC) { 1255 // Check that the operands are the same type 1256 Type *Op0Ty = IC.getOperand(0)->getType(); 1257 Type *Op1Ty = IC.getOperand(1)->getType(); 1258 Assert1(Op0Ty == Op1Ty, 1259 "Both operands to ICmp instruction are not of the same type!", &IC); 1260 // Check that the operands are the right type 1261 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(), 1262 "Invalid operand types for ICmp instruction", &IC); 1263 // Check that the predicate is valid. 1264 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE && 1265 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE, 1266 "Invalid predicate in ICmp instruction!", &IC); 1267 1268 visitInstruction(IC); 1269 } 1270 1271 void Verifier::visitFCmpInst(FCmpInst &FC) { 1272 // Check that the operands are the same type 1273 Type *Op0Ty = FC.getOperand(0)->getType(); 1274 Type *Op1Ty = FC.getOperand(1)->getType(); 1275 Assert1(Op0Ty == Op1Ty, 1276 "Both operands to FCmp instruction are not of the same type!", &FC); 1277 // Check that the operands are the right type 1278 Assert1(Op0Ty->isFPOrFPVectorTy(), 1279 "Invalid operand types for FCmp instruction", &FC); 1280 // Check that the predicate is valid. 1281 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE && 1282 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE, 1283 "Invalid predicate in FCmp instruction!", &FC); 1284 1285 visitInstruction(FC); 1286 } 1287 1288 void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 1289 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0), 1290 EI.getOperand(1)), 1291 "Invalid extractelement operands!", &EI); 1292 visitInstruction(EI); 1293 } 1294 1295 void Verifier::visitInsertElementInst(InsertElementInst &IE) { 1296 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0), 1297 IE.getOperand(1), 1298 IE.getOperand(2)), 1299 "Invalid insertelement operands!", &IE); 1300 visitInstruction(IE); 1301 } 1302 1303 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 1304 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 1305 SV.getOperand(2)), 1306 "Invalid shufflevector operands!", &SV); 1307 visitInstruction(SV); 1308 } 1309 1310 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 1311 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 1312 1313 Assert1(isa<PointerType>(TargetTy), 1314 "GEP base pointer is not a vector or a vector of pointers", &GEP); 1315 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(), 1316 "GEP into unsized type!", &GEP); 1317 1318 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end()); 1319 Type *ElTy = 1320 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs); 1321 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP); 1322 1323 if (GEP.getPointerOperandType()->isPointerTy()) { 1324 // Validate GEPs with scalar indices. 1325 Assert2(GEP.getType()->isPointerTy() && 1326 cast<PointerType>(GEP.getType())->getElementType() == ElTy, 1327 "GEP is not of right type for indices!", &GEP, ElTy); 1328 } else { 1329 // Validate GEPs with a vector index. 1330 Assert1(Idxs.size() == 1, "Invalid number of indices!", &GEP); 1331 Value *Index = Idxs[0]; 1332 Type *IndexTy = Index->getType(); 1333 Assert1(IndexTy->isVectorTy(), 1334 "Vector GEP must have vector indices!", &GEP); 1335 Assert1(GEP.getType()->isVectorTy(), 1336 "Vector GEP must return a vector value", &GEP); 1337 Type *ElemPtr = cast<VectorType>(GEP.getType())->getElementType(); 1338 Assert1(ElemPtr->isPointerTy(), 1339 "Vector GEP pointer operand is not a pointer!", &GEP); 1340 unsigned IndexWidth = cast<VectorType>(IndexTy)->getNumElements(); 1341 unsigned GepWidth = cast<VectorType>(GEP.getType())->getNumElements(); 1342 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP); 1343 Assert1(ElTy == cast<PointerType>(ElemPtr)->getElementType(), 1344 "Vector GEP type does not match pointer type!", &GEP); 1345 } 1346 visitInstruction(GEP); 1347 } 1348 1349 void Verifier::visitLoadInst(LoadInst &LI) { 1350 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 1351 Assert1(PTy, "Load operand must be a pointer.", &LI); 1352 Type *ElTy = PTy->getElementType(); 1353 Assert2(ElTy == LI.getType(), 1354 "Load result type does not match pointer operand type!", &LI, ElTy); 1355 if (LI.isAtomic()) { 1356 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease, 1357 "Load cannot have Release ordering", &LI); 1358 Assert1(LI.getAlignment() != 0, 1359 "Atomic load must specify explicit alignment", &LI); 1360 } else { 1361 Assert1(LI.getSynchScope() == CrossThread, 1362 "Non-atomic load cannot have SynchronizationScope specified", &LI); 1363 } 1364 1365 if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) { 1366 unsigned NumOperands = Range->getNumOperands(); 1367 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range); 1368 unsigned NumRanges = NumOperands / 2; 1369 Assert1(NumRanges >= 1, "It should have at least one range!", Range); 1370 for (unsigned i = 0; i < NumRanges; ++i) { 1371 ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i)); 1372 Assert1(Low, "The lower limit must be an integer!", Low); 1373 ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1)); 1374 Assert1(High, "The upper limit must be an integer!", High); 1375 Assert1(High->getType() == Low->getType() && 1376 High->getType() == ElTy, "Range types must match load type!", 1377 &LI); 1378 Assert1(High->getValue() != Low->getValue(), "Range must not be empty!", 1379 Range); 1380 } 1381 } 1382 1383 visitInstruction(LI); 1384 } 1385 1386 void Verifier::visitStoreInst(StoreInst &SI) { 1387 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 1388 Assert1(PTy, "Store operand must be a pointer.", &SI); 1389 Type *ElTy = PTy->getElementType(); 1390 Assert2(ElTy == SI.getOperand(0)->getType(), 1391 "Stored value type does not match pointer operand type!", 1392 &SI, ElTy); 1393 if (SI.isAtomic()) { 1394 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease, 1395 "Store cannot have Acquire ordering", &SI); 1396 Assert1(SI.getAlignment() != 0, 1397 "Atomic store must specify explicit alignment", &SI); 1398 } else { 1399 Assert1(SI.getSynchScope() == CrossThread, 1400 "Non-atomic store cannot have SynchronizationScope specified", &SI); 1401 } 1402 visitInstruction(SI); 1403 } 1404 1405 void Verifier::visitAllocaInst(AllocaInst &AI) { 1406 PointerType *PTy = AI.getType(); 1407 Assert1(PTy->getAddressSpace() == 0, 1408 "Allocation instruction pointer not in the generic address space!", 1409 &AI); 1410 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type", 1411 &AI); 1412 Assert1(AI.getArraySize()->getType()->isIntegerTy(), 1413 "Alloca array size must have integer type", &AI); 1414 visitInstruction(AI); 1415 } 1416 1417 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 1418 Assert1(CXI.getOrdering() != NotAtomic, 1419 "cmpxchg instructions must be atomic.", &CXI); 1420 Assert1(CXI.getOrdering() != Unordered, 1421 "cmpxchg instructions cannot be unordered.", &CXI); 1422 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType()); 1423 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI); 1424 Type *ElTy = PTy->getElementType(); 1425 Assert2(ElTy == CXI.getOperand(1)->getType(), 1426 "Expected value type does not match pointer operand type!", 1427 &CXI, ElTy); 1428 Assert2(ElTy == CXI.getOperand(2)->getType(), 1429 "Stored value type does not match pointer operand type!", 1430 &CXI, ElTy); 1431 visitInstruction(CXI); 1432 } 1433 1434 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 1435 Assert1(RMWI.getOrdering() != NotAtomic, 1436 "atomicrmw instructions must be atomic.", &RMWI); 1437 Assert1(RMWI.getOrdering() != Unordered, 1438 "atomicrmw instructions cannot be unordered.", &RMWI); 1439 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType()); 1440 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI); 1441 Type *ElTy = PTy->getElementType(); 1442 Assert2(ElTy == RMWI.getOperand(1)->getType(), 1443 "Argument value type does not match pointer operand type!", 1444 &RMWI, ElTy); 1445 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() && 1446 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP, 1447 "Invalid binary operation!", &RMWI); 1448 visitInstruction(RMWI); 1449 } 1450 1451 void Verifier::visitFenceInst(FenceInst &FI) { 1452 const AtomicOrdering Ordering = FI.getOrdering(); 1453 Assert1(Ordering == Acquire || Ordering == Release || 1454 Ordering == AcquireRelease || Ordering == SequentiallyConsistent, 1455 "fence instructions may only have " 1456 "acquire, release, acq_rel, or seq_cst ordering.", &FI); 1457 visitInstruction(FI); 1458 } 1459 1460 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 1461 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 1462 EVI.getIndices()) == 1463 EVI.getType(), 1464 "Invalid ExtractValueInst operands!", &EVI); 1465 1466 visitInstruction(EVI); 1467 } 1468 1469 void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 1470 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 1471 IVI.getIndices()) == 1472 IVI.getOperand(1)->getType(), 1473 "Invalid InsertValueInst operands!", &IVI); 1474 1475 visitInstruction(IVI); 1476 } 1477 1478 void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 1479 BasicBlock *BB = LPI.getParent(); 1480 1481 // The landingpad instruction is ill-formed if it doesn't have any clauses and 1482 // isn't a cleanup. 1483 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(), 1484 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 1485 1486 // The landingpad instruction defines its parent as a landing pad block. The 1487 // landing pad block may be branched to only by the unwind edge of an invoke. 1488 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) { 1489 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()); 1490 Assert1(II && II->getUnwindDest() == BB, 1491 "Block containing LandingPadInst must be jumped to " 1492 "only by the unwind edge of an invoke.", &LPI); 1493 } 1494 1495 // The landingpad instruction must be the first non-PHI instruction in the 1496 // block. 1497 Assert1(LPI.getParent()->getLandingPadInst() == &LPI, 1498 "LandingPadInst not the first non-PHI instruction in the block.", 1499 &LPI); 1500 1501 // The personality functions for all landingpad instructions within the same 1502 // function should match. 1503 if (PersonalityFn) 1504 Assert1(LPI.getPersonalityFn() == PersonalityFn, 1505 "Personality function doesn't match others in function", &LPI); 1506 PersonalityFn = LPI.getPersonalityFn(); 1507 1508 // All operands must be constants. 1509 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!", 1510 &LPI); 1511 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 1512 Value *Clause = LPI.getClause(i); 1513 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI); 1514 if (LPI.isCatch(i)) { 1515 Assert1(isa<PointerType>(Clause->getType()), 1516 "Catch operand does not have pointer type!", &LPI); 1517 } else { 1518 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 1519 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 1520 "Filter operand is not an array of constants!", &LPI); 1521 } 1522 } 1523 1524 visitInstruction(LPI); 1525 } 1526 1527 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 1528 Instruction *Op = cast<Instruction>(I.getOperand(i)); 1529 BasicBlock *BB = I.getParent(); 1530 BasicBlock *OpBlock = Op->getParent(); 1531 PHINode *PN = dyn_cast<PHINode>(&I); 1532 1533 // DT can handle non phi instructions for us. 1534 if (!PN) { 1535 // Definition must dominate use unless use is unreachable! 1536 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB) || 1537 DT->dominates(Op, &I), 1538 "Instruction does not dominate all uses!", Op, &I); 1539 return; 1540 } 1541 1542 // Check that a definition dominates all of its uses. 1543 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 1544 // Invoke results are only usable in the normal destination, not in the 1545 // exceptional destination. 1546 BasicBlock *NormalDest = II->getNormalDest(); 1547 1548 1549 // PHI nodes differ from other nodes because they actually "use" the 1550 // value in the predecessor basic blocks they correspond to. 1551 BasicBlock *UseBlock = BB; 1552 unsigned j = PHINode::getIncomingValueNumForOperand(i); 1553 UseBlock = PN->getIncomingBlock(j); 1554 Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB", 1555 Op, &I); 1556 1557 if (UseBlock == OpBlock) { 1558 // Special case of a phi node in the normal destination or the unwind 1559 // destination. 1560 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock), 1561 "Invoke result not available in the unwind destination!", 1562 Op, &I); 1563 } else { 1564 Assert2(DT->dominates(II, UseBlock) || 1565 !DT->isReachableFromEntry(UseBlock), 1566 "Invoke result does not dominate all uses!", Op, &I); 1567 } 1568 } 1569 1570 // PHI nodes are more difficult than other nodes because they actually 1571 // "use" the value in the predecessor basic blocks they correspond to. 1572 unsigned j = PHINode::getIncomingValueNumForOperand(i); 1573 BasicBlock *PredBB = PN->getIncomingBlock(j); 1574 Assert2(PredBB && (DT->dominates(OpBlock, PredBB) || 1575 !DT->isReachableFromEntry(PredBB)), 1576 "Instruction does not dominate all uses!", Op, &I); 1577 } 1578 1579 /// verifyInstruction - Verify that an instruction is well formed. 1580 /// 1581 void Verifier::visitInstruction(Instruction &I) { 1582 BasicBlock *BB = I.getParent(); 1583 Assert1(BB, "Instruction not embedded in basic block!", &I); 1584 1585 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 1586 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); 1587 UI != UE; ++UI) 1588 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB), 1589 "Only PHI nodes may reference their own value!", &I); 1590 } 1591 1592 // Check that void typed values don't have names 1593 Assert1(!I.getType()->isVoidTy() || !I.hasName(), 1594 "Instruction has a name, but provides a void value!", &I); 1595 1596 // Check that the return value of the instruction is either void or a legal 1597 // value type. 1598 Assert1(I.getType()->isVoidTy() || 1599 I.getType()->isFirstClassType(), 1600 "Instruction returns a non-scalar type!", &I); 1601 1602 // Check that the instruction doesn't produce metadata. Calls are already 1603 // checked against the callee type. 1604 Assert1(!I.getType()->isMetadataTy() || 1605 isa<CallInst>(I) || isa<InvokeInst>(I), 1606 "Invalid use of metadata!", &I); 1607 1608 // Check that all uses of the instruction, if they are instructions 1609 // themselves, actually have parent basic blocks. If the use is not an 1610 // instruction, it is an error! 1611 for (User::use_iterator UI = I.use_begin(), UE = I.use_end(); 1612 UI != UE; ++UI) { 1613 if (Instruction *Used = dyn_cast<Instruction>(*UI)) 1614 Assert2(Used->getParent() != 0, "Instruction referencing instruction not" 1615 " embedded in a basic block!", &I, Used); 1616 else { 1617 CheckFailed("Use of instruction is not an instruction!", *UI); 1618 return; 1619 } 1620 } 1621 1622 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 1623 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I); 1624 1625 // Check to make sure that only first-class-values are operands to 1626 // instructions. 1627 if (!I.getOperand(i)->getType()->isFirstClassType()) { 1628 Assert1(0, "Instruction operands must be first-class values!", &I); 1629 } 1630 1631 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 1632 // Check to make sure that the "address of" an intrinsic function is never 1633 // taken. 1634 Assert1(!F->isIntrinsic() || (i + 1 == e && isa<CallInst>(I)), 1635 "Cannot take the address of an intrinsic!", &I); 1636 Assert1(F->getParent() == Mod, "Referencing function in another module!", 1637 &I); 1638 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 1639 Assert1(OpBB->getParent() == BB->getParent(), 1640 "Referring to a basic block in another function!", &I); 1641 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 1642 Assert1(OpArg->getParent() == BB->getParent(), 1643 "Referring to an argument in another function!", &I); 1644 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 1645 Assert1(GV->getParent() == Mod, "Referencing global in another module!", 1646 &I); 1647 } else if (isa<Instruction>(I.getOperand(i))) { 1648 verifyDominatesUse(I, i); 1649 } else if (isa<InlineAsm>(I.getOperand(i))) { 1650 Assert1((i + 1 == e && isa<CallInst>(I)) || 1651 (i + 3 == e && isa<InvokeInst>(I)), 1652 "Cannot take the address of an inline asm!", &I); 1653 } 1654 } 1655 1656 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 1657 Assert1(I.getType()->isFPOrFPVectorTy(), 1658 "fpmath requires a floating point result!", &I); 1659 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 1660 Value *Op0 = MD->getOperand(0); 1661 if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) { 1662 APFloat Accuracy = CFP0->getValueAPF(); 1663 Assert1(Accuracy.isNormal() && !Accuracy.isNegative(), 1664 "fpmath accuracy not a positive number!", &I); 1665 } else { 1666 Assert1(false, "invalid fpmath accuracy!", &I); 1667 } 1668 } 1669 1670 MDNode *MD = I.getMetadata(LLVMContext::MD_range); 1671 Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I); 1672 1673 InstsInThisBlock.insert(&I); 1674 } 1675 1676 // Flags used by TableGen to mark intrinsic parameters with the 1677 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes. 1678 static const unsigned ExtendedElementVectorType = 0x40000000; 1679 static const unsigned TruncatedElementVectorType = 0x20000000; 1680 1681 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways. 1682 /// 1683 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) { 1684 Function *IF = CI.getCalledFunction(); 1685 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!", 1686 IF); 1687 1688 #define GET_INTRINSIC_VERIFIER 1689 #include "llvm/Intrinsics.gen" 1690 #undef GET_INTRINSIC_VERIFIER 1691 1692 // If the intrinsic takes MDNode arguments, verify that they are either global 1693 // or are local to *this* function. 1694 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i) 1695 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i))) 1696 visitMDNode(*MD, CI.getParent()->getParent()); 1697 1698 switch (ID) { 1699 default: 1700 break; 1701 case Intrinsic::ctlz: // llvm.ctlz 1702 case Intrinsic::cttz: // llvm.cttz 1703 Assert1(isa<ConstantInt>(CI.getArgOperand(1)), 1704 "is_zero_undef argument of bit counting intrinsics must be a " 1705 "constant int", &CI); 1706 break; 1707 case Intrinsic::dbg_declare: { // llvm.dbg.declare 1708 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)), 1709 "invalid llvm.dbg.declare intrinsic call 1", &CI); 1710 MDNode *MD = cast<MDNode>(CI.getArgOperand(0)); 1711 Assert1(MD->getNumOperands() == 1, 1712 "invalid llvm.dbg.declare intrinsic call 2", &CI); 1713 } break; 1714 case Intrinsic::memcpy: 1715 case Intrinsic::memmove: 1716 case Intrinsic::memset: 1717 Assert1(isa<ConstantInt>(CI.getArgOperand(3)), 1718 "alignment argument of memory intrinsics must be a constant int", 1719 &CI); 1720 Assert1(isa<ConstantInt>(CI.getArgOperand(4)), 1721 "isvolatile argument of memory intrinsics must be a constant int", 1722 &CI); 1723 break; 1724 case Intrinsic::gcroot: 1725 case Intrinsic::gcwrite: 1726 case Intrinsic::gcread: 1727 if (ID == Intrinsic::gcroot) { 1728 AllocaInst *AI = 1729 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts()); 1730 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI); 1731 Assert1(isa<Constant>(CI.getArgOperand(1)), 1732 "llvm.gcroot parameter #2 must be a constant.", &CI); 1733 if (!AI->getType()->getElementType()->isPointerTy()) { 1734 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)), 1735 "llvm.gcroot parameter #1 must either be a pointer alloca, " 1736 "or argument #2 must be a non-null constant.", &CI); 1737 } 1738 } 1739 1740 Assert1(CI.getParent()->getParent()->hasGC(), 1741 "Enclosing function does not use GC.", &CI); 1742 break; 1743 case Intrinsic::init_trampoline: 1744 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()), 1745 "llvm.init_trampoline parameter #2 must resolve to a function.", 1746 &CI); 1747 break; 1748 case Intrinsic::prefetch: 1749 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) && 1750 isa<ConstantInt>(CI.getArgOperand(2)) && 1751 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 && 1752 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4, 1753 "invalid arguments to llvm.prefetch", 1754 &CI); 1755 break; 1756 case Intrinsic::stackprotector: 1757 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()), 1758 "llvm.stackprotector parameter #2 must resolve to an alloca.", 1759 &CI); 1760 break; 1761 case Intrinsic::lifetime_start: 1762 case Intrinsic::lifetime_end: 1763 case Intrinsic::invariant_start: 1764 Assert1(isa<ConstantInt>(CI.getArgOperand(0)), 1765 "size argument of memory use markers must be a constant integer", 1766 &CI); 1767 break; 1768 case Intrinsic::invariant_end: 1769 Assert1(isa<ConstantInt>(CI.getArgOperand(1)), 1770 "llvm.invariant.end parameter #2 must be a constant integer", &CI); 1771 break; 1772 } 1773 } 1774 1775 /// Produce a string to identify an intrinsic parameter or return value. 1776 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the 1777 /// parameters beginning with NumRets. 1778 /// 1779 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) { 1780 if (ArgNo >= NumRets) 1781 return "Intrinsic parameter #" + utostr(ArgNo - NumRets); 1782 if (NumRets == 1) 1783 return "Intrinsic result type"; 1784 return "Intrinsic result type #" + utostr(ArgNo); 1785 } 1786 1787 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, 1788 int VT, unsigned ArgNo, std::string &Suffix) { 1789 FunctionType *FTy = F->getFunctionType(); 1790 1791 unsigned NumElts = 0; 1792 Type *EltTy = Ty; 1793 VectorType *VTy = dyn_cast<VectorType>(Ty); 1794 if (VTy) { 1795 EltTy = VTy->getElementType(); 1796 NumElts = VTy->getNumElements(); 1797 } 1798 1799 Type *RetTy = FTy->getReturnType(); 1800 StructType *ST = dyn_cast<StructType>(RetTy); 1801 unsigned NumRetVals; 1802 if (RetTy->isVoidTy()) 1803 NumRetVals = 0; 1804 else if (ST) 1805 NumRetVals = ST->getNumElements(); 1806 else 1807 NumRetVals = 1; 1808 1809 if (VT < 0) { 1810 int Match = ~VT; 1811 1812 // Check flags that indicate a type that is an integral vector type with 1813 // elements that are larger or smaller than the elements of the matched 1814 // type. 1815 if ((Match & (ExtendedElementVectorType | 1816 TruncatedElementVectorType)) != 0) { 1817 IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy); 1818 if (!VTy || !IEltTy) { 1819 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not " 1820 "an integral vector type.", F); 1821 return false; 1822 } 1823 // Adjust the current Ty (in the opposite direction) rather than 1824 // the type being matched against. 1825 if ((Match & ExtendedElementVectorType) != 0) { 1826 if ((IEltTy->getBitWidth() & 1) != 0) { 1827 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector " 1828 "element bit-width is odd.", F); 1829 return false; 1830 } 1831 Ty = VectorType::getTruncatedElementVectorType(VTy); 1832 } else 1833 Ty = VectorType::getExtendedElementVectorType(VTy); 1834 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType); 1835 } 1836 1837 if (Match <= static_cast<int>(NumRetVals - 1)) { 1838 if (ST) 1839 RetTy = ST->getElementType(Match); 1840 1841 if (Ty != RetTy) { 1842 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not " 1843 "match return type.", F); 1844 return false; 1845 } 1846 } else { 1847 if (Ty != FTy->getParamType(Match - NumRetVals)) { 1848 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not " 1849 "match parameter %" + utostr(Match - NumRetVals) + ".", F); 1850 return false; 1851 } 1852 } 1853 } else if (VT == MVT::iAny) { 1854 if (!EltTy->isIntegerTy()) { 1855 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not " 1856 "an integer type.", F); 1857 return false; 1858 } 1859 1860 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth(); 1861 Suffix += "."; 1862 1863 if (EltTy != Ty) 1864 Suffix += "v" + utostr(NumElts); 1865 1866 Suffix += "i" + utostr(GotBits); 1867 1868 // Check some constraints on various intrinsics. 1869 switch (ID) { 1870 default: break; // Not everything needs to be checked. 1871 case Intrinsic::bswap: 1872 if (GotBits < 16 || GotBits % 16 != 0) { 1873 CheckFailed("Intrinsic requires even byte width argument", F); 1874 return false; 1875 } 1876 break; 1877 } 1878 } else if (VT == MVT::fAny) { 1879 if (!EltTy->isFloatingPointTy()) { 1880 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not " 1881 "a floating-point type.", F); 1882 return false; 1883 } 1884 1885 Suffix += "."; 1886 1887 if (EltTy != Ty) 1888 Suffix += "v" + utostr(NumElts); 1889 1890 Suffix += EVT::getEVT(EltTy).getEVTString(); 1891 } else if (VT == MVT::vAny) { 1892 if (!VTy) { 1893 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.", 1894 F); 1895 return false; 1896 } 1897 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString(); 1898 } else if (VT == MVT::iPTR) { 1899 if (!Ty->isPointerTy()) { 1900 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a " 1901 "pointer and a pointer is required.", F); 1902 return false; 1903 } 1904 } else if (VT == MVT::iPTRAny) { 1905 // Outside of TableGen, we don't distinguish iPTRAny (to any address space) 1906 // and iPTR. In the verifier, we can not distinguish which case we have so 1907 // allow either case to be legal. 1908 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 1909 EVT PointeeVT = EVT::getEVT(PTyp->getElementType(), true); 1910 if (PointeeVT == MVT::Other) { 1911 CheckFailed("Intrinsic has pointer to complex type."); 1912 return false; 1913 } 1914 Suffix += ".p" + utostr(PTyp->getAddressSpace()) + 1915 PointeeVT.getEVTString(); 1916 } else { 1917 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a " 1918 "pointer and a pointer is required.", F); 1919 return false; 1920 } 1921 } else if (EVT((MVT::SimpleValueType)VT).isVector()) { 1922 EVT VVT = EVT((MVT::SimpleValueType)VT); 1923 1924 // If this is a vector argument, verify the number and type of elements. 1925 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) { 1926 CheckFailed("Intrinsic prototype has incorrect vector element type!", F); 1927 return false; 1928 } 1929 1930 if (VVT.getVectorNumElements() != NumElts) { 1931 CheckFailed("Intrinsic prototype has incorrect number of " 1932 "vector elements!", F); 1933 return false; 1934 } 1935 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) != 1936 EltTy) { 1937 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F); 1938 return false; 1939 } else if (EltTy != Ty) { 1940 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector " 1941 "and a scalar is required.", F); 1942 return false; 1943 } 1944 1945 return true; 1946 } 1947 1948 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into 1949 /// Intrinsics.gen. This implements a little state machine that verifies the 1950 /// prototype of intrinsics. 1951 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F, 1952 unsigned NumRetVals, 1953 unsigned NumParams, ...) { 1954 va_list VA; 1955 va_start(VA, NumParams); 1956 FunctionType *FTy = F->getFunctionType(); 1957 1958 // For overloaded intrinsics, the Suffix of the function name must match the 1959 // types of the arguments. This variable keeps track of the expected 1960 // suffix, to be checked at the end. 1961 std::string Suffix; 1962 1963 if (FTy->getNumParams() + FTy->isVarArg() != NumParams) { 1964 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F); 1965 return; 1966 } 1967 1968 Type *Ty = FTy->getReturnType(); 1969 StructType *ST = dyn_cast<StructType>(Ty); 1970 1971 if (NumRetVals == 0 && !Ty->isVoidTy()) { 1972 CheckFailed("Intrinsic should return void", F); 1973 return; 1974 } 1975 1976 // Verify the return types. 1977 if (ST && ST->getNumElements() != NumRetVals) { 1978 CheckFailed("Intrinsic prototype has incorrect number of return types!", F); 1979 return; 1980 } 1981 1982 for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) { 1983 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative. 1984 1985 if (ST) Ty = ST->getElementType(ArgNo); 1986 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix)) 1987 break; 1988 } 1989 1990 // Verify the parameter types. 1991 for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) { 1992 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative. 1993 1994 if (VT == MVT::isVoid && ArgNo > 0) { 1995 if (!FTy->isVarArg()) 1996 CheckFailed("Intrinsic prototype has no '...'!", F); 1997 break; 1998 } 1999 2000 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT, 2001 ArgNo + NumRetVals, Suffix)) 2002 break; 2003 } 2004 2005 va_end(VA); 2006 2007 // For intrinsics without pointer arguments, if we computed a Suffix then the 2008 // intrinsic is overloaded and we need to make sure that the name of the 2009 // function is correct. We add the suffix to the name of the intrinsic and 2010 // compare against the given function name. If they are not the same, the 2011 // function name is invalid. This ensures that overloading of intrinsics 2012 // uses a sane and consistent naming convention. Note that intrinsics with 2013 // pointer argument may or may not be overloaded so we will check assuming it 2014 // has a suffix and not. 2015 if (!Suffix.empty()) { 2016 std::string Name(Intrinsic::getName(ID)); 2017 if (Name + Suffix != F->getName()) { 2018 CheckFailed("Overloaded intrinsic has incorrect suffix: '" + 2019 F->getName().substr(Name.length()) + "'. It should be '" + 2020 Suffix + "'", F); 2021 } 2022 } 2023 2024 // Check parameter attributes. 2025 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID), 2026 "Intrinsic has wrong parameter attributes!", F); 2027 } 2028 2029 2030 //===----------------------------------------------------------------------===// 2031 // Implement the public interfaces to this file... 2032 //===----------------------------------------------------------------------===// 2033 2034 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) { 2035 return new Verifier(action); 2036 } 2037 2038 2039 /// verifyFunction - Check a function for errors, printing messages on stderr. 2040 /// Return true if the function is corrupt. 2041 /// 2042 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) { 2043 Function &F = const_cast<Function&>(f); 2044 assert(!F.isDeclaration() && "Cannot verify external functions"); 2045 2046 FunctionPassManager FPM(F.getParent()); 2047 Verifier *V = new Verifier(action); 2048 FPM.add(V); 2049 FPM.run(F); 2050 return V->Broken; 2051 } 2052 2053 /// verifyModule - Check a module for errors, printing messages on stderr. 2054 /// Return true if the module is corrupt. 2055 /// 2056 bool llvm::verifyModule(const Module &M, VerifierFailureAction action, 2057 std::string *ErrorInfo) { 2058 PassManager PM; 2059 Verifier *V = new Verifier(action); 2060 PM.add(V); 2061 PM.run(const_cast<Module&>(M)); 2062 2063 if (ErrorInfo && V->Broken) 2064 *ErrorInfo = V->MessagesStr.str(); 2065 return V->Broken; 2066 } 2067