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 // * Landingpad instructions must be in a function with a personality function. 43 // * All other things that are tested by asserts spread about the code... 44 // 45 //===----------------------------------------------------------------------===// 46 47 #include "llvm/IR/Verifier.h" 48 #include "llvm/ADT/MapVector.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/IR/CFG.h" 55 #include "llvm/IR/CallSite.h" 56 #include "llvm/IR/CallingConv.h" 57 #include "llvm/IR/ConstantRange.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugInfo.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Dominators.h" 64 #include "llvm/IR/InlineAsm.h" 65 #include "llvm/IR/InstIterator.h" 66 #include "llvm/IR/InstVisitor.h" 67 #include "llvm/IR/IntrinsicInst.h" 68 #include "llvm/IR/LLVMContext.h" 69 #include "llvm/IR/Metadata.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/ModuleSlotTracker.h" 72 #include "llvm/IR/PassManager.h" 73 #include "llvm/IR/Statepoint.h" 74 #include "llvm/Pass.h" 75 #include "llvm/Support/CommandLine.h" 76 #include "llvm/Support/Debug.h" 77 #include "llvm/Support/ErrorHandling.h" 78 #include "llvm/Support/raw_ostream.h" 79 #include <algorithm> 80 #include <cstdarg> 81 using namespace llvm; 82 83 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true)); 84 85 namespace { 86 struct VerifierSupport { 87 raw_ostream *OS; 88 const Module *M = nullptr; 89 Optional<ModuleSlotTracker> MST; 90 91 /// Track the brokenness of the module while recursively visiting. 92 bool Broken = false; 93 /// Broken debug info can be "recovered" from by stripping the debug info. 94 bool BrokenDebugInfo = false; 95 /// Whether to treat broken debug info as an error. 96 bool TreatBrokenDebugInfoAsError = true; 97 98 explicit VerifierSupport(raw_ostream *OS) : OS(OS) {} 99 100 private: 101 template <class NodeTy> void Write(const ilist_iterator<NodeTy> &I) { 102 Write(&*I); 103 } 104 105 void Write(const Module *M) { 106 if (!M) 107 return; 108 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 109 } 110 111 void Write(const Value *V) { 112 if (!V) 113 return; 114 if (isa<Instruction>(V)) { 115 V->print(*OS, *MST); 116 *OS << '\n'; 117 } else { 118 V->printAsOperand(*OS, true, *MST); 119 *OS << '\n'; 120 } 121 } 122 void Write(ImmutableCallSite CS) { 123 Write(CS.getInstruction()); 124 } 125 126 void Write(const Metadata *MD) { 127 if (!MD) 128 return; 129 MD->print(*OS, *MST, M); 130 *OS << '\n'; 131 } 132 133 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) { 134 Write(MD.get()); 135 } 136 137 void Write(const NamedMDNode *NMD) { 138 if (!NMD) 139 return; 140 NMD->print(*OS, *MST); 141 *OS << '\n'; 142 } 143 144 void Write(Type *T) { 145 if (!T) 146 return; 147 *OS << ' ' << *T; 148 } 149 150 void Write(const Comdat *C) { 151 if (!C) 152 return; 153 *OS << *C; 154 } 155 156 template <typename T> void Write(ArrayRef<T> Vs) { 157 for (const T &V : Vs) 158 Write(V); 159 } 160 161 template <typename T1, typename... Ts> 162 void WriteTs(const T1 &V1, const Ts &... Vs) { 163 Write(V1); 164 WriteTs(Vs...); 165 } 166 167 template <typename... Ts> void WriteTs() {} 168 169 public: 170 /// \brief A check failed, so printout out the condition and the message. 171 /// 172 /// This provides a nice place to put a breakpoint if you want to see why 173 /// something is not correct. 174 void CheckFailed(const Twine &Message) { 175 if (OS) 176 *OS << Message << '\n'; 177 Broken = true; 178 } 179 180 /// \brief A check failed (with values to print). 181 /// 182 /// This calls the Message-only version so that the above is easier to set a 183 /// breakpoint on. 184 template <typename T1, typename... Ts> 185 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) { 186 CheckFailed(Message); 187 if (OS) 188 WriteTs(V1, Vs...); 189 } 190 191 /// A debug info check failed. 192 void DebugInfoCheckFailed(const Twine &Message) { 193 if (OS) 194 *OS << Message << '\n'; 195 Broken |= TreatBrokenDebugInfoAsError; 196 BrokenDebugInfo = true; 197 } 198 199 /// A debug info check failed (with values to print). 200 template <typename T1, typename... Ts> 201 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, 202 const Ts &... Vs) { 203 DebugInfoCheckFailed(Message); 204 if (OS) 205 WriteTs(V1, Vs...); 206 } 207 }; 208 209 class Verifier : public InstVisitor<Verifier>, VerifierSupport { 210 friend class InstVisitor<Verifier>; 211 212 LLVMContext *Context; 213 DominatorTree DT; 214 215 /// \brief When verifying a basic block, keep track of all of the 216 /// instructions we have seen so far. 217 /// 218 /// This allows us to do efficient dominance checks for the case when an 219 /// instruction has an operand that is an instruction in the same block. 220 SmallPtrSet<Instruction *, 16> InstsInThisBlock; 221 222 /// \brief Keep track of the metadata nodes that have been checked already. 223 SmallPtrSet<const Metadata *, 32> MDNodes; 224 225 /// Track all DICompileUnits visited. 226 SmallPtrSet<const Metadata *, 2> CUVisited; 227 228 /// \brief The result type for a landingpad. 229 Type *LandingPadResultTy; 230 231 /// \brief Whether we've seen a call to @llvm.localescape in this function 232 /// already. 233 bool SawFrameEscape; 234 235 /// Stores the count of how many objects were passed to llvm.localescape for a 236 /// given function and the largest index passed to llvm.localrecover. 237 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo; 238 239 // Maps catchswitches and cleanuppads that unwind to siblings to the 240 // terminators that indicate the unwind, used to detect cycles therein. 241 MapVector<Instruction *, TerminatorInst *> SiblingFuncletInfo; 242 243 /// Cache of constants visited in search of ConstantExprs. 244 SmallPtrSet<const Constant *, 32> ConstantExprVisited; 245 246 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic. 247 SmallVector<const Function *, 4> DeoptimizeDeclarations; 248 249 // Verify that this GlobalValue is only used in this module. 250 // This map is used to avoid visiting uses twice. We can arrive at a user 251 // twice, if they have multiple operands. In particular for very large 252 // constant expressions, we can arrive at a particular user many times. 253 SmallPtrSet<const Value *, 32> GlobalValueVisited; 254 255 void checkAtomicMemAccessSize(const Module *M, Type *Ty, 256 const Instruction *I); 257 258 void updateModule(const Module *NewM) { 259 if (M == NewM) 260 return; 261 MST.emplace(NewM); 262 M = NewM; 263 } 264 265 public: 266 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError) 267 : VerifierSupport(OS), Context(nullptr), LandingPadResultTy(nullptr), 268 SawFrameEscape(false) { 269 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError; 270 } 271 272 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; } 273 274 bool verify(const Function &F) { 275 updateModule(F.getParent()); 276 Context = &M->getContext(); 277 278 // First ensure the function is well-enough formed to compute dominance 279 // information, and directly compute a dominance tree. We don't rely on the 280 // pass manager to provide this as it isolates us from a potentially 281 // out-of-date dominator tree and makes it significantly more complex to run 282 // this code outside of a pass manager. 283 // FIXME: It's really gross that we have to cast away constness here. 284 if (!F.empty()) 285 DT.recalculate(const_cast<Function &>(F)); 286 287 for (const BasicBlock &BB : F) { 288 if (!BB.empty() && BB.back().isTerminator()) 289 continue; 290 291 if (OS) { 292 *OS << "Basic Block in function '" << F.getName() 293 << "' does not have terminator!\n"; 294 BB.printAsOperand(*OS, true, *MST); 295 *OS << "\n"; 296 } 297 return false; 298 } 299 300 Broken = false; 301 // FIXME: We strip const here because the inst visitor strips const. 302 visit(const_cast<Function &>(F)); 303 verifySiblingFuncletUnwinds(); 304 InstsInThisBlock.clear(); 305 LandingPadResultTy = nullptr; 306 SawFrameEscape = false; 307 SiblingFuncletInfo.clear(); 308 309 return !Broken; 310 } 311 312 bool verify(const Module &M) { 313 updateModule(&M); 314 Context = &M.getContext(); 315 Broken = false; 316 317 // Collect all declarations of the llvm.experimental.deoptimize intrinsic. 318 for (const Function &F : M) 319 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize) 320 DeoptimizeDeclarations.push_back(&F); 321 322 // Now that we've visited every function, verify that we never asked to 323 // recover a frame index that wasn't escaped. 324 verifyFrameRecoverIndices(); 325 for (const GlobalVariable &GV : M.globals()) 326 visitGlobalVariable(GV); 327 328 for (const GlobalAlias &GA : M.aliases()) 329 visitGlobalAlias(GA); 330 331 for (const NamedMDNode &NMD : M.named_metadata()) 332 visitNamedMDNode(NMD); 333 334 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable()) 335 visitComdat(SMEC.getValue()); 336 337 visitModuleFlags(M); 338 visitModuleIdents(M); 339 340 verifyCompileUnits(); 341 342 verifyDeoptimizeCallingConvs(); 343 344 return !Broken; 345 } 346 347 private: 348 // Verification methods... 349 void visitGlobalValue(const GlobalValue &GV); 350 void visitGlobalVariable(const GlobalVariable &GV); 351 void visitGlobalAlias(const GlobalAlias &GA); 352 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C); 353 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited, 354 const GlobalAlias &A, const Constant &C); 355 void visitNamedMDNode(const NamedMDNode &NMD); 356 void visitMDNode(const MDNode &MD); 357 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F); 358 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F); 359 void visitComdat(const Comdat &C); 360 void visitModuleIdents(const Module &M); 361 void visitModuleFlags(const Module &M); 362 void visitModuleFlag(const MDNode *Op, 363 DenseMap<const MDString *, const MDNode *> &SeenIDs, 364 SmallVectorImpl<const MDNode *> &Requirements); 365 void visitFunction(const Function &F); 366 void visitBasicBlock(BasicBlock &BB); 367 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty); 368 void visitDereferenceableMetadata(Instruction& I, MDNode* MD); 369 370 template <class Ty> bool isValidMetadataArray(const MDTuple &N); 371 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N); 372 #include "llvm/IR/Metadata.def" 373 void visitDIScope(const DIScope &N); 374 void visitDIVariable(const DIVariable &N); 375 void visitDILexicalBlockBase(const DILexicalBlockBase &N); 376 void visitDITemplateParameter(const DITemplateParameter &N); 377 378 void visitTemplateParams(const MDNode &N, const Metadata &RawParams); 379 380 // InstVisitor overrides... 381 using InstVisitor<Verifier>::visit; 382 void visit(Instruction &I); 383 384 void visitTruncInst(TruncInst &I); 385 void visitZExtInst(ZExtInst &I); 386 void visitSExtInst(SExtInst &I); 387 void visitFPTruncInst(FPTruncInst &I); 388 void visitFPExtInst(FPExtInst &I); 389 void visitFPToUIInst(FPToUIInst &I); 390 void visitFPToSIInst(FPToSIInst &I); 391 void visitUIToFPInst(UIToFPInst &I); 392 void visitSIToFPInst(SIToFPInst &I); 393 void visitIntToPtrInst(IntToPtrInst &I); 394 void visitPtrToIntInst(PtrToIntInst &I); 395 void visitBitCastInst(BitCastInst &I); 396 void visitAddrSpaceCastInst(AddrSpaceCastInst &I); 397 void visitPHINode(PHINode &PN); 398 void visitBinaryOperator(BinaryOperator &B); 399 void visitICmpInst(ICmpInst &IC); 400 void visitFCmpInst(FCmpInst &FC); 401 void visitExtractElementInst(ExtractElementInst &EI); 402 void visitInsertElementInst(InsertElementInst &EI); 403 void visitShuffleVectorInst(ShuffleVectorInst &EI); 404 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 405 void visitCallInst(CallInst &CI); 406 void visitInvokeInst(InvokeInst &II); 407 void visitGetElementPtrInst(GetElementPtrInst &GEP); 408 void visitLoadInst(LoadInst &LI); 409 void visitStoreInst(StoreInst &SI); 410 void verifyDominatesUse(Instruction &I, unsigned i); 411 void visitInstruction(Instruction &I); 412 void visitTerminatorInst(TerminatorInst &I); 413 void visitBranchInst(BranchInst &BI); 414 void visitReturnInst(ReturnInst &RI); 415 void visitSwitchInst(SwitchInst &SI); 416 void visitIndirectBrInst(IndirectBrInst &BI); 417 void visitSelectInst(SelectInst &SI); 418 void visitUserOp1(Instruction &I); 419 void visitUserOp2(Instruction &I) { visitUserOp1(I); } 420 void visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS); 421 template <class DbgIntrinsicTy> 422 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII); 423 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 424 void visitAtomicRMWInst(AtomicRMWInst &RMWI); 425 void visitFenceInst(FenceInst &FI); 426 void visitAllocaInst(AllocaInst &AI); 427 void visitExtractValueInst(ExtractValueInst &EVI); 428 void visitInsertValueInst(InsertValueInst &IVI); 429 void visitEHPadPredecessors(Instruction &I); 430 void visitLandingPadInst(LandingPadInst &LPI); 431 void visitCatchPadInst(CatchPadInst &CPI); 432 void visitCatchReturnInst(CatchReturnInst &CatchReturn); 433 void visitCleanupPadInst(CleanupPadInst &CPI); 434 void visitFuncletPadInst(FuncletPadInst &FPI); 435 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch); 436 void visitCleanupReturnInst(CleanupReturnInst &CRI); 437 438 void verifyCallSite(CallSite CS); 439 void verifySwiftErrorCallSite(CallSite CS, const Value *SwiftErrorVal); 440 void verifySwiftErrorValue(const Value *SwiftErrorVal); 441 void verifyMustTailCall(CallInst &CI); 442 bool performTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT, 443 unsigned ArgNo, std::string &Suffix); 444 bool verifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 445 SmallVectorImpl<Type *> &ArgTys); 446 bool verifyIntrinsicIsVarArg(bool isVarArg, 447 ArrayRef<Intrinsic::IITDescriptor> &Infos); 448 bool verifyAttributeCount(AttributeSet Attrs, unsigned Params); 449 void verifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction, 450 const Value *V); 451 void verifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 452 bool isReturnValue, const Value *V); 453 void verifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 454 const Value *V); 455 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs); 456 457 void visitConstantExprsRecursively(const Constant *EntryC); 458 void visitConstantExpr(const ConstantExpr *CE); 459 void verifyStatepoint(ImmutableCallSite CS); 460 void verifyFrameRecoverIndices(); 461 void verifySiblingFuncletUnwinds(); 462 463 void verifyBitPieceExpression(const DbgInfoIntrinsic &I); 464 465 /// Module-level debug info verification... 466 void verifyCompileUnits(); 467 468 /// Module-level verification that all @llvm.experimental.deoptimize 469 /// declarations share the same calling convention. 470 void verifyDeoptimizeCallingConvs(); 471 }; 472 } // End anonymous namespace 473 474 /// We know that cond should be true, if not print an error message. 475 #define Assert(C, ...) \ 476 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0) 477 478 /// We know that a debug info condition should be true, if not print 479 /// an error message. 480 #define AssertDI(C, ...) \ 481 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (0) 482 483 484 void Verifier::visit(Instruction &I) { 485 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 486 Assert(I.getOperand(i) != nullptr, "Operand is null", &I); 487 InstVisitor<Verifier>::visit(I); 488 } 489 490 // Helper to recursively iterate over indirect users. By 491 // returning false, the callback can ask to stop recursing 492 // further. 493 static void forEachUser(const Value *User, 494 SmallPtrSet<const Value *, 32> &Visited, 495 llvm::function_ref<bool(const Value *)> Callback) { 496 if (!Visited.insert(User).second) 497 return; 498 for (const Value *TheNextUser : User->materialized_users()) 499 if (Callback(TheNextUser)) 500 forEachUser(TheNextUser, Visited, Callback); 501 } 502 503 void Verifier::visitGlobalValue(const GlobalValue &GV) { 504 Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(), 505 "Global is external, but doesn't have external or weak linkage!", &GV); 506 507 Assert(GV.getAlignment() <= Value::MaximumAlignment, 508 "huge alignment values are unsupported", &GV); 509 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 510 "Only global variables can have appending linkage!", &GV); 511 512 if (GV.hasAppendingLinkage()) { 513 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 514 Assert(GVar && GVar->getValueType()->isArrayTy(), 515 "Only global arrays can have appending linkage!", GVar); 516 } 517 518 if (GV.isDeclarationForLinker()) 519 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV); 520 521 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool { 522 if (const Instruction *I = dyn_cast<Instruction>(V)) { 523 if (!I->getParent() || !I->getParent()->getParent()) 524 CheckFailed("Global is referenced by parentless instruction!", &GV, 525 M, I); 526 else if (I->getParent()->getParent()->getParent() != M) 527 CheckFailed("Global is referenced in a different module!", &GV, 528 M, I, I->getParent()->getParent(), 529 I->getParent()->getParent()->getParent()); 530 return false; 531 } else if (const Function *F = dyn_cast<Function>(V)) { 532 if (F->getParent() != M) 533 CheckFailed("Global is used by function in a different module", &GV, 534 M, F, F->getParent()); 535 return false; 536 } 537 return true; 538 }); 539 } 540 541 void Verifier::visitGlobalVariable(const GlobalVariable &GV) { 542 if (GV.hasInitializer()) { 543 Assert(GV.getInitializer()->getType() == GV.getValueType(), 544 "Global variable initializer type does not match global " 545 "variable type!", 546 &GV); 547 548 // If the global has common linkage, it must have a zero initializer and 549 // cannot be constant. 550 if (GV.hasCommonLinkage()) { 551 Assert(GV.getInitializer()->isNullValue(), 552 "'common' global must have a zero initializer!", &GV); 553 Assert(!GV.isConstant(), "'common' global may not be marked constant!", 554 &GV); 555 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV); 556 } 557 } 558 559 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 560 GV.getName() == "llvm.global_dtors")) { 561 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 562 "invalid linkage for intrinsic global variable", &GV); 563 // Don't worry about emitting an error for it not being an array, 564 // visitGlobalValue will complain on appending non-array. 565 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) { 566 StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 567 PointerType *FuncPtrTy = 568 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo(); 569 // FIXME: Reject the 2-field form in LLVM 4.0. 570 Assert(STy && 571 (STy->getNumElements() == 2 || STy->getNumElements() == 3) && 572 STy->getTypeAtIndex(0u)->isIntegerTy(32) && 573 STy->getTypeAtIndex(1) == FuncPtrTy, 574 "wrong type for intrinsic global variable", &GV); 575 if (STy->getNumElements() == 3) { 576 Type *ETy = STy->getTypeAtIndex(2); 577 Assert(ETy->isPointerTy() && 578 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8), 579 "wrong type for intrinsic global variable", &GV); 580 } 581 } 582 } 583 584 if (GV.hasName() && (GV.getName() == "llvm.used" || 585 GV.getName() == "llvm.compiler.used")) { 586 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 587 "invalid linkage for intrinsic global variable", &GV); 588 Type *GVType = GV.getValueType(); 589 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) { 590 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType()); 591 Assert(PTy, "wrong type for intrinsic global variable", &GV); 592 if (GV.hasInitializer()) { 593 const Constant *Init = GV.getInitializer(); 594 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init); 595 Assert(InitArray, "wrong initalizer for intrinsic global variable", 596 Init); 597 for (Value *Op : InitArray->operands()) { 598 Value *V = Op->stripPointerCastsNoFollowAliases(); 599 Assert(isa<GlobalVariable>(V) || isa<Function>(V) || 600 isa<GlobalAlias>(V), 601 "invalid llvm.used member", V); 602 Assert(V->hasName(), "members of llvm.used must be named", V); 603 } 604 } 605 } 606 } 607 608 Assert(!GV.hasDLLImportStorageClass() || 609 (GV.isDeclaration() && GV.hasExternalLinkage()) || 610 GV.hasAvailableExternallyLinkage(), 611 "Global is marked as dllimport, but not external", &GV); 612 613 if (!GV.hasInitializer()) { 614 visitGlobalValue(GV); 615 return; 616 } 617 618 // Walk any aggregate initializers looking for bitcasts between address spaces 619 visitConstantExprsRecursively(GV.getInitializer()); 620 621 visitGlobalValue(GV); 622 } 623 624 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) { 625 SmallPtrSet<const GlobalAlias*, 4> Visited; 626 Visited.insert(&GA); 627 visitAliaseeSubExpr(Visited, GA, C); 628 } 629 630 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited, 631 const GlobalAlias &GA, const Constant &C) { 632 if (const auto *GV = dyn_cast<GlobalValue>(&C)) { 633 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition", 634 &GA); 635 636 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) { 637 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA); 638 639 Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias", 640 &GA); 641 } else { 642 // Only continue verifying subexpressions of GlobalAliases. 643 // Do not recurse into global initializers. 644 return; 645 } 646 } 647 648 if (const auto *CE = dyn_cast<ConstantExpr>(&C)) 649 visitConstantExprsRecursively(CE); 650 651 for (const Use &U : C.operands()) { 652 Value *V = &*U; 653 if (const auto *GA2 = dyn_cast<GlobalAlias>(V)) 654 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee()); 655 else if (const auto *C2 = dyn_cast<Constant>(V)) 656 visitAliaseeSubExpr(Visited, GA, *C2); 657 } 658 } 659 660 void Verifier::visitGlobalAlias(const GlobalAlias &GA) { 661 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()), 662 "Alias should have private, internal, linkonce, weak, linkonce_odr, " 663 "weak_odr, or external linkage!", 664 &GA); 665 const Constant *Aliasee = GA.getAliasee(); 666 Assert(Aliasee, "Aliasee cannot be NULL!", &GA); 667 Assert(GA.getType() == Aliasee->getType(), 668 "Alias and aliasee types should match!", &GA); 669 670 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee), 671 "Aliasee should be either GlobalValue or ConstantExpr", &GA); 672 673 visitAliaseeSubExpr(GA, *Aliasee); 674 675 visitGlobalValue(GA); 676 } 677 678 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) { 679 for (const MDNode *MD : NMD.operands()) { 680 if (NMD.getName() == "llvm.dbg.cu") { 681 AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD); 682 } 683 684 if (!MD) 685 continue; 686 687 visitMDNode(*MD); 688 } 689 } 690 691 void Verifier::visitMDNode(const MDNode &MD) { 692 // Only visit each node once. Metadata can be mutually recursive, so this 693 // avoids infinite recursion here, as well as being an optimization. 694 if (!MDNodes.insert(&MD).second) 695 return; 696 697 switch (MD.getMetadataID()) { 698 default: 699 llvm_unreachable("Invalid MDNode subclass"); 700 case Metadata::MDTupleKind: 701 break; 702 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 703 case Metadata::CLASS##Kind: \ 704 visit##CLASS(cast<CLASS>(MD)); \ 705 break; 706 #include "llvm/IR/Metadata.def" 707 } 708 709 for (const Metadata *Op : MD.operands()) { 710 if (!Op) 711 continue; 712 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!", 713 &MD, Op); 714 if (auto *N = dyn_cast<MDNode>(Op)) { 715 visitMDNode(*N); 716 continue; 717 } 718 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) { 719 visitValueAsMetadata(*V, nullptr); 720 continue; 721 } 722 } 723 724 // Check these last, so we diagnose problems in operands first. 725 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD); 726 Assert(MD.isResolved(), "All nodes should be resolved!", &MD); 727 } 728 729 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) { 730 Assert(MD.getValue(), "Expected valid value", &MD); 731 Assert(!MD.getValue()->getType()->isMetadataTy(), 732 "Unexpected metadata round-trip through values", &MD, MD.getValue()); 733 734 auto *L = dyn_cast<LocalAsMetadata>(&MD); 735 if (!L) 736 return; 737 738 Assert(F, "function-local metadata used outside a function", L); 739 740 // If this was an instruction, bb, or argument, verify that it is in the 741 // function that we expect. 742 Function *ActualF = nullptr; 743 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) { 744 Assert(I->getParent(), "function-local metadata not in basic block", L, I); 745 ActualF = I->getParent()->getParent(); 746 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue())) 747 ActualF = BB->getParent(); 748 else if (Argument *A = dyn_cast<Argument>(L->getValue())) 749 ActualF = A->getParent(); 750 assert(ActualF && "Unimplemented function local metadata case!"); 751 752 Assert(ActualF == F, "function-local metadata used in wrong function", L); 753 } 754 755 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) { 756 Metadata *MD = MDV.getMetadata(); 757 if (auto *N = dyn_cast<MDNode>(MD)) { 758 visitMDNode(*N); 759 return; 760 } 761 762 // Only visit each node once. Metadata can be mutually recursive, so this 763 // avoids infinite recursion here, as well as being an optimization. 764 if (!MDNodes.insert(MD).second) 765 return; 766 767 if (auto *V = dyn_cast<ValueAsMetadata>(MD)) 768 visitValueAsMetadata(*V, F); 769 } 770 771 static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); } 772 static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); } 773 static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); } 774 775 template <class Ty> 776 bool isValidMetadataArrayImpl(const MDTuple &N, bool AllowNull) { 777 for (Metadata *MD : N.operands()) { 778 if (MD) { 779 if (!isa<Ty>(MD)) 780 return false; 781 } else { 782 if (!AllowNull) 783 return false; 784 } 785 } 786 return true; 787 } 788 789 template <class Ty> 790 bool isValidMetadataArray(const MDTuple &N) { 791 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ false); 792 } 793 794 template <class Ty> 795 bool isValidMetadataNullArray(const MDTuple &N) { 796 return isValidMetadataArrayImpl<Ty>(N, /* AllowNull */ true); 797 } 798 799 void Verifier::visitDILocation(const DILocation &N) { 800 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 801 "location requires a valid scope", &N, N.getRawScope()); 802 if (auto *IA = N.getRawInlinedAt()) 803 AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA); 804 } 805 806 void Verifier::visitGenericDINode(const GenericDINode &N) { 807 AssertDI(N.getTag(), "invalid tag", &N); 808 } 809 810 void Verifier::visitDIScope(const DIScope &N) { 811 if (auto *F = N.getRawFile()) 812 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 813 } 814 815 void Verifier::visitDISubrange(const DISubrange &N) { 816 AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N); 817 AssertDI(N.getCount() >= -1, "invalid subrange count", &N); 818 } 819 820 void Verifier::visitDIEnumerator(const DIEnumerator &N) { 821 AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N); 822 } 823 824 void Verifier::visitDIBasicType(const DIBasicType &N) { 825 AssertDI(N.getTag() == dwarf::DW_TAG_base_type || 826 N.getTag() == dwarf::DW_TAG_unspecified_type, 827 "invalid tag", &N); 828 } 829 830 void Verifier::visitDIDerivedType(const DIDerivedType &N) { 831 // Common scope checks. 832 visitDIScope(N); 833 834 AssertDI(N.getTag() == dwarf::DW_TAG_typedef || 835 N.getTag() == dwarf::DW_TAG_pointer_type || 836 N.getTag() == dwarf::DW_TAG_ptr_to_member_type || 837 N.getTag() == dwarf::DW_TAG_reference_type || 838 N.getTag() == dwarf::DW_TAG_rvalue_reference_type || 839 N.getTag() == dwarf::DW_TAG_const_type || 840 N.getTag() == dwarf::DW_TAG_volatile_type || 841 N.getTag() == dwarf::DW_TAG_restrict_type || 842 N.getTag() == dwarf::DW_TAG_member || 843 N.getTag() == dwarf::DW_TAG_inheritance || 844 N.getTag() == dwarf::DW_TAG_friend, 845 "invalid tag", &N); 846 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) { 847 AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N, 848 N.getRawExtraData()); 849 } 850 851 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 852 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 853 N.getRawBaseType()); 854 } 855 856 static bool hasConflictingReferenceFlags(unsigned Flags) { 857 return (Flags & DINode::FlagLValueReference) && 858 (Flags & DINode::FlagRValueReference); 859 } 860 861 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) { 862 auto *Params = dyn_cast<MDTuple>(&RawParams); 863 AssertDI(Params, "invalid template params", &N, &RawParams); 864 for (Metadata *Op : Params->operands()) { 865 AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter", 866 &N, Params, Op); 867 } 868 } 869 870 void Verifier::visitDICompositeType(const DICompositeType &N) { 871 // Common scope checks. 872 visitDIScope(N); 873 874 AssertDI(N.getTag() == dwarf::DW_TAG_array_type || 875 N.getTag() == dwarf::DW_TAG_structure_type || 876 N.getTag() == dwarf::DW_TAG_union_type || 877 N.getTag() == dwarf::DW_TAG_enumeration_type || 878 N.getTag() == dwarf::DW_TAG_class_type, 879 "invalid tag", &N); 880 881 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 882 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 883 N.getRawBaseType()); 884 885 AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()), 886 "invalid composite elements", &N, N.getRawElements()); 887 AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N, 888 N.getRawVTableHolder()); 889 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 890 "invalid reference flags", &N); 891 if (auto *Params = N.getRawTemplateParams()) 892 visitTemplateParams(N, *Params); 893 894 if (N.getTag() == dwarf::DW_TAG_class_type || 895 N.getTag() == dwarf::DW_TAG_union_type) { 896 AssertDI(N.getFile() && !N.getFile()->getFilename().empty(), 897 "class/union requires a filename", &N, N.getFile()); 898 } 899 } 900 901 void Verifier::visitDISubroutineType(const DISubroutineType &N) { 902 AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N); 903 if (auto *Types = N.getRawTypeArray()) { 904 AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types); 905 for (Metadata *Ty : N.getTypeArray()->operands()) { 906 AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty); 907 } 908 } 909 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 910 "invalid reference flags", &N); 911 } 912 913 void Verifier::visitDIFile(const DIFile &N) { 914 AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N); 915 } 916 917 void Verifier::visitDICompileUnit(const DICompileUnit &N) { 918 AssertDI(N.isDistinct(), "compile units must be distinct", &N); 919 AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N); 920 921 // Don't bother verifying the compilation directory or producer string 922 // as those could be empty. 923 AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N, 924 N.getRawFile()); 925 AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N, 926 N.getFile()); 927 928 AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind), 929 "invalid emission kind", &N); 930 931 if (auto *Array = N.getRawEnumTypes()) { 932 AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array); 933 for (Metadata *Op : N.getEnumTypes()->operands()) { 934 auto *Enum = dyn_cast_or_null<DICompositeType>(Op); 935 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type, 936 "invalid enum type", &N, N.getEnumTypes(), Op); 937 } 938 } 939 if (auto *Array = N.getRawRetainedTypes()) { 940 AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array); 941 for (Metadata *Op : N.getRetainedTypes()->operands()) { 942 AssertDI(Op && (isa<DIType>(Op) || 943 (isa<DISubprogram>(Op) && 944 cast<DISubprogram>(Op)->isDefinition() == false)), 945 "invalid retained type", &N, Op); 946 } 947 } 948 if (auto *Array = N.getRawGlobalVariables()) { 949 AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array); 950 for (Metadata *Op : N.getGlobalVariables()->operands()) { 951 AssertDI(Op && isa<DIGlobalVariable>(Op), "invalid global variable ref", 952 &N, Op); 953 } 954 } 955 if (auto *Array = N.getRawImportedEntities()) { 956 AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array); 957 for (Metadata *Op : N.getImportedEntities()->operands()) { 958 AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", 959 &N, Op); 960 } 961 } 962 if (auto *Array = N.getRawMacros()) { 963 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 964 for (Metadata *Op : N.getMacros()->operands()) { 965 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 966 } 967 } 968 CUVisited.insert(&N); 969 } 970 971 void Verifier::visitDISubprogram(const DISubprogram &N) { 972 AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N); 973 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 974 if (auto *F = N.getRawFile()) 975 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 976 if (auto *T = N.getRawType()) 977 AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T); 978 AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N, 979 N.getRawContainingType()); 980 if (auto *Params = N.getRawTemplateParams()) 981 visitTemplateParams(N, *Params); 982 if (auto *S = N.getRawDeclaration()) 983 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(), 984 "invalid subprogram declaration", &N, S); 985 if (auto *RawVars = N.getRawVariables()) { 986 auto *Vars = dyn_cast<MDTuple>(RawVars); 987 AssertDI(Vars, "invalid variable list", &N, RawVars); 988 for (Metadata *Op : Vars->operands()) { 989 AssertDI(Op && isa<DILocalVariable>(Op), "invalid local variable", &N, 990 Vars, Op); 991 } 992 } 993 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 994 "invalid reference flags", &N); 995 996 auto *Unit = N.getRawUnit(); 997 if (N.isDefinition()) { 998 // Subprogram definitions (not part of the type hierarchy). 999 AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N); 1000 AssertDI(Unit, "subprogram definitions must have a compile unit", &N); 1001 AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit); 1002 } else { 1003 // Subprogram declarations (part of the type hierarchy). 1004 AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N); 1005 } 1006 } 1007 1008 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) { 1009 AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N); 1010 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1011 "invalid local scope", &N, N.getRawScope()); 1012 } 1013 1014 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) { 1015 visitDILexicalBlockBase(N); 1016 1017 AssertDI(N.getLine() || !N.getColumn(), 1018 "cannot have column info without line info", &N); 1019 } 1020 1021 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) { 1022 visitDILexicalBlockBase(N); 1023 } 1024 1025 void Verifier::visitDINamespace(const DINamespace &N) { 1026 AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N); 1027 if (auto *S = N.getRawScope()) 1028 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S); 1029 } 1030 1031 void Verifier::visitDIMacro(const DIMacro &N) { 1032 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define || 1033 N.getMacinfoType() == dwarf::DW_MACINFO_undef, 1034 "invalid macinfo type", &N); 1035 AssertDI(!N.getName().empty(), "anonymous macro", &N); 1036 if (!N.getValue().empty()) { 1037 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix"); 1038 } 1039 } 1040 1041 void Verifier::visitDIMacroFile(const DIMacroFile &N) { 1042 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file, 1043 "invalid macinfo type", &N); 1044 if (auto *F = N.getRawFile()) 1045 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1046 1047 if (auto *Array = N.getRawElements()) { 1048 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1049 for (Metadata *Op : N.getElements()->operands()) { 1050 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1051 } 1052 } 1053 } 1054 1055 void Verifier::visitDIModule(const DIModule &N) { 1056 AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N); 1057 AssertDI(!N.getName().empty(), "anonymous module", &N); 1058 } 1059 1060 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) { 1061 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1062 } 1063 1064 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) { 1065 visitDITemplateParameter(N); 1066 1067 AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag", 1068 &N); 1069 } 1070 1071 void Verifier::visitDITemplateValueParameter( 1072 const DITemplateValueParameter &N) { 1073 visitDITemplateParameter(N); 1074 1075 AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter || 1076 N.getTag() == dwarf::DW_TAG_GNU_template_template_param || 1077 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack, 1078 "invalid tag", &N); 1079 } 1080 1081 void Verifier::visitDIVariable(const DIVariable &N) { 1082 if (auto *S = N.getRawScope()) 1083 AssertDI(isa<DIScope>(S), "invalid scope", &N, S); 1084 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1085 if (auto *F = N.getRawFile()) 1086 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1087 } 1088 1089 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) { 1090 // Checks common to all variables. 1091 visitDIVariable(N); 1092 1093 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1094 AssertDI(!N.getName().empty(), "missing global variable name", &N); 1095 if (auto *V = N.getRawVariable()) { 1096 AssertDI(isa<ConstantAsMetadata>(V) && 1097 !isa<Function>(cast<ConstantAsMetadata>(V)->getValue()), 1098 "invalid global varaible ref", &N, V); 1099 visitConstantExprsRecursively(cast<ConstantAsMetadata>(V)->getValue()); 1100 } 1101 if (auto *Member = N.getRawStaticDataMemberDeclaration()) { 1102 AssertDI(isa<DIDerivedType>(Member), 1103 "invalid static data member declaration", &N, Member); 1104 } 1105 } 1106 1107 void Verifier::visitDILocalVariable(const DILocalVariable &N) { 1108 // Checks common to all variables. 1109 visitDIVariable(N); 1110 1111 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1112 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1113 "local variable requires a valid scope", &N, N.getRawScope()); 1114 } 1115 1116 void Verifier::visitDIExpression(const DIExpression &N) { 1117 AssertDI(N.isValid(), "invalid expression", &N); 1118 } 1119 1120 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) { 1121 AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N); 1122 if (auto *T = N.getRawType()) 1123 AssertDI(isType(T), "invalid type ref", &N, T); 1124 if (auto *F = N.getRawFile()) 1125 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1126 } 1127 1128 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) { 1129 AssertDI(N.getTag() == dwarf::DW_TAG_imported_module || 1130 N.getTag() == dwarf::DW_TAG_imported_declaration, 1131 "invalid tag", &N); 1132 if (auto *S = N.getRawScope()) 1133 AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S); 1134 AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N, 1135 N.getRawEntity()); 1136 } 1137 1138 void Verifier::visitComdat(const Comdat &C) { 1139 // The Module is invalid if the GlobalValue has private linkage. Entities 1140 // with private linkage don't have entries in the symbol table. 1141 if (const GlobalValue *GV = M->getNamedValue(C.getName())) 1142 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage", 1143 GV); 1144 } 1145 1146 void Verifier::visitModuleIdents(const Module &M) { 1147 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident"); 1148 if (!Idents) 1149 return; 1150 1151 // llvm.ident takes a list of metadata entry. Each entry has only one string. 1152 // Scan each llvm.ident entry and make sure that this requirement is met. 1153 for (const MDNode *N : Idents->operands()) { 1154 Assert(N->getNumOperands() == 1, 1155 "incorrect number of operands in llvm.ident metadata", N); 1156 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)), 1157 ("invalid value for llvm.ident metadata entry operand" 1158 "(the operand should be a string)"), 1159 N->getOperand(0)); 1160 } 1161 } 1162 1163 void Verifier::visitModuleFlags(const Module &M) { 1164 const NamedMDNode *Flags = M.getModuleFlagsMetadata(); 1165 if (!Flags) return; 1166 1167 // Scan each flag, and track the flags and requirements. 1168 DenseMap<const MDString*, const MDNode*> SeenIDs; 1169 SmallVector<const MDNode*, 16> Requirements; 1170 for (const MDNode *MDN : Flags->operands()) 1171 visitModuleFlag(MDN, SeenIDs, Requirements); 1172 1173 // Validate that the requirements in the module are valid. 1174 for (const MDNode *Requirement : Requirements) { 1175 const MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1176 const Metadata *ReqValue = Requirement->getOperand(1); 1177 1178 const MDNode *Op = SeenIDs.lookup(Flag); 1179 if (!Op) { 1180 CheckFailed("invalid requirement on flag, flag is not present in module", 1181 Flag); 1182 continue; 1183 } 1184 1185 if (Op->getOperand(2) != ReqValue) { 1186 CheckFailed(("invalid requirement on flag, " 1187 "flag does not have the required value"), 1188 Flag); 1189 continue; 1190 } 1191 } 1192 } 1193 1194 void 1195 Verifier::visitModuleFlag(const MDNode *Op, 1196 DenseMap<const MDString *, const MDNode *> &SeenIDs, 1197 SmallVectorImpl<const MDNode *> &Requirements) { 1198 // Each module flag should have three arguments, the merge behavior (a 1199 // constant int), the flag ID (an MDString), and the value. 1200 Assert(Op->getNumOperands() == 3, 1201 "incorrect number of operands in module flag", Op); 1202 Module::ModFlagBehavior MFB; 1203 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) { 1204 Assert( 1205 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)), 1206 "invalid behavior operand in module flag (expected constant integer)", 1207 Op->getOperand(0)); 1208 Assert(false, 1209 "invalid behavior operand in module flag (unexpected constant)", 1210 Op->getOperand(0)); 1211 } 1212 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1)); 1213 Assert(ID, "invalid ID operand in module flag (expected metadata string)", 1214 Op->getOperand(1)); 1215 1216 // Sanity check the values for behaviors with additional requirements. 1217 switch (MFB) { 1218 case Module::Error: 1219 case Module::Warning: 1220 case Module::Override: 1221 // These behavior types accept any value. 1222 break; 1223 1224 case Module::Require: { 1225 // The value should itself be an MDNode with two operands, a flag ID (an 1226 // MDString), and a value. 1227 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2)); 1228 Assert(Value && Value->getNumOperands() == 2, 1229 "invalid value for 'require' module flag (expected metadata pair)", 1230 Op->getOperand(2)); 1231 Assert(isa<MDString>(Value->getOperand(0)), 1232 ("invalid value for 'require' module flag " 1233 "(first value operand should be a string)"), 1234 Value->getOperand(0)); 1235 1236 // Append it to the list of requirements, to check once all module flags are 1237 // scanned. 1238 Requirements.push_back(Value); 1239 break; 1240 } 1241 1242 case Module::Append: 1243 case Module::AppendUnique: { 1244 // These behavior types require the operand be an MDNode. 1245 Assert(isa<MDNode>(Op->getOperand(2)), 1246 "invalid value for 'append'-type module flag " 1247 "(expected a metadata node)", 1248 Op->getOperand(2)); 1249 break; 1250 } 1251 } 1252 1253 // Unless this is a "requires" flag, check the ID is unique. 1254 if (MFB != Module::Require) { 1255 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second; 1256 Assert(Inserted, 1257 "module flag identifiers must be unique (or of 'require' type)", ID); 1258 } 1259 } 1260 1261 void Verifier::verifyAttributeTypes(AttributeSet Attrs, unsigned Idx, 1262 bool isFunction, const Value *V) { 1263 unsigned Slot = ~0U; 1264 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I) 1265 if (Attrs.getSlotIndex(I) == Idx) { 1266 Slot = I; 1267 break; 1268 } 1269 1270 assert(Slot != ~0U && "Attribute set inconsistency!"); 1271 1272 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot); 1273 I != E; ++I) { 1274 if (I->isStringAttribute()) 1275 continue; 1276 1277 if (I->getKindAsEnum() == Attribute::NoReturn || 1278 I->getKindAsEnum() == Attribute::NoUnwind || 1279 I->getKindAsEnum() == Attribute::NoInline || 1280 I->getKindAsEnum() == Attribute::AlwaysInline || 1281 I->getKindAsEnum() == Attribute::OptimizeForSize || 1282 I->getKindAsEnum() == Attribute::StackProtect || 1283 I->getKindAsEnum() == Attribute::StackProtectReq || 1284 I->getKindAsEnum() == Attribute::StackProtectStrong || 1285 I->getKindAsEnum() == Attribute::SafeStack || 1286 I->getKindAsEnum() == Attribute::NoRedZone || 1287 I->getKindAsEnum() == Attribute::NoImplicitFloat || 1288 I->getKindAsEnum() == Attribute::Naked || 1289 I->getKindAsEnum() == Attribute::InlineHint || 1290 I->getKindAsEnum() == Attribute::StackAlignment || 1291 I->getKindAsEnum() == Attribute::UWTable || 1292 I->getKindAsEnum() == Attribute::NonLazyBind || 1293 I->getKindAsEnum() == Attribute::ReturnsTwice || 1294 I->getKindAsEnum() == Attribute::SanitizeAddress || 1295 I->getKindAsEnum() == Attribute::SanitizeThread || 1296 I->getKindAsEnum() == Attribute::SanitizeMemory || 1297 I->getKindAsEnum() == Attribute::MinSize || 1298 I->getKindAsEnum() == Attribute::NoDuplicate || 1299 I->getKindAsEnum() == Attribute::Builtin || 1300 I->getKindAsEnum() == Attribute::NoBuiltin || 1301 I->getKindAsEnum() == Attribute::Cold || 1302 I->getKindAsEnum() == Attribute::OptimizeNone || 1303 I->getKindAsEnum() == Attribute::JumpTable || 1304 I->getKindAsEnum() == Attribute::Convergent || 1305 I->getKindAsEnum() == Attribute::ArgMemOnly || 1306 I->getKindAsEnum() == Attribute::NoRecurse || 1307 I->getKindAsEnum() == Attribute::InaccessibleMemOnly || 1308 I->getKindAsEnum() == Attribute::InaccessibleMemOrArgMemOnly || 1309 I->getKindAsEnum() == Attribute::AllocSize) { 1310 if (!isFunction) { 1311 CheckFailed("Attribute '" + I->getAsString() + 1312 "' only applies to functions!", V); 1313 return; 1314 } 1315 } else if (I->getKindAsEnum() == Attribute::ReadOnly || 1316 I->getKindAsEnum() == Attribute::ReadNone) { 1317 if (Idx == 0) { 1318 CheckFailed("Attribute '" + I->getAsString() + 1319 "' does not apply to function returns"); 1320 return; 1321 } 1322 } else if (isFunction) { 1323 CheckFailed("Attribute '" + I->getAsString() + 1324 "' does not apply to functions!", V); 1325 return; 1326 } 1327 } 1328 } 1329 1330 // VerifyParameterAttrs - Check the given attributes for an argument or return 1331 // value of the specified type. The value V is printed in error messages. 1332 void Verifier::verifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty, 1333 bool isReturnValue, const Value *V) { 1334 if (!Attrs.hasAttributes(Idx)) 1335 return; 1336 1337 verifyAttributeTypes(Attrs, Idx, false, V); 1338 1339 if (isReturnValue) 1340 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 1341 !Attrs.hasAttribute(Idx, Attribute::Nest) && 1342 !Attrs.hasAttribute(Idx, Attribute::StructRet) && 1343 !Attrs.hasAttribute(Idx, Attribute::NoCapture) && 1344 !Attrs.hasAttribute(Idx, Attribute::Returned) && 1345 !Attrs.hasAttribute(Idx, Attribute::InAlloca) && 1346 !Attrs.hasAttribute(Idx, Attribute::SwiftSelf) && 1347 !Attrs.hasAttribute(Idx, Attribute::SwiftError), 1348 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', " 1349 "'returned', 'swiftself', and 'swifterror' do not apply to return " 1350 "values!", 1351 V); 1352 1353 // Check for mutually incompatible attributes. Only inreg is compatible with 1354 // sret. 1355 unsigned AttrCount = 0; 1356 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal); 1357 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca); 1358 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) || 1359 Attrs.hasAttribute(Idx, Attribute::InReg); 1360 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest); 1361 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', " 1362 "and 'sret' are incompatible!", 1363 V); 1364 1365 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) && 1366 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), 1367 "Attributes " 1368 "'inalloca and readonly' are incompatible!", 1369 V); 1370 1371 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) && 1372 Attrs.hasAttribute(Idx, Attribute::Returned)), 1373 "Attributes " 1374 "'sret and returned' are incompatible!", 1375 V); 1376 1377 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) && 1378 Attrs.hasAttribute(Idx, Attribute::SExt)), 1379 "Attributes " 1380 "'zeroext and signext' are incompatible!", 1381 V); 1382 1383 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) && 1384 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), 1385 "Attributes " 1386 "'readnone and readonly' are incompatible!", 1387 V); 1388 1389 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) && 1390 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), 1391 "Attributes " 1392 "'noinline and alwaysinline' are incompatible!", 1393 V); 1394 1395 Assert(!AttrBuilder(Attrs, Idx) 1396 .overlaps(AttributeFuncs::typeIncompatible(Ty)), 1397 "Wrong types for attribute: " + 1398 AttributeSet::get(*Context, Idx, 1399 AttributeFuncs::typeIncompatible(Ty)).getAsString(Idx), 1400 V); 1401 1402 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) { 1403 SmallPtrSet<Type*, 4> Visited; 1404 if (!PTy->getElementType()->isSized(&Visited)) { 1405 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) && 1406 !Attrs.hasAttribute(Idx, Attribute::InAlloca), 1407 "Attributes 'byval' and 'inalloca' do not support unsized types!", 1408 V); 1409 } 1410 if (!isa<PointerType>(PTy->getElementType())) 1411 Assert(!Attrs.hasAttribute(Idx, Attribute::SwiftError), 1412 "Attribute 'swifterror' only applies to parameters " 1413 "with pointer to pointer type!", 1414 V); 1415 } else { 1416 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal), 1417 "Attribute 'byval' only applies to parameters with pointer type!", 1418 V); 1419 Assert(!Attrs.hasAttribute(Idx, Attribute::SwiftError), 1420 "Attribute 'swifterror' only applies to parameters " 1421 "with pointer type!", 1422 V); 1423 } 1424 } 1425 1426 // Check parameter attributes against a function type. 1427 // The value V is printed in error messages. 1428 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs, 1429 const Value *V) { 1430 if (Attrs.isEmpty()) 1431 return; 1432 1433 bool SawNest = false; 1434 bool SawReturned = false; 1435 bool SawSRet = false; 1436 bool SawSwiftSelf = false; 1437 bool SawSwiftError = false; 1438 1439 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) { 1440 unsigned Idx = Attrs.getSlotIndex(i); 1441 1442 Type *Ty; 1443 if (Idx == 0) 1444 Ty = FT->getReturnType(); 1445 else if (Idx-1 < FT->getNumParams()) 1446 Ty = FT->getParamType(Idx-1); 1447 else 1448 break; // VarArgs attributes, verified elsewhere. 1449 1450 verifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V); 1451 1452 if (Idx == 0) 1453 continue; 1454 1455 if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 1456 Assert(!SawNest, "More than one parameter has attribute nest!", V); 1457 SawNest = true; 1458 } 1459 1460 if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 1461 Assert(!SawReturned, "More than one parameter has attribute returned!", 1462 V); 1463 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()), 1464 "Incompatible " 1465 "argument and return types for 'returned' attribute", 1466 V); 1467 SawReturned = true; 1468 } 1469 1470 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) { 1471 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V); 1472 Assert(Idx == 1 || Idx == 2, 1473 "Attribute 'sret' is not on first or second parameter!", V); 1474 SawSRet = true; 1475 } 1476 1477 if (Attrs.hasAttribute(Idx, Attribute::SwiftSelf)) { 1478 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V); 1479 SawSwiftSelf = true; 1480 } 1481 1482 if (Attrs.hasAttribute(Idx, Attribute::SwiftError)) { 1483 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", 1484 V); 1485 SawSwiftError = true; 1486 } 1487 1488 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) { 1489 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!", 1490 V); 1491 } 1492 } 1493 1494 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex)) 1495 return; 1496 1497 verifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V); 1498 1499 Assert( 1500 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1501 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)), 1502 "Attributes 'readnone and readonly' are incompatible!", V); 1503 1504 Assert( 1505 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1506 Attrs.hasAttribute(AttributeSet::FunctionIndex, 1507 Attribute::InaccessibleMemOrArgMemOnly)), 1508 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are incompatible!", V); 1509 1510 Assert( 1511 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) && 1512 Attrs.hasAttribute(AttributeSet::FunctionIndex, 1513 Attribute::InaccessibleMemOnly)), 1514 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V); 1515 1516 Assert( 1517 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) && 1518 Attrs.hasAttribute(AttributeSet::FunctionIndex, 1519 Attribute::AlwaysInline)), 1520 "Attributes 'noinline and alwaysinline' are incompatible!", V); 1521 1522 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 1523 Attribute::OptimizeNone)) { 1524 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline), 1525 "Attribute 'optnone' requires 'noinline'!", V); 1526 1527 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, 1528 Attribute::OptimizeForSize), 1529 "Attributes 'optsize and optnone' are incompatible!", V); 1530 1531 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize), 1532 "Attributes 'minsize and optnone' are incompatible!", V); 1533 } 1534 1535 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, 1536 Attribute::JumpTable)) { 1537 const GlobalValue *GV = cast<GlobalValue>(V); 1538 Assert(GV->hasUnnamedAddr(), 1539 "Attribute 'jumptable' requires 'unnamed_addr'", V); 1540 } 1541 1542 if (Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::AllocSize)) { 1543 std::pair<unsigned, Optional<unsigned>> Args = 1544 Attrs.getAllocSizeArgs(AttributeSet::FunctionIndex); 1545 1546 auto CheckParam = [&](StringRef Name, unsigned ParamNo) { 1547 if (ParamNo >= FT->getNumParams()) { 1548 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V); 1549 return false; 1550 } 1551 1552 if (!FT->getParamType(ParamNo)->isIntegerTy()) { 1553 CheckFailed("'allocsize' " + Name + 1554 " argument must refer to an integer parameter", 1555 V); 1556 return false; 1557 } 1558 1559 return true; 1560 }; 1561 1562 if (!CheckParam("element size", Args.first)) 1563 return; 1564 1565 if (Args.second && !CheckParam("number of elements", *Args.second)) 1566 return; 1567 } 1568 } 1569 1570 void Verifier::verifyFunctionMetadata( 1571 ArrayRef<std::pair<unsigned, MDNode *>> MDs) { 1572 for (const auto &Pair : MDs) { 1573 if (Pair.first == LLVMContext::MD_prof) { 1574 MDNode *MD = Pair.second; 1575 Assert(MD->getNumOperands() == 2, 1576 "!prof annotations should have exactly 2 operands", MD); 1577 1578 // Check first operand. 1579 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", 1580 MD); 1581 Assert(isa<MDString>(MD->getOperand(0)), 1582 "expected string with name of the !prof annotation", MD); 1583 MDString *MDS = cast<MDString>(MD->getOperand(0)); 1584 StringRef ProfName = MDS->getString(); 1585 Assert(ProfName.equals("function_entry_count"), 1586 "first operand should be 'function_entry_count'", MD); 1587 1588 // Check second operand. 1589 Assert(MD->getOperand(1) != nullptr, "second operand should not be null", 1590 MD); 1591 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)), 1592 "expected integer argument to function_entry_count", MD); 1593 } 1594 } 1595 } 1596 1597 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) { 1598 if (!ConstantExprVisited.insert(EntryC).second) 1599 return; 1600 1601 SmallVector<const Constant *, 16> Stack; 1602 Stack.push_back(EntryC); 1603 1604 while (!Stack.empty()) { 1605 const Constant *C = Stack.pop_back_val(); 1606 1607 // Check this constant expression. 1608 if (const auto *CE = dyn_cast<ConstantExpr>(C)) 1609 visitConstantExpr(CE); 1610 1611 if (const auto *GV = dyn_cast<GlobalValue>(C)) { 1612 // Global Values get visited separately, but we do need to make sure 1613 // that the global value is in the correct module 1614 Assert(GV->getParent() == M, "Referencing global in another module!", 1615 EntryC, M, GV, GV->getParent()); 1616 continue; 1617 } 1618 1619 // Visit all sub-expressions. 1620 for (const Use &U : C->operands()) { 1621 const auto *OpC = dyn_cast<Constant>(U); 1622 if (!OpC) 1623 continue; 1624 if (!ConstantExprVisited.insert(OpC).second) 1625 continue; 1626 Stack.push_back(OpC); 1627 } 1628 } 1629 } 1630 1631 void Verifier::visitConstantExpr(const ConstantExpr *CE) { 1632 if (CE->getOpcode() != Instruction::BitCast) 1633 return; 1634 1635 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0), 1636 CE->getType()), 1637 "Invalid bitcast", CE); 1638 } 1639 1640 bool Verifier::verifyAttributeCount(AttributeSet Attrs, unsigned Params) { 1641 if (Attrs.getNumSlots() == 0) 1642 return true; 1643 1644 unsigned LastSlot = Attrs.getNumSlots() - 1; 1645 unsigned LastIndex = Attrs.getSlotIndex(LastSlot); 1646 if (LastIndex <= Params 1647 || (LastIndex == AttributeSet::FunctionIndex 1648 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params))) 1649 return true; 1650 1651 return false; 1652 } 1653 1654 /// Verify that statepoint intrinsic is well formed. 1655 void Verifier::verifyStatepoint(ImmutableCallSite CS) { 1656 assert(CS.getCalledFunction() && 1657 CS.getCalledFunction()->getIntrinsicID() == 1658 Intrinsic::experimental_gc_statepoint); 1659 1660 const Instruction &CI = *CS.getInstruction(); 1661 1662 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory() && 1663 !CS.onlyAccessesArgMemory(), 1664 "gc.statepoint must read and write all memory to preserve " 1665 "reordering restrictions required by safepoint semantics", 1666 &CI); 1667 1668 const Value *IDV = CS.getArgument(0); 1669 Assert(isa<ConstantInt>(IDV), "gc.statepoint ID must be a constant integer", 1670 &CI); 1671 1672 const Value *NumPatchBytesV = CS.getArgument(1); 1673 Assert(isa<ConstantInt>(NumPatchBytesV), 1674 "gc.statepoint number of patchable bytes must be a constant integer", 1675 &CI); 1676 const int64_t NumPatchBytes = 1677 cast<ConstantInt>(NumPatchBytesV)->getSExtValue(); 1678 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!"); 1679 Assert(NumPatchBytes >= 0, "gc.statepoint number of patchable bytes must be " 1680 "positive", 1681 &CI); 1682 1683 const Value *Target = CS.getArgument(2); 1684 auto *PT = dyn_cast<PointerType>(Target->getType()); 1685 Assert(PT && PT->getElementType()->isFunctionTy(), 1686 "gc.statepoint callee must be of function pointer type", &CI, Target); 1687 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType()); 1688 1689 const Value *NumCallArgsV = CS.getArgument(3); 1690 Assert(isa<ConstantInt>(NumCallArgsV), 1691 "gc.statepoint number of arguments to underlying call " 1692 "must be constant integer", 1693 &CI); 1694 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue(); 1695 Assert(NumCallArgs >= 0, 1696 "gc.statepoint number of arguments to underlying call " 1697 "must be positive", 1698 &CI); 1699 const int NumParams = (int)TargetFuncType->getNumParams(); 1700 if (TargetFuncType->isVarArg()) { 1701 Assert(NumCallArgs >= NumParams, 1702 "gc.statepoint mismatch in number of vararg call args", &CI); 1703 1704 // TODO: Remove this limitation 1705 Assert(TargetFuncType->getReturnType()->isVoidTy(), 1706 "gc.statepoint doesn't support wrapping non-void " 1707 "vararg functions yet", 1708 &CI); 1709 } else 1710 Assert(NumCallArgs == NumParams, 1711 "gc.statepoint mismatch in number of call args", &CI); 1712 1713 const Value *FlagsV = CS.getArgument(4); 1714 Assert(isa<ConstantInt>(FlagsV), 1715 "gc.statepoint flags must be constant integer", &CI); 1716 const uint64_t Flags = cast<ConstantInt>(FlagsV)->getZExtValue(); 1717 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0, 1718 "unknown flag used in gc.statepoint flags argument", &CI); 1719 1720 // Verify that the types of the call parameter arguments match 1721 // the type of the wrapped callee. 1722 for (int i = 0; i < NumParams; i++) { 1723 Type *ParamType = TargetFuncType->getParamType(i); 1724 Type *ArgType = CS.getArgument(5 + i)->getType(); 1725 Assert(ArgType == ParamType, 1726 "gc.statepoint call argument does not match wrapped " 1727 "function type", 1728 &CI); 1729 } 1730 1731 const int EndCallArgsInx = 4 + NumCallArgs; 1732 1733 const Value *NumTransitionArgsV = CS.getArgument(EndCallArgsInx+1); 1734 Assert(isa<ConstantInt>(NumTransitionArgsV), 1735 "gc.statepoint number of transition arguments " 1736 "must be constant integer", 1737 &CI); 1738 const int NumTransitionArgs = 1739 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue(); 1740 Assert(NumTransitionArgs >= 0, 1741 "gc.statepoint number of transition arguments must be positive", &CI); 1742 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs; 1743 1744 const Value *NumDeoptArgsV = CS.getArgument(EndTransitionArgsInx+1); 1745 Assert(isa<ConstantInt>(NumDeoptArgsV), 1746 "gc.statepoint number of deoptimization arguments " 1747 "must be constant integer", 1748 &CI); 1749 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue(); 1750 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments " 1751 "must be positive", 1752 &CI); 1753 1754 const int ExpectedNumArgs = 1755 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs; 1756 Assert(ExpectedNumArgs <= (int)CS.arg_size(), 1757 "gc.statepoint too few arguments according to length fields", &CI); 1758 1759 // Check that the only uses of this gc.statepoint are gc.result or 1760 // gc.relocate calls which are tied to this statepoint and thus part 1761 // of the same statepoint sequence 1762 for (const User *U : CI.users()) { 1763 const CallInst *Call = dyn_cast<const CallInst>(U); 1764 Assert(Call, "illegal use of statepoint token", &CI, U); 1765 if (!Call) continue; 1766 Assert(isa<GCRelocateInst>(Call) || isa<GCResultInst>(Call), 1767 "gc.result or gc.relocate are the only value uses" 1768 "of a gc.statepoint", 1769 &CI, U); 1770 if (isa<GCResultInst>(Call)) { 1771 Assert(Call->getArgOperand(0) == &CI, 1772 "gc.result connected to wrong gc.statepoint", &CI, Call); 1773 } else if (isa<GCRelocateInst>(Call)) { 1774 Assert(Call->getArgOperand(0) == &CI, 1775 "gc.relocate connected to wrong gc.statepoint", &CI, Call); 1776 } 1777 } 1778 1779 // Note: It is legal for a single derived pointer to be listed multiple 1780 // times. It's non-optimal, but it is legal. It can also happen after 1781 // insertion if we strip a bitcast away. 1782 // Note: It is really tempting to check that each base is relocated and 1783 // that a derived pointer is never reused as a base pointer. This turns 1784 // out to be problematic since optimizations run after safepoint insertion 1785 // can recognize equality properties that the insertion logic doesn't know 1786 // about. See example statepoint.ll in the verifier subdirectory 1787 } 1788 1789 void Verifier::verifyFrameRecoverIndices() { 1790 for (auto &Counts : FrameEscapeInfo) { 1791 Function *F = Counts.first; 1792 unsigned EscapedObjectCount = Counts.second.first; 1793 unsigned MaxRecoveredIndex = Counts.second.second; 1794 Assert(MaxRecoveredIndex <= EscapedObjectCount, 1795 "all indices passed to llvm.localrecover must be less than the " 1796 "number of arguments passed ot llvm.localescape in the parent " 1797 "function", 1798 F); 1799 } 1800 } 1801 1802 static Instruction *getSuccPad(TerminatorInst *Terminator) { 1803 BasicBlock *UnwindDest; 1804 if (auto *II = dyn_cast<InvokeInst>(Terminator)) 1805 UnwindDest = II->getUnwindDest(); 1806 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator)) 1807 UnwindDest = CSI->getUnwindDest(); 1808 else 1809 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest(); 1810 return UnwindDest->getFirstNonPHI(); 1811 } 1812 1813 void Verifier::verifySiblingFuncletUnwinds() { 1814 SmallPtrSet<Instruction *, 8> Visited; 1815 SmallPtrSet<Instruction *, 8> Active; 1816 for (const auto &Pair : SiblingFuncletInfo) { 1817 Instruction *PredPad = Pair.first; 1818 if (Visited.count(PredPad)) 1819 continue; 1820 Active.insert(PredPad); 1821 TerminatorInst *Terminator = Pair.second; 1822 do { 1823 Instruction *SuccPad = getSuccPad(Terminator); 1824 if (Active.count(SuccPad)) { 1825 // Found a cycle; report error 1826 Instruction *CyclePad = SuccPad; 1827 SmallVector<Instruction *, 8> CycleNodes; 1828 do { 1829 CycleNodes.push_back(CyclePad); 1830 TerminatorInst *CycleTerminator = SiblingFuncletInfo[CyclePad]; 1831 if (CycleTerminator != CyclePad) 1832 CycleNodes.push_back(CycleTerminator); 1833 CyclePad = getSuccPad(CycleTerminator); 1834 } while (CyclePad != SuccPad); 1835 Assert(false, "EH pads can't handle each other's exceptions", 1836 ArrayRef<Instruction *>(CycleNodes)); 1837 } 1838 // Don't re-walk a node we've already checked 1839 if (!Visited.insert(SuccPad).second) 1840 break; 1841 // Walk to this successor if it has a map entry. 1842 PredPad = SuccPad; 1843 auto TermI = SiblingFuncletInfo.find(PredPad); 1844 if (TermI == SiblingFuncletInfo.end()) 1845 break; 1846 Terminator = TermI->second; 1847 Active.insert(PredPad); 1848 } while (true); 1849 // Each node only has one successor, so we've walked all the active 1850 // nodes' successors. 1851 Active.clear(); 1852 } 1853 } 1854 1855 // visitFunction - Verify that a function is ok. 1856 // 1857 void Verifier::visitFunction(const Function &F) { 1858 visitGlobalValue(F); 1859 1860 // Check function arguments. 1861 FunctionType *FT = F.getFunctionType(); 1862 unsigned NumArgs = F.arg_size(); 1863 1864 Assert(Context == &F.getContext(), 1865 "Function context does not match Module context!", &F); 1866 1867 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 1868 Assert(FT->getNumParams() == NumArgs, 1869 "# formal arguments must match # of arguments for function type!", &F, 1870 FT); 1871 Assert(F.getReturnType()->isFirstClassType() || 1872 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(), 1873 "Functions cannot return aggregate values!", &F); 1874 1875 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 1876 "Invalid struct return type!", &F); 1877 1878 AttributeSet Attrs = F.getAttributes(); 1879 1880 Assert(verifyAttributeCount(Attrs, FT->getNumParams()), 1881 "Attribute after last parameter!", &F); 1882 1883 // Check function attributes. 1884 verifyFunctionAttrs(FT, Attrs, &F); 1885 1886 // On function declarations/definitions, we do not support the builtin 1887 // attribute. We do not check this in VerifyFunctionAttrs since that is 1888 // checking for Attributes that can/can not ever be on functions. 1889 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin), 1890 "Attribute 'builtin' can only be applied to a callsite.", &F); 1891 1892 // Check that this function meets the restrictions on this calling convention. 1893 // Sometimes varargs is used for perfectly forwarding thunks, so some of these 1894 // restrictions can be lifted. 1895 switch (F.getCallingConv()) { 1896 default: 1897 case CallingConv::C: 1898 break; 1899 case CallingConv::Fast: 1900 case CallingConv::Cold: 1901 case CallingConv::Intel_OCL_BI: 1902 case CallingConv::PTX_Kernel: 1903 case CallingConv::PTX_Device: 1904 Assert(!F.isVarArg(), "Calling convention does not support varargs or " 1905 "perfect forwarding!", 1906 &F); 1907 break; 1908 } 1909 1910 bool isLLVMdotName = F.getName().size() >= 5 && 1911 F.getName().substr(0, 5) == "llvm."; 1912 1913 // Check that the argument values match the function type for this function... 1914 unsigned i = 0; 1915 for (const Argument &Arg : F.args()) { 1916 Assert(Arg.getType() == FT->getParamType(i), 1917 "Argument value does not match function argument type!", &Arg, 1918 FT->getParamType(i)); 1919 Assert(Arg.getType()->isFirstClassType(), 1920 "Function arguments must have first-class types!", &Arg); 1921 if (!isLLVMdotName) { 1922 Assert(!Arg.getType()->isMetadataTy(), 1923 "Function takes metadata but isn't an intrinsic", &Arg, &F); 1924 Assert(!Arg.getType()->isTokenTy(), 1925 "Function takes token but isn't an intrinsic", &Arg, &F); 1926 } 1927 1928 // Check that swifterror argument is only used by loads and stores. 1929 if (Attrs.hasAttribute(i+1, Attribute::SwiftError)) { 1930 verifySwiftErrorValue(&Arg); 1931 } 1932 ++i; 1933 } 1934 1935 if (!isLLVMdotName) 1936 Assert(!F.getReturnType()->isTokenTy(), 1937 "Functions returns a token but isn't an intrinsic", &F); 1938 1939 // Get the function metadata attachments. 1940 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 1941 F.getAllMetadata(MDs); 1942 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync"); 1943 verifyFunctionMetadata(MDs); 1944 1945 // Check validity of the personality function 1946 if (F.hasPersonalityFn()) { 1947 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()); 1948 if (Per) 1949 Assert(Per->getParent() == F.getParent(), 1950 "Referencing personality function in another module!", 1951 &F, F.getParent(), Per, Per->getParent()); 1952 } 1953 1954 if (F.isMaterializable()) { 1955 // Function has a body somewhere we can't see. 1956 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F, 1957 MDs.empty() ? nullptr : MDs.front().second); 1958 } else if (F.isDeclaration()) { 1959 Assert(MDs.empty(), "function without a body cannot have metadata", &F, 1960 MDs.empty() ? nullptr : MDs.front().second); 1961 Assert(!F.hasPersonalityFn(), 1962 "Function declaration shouldn't have a personality routine", &F); 1963 } else { 1964 // Verify that this function (which has a body) is not named "llvm.*". It 1965 // is not legal to define intrinsics. 1966 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 1967 1968 // Check the entry node 1969 const BasicBlock *Entry = &F.getEntryBlock(); 1970 Assert(pred_empty(Entry), 1971 "Entry block to function must not have predecessors!", Entry); 1972 1973 // The address of the entry block cannot be taken, unless it is dead. 1974 if (Entry->hasAddressTaken()) { 1975 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(), 1976 "blockaddress may not be used with the entry block!", Entry); 1977 } 1978 1979 unsigned NumDebugAttachments = 0; 1980 // Visit metadata attachments. 1981 for (const auto &I : MDs) { 1982 // Verify that the attachment is legal. 1983 switch (I.first) { 1984 default: 1985 break; 1986 case LLVMContext::MD_dbg: 1987 ++NumDebugAttachments; 1988 AssertDI(NumDebugAttachments == 1, 1989 "function must have a single !dbg attachment", &F, I.second); 1990 AssertDI(isa<DISubprogram>(I.second), 1991 "function !dbg attachment must be a subprogram", &F, I.second); 1992 break; 1993 } 1994 1995 // Verify the metadata itself. 1996 visitMDNode(*I.second); 1997 } 1998 } 1999 2000 // If this function is actually an intrinsic, verify that it is only used in 2001 // direct call/invokes, never having its "address taken". 2002 // Only do this if the module is materialized, otherwise we don't have all the 2003 // uses. 2004 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) { 2005 const User *U; 2006 if (F.hasAddressTaken(&U)) 2007 Assert(0, "Invalid user of intrinsic instruction!", U); 2008 } 2009 2010 Assert(!F.hasDLLImportStorageClass() || 2011 (F.isDeclaration() && F.hasExternalLinkage()) || 2012 F.hasAvailableExternallyLinkage(), 2013 "Function is marked as dllimport, but not external.", &F); 2014 2015 auto *N = F.getSubprogram(); 2016 if (!N) 2017 return; 2018 2019 visitDISubprogram(*N); 2020 2021 // Check that all !dbg attachments lead to back to N (or, at least, another 2022 // subprogram that describes the same function). 2023 // 2024 // FIXME: Check this incrementally while visiting !dbg attachments. 2025 // FIXME: Only check when N is the canonical subprogram for F. 2026 SmallPtrSet<const MDNode *, 32> Seen; 2027 for (auto &BB : F) 2028 for (auto &I : BB) { 2029 // Be careful about using DILocation here since we might be dealing with 2030 // broken code (this is the Verifier after all). 2031 DILocation *DL = 2032 dyn_cast_or_null<DILocation>(I.getDebugLoc().getAsMDNode()); 2033 if (!DL) 2034 continue; 2035 if (!Seen.insert(DL).second) 2036 continue; 2037 2038 DILocalScope *Scope = DL->getInlinedAtScope(); 2039 if (Scope && !Seen.insert(Scope).second) 2040 continue; 2041 2042 DISubprogram *SP = Scope ? Scope->getSubprogram() : nullptr; 2043 2044 // Scope and SP could be the same MDNode and we don't want to skip 2045 // validation in that case 2046 if (SP && ((Scope != SP) && !Seen.insert(SP).second)) 2047 continue; 2048 2049 // FIXME: Once N is canonical, check "SP == &N". 2050 Assert(SP->describes(&F), 2051 "!dbg attachment points at wrong subprogram for function", N, &F, 2052 &I, DL, Scope, SP); 2053 } 2054 } 2055 2056 // verifyBasicBlock - Verify that a basic block is well formed... 2057 // 2058 void Verifier::visitBasicBlock(BasicBlock &BB) { 2059 InstsInThisBlock.clear(); 2060 2061 // Ensure that basic blocks have terminators! 2062 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 2063 2064 // Check constraints that this basic block imposes on all of the PHI nodes in 2065 // it. 2066 if (isa<PHINode>(BB.front())) { 2067 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB)); 2068 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 2069 std::sort(Preds.begin(), Preds.end()); 2070 PHINode *PN; 2071 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) { 2072 // Ensure that PHI nodes have at least one entry! 2073 Assert(PN->getNumIncomingValues() != 0, 2074 "PHI nodes must have at least one entry. If the block is dead, " 2075 "the PHI should be removed!", 2076 PN); 2077 Assert(PN->getNumIncomingValues() == Preds.size(), 2078 "PHINode should have one entry for each predecessor of its " 2079 "parent basic block!", 2080 PN); 2081 2082 // Get and sort all incoming values in the PHI node... 2083 Values.clear(); 2084 Values.reserve(PN->getNumIncomingValues()); 2085 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 2086 Values.push_back(std::make_pair(PN->getIncomingBlock(i), 2087 PN->getIncomingValue(i))); 2088 std::sort(Values.begin(), Values.end()); 2089 2090 for (unsigned i = 0, e = Values.size(); i != e; ++i) { 2091 // Check to make sure that if there is more than one entry for a 2092 // particular basic block in this PHI node, that the incoming values are 2093 // all identical. 2094 // 2095 Assert(i == 0 || Values[i].first != Values[i - 1].first || 2096 Values[i].second == Values[i - 1].second, 2097 "PHI node has multiple entries for the same basic block with " 2098 "different incoming values!", 2099 PN, Values[i].first, Values[i].second, Values[i - 1].second); 2100 2101 // Check to make sure that the predecessors and PHI node entries are 2102 // matched up. 2103 Assert(Values[i].first == Preds[i], 2104 "PHI node entries do not match predecessors!", PN, 2105 Values[i].first, Preds[i]); 2106 } 2107 } 2108 } 2109 2110 // Check that all instructions have their parent pointers set up correctly. 2111 for (auto &I : BB) 2112 { 2113 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!"); 2114 } 2115 } 2116 2117 void Verifier::visitTerminatorInst(TerminatorInst &I) { 2118 // Ensure that terminators only exist at the end of the basic block. 2119 Assert(&I == I.getParent()->getTerminator(), 2120 "Terminator found in the middle of a basic block!", I.getParent()); 2121 visitInstruction(I); 2122 } 2123 2124 void Verifier::visitBranchInst(BranchInst &BI) { 2125 if (BI.isConditional()) { 2126 Assert(BI.getCondition()->getType()->isIntegerTy(1), 2127 "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 2128 } 2129 visitTerminatorInst(BI); 2130 } 2131 2132 void Verifier::visitReturnInst(ReturnInst &RI) { 2133 Function *F = RI.getParent()->getParent(); 2134 unsigned N = RI.getNumOperands(); 2135 if (F->getReturnType()->isVoidTy()) 2136 Assert(N == 0, 2137 "Found return instr that returns non-void in Function of void " 2138 "return type!", 2139 &RI, F->getReturnType()); 2140 else 2141 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 2142 "Function return type does not match operand " 2143 "type of return inst!", 2144 &RI, F->getReturnType()); 2145 2146 // Check to make sure that the return value has necessary properties for 2147 // terminators... 2148 visitTerminatorInst(RI); 2149 } 2150 2151 void Verifier::visitSwitchInst(SwitchInst &SI) { 2152 // Check to make sure that all of the constants in the switch instruction 2153 // have the same type as the switched-on value. 2154 Type *SwitchTy = SI.getCondition()->getType(); 2155 SmallPtrSet<ConstantInt*, 32> Constants; 2156 for (auto &Case : SI.cases()) { 2157 Assert(Case.getCaseValue()->getType() == SwitchTy, 2158 "Switch constants must all be same type as switch value!", &SI); 2159 Assert(Constants.insert(Case.getCaseValue()).second, 2160 "Duplicate integer as switch case", &SI, Case.getCaseValue()); 2161 } 2162 2163 visitTerminatorInst(SI); 2164 } 2165 2166 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 2167 Assert(BI.getAddress()->getType()->isPointerTy(), 2168 "Indirectbr operand must have pointer type!", &BI); 2169 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 2170 Assert(BI.getDestination(i)->getType()->isLabelTy(), 2171 "Indirectbr destinations must all have pointer type!", &BI); 2172 2173 visitTerminatorInst(BI); 2174 } 2175 2176 void Verifier::visitSelectInst(SelectInst &SI) { 2177 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 2178 SI.getOperand(2)), 2179 "Invalid operands for select instruction!", &SI); 2180 2181 Assert(SI.getTrueValue()->getType() == SI.getType(), 2182 "Select values must have same type as select instruction!", &SI); 2183 visitInstruction(SI); 2184 } 2185 2186 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 2187 /// a pass, if any exist, it's an error. 2188 /// 2189 void Verifier::visitUserOp1(Instruction &I) { 2190 Assert(0, "User-defined operators should not live outside of a pass!", &I); 2191 } 2192 2193 void Verifier::visitTruncInst(TruncInst &I) { 2194 // Get the source and destination types 2195 Type *SrcTy = I.getOperand(0)->getType(); 2196 Type *DestTy = I.getType(); 2197 2198 // Get the size of the types in bits, we'll need this later 2199 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2200 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2201 2202 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 2203 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 2204 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2205 "trunc source and destination must both be a vector or neither", &I); 2206 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I); 2207 2208 visitInstruction(I); 2209 } 2210 2211 void Verifier::visitZExtInst(ZExtInst &I) { 2212 // Get the source and destination types 2213 Type *SrcTy = I.getOperand(0)->getType(); 2214 Type *DestTy = I.getType(); 2215 2216 // Get the size of the types in bits, we'll need this later 2217 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 2218 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 2219 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2220 "zext source and destination must both be a vector or neither", &I); 2221 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2222 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2223 2224 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I); 2225 2226 visitInstruction(I); 2227 } 2228 2229 void Verifier::visitSExtInst(SExtInst &I) { 2230 // Get the source and destination types 2231 Type *SrcTy = I.getOperand(0)->getType(); 2232 Type *DestTy = I.getType(); 2233 2234 // Get the size of the types in bits, we'll need this later 2235 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2236 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2237 2238 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 2239 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 2240 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2241 "sext source and destination must both be a vector or neither", &I); 2242 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I); 2243 2244 visitInstruction(I); 2245 } 2246 2247 void Verifier::visitFPTruncInst(FPTruncInst &I) { 2248 // Get the source and destination types 2249 Type *SrcTy = I.getOperand(0)->getType(); 2250 Type *DestTy = I.getType(); 2251 // Get the size of the types in bits, we'll need this later 2252 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2253 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2254 2255 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I); 2256 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I); 2257 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2258 "fptrunc source and destination must both be a vector or neither", &I); 2259 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I); 2260 2261 visitInstruction(I); 2262 } 2263 2264 void Verifier::visitFPExtInst(FPExtInst &I) { 2265 // Get the source and destination types 2266 Type *SrcTy = I.getOperand(0)->getType(); 2267 Type *DestTy = I.getType(); 2268 2269 // Get the size of the types in bits, we'll need this later 2270 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2271 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2272 2273 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I); 2274 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I); 2275 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2276 "fpext source and destination must both be a vector or neither", &I); 2277 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I); 2278 2279 visitInstruction(I); 2280 } 2281 2282 void Verifier::visitUIToFPInst(UIToFPInst &I) { 2283 // Get the source and destination types 2284 Type *SrcTy = I.getOperand(0)->getType(); 2285 Type *DestTy = I.getType(); 2286 2287 bool SrcVec = SrcTy->isVectorTy(); 2288 bool DstVec = DestTy->isVectorTy(); 2289 2290 Assert(SrcVec == DstVec, 2291 "UIToFP source and dest must both be vector or scalar", &I); 2292 Assert(SrcTy->isIntOrIntVectorTy(), 2293 "UIToFP source must be integer or integer vector", &I); 2294 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector", 2295 &I); 2296 2297 if (SrcVec && DstVec) 2298 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2299 cast<VectorType>(DestTy)->getNumElements(), 2300 "UIToFP source and dest vector length mismatch", &I); 2301 2302 visitInstruction(I); 2303 } 2304 2305 void Verifier::visitSIToFPInst(SIToFPInst &I) { 2306 // Get the source and destination types 2307 Type *SrcTy = I.getOperand(0)->getType(); 2308 Type *DestTy = I.getType(); 2309 2310 bool SrcVec = SrcTy->isVectorTy(); 2311 bool DstVec = DestTy->isVectorTy(); 2312 2313 Assert(SrcVec == DstVec, 2314 "SIToFP source and dest must both be vector or scalar", &I); 2315 Assert(SrcTy->isIntOrIntVectorTy(), 2316 "SIToFP source must be integer or integer vector", &I); 2317 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector", 2318 &I); 2319 2320 if (SrcVec && DstVec) 2321 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2322 cast<VectorType>(DestTy)->getNumElements(), 2323 "SIToFP source and dest vector length mismatch", &I); 2324 2325 visitInstruction(I); 2326 } 2327 2328 void Verifier::visitFPToUIInst(FPToUIInst &I) { 2329 // Get the source and destination types 2330 Type *SrcTy = I.getOperand(0)->getType(); 2331 Type *DestTy = I.getType(); 2332 2333 bool SrcVec = SrcTy->isVectorTy(); 2334 bool DstVec = DestTy->isVectorTy(); 2335 2336 Assert(SrcVec == DstVec, 2337 "FPToUI source and dest must both be vector or scalar", &I); 2338 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 2339 &I); 2340 Assert(DestTy->isIntOrIntVectorTy(), 2341 "FPToUI result must be integer or integer vector", &I); 2342 2343 if (SrcVec && DstVec) 2344 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2345 cast<VectorType>(DestTy)->getNumElements(), 2346 "FPToUI source and dest vector length mismatch", &I); 2347 2348 visitInstruction(I); 2349 } 2350 2351 void Verifier::visitFPToSIInst(FPToSIInst &I) { 2352 // Get the source and destination types 2353 Type *SrcTy = I.getOperand(0)->getType(); 2354 Type *DestTy = I.getType(); 2355 2356 bool SrcVec = SrcTy->isVectorTy(); 2357 bool DstVec = DestTy->isVectorTy(); 2358 2359 Assert(SrcVec == DstVec, 2360 "FPToSI source and dest must both be vector or scalar", &I); 2361 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", 2362 &I); 2363 Assert(DestTy->isIntOrIntVectorTy(), 2364 "FPToSI result must be integer or integer vector", &I); 2365 2366 if (SrcVec && DstVec) 2367 Assert(cast<VectorType>(SrcTy)->getNumElements() == 2368 cast<VectorType>(DestTy)->getNumElements(), 2369 "FPToSI source and dest vector length mismatch", &I); 2370 2371 visitInstruction(I); 2372 } 2373 2374 void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 2375 // Get the source and destination types 2376 Type *SrcTy = I.getOperand(0)->getType(); 2377 Type *DestTy = I.getType(); 2378 2379 Assert(SrcTy->getScalarType()->isPointerTy(), 2380 "PtrToInt source must be pointer", &I); 2381 Assert(DestTy->getScalarType()->isIntegerTy(), 2382 "PtrToInt result must be integral", &I); 2383 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch", 2384 &I); 2385 2386 if (SrcTy->isVectorTy()) { 2387 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 2388 VectorType *VDest = dyn_cast<VectorType>(DestTy); 2389 Assert(VSrc->getNumElements() == VDest->getNumElements(), 2390 "PtrToInt Vector width mismatch", &I); 2391 } 2392 2393 visitInstruction(I); 2394 } 2395 2396 void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 2397 // Get the source and destination types 2398 Type *SrcTy = I.getOperand(0)->getType(); 2399 Type *DestTy = I.getType(); 2400 2401 Assert(SrcTy->getScalarType()->isIntegerTy(), 2402 "IntToPtr source must be an integral", &I); 2403 Assert(DestTy->getScalarType()->isPointerTy(), 2404 "IntToPtr result must be a pointer", &I); 2405 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch", 2406 &I); 2407 if (SrcTy->isVectorTy()) { 2408 VectorType *VSrc = dyn_cast<VectorType>(SrcTy); 2409 VectorType *VDest = dyn_cast<VectorType>(DestTy); 2410 Assert(VSrc->getNumElements() == VDest->getNumElements(), 2411 "IntToPtr Vector width mismatch", &I); 2412 } 2413 visitInstruction(I); 2414 } 2415 2416 void Verifier::visitBitCastInst(BitCastInst &I) { 2417 Assert( 2418 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()), 2419 "Invalid bitcast", &I); 2420 visitInstruction(I); 2421 } 2422 2423 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 2424 Type *SrcTy = I.getOperand(0)->getType(); 2425 Type *DestTy = I.getType(); 2426 2427 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer", 2428 &I); 2429 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer", 2430 &I); 2431 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 2432 "AddrSpaceCast must be between different address spaces", &I); 2433 if (SrcTy->isVectorTy()) 2434 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(), 2435 "AddrSpaceCast vector pointer number of elements mismatch", &I); 2436 visitInstruction(I); 2437 } 2438 2439 /// visitPHINode - Ensure that a PHI node is well formed. 2440 /// 2441 void Verifier::visitPHINode(PHINode &PN) { 2442 // Ensure that the PHI nodes are all grouped together at the top of the block. 2443 // This can be tested by checking whether the instruction before this is 2444 // either nonexistent (because this is begin()) or is a PHI node. If not, 2445 // then there is some other instruction before a PHI. 2446 Assert(&PN == &PN.getParent()->front() || 2447 isa<PHINode>(--BasicBlock::iterator(&PN)), 2448 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent()); 2449 2450 // Check that a PHI doesn't yield a Token. 2451 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!"); 2452 2453 // Check that all of the values of the PHI node have the same type as the 2454 // result, and that the incoming blocks are really basic blocks. 2455 for (Value *IncValue : PN.incoming_values()) { 2456 Assert(PN.getType() == IncValue->getType(), 2457 "PHI node operands are not the same type as the result!", &PN); 2458 } 2459 2460 // All other PHI node constraints are checked in the visitBasicBlock method. 2461 2462 visitInstruction(PN); 2463 } 2464 2465 void Verifier::verifyCallSite(CallSite CS) { 2466 Instruction *I = CS.getInstruction(); 2467 2468 Assert(CS.getCalledValue()->getType()->isPointerTy(), 2469 "Called function must be a pointer!", I); 2470 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType()); 2471 2472 Assert(FPTy->getElementType()->isFunctionTy(), 2473 "Called function is not pointer to function type!", I); 2474 2475 Assert(FPTy->getElementType() == CS.getFunctionType(), 2476 "Called function is not the same type as the call!", I); 2477 2478 FunctionType *FTy = CS.getFunctionType(); 2479 2480 // Verify that the correct number of arguments are being passed 2481 if (FTy->isVarArg()) 2482 Assert(CS.arg_size() >= FTy->getNumParams(), 2483 "Called function requires more parameters than were provided!", I); 2484 else 2485 Assert(CS.arg_size() == FTy->getNumParams(), 2486 "Incorrect number of arguments passed to called function!", I); 2487 2488 // Verify that all arguments to the call match the function type. 2489 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2490 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i), 2491 "Call parameter type does not match function signature!", 2492 CS.getArgument(i), FTy->getParamType(i), I); 2493 2494 AttributeSet Attrs = CS.getAttributes(); 2495 2496 Assert(verifyAttributeCount(Attrs, CS.arg_size()), 2497 "Attribute after last parameter!", I); 2498 2499 // Verify call attributes. 2500 verifyFunctionAttrs(FTy, Attrs, I); 2501 2502 // Conservatively check the inalloca argument. 2503 // We have a bug if we can find that there is an underlying alloca without 2504 // inalloca. 2505 if (CS.hasInAllocaArgument()) { 2506 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1); 2507 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets())) 2508 Assert(AI->isUsedWithInAlloca(), 2509 "inalloca argument for call has mismatched alloca", AI, I); 2510 } 2511 2512 // For each argument of the callsite, if it has the swifterror argument, 2513 // make sure the underlying alloca has swifterror as well. 2514 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 2515 if (CS.paramHasAttr(i+1, Attribute::SwiftError)) { 2516 Value *SwiftErrorArg = CS.getArgument(i); 2517 auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets()); 2518 Assert(AI, "swifterror argument should come from alloca", AI, I); 2519 if (AI) 2520 Assert(AI->isSwiftError(), 2521 "swifterror argument for call has mismatched alloca", AI, I); 2522 } 2523 2524 if (FTy->isVarArg()) { 2525 // FIXME? is 'nest' even legal here? 2526 bool SawNest = false; 2527 bool SawReturned = false; 2528 2529 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) { 2530 if (Attrs.hasAttribute(Idx, Attribute::Nest)) 2531 SawNest = true; 2532 if (Attrs.hasAttribute(Idx, Attribute::Returned)) 2533 SawReturned = true; 2534 } 2535 2536 // Check attributes on the varargs part. 2537 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) { 2538 Type *Ty = CS.getArgument(Idx-1)->getType(); 2539 verifyParameterAttrs(Attrs, Idx, Ty, false, I); 2540 2541 if (Attrs.hasAttribute(Idx, Attribute::Nest)) { 2542 Assert(!SawNest, "More than one parameter has attribute nest!", I); 2543 SawNest = true; 2544 } 2545 2546 if (Attrs.hasAttribute(Idx, Attribute::Returned)) { 2547 Assert(!SawReturned, "More than one parameter has attribute returned!", 2548 I); 2549 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 2550 "Incompatible argument and return types for 'returned' " 2551 "attribute", 2552 I); 2553 SawReturned = true; 2554 } 2555 2556 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet), 2557 "Attribute 'sret' cannot be used for vararg call arguments!", I); 2558 2559 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) 2560 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I); 2561 } 2562 } 2563 2564 // Verify that there's no metadata unless it's a direct call to an intrinsic. 2565 if (CS.getCalledFunction() == nullptr || 2566 !CS.getCalledFunction()->getName().startswith("llvm.")) { 2567 for (Type *ParamTy : FTy->params()) { 2568 Assert(!ParamTy->isMetadataTy(), 2569 "Function has metadata parameter but isn't an intrinsic", I); 2570 Assert(!ParamTy->isTokenTy(), 2571 "Function has token parameter but isn't an intrinsic", I); 2572 } 2573 } 2574 2575 // Verify that indirect calls don't return tokens. 2576 if (CS.getCalledFunction() == nullptr) 2577 Assert(!FTy->getReturnType()->isTokenTy(), 2578 "Return type cannot be token for indirect call!"); 2579 2580 if (Function *F = CS.getCalledFunction()) 2581 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 2582 visitIntrinsicCallSite(ID, CS); 2583 2584 // Verify that a callsite has at most one "deopt", at most one "funclet" and 2585 // at most one "gc-transition" operand bundle. 2586 bool FoundDeoptBundle = false, FoundFuncletBundle = false, 2587 FoundGCTransitionBundle = false; 2588 for (unsigned i = 0, e = CS.getNumOperandBundles(); i < e; ++i) { 2589 OperandBundleUse BU = CS.getOperandBundleAt(i); 2590 uint32_t Tag = BU.getTagID(); 2591 if (Tag == LLVMContext::OB_deopt) { 2592 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", I); 2593 FoundDeoptBundle = true; 2594 } else if (Tag == LLVMContext::OB_gc_transition) { 2595 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles", 2596 I); 2597 FoundGCTransitionBundle = true; 2598 } else if (Tag == LLVMContext::OB_funclet) { 2599 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", I); 2600 FoundFuncletBundle = true; 2601 Assert(BU.Inputs.size() == 1, 2602 "Expected exactly one funclet bundle operand", I); 2603 Assert(isa<FuncletPadInst>(BU.Inputs.front()), 2604 "Funclet bundle operands should correspond to a FuncletPadInst", 2605 I); 2606 } 2607 } 2608 2609 // Verify that each inlinable callsite of a debug-info-bearing function in a 2610 // debug-info-bearing function has a debug location attached to it. Failure to 2611 // do so causes assertion failures when the inliner sets up inline scope info. 2612 if (I->getFunction()->getSubprogram() && CS.getCalledFunction() && 2613 CS.getCalledFunction()->getSubprogram()) 2614 Assert(I->getDebugLoc(), "inlinable function call in a function with debug " 2615 "info must have a !dbg location", 2616 I); 2617 2618 visitInstruction(*I); 2619 } 2620 2621 /// Two types are "congruent" if they are identical, or if they are both pointer 2622 /// types with different pointee types and the same address space. 2623 static bool isTypeCongruent(Type *L, Type *R) { 2624 if (L == R) 2625 return true; 2626 PointerType *PL = dyn_cast<PointerType>(L); 2627 PointerType *PR = dyn_cast<PointerType>(R); 2628 if (!PL || !PR) 2629 return false; 2630 return PL->getAddressSpace() == PR->getAddressSpace(); 2631 } 2632 2633 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) { 2634 static const Attribute::AttrKind ABIAttrs[] = { 2635 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 2636 Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf, 2637 Attribute::SwiftError}; 2638 AttrBuilder Copy; 2639 for (auto AK : ABIAttrs) { 2640 if (Attrs.hasAttribute(I + 1, AK)) 2641 Copy.addAttribute(AK); 2642 } 2643 if (Attrs.hasAttribute(I + 1, Attribute::Alignment)) 2644 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1)); 2645 return Copy; 2646 } 2647 2648 void Verifier::verifyMustTailCall(CallInst &CI) { 2649 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI); 2650 2651 // - The caller and callee prototypes must match. Pointer types of 2652 // parameters or return types may differ in pointee type, but not 2653 // address space. 2654 Function *F = CI.getParent()->getParent(); 2655 FunctionType *CallerTy = F->getFunctionType(); 2656 FunctionType *CalleeTy = CI.getFunctionType(); 2657 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(), 2658 "cannot guarantee tail call due to mismatched parameter counts", &CI); 2659 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(), 2660 "cannot guarantee tail call due to mismatched varargs", &CI); 2661 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()), 2662 "cannot guarantee tail call due to mismatched return types", &CI); 2663 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 2664 Assert( 2665 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)), 2666 "cannot guarantee tail call due to mismatched parameter types", &CI); 2667 } 2668 2669 // - The calling conventions of the caller and callee must match. 2670 Assert(F->getCallingConv() == CI.getCallingConv(), 2671 "cannot guarantee tail call due to mismatched calling conv", &CI); 2672 2673 // - All ABI-impacting function attributes, such as sret, byval, inreg, 2674 // returned, and inalloca, must match. 2675 AttributeSet CallerAttrs = F->getAttributes(); 2676 AttributeSet CalleeAttrs = CI.getAttributes(); 2677 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 2678 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs); 2679 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 2680 Assert(CallerABIAttrs == CalleeABIAttrs, 2681 "cannot guarantee tail call due to mismatched ABI impacting " 2682 "function attributes", 2683 &CI, CI.getOperand(I)); 2684 } 2685 2686 // - The call must immediately precede a :ref:`ret <i_ret>` instruction, 2687 // or a pointer bitcast followed by a ret instruction. 2688 // - The ret instruction must return the (possibly bitcasted) value 2689 // produced by the call or void. 2690 Value *RetVal = &CI; 2691 Instruction *Next = CI.getNextNode(); 2692 2693 // Handle the optional bitcast. 2694 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) { 2695 Assert(BI->getOperand(0) == RetVal, 2696 "bitcast following musttail call must use the call", BI); 2697 RetVal = BI; 2698 Next = BI->getNextNode(); 2699 } 2700 2701 // Check the return. 2702 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 2703 Assert(Ret, "musttail call must be precede a ret with an optional bitcast", 2704 &CI); 2705 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal, 2706 "musttail call result must be returned", Ret); 2707 } 2708 2709 void Verifier::visitCallInst(CallInst &CI) { 2710 verifyCallSite(&CI); 2711 2712 if (CI.isMustTailCall()) 2713 verifyMustTailCall(CI); 2714 } 2715 2716 void Verifier::visitInvokeInst(InvokeInst &II) { 2717 verifyCallSite(&II); 2718 2719 // Verify that the first non-PHI instruction of the unwind destination is an 2720 // exception handling instruction. 2721 Assert( 2722 II.getUnwindDest()->isEHPad(), 2723 "The unwind destination does not have an exception handling instruction!", 2724 &II); 2725 2726 visitTerminatorInst(II); 2727 } 2728 2729 /// visitBinaryOperator - Check that both arguments to the binary operator are 2730 /// of the same type! 2731 /// 2732 void Verifier::visitBinaryOperator(BinaryOperator &B) { 2733 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 2734 "Both operands to a binary operator are not of the same type!", &B); 2735 2736 switch (B.getOpcode()) { 2737 // Check that integer arithmetic operators are only used with 2738 // integral operands. 2739 case Instruction::Add: 2740 case Instruction::Sub: 2741 case Instruction::Mul: 2742 case Instruction::SDiv: 2743 case Instruction::UDiv: 2744 case Instruction::SRem: 2745 case Instruction::URem: 2746 Assert(B.getType()->isIntOrIntVectorTy(), 2747 "Integer arithmetic operators only work with integral types!", &B); 2748 Assert(B.getType() == B.getOperand(0)->getType(), 2749 "Integer arithmetic operators must have same type " 2750 "for operands and result!", 2751 &B); 2752 break; 2753 // Check that floating-point arithmetic operators are only used with 2754 // floating-point operands. 2755 case Instruction::FAdd: 2756 case Instruction::FSub: 2757 case Instruction::FMul: 2758 case Instruction::FDiv: 2759 case Instruction::FRem: 2760 Assert(B.getType()->isFPOrFPVectorTy(), 2761 "Floating-point arithmetic operators only work with " 2762 "floating-point types!", 2763 &B); 2764 Assert(B.getType() == B.getOperand(0)->getType(), 2765 "Floating-point arithmetic operators must have same type " 2766 "for operands and result!", 2767 &B); 2768 break; 2769 // Check that logical operators are only used with integral operands. 2770 case Instruction::And: 2771 case Instruction::Or: 2772 case Instruction::Xor: 2773 Assert(B.getType()->isIntOrIntVectorTy(), 2774 "Logical operators only work with integral types!", &B); 2775 Assert(B.getType() == B.getOperand(0)->getType(), 2776 "Logical operators must have same type for operands and result!", 2777 &B); 2778 break; 2779 case Instruction::Shl: 2780 case Instruction::LShr: 2781 case Instruction::AShr: 2782 Assert(B.getType()->isIntOrIntVectorTy(), 2783 "Shifts only work with integral types!", &B); 2784 Assert(B.getType() == B.getOperand(0)->getType(), 2785 "Shift return type must be same as operands!", &B); 2786 break; 2787 default: 2788 llvm_unreachable("Unknown BinaryOperator opcode!"); 2789 } 2790 2791 visitInstruction(B); 2792 } 2793 2794 void Verifier::visitICmpInst(ICmpInst &IC) { 2795 // Check that the operands are the same type 2796 Type *Op0Ty = IC.getOperand(0)->getType(); 2797 Type *Op1Ty = IC.getOperand(1)->getType(); 2798 Assert(Op0Ty == Op1Ty, 2799 "Both operands to ICmp instruction are not of the same type!", &IC); 2800 // Check that the operands are the right type 2801 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(), 2802 "Invalid operand types for ICmp instruction", &IC); 2803 // Check that the predicate is valid. 2804 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE && 2805 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE, 2806 "Invalid predicate in ICmp instruction!", &IC); 2807 2808 visitInstruction(IC); 2809 } 2810 2811 void Verifier::visitFCmpInst(FCmpInst &FC) { 2812 // Check that the operands are the same type 2813 Type *Op0Ty = FC.getOperand(0)->getType(); 2814 Type *Op1Ty = FC.getOperand(1)->getType(); 2815 Assert(Op0Ty == Op1Ty, 2816 "Both operands to FCmp instruction are not of the same type!", &FC); 2817 // Check that the operands are the right type 2818 Assert(Op0Ty->isFPOrFPVectorTy(), 2819 "Invalid operand types for FCmp instruction", &FC); 2820 // Check that the predicate is valid. 2821 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE && 2822 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE, 2823 "Invalid predicate in FCmp instruction!", &FC); 2824 2825 visitInstruction(FC); 2826 } 2827 2828 void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 2829 Assert( 2830 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)), 2831 "Invalid extractelement operands!", &EI); 2832 visitInstruction(EI); 2833 } 2834 2835 void Verifier::visitInsertElementInst(InsertElementInst &IE) { 2836 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1), 2837 IE.getOperand(2)), 2838 "Invalid insertelement operands!", &IE); 2839 visitInstruction(IE); 2840 } 2841 2842 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 2843 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 2844 SV.getOperand(2)), 2845 "Invalid shufflevector operands!", &SV); 2846 visitInstruction(SV); 2847 } 2848 2849 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 2850 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 2851 2852 Assert(isa<PointerType>(TargetTy), 2853 "GEP base pointer is not a vector or a vector of pointers", &GEP); 2854 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP); 2855 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end()); 2856 Type *ElTy = 2857 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs); 2858 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP); 2859 2860 Assert(GEP.getType()->getScalarType()->isPointerTy() && 2861 GEP.getResultElementType() == ElTy, 2862 "GEP is not of right type for indices!", &GEP, ElTy); 2863 2864 if (GEP.getType()->isVectorTy()) { 2865 // Additional checks for vector GEPs. 2866 unsigned GEPWidth = GEP.getType()->getVectorNumElements(); 2867 if (GEP.getPointerOperandType()->isVectorTy()) 2868 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(), 2869 "Vector GEP result width doesn't match operand's", &GEP); 2870 for (Value *Idx : Idxs) { 2871 Type *IndexTy = Idx->getType(); 2872 if (IndexTy->isVectorTy()) { 2873 unsigned IndexWidth = IndexTy->getVectorNumElements(); 2874 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP); 2875 } 2876 Assert(IndexTy->getScalarType()->isIntegerTy(), 2877 "All GEP indices should be of integer type"); 2878 } 2879 } 2880 visitInstruction(GEP); 2881 } 2882 2883 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 2884 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 2885 } 2886 2887 void Verifier::visitRangeMetadata(Instruction& I, 2888 MDNode* Range, Type* Ty) { 2889 assert(Range && 2890 Range == I.getMetadata(LLVMContext::MD_range) && 2891 "precondition violation"); 2892 2893 unsigned NumOperands = Range->getNumOperands(); 2894 Assert(NumOperands % 2 == 0, "Unfinished range!", Range); 2895 unsigned NumRanges = NumOperands / 2; 2896 Assert(NumRanges >= 1, "It should have at least one range!", Range); 2897 2898 ConstantRange LastRange(1); // Dummy initial value 2899 for (unsigned i = 0; i < NumRanges; ++i) { 2900 ConstantInt *Low = 2901 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i)); 2902 Assert(Low, "The lower limit must be an integer!", Low); 2903 ConstantInt *High = 2904 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1)); 2905 Assert(High, "The upper limit must be an integer!", High); 2906 Assert(High->getType() == Low->getType() && High->getType() == Ty, 2907 "Range types must match instruction type!", &I); 2908 2909 APInt HighV = High->getValue(); 2910 APInt LowV = Low->getValue(); 2911 ConstantRange CurRange(LowV, HighV); 2912 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(), 2913 "Range must not be empty!", Range); 2914 if (i != 0) { 2915 Assert(CurRange.intersectWith(LastRange).isEmptySet(), 2916 "Intervals are overlapping", Range); 2917 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 2918 Range); 2919 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 2920 Range); 2921 } 2922 LastRange = ConstantRange(LowV, HighV); 2923 } 2924 if (NumRanges > 2) { 2925 APInt FirstLow = 2926 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue(); 2927 APInt FirstHigh = 2928 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue(); 2929 ConstantRange FirstRange(FirstLow, FirstHigh); 2930 Assert(FirstRange.intersectWith(LastRange).isEmptySet(), 2931 "Intervals are overlapping", Range); 2932 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 2933 Range); 2934 } 2935 } 2936 2937 void Verifier::checkAtomicMemAccessSize(const Module *M, Type *Ty, 2938 const Instruction *I) { 2939 unsigned Size = M->getDataLayout().getTypeSizeInBits(Ty); 2940 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I); 2941 Assert(!(Size & (Size - 1)), 2942 "atomic memory access' operand must have a power-of-two size", Ty, I); 2943 } 2944 2945 void Verifier::visitLoadInst(LoadInst &LI) { 2946 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 2947 Assert(PTy, "Load operand must be a pointer.", &LI); 2948 Type *ElTy = LI.getType(); 2949 Assert(LI.getAlignment() <= Value::MaximumAlignment, 2950 "huge alignment values are unsupported", &LI); 2951 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI); 2952 if (LI.isAtomic()) { 2953 Assert(LI.getOrdering() != AtomicOrdering::Release && 2954 LI.getOrdering() != AtomicOrdering::AcquireRelease, 2955 "Load cannot have Release ordering", &LI); 2956 Assert(LI.getAlignment() != 0, 2957 "Atomic load must specify explicit alignment", &LI); 2958 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() || 2959 ElTy->isFloatingPointTy(), 2960 "atomic load operand must have integer, pointer, or floating point " 2961 "type!", 2962 ElTy, &LI); 2963 checkAtomicMemAccessSize(M, ElTy, &LI); 2964 } else { 2965 Assert(LI.getSynchScope() == CrossThread, 2966 "Non-atomic load cannot have SynchronizationScope specified", &LI); 2967 } 2968 2969 visitInstruction(LI); 2970 } 2971 2972 void Verifier::visitStoreInst(StoreInst &SI) { 2973 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 2974 Assert(PTy, "Store operand must be a pointer.", &SI); 2975 Type *ElTy = PTy->getElementType(); 2976 Assert(ElTy == SI.getOperand(0)->getType(), 2977 "Stored value type does not match pointer operand type!", &SI, ElTy); 2978 Assert(SI.getAlignment() <= Value::MaximumAlignment, 2979 "huge alignment values are unsupported", &SI); 2980 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI); 2981 if (SI.isAtomic()) { 2982 Assert(SI.getOrdering() != AtomicOrdering::Acquire && 2983 SI.getOrdering() != AtomicOrdering::AcquireRelease, 2984 "Store cannot have Acquire ordering", &SI); 2985 Assert(SI.getAlignment() != 0, 2986 "Atomic store must specify explicit alignment", &SI); 2987 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy() || 2988 ElTy->isFloatingPointTy(), 2989 "atomic store operand must have integer, pointer, or floating point " 2990 "type!", 2991 ElTy, &SI); 2992 checkAtomicMemAccessSize(M, ElTy, &SI); 2993 } else { 2994 Assert(SI.getSynchScope() == CrossThread, 2995 "Non-atomic store cannot have SynchronizationScope specified", &SI); 2996 } 2997 visitInstruction(SI); 2998 } 2999 3000 /// Check that SwiftErrorVal is used as a swifterror argument in CS. 3001 void Verifier::verifySwiftErrorCallSite(CallSite CS, 3002 const Value *SwiftErrorVal) { 3003 unsigned Idx = 0; 3004 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 3005 I != E; ++I, ++Idx) { 3006 if (*I == SwiftErrorVal) { 3007 Assert(CS.paramHasAttr(Idx+1, Attribute::SwiftError), 3008 "swifterror value when used in a callsite should be marked " 3009 "with swifterror attribute", 3010 SwiftErrorVal, CS); 3011 } 3012 } 3013 } 3014 3015 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) { 3016 // Check that swifterror value is only used by loads, stores, or as 3017 // a swifterror argument. 3018 for (const User *U : SwiftErrorVal->users()) { 3019 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) || 3020 isa<InvokeInst>(U), 3021 "swifterror value can only be loaded and stored from, or " 3022 "as a swifterror argument!", 3023 SwiftErrorVal, U); 3024 // If it is used by a store, check it is the second operand. 3025 if (auto StoreI = dyn_cast<StoreInst>(U)) 3026 Assert(StoreI->getOperand(1) == SwiftErrorVal, 3027 "swifterror value should be the second operand when used " 3028 "by stores", SwiftErrorVal, U); 3029 if (auto CallI = dyn_cast<CallInst>(U)) 3030 verifySwiftErrorCallSite(const_cast<CallInst*>(CallI), SwiftErrorVal); 3031 if (auto II = dyn_cast<InvokeInst>(U)) 3032 verifySwiftErrorCallSite(const_cast<InvokeInst*>(II), SwiftErrorVal); 3033 } 3034 } 3035 3036 void Verifier::visitAllocaInst(AllocaInst &AI) { 3037 SmallPtrSet<Type*, 4> Visited; 3038 PointerType *PTy = AI.getType(); 3039 Assert(PTy->getAddressSpace() == 0, 3040 "Allocation instruction pointer not in the generic address space!", 3041 &AI); 3042 Assert(AI.getAllocatedType()->isSized(&Visited), 3043 "Cannot allocate unsized type", &AI); 3044 Assert(AI.getArraySize()->getType()->isIntegerTy(), 3045 "Alloca array size must have integer type", &AI); 3046 Assert(AI.getAlignment() <= Value::MaximumAlignment, 3047 "huge alignment values are unsupported", &AI); 3048 3049 if (AI.isSwiftError()) { 3050 verifySwiftErrorValue(&AI); 3051 } 3052 3053 visitInstruction(AI); 3054 } 3055 3056 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 3057 3058 // FIXME: more conditions??? 3059 Assert(CXI.getSuccessOrdering() != AtomicOrdering::NotAtomic, 3060 "cmpxchg instructions must be atomic.", &CXI); 3061 Assert(CXI.getFailureOrdering() != AtomicOrdering::NotAtomic, 3062 "cmpxchg instructions must be atomic.", &CXI); 3063 Assert(CXI.getSuccessOrdering() != AtomicOrdering::Unordered, 3064 "cmpxchg instructions cannot be unordered.", &CXI); 3065 Assert(CXI.getFailureOrdering() != AtomicOrdering::Unordered, 3066 "cmpxchg instructions cannot be unordered.", &CXI); 3067 Assert(!isStrongerThan(CXI.getFailureOrdering(), CXI.getSuccessOrdering()), 3068 "cmpxchg instructions failure argument shall be no stronger than the " 3069 "success argument", 3070 &CXI); 3071 Assert(CXI.getFailureOrdering() != AtomicOrdering::Release && 3072 CXI.getFailureOrdering() != AtomicOrdering::AcquireRelease, 3073 "cmpxchg failure ordering cannot include release semantics", &CXI); 3074 3075 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType()); 3076 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI); 3077 Type *ElTy = PTy->getElementType(); 3078 Assert(ElTy->isIntegerTy() || ElTy->isPointerTy(), 3079 "cmpxchg operand must have integer or pointer type", 3080 ElTy, &CXI); 3081 checkAtomicMemAccessSize(M, ElTy, &CXI); 3082 Assert(ElTy == CXI.getOperand(1)->getType(), 3083 "Expected value type does not match pointer operand type!", &CXI, 3084 ElTy); 3085 Assert(ElTy == CXI.getOperand(2)->getType(), 3086 "Stored value type does not match pointer operand type!", &CXI, ElTy); 3087 visitInstruction(CXI); 3088 } 3089 3090 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 3091 Assert(RMWI.getOrdering() != AtomicOrdering::NotAtomic, 3092 "atomicrmw instructions must be atomic.", &RMWI); 3093 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered, 3094 "atomicrmw instructions cannot be unordered.", &RMWI); 3095 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType()); 3096 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI); 3097 Type *ElTy = PTy->getElementType(); 3098 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!", 3099 &RMWI, ElTy); 3100 checkAtomicMemAccessSize(M, ElTy, &RMWI); 3101 Assert(ElTy == RMWI.getOperand(1)->getType(), 3102 "Argument value type does not match pointer operand type!", &RMWI, 3103 ElTy); 3104 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() && 3105 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP, 3106 "Invalid binary operation!", &RMWI); 3107 visitInstruction(RMWI); 3108 } 3109 3110 void Verifier::visitFenceInst(FenceInst &FI) { 3111 const AtomicOrdering Ordering = FI.getOrdering(); 3112 Assert(Ordering == AtomicOrdering::Acquire || 3113 Ordering == AtomicOrdering::Release || 3114 Ordering == AtomicOrdering::AcquireRelease || 3115 Ordering == AtomicOrdering::SequentiallyConsistent, 3116 "fence instructions may only have acquire, release, acq_rel, or " 3117 "seq_cst ordering.", 3118 &FI); 3119 visitInstruction(FI); 3120 } 3121 3122 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 3123 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 3124 EVI.getIndices()) == EVI.getType(), 3125 "Invalid ExtractValueInst operands!", &EVI); 3126 3127 visitInstruction(EVI); 3128 } 3129 3130 void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 3131 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 3132 IVI.getIndices()) == 3133 IVI.getOperand(1)->getType(), 3134 "Invalid InsertValueInst operands!", &IVI); 3135 3136 visitInstruction(IVI); 3137 } 3138 3139 static Value *getParentPad(Value *EHPad) { 3140 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 3141 return FPI->getParentPad(); 3142 3143 return cast<CatchSwitchInst>(EHPad)->getParentPad(); 3144 } 3145 3146 void Verifier::visitEHPadPredecessors(Instruction &I) { 3147 assert(I.isEHPad()); 3148 3149 BasicBlock *BB = I.getParent(); 3150 Function *F = BB->getParent(); 3151 3152 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I); 3153 3154 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) { 3155 // The landingpad instruction defines its parent as a landing pad block. The 3156 // landing pad block may be branched to only by the unwind edge of an 3157 // invoke. 3158 for (BasicBlock *PredBB : predecessors(BB)) { 3159 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator()); 3160 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 3161 "Block containing LandingPadInst must be jumped to " 3162 "only by the unwind edge of an invoke.", 3163 LPI); 3164 } 3165 return; 3166 } 3167 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) { 3168 if (!pred_empty(BB)) 3169 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(), 3170 "Block containg CatchPadInst must be jumped to " 3171 "only by its catchswitch.", 3172 CPI); 3173 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(), 3174 "Catchswitch cannot unwind to one of its catchpads", 3175 CPI->getCatchSwitch(), CPI); 3176 return; 3177 } 3178 3179 // Verify that each pred has a legal terminator with a legal to/from EH 3180 // pad relationship. 3181 Instruction *ToPad = &I; 3182 Value *ToPadParent = getParentPad(ToPad); 3183 for (BasicBlock *PredBB : predecessors(BB)) { 3184 TerminatorInst *TI = PredBB->getTerminator(); 3185 Value *FromPad; 3186 if (auto *II = dyn_cast<InvokeInst>(TI)) { 3187 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB, 3188 "EH pad must be jumped to via an unwind edge", ToPad, II); 3189 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet)) 3190 FromPad = Bundle->Inputs[0]; 3191 else 3192 FromPad = ConstantTokenNone::get(II->getContext()); 3193 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 3194 FromPad = CRI->getOperand(0); 3195 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI); 3196 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 3197 FromPad = CSI; 3198 } else { 3199 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI); 3200 } 3201 3202 // The edge may exit from zero or more nested pads. 3203 SmallSet<Value *, 8> Seen; 3204 for (;; FromPad = getParentPad(FromPad)) { 3205 Assert(FromPad != ToPad, 3206 "EH pad cannot handle exceptions raised within it", FromPad, TI); 3207 if (FromPad == ToPadParent) { 3208 // This is a legal unwind edge. 3209 break; 3210 } 3211 Assert(!isa<ConstantTokenNone>(FromPad), 3212 "A single unwind edge may only enter one EH pad", TI); 3213 Assert(Seen.insert(FromPad).second, 3214 "EH pad jumps through a cycle of pads", FromPad); 3215 } 3216 } 3217 } 3218 3219 void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 3220 // The landingpad instruction is ill-formed if it doesn't have any clauses and 3221 // isn't a cleanup. 3222 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(), 3223 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 3224 3225 visitEHPadPredecessors(LPI); 3226 3227 if (!LandingPadResultTy) 3228 LandingPadResultTy = LPI.getType(); 3229 else 3230 Assert(LandingPadResultTy == LPI.getType(), 3231 "The landingpad instruction should have a consistent result type " 3232 "inside a function.", 3233 &LPI); 3234 3235 Function *F = LPI.getParent()->getParent(); 3236 Assert(F->hasPersonalityFn(), 3237 "LandingPadInst needs to be in a function with a personality.", &LPI); 3238 3239 // The landingpad instruction must be the first non-PHI instruction in the 3240 // block. 3241 Assert(LPI.getParent()->getLandingPadInst() == &LPI, 3242 "LandingPadInst not the first non-PHI instruction in the block.", 3243 &LPI); 3244 3245 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 3246 Constant *Clause = LPI.getClause(i); 3247 if (LPI.isCatch(i)) { 3248 Assert(isa<PointerType>(Clause->getType()), 3249 "Catch operand does not have pointer type!", &LPI); 3250 } else { 3251 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 3252 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 3253 "Filter operand is not an array of constants!", &LPI); 3254 } 3255 } 3256 3257 visitInstruction(LPI); 3258 } 3259 3260 void Verifier::visitCatchPadInst(CatchPadInst &CPI) { 3261 BasicBlock *BB = CPI.getParent(); 3262 3263 Function *F = BB->getParent(); 3264 Assert(F->hasPersonalityFn(), 3265 "CatchPadInst needs to be in a function with a personality.", &CPI); 3266 3267 Assert(isa<CatchSwitchInst>(CPI.getParentPad()), 3268 "CatchPadInst needs to be directly nested in a CatchSwitchInst.", 3269 CPI.getParentPad()); 3270 3271 // The catchpad instruction must be the first non-PHI instruction in the 3272 // block. 3273 Assert(BB->getFirstNonPHI() == &CPI, 3274 "CatchPadInst not the first non-PHI instruction in the block.", &CPI); 3275 3276 visitEHPadPredecessors(CPI); 3277 visitFuncletPadInst(CPI); 3278 } 3279 3280 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) { 3281 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)), 3282 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn, 3283 CatchReturn.getOperand(0)); 3284 3285 visitTerminatorInst(CatchReturn); 3286 } 3287 3288 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) { 3289 BasicBlock *BB = CPI.getParent(); 3290 3291 Function *F = BB->getParent(); 3292 Assert(F->hasPersonalityFn(), 3293 "CleanupPadInst needs to be in a function with a personality.", &CPI); 3294 3295 // The cleanuppad instruction must be the first non-PHI instruction in the 3296 // block. 3297 Assert(BB->getFirstNonPHI() == &CPI, 3298 "CleanupPadInst not the first non-PHI instruction in the block.", 3299 &CPI); 3300 3301 auto *ParentPad = CPI.getParentPad(); 3302 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3303 "CleanupPadInst has an invalid parent.", &CPI); 3304 3305 visitEHPadPredecessors(CPI); 3306 visitFuncletPadInst(CPI); 3307 } 3308 3309 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) { 3310 User *FirstUser = nullptr; 3311 Value *FirstUnwindPad = nullptr; 3312 SmallVector<FuncletPadInst *, 8> Worklist({&FPI}); 3313 SmallSet<FuncletPadInst *, 8> Seen; 3314 3315 while (!Worklist.empty()) { 3316 FuncletPadInst *CurrentPad = Worklist.pop_back_val(); 3317 Assert(Seen.insert(CurrentPad).second, 3318 "FuncletPadInst must not be nested within itself", CurrentPad); 3319 Value *UnresolvedAncestorPad = nullptr; 3320 for (User *U : CurrentPad->users()) { 3321 BasicBlock *UnwindDest; 3322 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) { 3323 UnwindDest = CRI->getUnwindDest(); 3324 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) { 3325 // We allow catchswitch unwind to caller to nest 3326 // within an outer pad that unwinds somewhere else, 3327 // because catchswitch doesn't have a nounwind variant. 3328 // See e.g. SimplifyCFGOpt::SimplifyUnreachable. 3329 if (CSI->unwindsToCaller()) 3330 continue; 3331 UnwindDest = CSI->getUnwindDest(); 3332 } else if (auto *II = dyn_cast<InvokeInst>(U)) { 3333 UnwindDest = II->getUnwindDest(); 3334 } else if (isa<CallInst>(U)) { 3335 // Calls which don't unwind may be found inside funclet 3336 // pads that unwind somewhere else. We don't *require* 3337 // such calls to be annotated nounwind. 3338 continue; 3339 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) { 3340 // The unwind dest for a cleanup can only be found by 3341 // recursive search. Add it to the worklist, and we'll 3342 // search for its first use that determines where it unwinds. 3343 Worklist.push_back(CPI); 3344 continue; 3345 } else { 3346 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U); 3347 continue; 3348 } 3349 3350 Value *UnwindPad; 3351 bool ExitsFPI; 3352 if (UnwindDest) { 3353 UnwindPad = UnwindDest->getFirstNonPHI(); 3354 if (!cast<Instruction>(UnwindPad)->isEHPad()) 3355 continue; 3356 Value *UnwindParent = getParentPad(UnwindPad); 3357 // Ignore unwind edges that don't exit CurrentPad. 3358 if (UnwindParent == CurrentPad) 3359 continue; 3360 // Determine whether the original funclet pad is exited, 3361 // and if we are scanning nested pads determine how many 3362 // of them are exited so we can stop searching their 3363 // children. 3364 Value *ExitedPad = CurrentPad; 3365 ExitsFPI = false; 3366 do { 3367 if (ExitedPad == &FPI) { 3368 ExitsFPI = true; 3369 // Now we can resolve any ancestors of CurrentPad up to 3370 // FPI, but not including FPI since we need to make sure 3371 // to check all direct users of FPI for consistency. 3372 UnresolvedAncestorPad = &FPI; 3373 break; 3374 } 3375 Value *ExitedParent = getParentPad(ExitedPad); 3376 if (ExitedParent == UnwindParent) { 3377 // ExitedPad is the ancestor-most pad which this unwind 3378 // edge exits, so we can resolve up to it, meaning that 3379 // ExitedParent is the first ancestor still unresolved. 3380 UnresolvedAncestorPad = ExitedParent; 3381 break; 3382 } 3383 ExitedPad = ExitedParent; 3384 } while (!isa<ConstantTokenNone>(ExitedPad)); 3385 } else { 3386 // Unwinding to caller exits all pads. 3387 UnwindPad = ConstantTokenNone::get(FPI.getContext()); 3388 ExitsFPI = true; 3389 UnresolvedAncestorPad = &FPI; 3390 } 3391 3392 if (ExitsFPI) { 3393 // This unwind edge exits FPI. Make sure it agrees with other 3394 // such edges. 3395 if (FirstUser) { 3396 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet " 3397 "pad must have the same unwind " 3398 "dest", 3399 &FPI, U, FirstUser); 3400 } else { 3401 FirstUser = U; 3402 FirstUnwindPad = UnwindPad; 3403 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds 3404 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) && 3405 getParentPad(UnwindPad) == getParentPad(&FPI)) 3406 SiblingFuncletInfo[&FPI] = cast<TerminatorInst>(U); 3407 } 3408 } 3409 // Make sure we visit all uses of FPI, but for nested pads stop as 3410 // soon as we know where they unwind to. 3411 if (CurrentPad != &FPI) 3412 break; 3413 } 3414 if (UnresolvedAncestorPad) { 3415 if (CurrentPad == UnresolvedAncestorPad) { 3416 // When CurrentPad is FPI itself, we don't mark it as resolved even if 3417 // we've found an unwind edge that exits it, because we need to verify 3418 // all direct uses of FPI. 3419 assert(CurrentPad == &FPI); 3420 continue; 3421 } 3422 // Pop off the worklist any nested pads that we've found an unwind 3423 // destination for. The pads on the worklist are the uncles, 3424 // great-uncles, etc. of CurrentPad. We've found an unwind destination 3425 // for all ancestors of CurrentPad up to but not including 3426 // UnresolvedAncestorPad. 3427 Value *ResolvedPad = CurrentPad; 3428 while (!Worklist.empty()) { 3429 Value *UnclePad = Worklist.back(); 3430 Value *AncestorPad = getParentPad(UnclePad); 3431 // Walk ResolvedPad up the ancestor list until we either find the 3432 // uncle's parent or the last resolved ancestor. 3433 while (ResolvedPad != AncestorPad) { 3434 Value *ResolvedParent = getParentPad(ResolvedPad); 3435 if (ResolvedParent == UnresolvedAncestorPad) { 3436 break; 3437 } 3438 ResolvedPad = ResolvedParent; 3439 } 3440 // If the resolved ancestor search didn't find the uncle's parent, 3441 // then the uncle is not yet resolved. 3442 if (ResolvedPad != AncestorPad) 3443 break; 3444 // This uncle is resolved, so pop it from the worklist. 3445 Worklist.pop_back(); 3446 } 3447 } 3448 } 3449 3450 if (FirstUnwindPad) { 3451 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) { 3452 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest(); 3453 Value *SwitchUnwindPad; 3454 if (SwitchUnwindDest) 3455 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI(); 3456 else 3457 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext()); 3458 Assert(SwitchUnwindPad == FirstUnwindPad, 3459 "Unwind edges out of a catch must have the same unwind dest as " 3460 "the parent catchswitch", 3461 &FPI, FirstUser, CatchSwitch); 3462 } 3463 } 3464 3465 visitInstruction(FPI); 3466 } 3467 3468 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) { 3469 BasicBlock *BB = CatchSwitch.getParent(); 3470 3471 Function *F = BB->getParent(); 3472 Assert(F->hasPersonalityFn(), 3473 "CatchSwitchInst needs to be in a function with a personality.", 3474 &CatchSwitch); 3475 3476 // The catchswitch instruction must be the first non-PHI instruction in the 3477 // block. 3478 Assert(BB->getFirstNonPHI() == &CatchSwitch, 3479 "CatchSwitchInst not the first non-PHI instruction in the block.", 3480 &CatchSwitch); 3481 3482 auto *ParentPad = CatchSwitch.getParentPad(); 3483 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 3484 "CatchSwitchInst has an invalid parent.", ParentPad); 3485 3486 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) { 3487 Instruction *I = UnwindDest->getFirstNonPHI(); 3488 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 3489 "CatchSwitchInst must unwind to an EH block which is not a " 3490 "landingpad.", 3491 &CatchSwitch); 3492 3493 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds 3494 if (getParentPad(I) == ParentPad) 3495 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch; 3496 } 3497 3498 Assert(CatchSwitch.getNumHandlers() != 0, 3499 "CatchSwitchInst cannot have empty handler list", &CatchSwitch); 3500 3501 for (BasicBlock *Handler : CatchSwitch.handlers()) { 3502 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()), 3503 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler); 3504 } 3505 3506 visitEHPadPredecessors(CatchSwitch); 3507 visitTerminatorInst(CatchSwitch); 3508 } 3509 3510 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) { 3511 Assert(isa<CleanupPadInst>(CRI.getOperand(0)), 3512 "CleanupReturnInst needs to be provided a CleanupPad", &CRI, 3513 CRI.getOperand(0)); 3514 3515 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) { 3516 Instruction *I = UnwindDest->getFirstNonPHI(); 3517 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 3518 "CleanupReturnInst must unwind to an EH block which is not a " 3519 "landingpad.", 3520 &CRI); 3521 } 3522 3523 visitTerminatorInst(CRI); 3524 } 3525 3526 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 3527 Instruction *Op = cast<Instruction>(I.getOperand(i)); 3528 // If the we have an invalid invoke, don't try to compute the dominance. 3529 // We already reject it in the invoke specific checks and the dominance 3530 // computation doesn't handle multiple edges. 3531 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 3532 if (II->getNormalDest() == II->getUnwindDest()) 3533 return; 3534 } 3535 3536 // Quick check whether the def has already been encountered in the same block. 3537 // PHI nodes are not checked to prevent accepting preceeding PHIs, because PHI 3538 // uses are defined to happen on the incoming edge, not at the instruction. 3539 // 3540 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata) 3541 // wrapping an SSA value, assert that we've already encountered it. See 3542 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp. 3543 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op)) 3544 return; 3545 3546 const Use &U = I.getOperandUse(i); 3547 Assert(DT.dominates(Op, U), 3548 "Instruction does not dominate all uses!", Op, &I); 3549 } 3550 3551 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) { 3552 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null " 3553 "apply only to pointer types", &I); 3554 Assert(isa<LoadInst>(I), 3555 "dereferenceable, dereferenceable_or_null apply only to load" 3556 " instructions, use attributes for calls or invokes", &I); 3557 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null " 3558 "take one operand!", &I); 3559 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 3560 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, " 3561 "dereferenceable_or_null metadata value must be an i64!", &I); 3562 } 3563 3564 /// verifyInstruction - Verify that an instruction is well formed. 3565 /// 3566 void Verifier::visitInstruction(Instruction &I) { 3567 BasicBlock *BB = I.getParent(); 3568 Assert(BB, "Instruction not embedded in basic block!", &I); 3569 3570 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 3571 for (User *U : I.users()) { 3572 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB), 3573 "Only PHI nodes may reference their own value!", &I); 3574 } 3575 } 3576 3577 // Check that void typed values don't have names 3578 Assert(!I.getType()->isVoidTy() || !I.hasName(), 3579 "Instruction has a name, but provides a void value!", &I); 3580 3581 // Check that the return value of the instruction is either void or a legal 3582 // value type. 3583 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(), 3584 "Instruction returns a non-scalar type!", &I); 3585 3586 // Check that the instruction doesn't produce metadata. Calls are already 3587 // checked against the callee type. 3588 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I), 3589 "Invalid use of metadata!", &I); 3590 3591 // Check that all uses of the instruction, if they are instructions 3592 // themselves, actually have parent basic blocks. If the use is not an 3593 // instruction, it is an error! 3594 for (Use &U : I.uses()) { 3595 if (Instruction *Used = dyn_cast<Instruction>(U.getUser())) 3596 Assert(Used->getParent() != nullptr, 3597 "Instruction referencing" 3598 " instruction not embedded in a basic block!", 3599 &I, Used); 3600 else { 3601 CheckFailed("Use of instruction is not an instruction!", U); 3602 return; 3603 } 3604 } 3605 3606 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 3607 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I); 3608 3609 // Check to make sure that only first-class-values are operands to 3610 // instructions. 3611 if (!I.getOperand(i)->getType()->isFirstClassType()) { 3612 Assert(0, "Instruction operands must be first-class values!", &I); 3613 } 3614 3615 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 3616 // Check to make sure that the "address of" an intrinsic function is never 3617 // taken. 3618 Assert( 3619 !F->isIntrinsic() || 3620 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0), 3621 "Cannot take the address of an intrinsic!", &I); 3622 Assert( 3623 !F->isIntrinsic() || isa<CallInst>(I) || 3624 F->getIntrinsicID() == Intrinsic::donothing || 3625 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void || 3626 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 || 3627 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint, 3628 "Cannot invoke an intrinsic other than donothing, patchpoint or " 3629 "statepoint", 3630 &I); 3631 Assert(F->getParent() == M, "Referencing function in another module!", 3632 &I, M, F, F->getParent()); 3633 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 3634 Assert(OpBB->getParent() == BB->getParent(), 3635 "Referring to a basic block in another function!", &I); 3636 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 3637 Assert(OpArg->getParent() == BB->getParent(), 3638 "Referring to an argument in another function!", &I); 3639 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 3640 Assert(GV->getParent() == M, "Referencing global in another module!", &I, M, GV, GV->getParent()); 3641 } else if (isa<Instruction>(I.getOperand(i))) { 3642 verifyDominatesUse(I, i); 3643 } else if (isa<InlineAsm>(I.getOperand(i))) { 3644 Assert((i + 1 == e && isa<CallInst>(I)) || 3645 (i + 3 == e && isa<InvokeInst>(I)), 3646 "Cannot take the address of an inline asm!", &I); 3647 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 3648 if (CE->getType()->isPtrOrPtrVectorTy()) { 3649 // If we have a ConstantExpr pointer, we need to see if it came from an 3650 // illegal bitcast (inttoptr <constant int> ) 3651 visitConstantExprsRecursively(CE); 3652 } 3653 } 3654 } 3655 3656 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 3657 Assert(I.getType()->isFPOrFPVectorTy(), 3658 "fpmath requires a floating point result!", &I); 3659 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 3660 if (ConstantFP *CFP0 = 3661 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) { 3662 const APFloat &Accuracy = CFP0->getValueAPF(); 3663 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 3664 "fpmath accuracy not a positive number!", &I); 3665 } else { 3666 Assert(false, "invalid fpmath accuracy!", &I); 3667 } 3668 } 3669 3670 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) { 3671 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I), 3672 "Ranges are only for loads, calls and invokes!", &I); 3673 visitRangeMetadata(I, Range, I.getType()); 3674 } 3675 3676 if (I.getMetadata(LLVMContext::MD_nonnull)) { 3677 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types", 3678 &I); 3679 Assert(isa<LoadInst>(I), 3680 "nonnull applies only to load instructions, use attributes" 3681 " for calls or invokes", 3682 &I); 3683 } 3684 3685 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable)) 3686 visitDereferenceableMetadata(I, MD); 3687 3688 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null)) 3689 visitDereferenceableMetadata(I, MD); 3690 3691 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) { 3692 Assert(I.getType()->isPointerTy(), "align applies only to pointer types", 3693 &I); 3694 Assert(isa<LoadInst>(I), "align applies only to load instructions, " 3695 "use attributes for calls or invokes", &I); 3696 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I); 3697 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0)); 3698 Assert(CI && CI->getType()->isIntegerTy(64), 3699 "align metadata value must be an i64!", &I); 3700 uint64_t Align = CI->getZExtValue(); 3701 Assert(isPowerOf2_64(Align), 3702 "align metadata value must be a power of 2!", &I); 3703 Assert(Align <= Value::MaximumAlignment, 3704 "alignment is larger that implementation defined limit", &I); 3705 } 3706 3707 if (MDNode *N = I.getDebugLoc().getAsMDNode()) { 3708 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N); 3709 visitMDNode(*N); 3710 } 3711 3712 if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) 3713 verifyBitPieceExpression(*DII); 3714 3715 InstsInThisBlock.insert(&I); 3716 } 3717 3718 /// Verify that the specified type (which comes from an intrinsic argument or 3719 /// return value) matches the type constraints specified by the .td file (e.g. 3720 /// an "any integer" argument really is an integer). 3721 /// 3722 /// This returns true on error but does not print a message. 3723 bool Verifier::verifyIntrinsicType(Type *Ty, 3724 ArrayRef<Intrinsic::IITDescriptor> &Infos, 3725 SmallVectorImpl<Type*> &ArgTys) { 3726 using namespace Intrinsic; 3727 3728 // If we ran out of descriptors, there are too many arguments. 3729 if (Infos.empty()) return true; 3730 IITDescriptor D = Infos.front(); 3731 Infos = Infos.slice(1); 3732 3733 switch (D.Kind) { 3734 case IITDescriptor::Void: return !Ty->isVoidTy(); 3735 case IITDescriptor::VarArg: return true; 3736 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 3737 case IITDescriptor::Token: return !Ty->isTokenTy(); 3738 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 3739 case IITDescriptor::Half: return !Ty->isHalfTy(); 3740 case IITDescriptor::Float: return !Ty->isFloatTy(); 3741 case IITDescriptor::Double: return !Ty->isDoubleTy(); 3742 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 3743 case IITDescriptor::Vector: { 3744 VectorType *VT = dyn_cast<VectorType>(Ty); 3745 return !VT || VT->getNumElements() != D.Vector_Width || 3746 verifyIntrinsicType(VT->getElementType(), Infos, ArgTys); 3747 } 3748 case IITDescriptor::Pointer: { 3749 PointerType *PT = dyn_cast<PointerType>(Ty); 3750 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 3751 verifyIntrinsicType(PT->getElementType(), Infos, ArgTys); 3752 } 3753 3754 case IITDescriptor::Struct: { 3755 StructType *ST = dyn_cast<StructType>(Ty); 3756 if (!ST || ST->getNumElements() != D.Struct_NumElements) 3757 return true; 3758 3759 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 3760 if (verifyIntrinsicType(ST->getElementType(i), Infos, ArgTys)) 3761 return true; 3762 return false; 3763 } 3764 3765 case IITDescriptor::Argument: 3766 // Two cases here - If this is the second occurrence of an argument, verify 3767 // that the later instance matches the previous instance. 3768 if (D.getArgumentNumber() < ArgTys.size()) 3769 return Ty != ArgTys[D.getArgumentNumber()]; 3770 3771 // Otherwise, if this is the first instance of an argument, record it and 3772 // verify the "Any" kind. 3773 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error"); 3774 ArgTys.push_back(Ty); 3775 3776 switch (D.getArgumentKind()) { 3777 case IITDescriptor::AK_Any: return false; // Success 3778 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 3779 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 3780 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 3781 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 3782 } 3783 llvm_unreachable("all argument kinds not covered"); 3784 3785 case IITDescriptor::ExtendArgument: { 3786 // This may only be used when referring to a previous vector argument. 3787 if (D.getArgumentNumber() >= ArgTys.size()) 3788 return true; 3789 3790 Type *NewTy = ArgTys[D.getArgumentNumber()]; 3791 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 3792 NewTy = VectorType::getExtendedElementVectorType(VTy); 3793 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 3794 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 3795 else 3796 return true; 3797 3798 return Ty != NewTy; 3799 } 3800 case IITDescriptor::TruncArgument: { 3801 // This may only be used when referring to a previous vector argument. 3802 if (D.getArgumentNumber() >= ArgTys.size()) 3803 return true; 3804 3805 Type *NewTy = ArgTys[D.getArgumentNumber()]; 3806 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 3807 NewTy = VectorType::getTruncatedElementVectorType(VTy); 3808 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 3809 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 3810 else 3811 return true; 3812 3813 return Ty != NewTy; 3814 } 3815 case IITDescriptor::HalfVecArgument: 3816 // This may only be used when referring to a previous vector argument. 3817 return D.getArgumentNumber() >= ArgTys.size() || 3818 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 3819 VectorType::getHalfElementsVectorType( 3820 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 3821 case IITDescriptor::SameVecWidthArgument: { 3822 if (D.getArgumentNumber() >= ArgTys.size()) 3823 return true; 3824 VectorType * ReferenceType = 3825 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 3826 VectorType *ThisArgType = dyn_cast<VectorType>(Ty); 3827 if (!ThisArgType || !ReferenceType || 3828 (ReferenceType->getVectorNumElements() != 3829 ThisArgType->getVectorNumElements())) 3830 return true; 3831 return verifyIntrinsicType(ThisArgType->getVectorElementType(), 3832 Infos, ArgTys); 3833 } 3834 case IITDescriptor::PtrToArgument: { 3835 if (D.getArgumentNumber() >= ArgTys.size()) 3836 return true; 3837 Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 3838 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 3839 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 3840 } 3841 case IITDescriptor::VecOfPtrsToElt: { 3842 if (D.getArgumentNumber() >= ArgTys.size()) 3843 return true; 3844 VectorType * ReferenceType = 3845 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 3846 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty); 3847 if (!ThisArgVecTy || !ReferenceType || 3848 (ReferenceType->getVectorNumElements() != 3849 ThisArgVecTy->getVectorNumElements())) 3850 return true; 3851 PointerType *ThisArgEltTy = 3852 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType()); 3853 if (!ThisArgEltTy) 3854 return true; 3855 return ThisArgEltTy->getElementType() != 3856 ReferenceType->getVectorElementType(); 3857 } 3858 } 3859 llvm_unreachable("unhandled"); 3860 } 3861 3862 /// Verify if the intrinsic has variable arguments. This method is intended to 3863 /// be called after all the fixed arguments have been verified first. 3864 /// 3865 /// This method returns true on error and does not print an error message. 3866 bool 3867 Verifier::verifyIntrinsicIsVarArg(bool isVarArg, 3868 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 3869 using namespace Intrinsic; 3870 3871 // If there are no descriptors left, then it can't be a vararg. 3872 if (Infos.empty()) 3873 return isVarArg; 3874 3875 // There should be only one descriptor remaining at this point. 3876 if (Infos.size() != 1) 3877 return true; 3878 3879 // Check and verify the descriptor. 3880 IITDescriptor D = Infos.front(); 3881 Infos = Infos.slice(1); 3882 if (D.Kind == IITDescriptor::VarArg) 3883 return !isVarArg; 3884 3885 return true; 3886 } 3887 3888 /// Allow intrinsics to be verified in different ways. 3889 void Verifier::visitIntrinsicCallSite(Intrinsic::ID ID, CallSite CS) { 3890 Function *IF = CS.getCalledFunction(); 3891 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!", 3892 IF); 3893 3894 // Verify that the intrinsic prototype lines up with what the .td files 3895 // describe. 3896 FunctionType *IFTy = IF->getFunctionType(); 3897 bool IsVarArg = IFTy->isVarArg(); 3898 3899 SmallVector<Intrinsic::IITDescriptor, 8> Table; 3900 getIntrinsicInfoTableEntries(ID, Table); 3901 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 3902 3903 SmallVector<Type *, 4> ArgTys; 3904 Assert(!verifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys), 3905 "Intrinsic has incorrect return type!", IF); 3906 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i) 3907 Assert(!verifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys), 3908 "Intrinsic has incorrect argument type!", IF); 3909 3910 // Verify if the intrinsic call matches the vararg property. 3911 if (IsVarArg) 3912 Assert(!verifyIntrinsicIsVarArg(IsVarArg, TableRef), 3913 "Intrinsic was not defined with variable arguments!", IF); 3914 else 3915 Assert(!verifyIntrinsicIsVarArg(IsVarArg, TableRef), 3916 "Callsite was not defined with variable arguments!", IF); 3917 3918 // All descriptors should be absorbed by now. 3919 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF); 3920 3921 // Now that we have the intrinsic ID and the actual argument types (and we 3922 // know they are legal for the intrinsic!) get the intrinsic name through the 3923 // usual means. This allows us to verify the mangling of argument types into 3924 // the name. 3925 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys); 3926 Assert(ExpectedName == IF->getName(), 3927 "Intrinsic name not mangled correctly for type arguments! " 3928 "Should be: " + 3929 ExpectedName, 3930 IF); 3931 3932 // If the intrinsic takes MDNode arguments, verify that they are either global 3933 // or are local to *this* function. 3934 for (Value *V : CS.args()) 3935 if (auto *MD = dyn_cast<MetadataAsValue>(V)) 3936 visitMetadataAsValue(*MD, CS.getCaller()); 3937 3938 switch (ID) { 3939 default: 3940 break; 3941 case Intrinsic::ctlz: // llvm.ctlz 3942 case Intrinsic::cttz: // llvm.cttz 3943 Assert(isa<ConstantInt>(CS.getArgOperand(1)), 3944 "is_zero_undef argument of bit counting intrinsics must be a " 3945 "constant int", 3946 CS); 3947 break; 3948 case Intrinsic::dbg_declare: // llvm.dbg.declare 3949 Assert(isa<MetadataAsValue>(CS.getArgOperand(0)), 3950 "invalid llvm.dbg.declare intrinsic call 1", CS); 3951 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(*CS.getInstruction())); 3952 break; 3953 case Intrinsic::dbg_value: // llvm.dbg.value 3954 visitDbgIntrinsic("value", cast<DbgValueInst>(*CS.getInstruction())); 3955 break; 3956 case Intrinsic::memcpy: 3957 case Intrinsic::memmove: 3958 case Intrinsic::memset: { 3959 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CS.getArgOperand(3)); 3960 Assert(AlignCI, 3961 "alignment argument of memory intrinsics must be a constant int", 3962 CS); 3963 const APInt &AlignVal = AlignCI->getValue(); 3964 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(), 3965 "alignment argument of memory intrinsics must be a power of 2", CS); 3966 Assert(isa<ConstantInt>(CS.getArgOperand(4)), 3967 "isvolatile argument of memory intrinsics must be a constant int", 3968 CS); 3969 break; 3970 } 3971 case Intrinsic::gcroot: 3972 case Intrinsic::gcwrite: 3973 case Intrinsic::gcread: 3974 if (ID == Intrinsic::gcroot) { 3975 AllocaInst *AI = 3976 dyn_cast<AllocaInst>(CS.getArgOperand(0)->stripPointerCasts()); 3977 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", CS); 3978 Assert(isa<Constant>(CS.getArgOperand(1)), 3979 "llvm.gcroot parameter #2 must be a constant.", CS); 3980 if (!AI->getAllocatedType()->isPointerTy()) { 3981 Assert(!isa<ConstantPointerNull>(CS.getArgOperand(1)), 3982 "llvm.gcroot parameter #1 must either be a pointer alloca, " 3983 "or argument #2 must be a non-null constant.", 3984 CS); 3985 } 3986 } 3987 3988 Assert(CS.getParent()->getParent()->hasGC(), 3989 "Enclosing function does not use GC.", CS); 3990 break; 3991 case Intrinsic::init_trampoline: 3992 Assert(isa<Function>(CS.getArgOperand(1)->stripPointerCasts()), 3993 "llvm.init_trampoline parameter #2 must resolve to a function.", 3994 CS); 3995 break; 3996 case Intrinsic::prefetch: 3997 Assert(isa<ConstantInt>(CS.getArgOperand(1)) && 3998 isa<ConstantInt>(CS.getArgOperand(2)) && 3999 cast<ConstantInt>(CS.getArgOperand(1))->getZExtValue() < 2 && 4000 cast<ConstantInt>(CS.getArgOperand(2))->getZExtValue() < 4, 4001 "invalid arguments to llvm.prefetch", CS); 4002 break; 4003 case Intrinsic::stackprotector: 4004 Assert(isa<AllocaInst>(CS.getArgOperand(1)->stripPointerCasts()), 4005 "llvm.stackprotector parameter #2 must resolve to an alloca.", CS); 4006 break; 4007 case Intrinsic::lifetime_start: 4008 case Intrinsic::lifetime_end: 4009 case Intrinsic::invariant_start: 4010 Assert(isa<ConstantInt>(CS.getArgOperand(0)), 4011 "size argument of memory use markers must be a constant integer", 4012 CS); 4013 break; 4014 case Intrinsic::invariant_end: 4015 Assert(isa<ConstantInt>(CS.getArgOperand(1)), 4016 "llvm.invariant.end parameter #2 must be a constant integer", CS); 4017 break; 4018 4019 case Intrinsic::localescape: { 4020 BasicBlock *BB = CS.getParent(); 4021 Assert(BB == &BB->getParent()->front(), 4022 "llvm.localescape used outside of entry block", CS); 4023 Assert(!SawFrameEscape, 4024 "multiple calls to llvm.localescape in one function", CS); 4025 for (Value *Arg : CS.args()) { 4026 if (isa<ConstantPointerNull>(Arg)) 4027 continue; // Null values are allowed as placeholders. 4028 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts()); 4029 Assert(AI && AI->isStaticAlloca(), 4030 "llvm.localescape only accepts static allocas", CS); 4031 } 4032 FrameEscapeInfo[BB->getParent()].first = CS.getNumArgOperands(); 4033 SawFrameEscape = true; 4034 break; 4035 } 4036 case Intrinsic::localrecover: { 4037 Value *FnArg = CS.getArgOperand(0)->stripPointerCasts(); 4038 Function *Fn = dyn_cast<Function>(FnArg); 4039 Assert(Fn && !Fn->isDeclaration(), 4040 "llvm.localrecover first " 4041 "argument must be function defined in this module", 4042 CS); 4043 auto *IdxArg = dyn_cast<ConstantInt>(CS.getArgOperand(2)); 4044 Assert(IdxArg, "idx argument of llvm.localrecover must be a constant int", 4045 CS); 4046 auto &Entry = FrameEscapeInfo[Fn]; 4047 Entry.second = unsigned( 4048 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1)); 4049 break; 4050 } 4051 4052 case Intrinsic::experimental_gc_statepoint: 4053 Assert(!CS.isInlineAsm(), 4054 "gc.statepoint support for inline assembly unimplemented", CS); 4055 Assert(CS.getParent()->getParent()->hasGC(), 4056 "Enclosing function does not use GC.", CS); 4057 4058 verifyStatepoint(CS); 4059 break; 4060 case Intrinsic::experimental_gc_result: { 4061 Assert(CS.getParent()->getParent()->hasGC(), 4062 "Enclosing function does not use GC.", CS); 4063 // Are we tied to a statepoint properly? 4064 CallSite StatepointCS(CS.getArgOperand(0)); 4065 const Function *StatepointFn = 4066 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr; 4067 Assert(StatepointFn && StatepointFn->isDeclaration() && 4068 StatepointFn->getIntrinsicID() == 4069 Intrinsic::experimental_gc_statepoint, 4070 "gc.result operand #1 must be from a statepoint", CS, 4071 CS.getArgOperand(0)); 4072 4073 // Assert that result type matches wrapped callee. 4074 const Value *Target = StatepointCS.getArgument(2); 4075 auto *PT = cast<PointerType>(Target->getType()); 4076 auto *TargetFuncType = cast<FunctionType>(PT->getElementType()); 4077 Assert(CS.getType() == TargetFuncType->getReturnType(), 4078 "gc.result result type does not match wrapped callee", CS); 4079 break; 4080 } 4081 case Intrinsic::experimental_gc_relocate: { 4082 Assert(CS.getNumArgOperands() == 3, "wrong number of arguments", CS); 4083 4084 Assert(isa<PointerType>(CS.getType()->getScalarType()), 4085 "gc.relocate must return a pointer or a vector of pointers", CS); 4086 4087 // Check that this relocate is correctly tied to the statepoint 4088 4089 // This is case for relocate on the unwinding path of an invoke statepoint 4090 if (LandingPadInst *LandingPad = 4091 dyn_cast<LandingPadInst>(CS.getArgOperand(0))) { 4092 4093 const BasicBlock *InvokeBB = 4094 LandingPad->getParent()->getUniquePredecessor(); 4095 4096 // Landingpad relocates should have only one predecessor with invoke 4097 // statepoint terminator 4098 Assert(InvokeBB, "safepoints should have unique landingpads", 4099 LandingPad->getParent()); 4100 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed", 4101 InvokeBB); 4102 Assert(isStatepoint(InvokeBB->getTerminator()), 4103 "gc relocate should be linked to a statepoint", InvokeBB); 4104 } 4105 else { 4106 // In all other cases relocate should be tied to the statepoint directly. 4107 // This covers relocates on a normal return path of invoke statepoint and 4108 // relocates of a call statepoint. 4109 auto Token = CS.getArgOperand(0); 4110 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)), 4111 "gc relocate is incorrectly tied to the statepoint", CS, Token); 4112 } 4113 4114 // Verify rest of the relocate arguments. 4115 4116 ImmutableCallSite StatepointCS( 4117 cast<GCRelocateInst>(*CS.getInstruction()).getStatepoint()); 4118 4119 // Both the base and derived must be piped through the safepoint. 4120 Value* Base = CS.getArgOperand(1); 4121 Assert(isa<ConstantInt>(Base), 4122 "gc.relocate operand #2 must be integer offset", CS); 4123 4124 Value* Derived = CS.getArgOperand(2); 4125 Assert(isa<ConstantInt>(Derived), 4126 "gc.relocate operand #3 must be integer offset", CS); 4127 4128 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue(); 4129 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue(); 4130 // Check the bounds 4131 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(), 4132 "gc.relocate: statepoint base index out of bounds", CS); 4133 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(), 4134 "gc.relocate: statepoint derived index out of bounds", CS); 4135 4136 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters' 4137 // section of the statepoint's argument. 4138 Assert(StatepointCS.arg_size() > 0, 4139 "gc.statepoint: insufficient arguments"); 4140 Assert(isa<ConstantInt>(StatepointCS.getArgument(3)), 4141 "gc.statement: number of call arguments must be constant integer"); 4142 const unsigned NumCallArgs = 4143 cast<ConstantInt>(StatepointCS.getArgument(3))->getZExtValue(); 4144 Assert(StatepointCS.arg_size() > NumCallArgs + 5, 4145 "gc.statepoint: mismatch in number of call arguments"); 4146 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)), 4147 "gc.statepoint: number of transition arguments must be " 4148 "a constant integer"); 4149 const int NumTransitionArgs = 4150 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 5)) 4151 ->getZExtValue(); 4152 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1; 4153 Assert(isa<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)), 4154 "gc.statepoint: number of deoptimization arguments must be " 4155 "a constant integer"); 4156 const int NumDeoptArgs = 4157 cast<ConstantInt>(StatepointCS.getArgument(DeoptArgsStart)) 4158 ->getZExtValue(); 4159 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs; 4160 const int GCParamArgsEnd = StatepointCS.arg_size(); 4161 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd, 4162 "gc.relocate: statepoint base index doesn't fall within the " 4163 "'gc parameters' section of the statepoint call", 4164 CS); 4165 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd, 4166 "gc.relocate: statepoint derived index doesn't fall within the " 4167 "'gc parameters' section of the statepoint call", 4168 CS); 4169 4170 // Relocated value must be either a pointer type or vector-of-pointer type, 4171 // but gc_relocate does not need to return the same pointer type as the 4172 // relocated pointer. It can be casted to the correct type later if it's 4173 // desired. However, they must have the same address space and 'vectorness' 4174 GCRelocateInst &Relocate = cast<GCRelocateInst>(*CS.getInstruction()); 4175 Assert(Relocate.getDerivedPtr()->getType()->getScalarType()->isPointerTy(), 4176 "gc.relocate: relocated value must be a gc pointer", CS); 4177 4178 auto ResultType = CS.getType(); 4179 auto DerivedType = Relocate.getDerivedPtr()->getType(); 4180 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(), 4181 "gc.relocate: vector relocates to vector and pointer to pointer", 4182 CS); 4183 Assert( 4184 ResultType->getPointerAddressSpace() == 4185 DerivedType->getPointerAddressSpace(), 4186 "gc.relocate: relocating a pointer shouldn't change its address space", 4187 CS); 4188 break; 4189 } 4190 case Intrinsic::eh_exceptioncode: 4191 case Intrinsic::eh_exceptionpointer: { 4192 Assert(isa<CatchPadInst>(CS.getArgOperand(0)), 4193 "eh.exceptionpointer argument must be a catchpad", CS); 4194 break; 4195 } 4196 case Intrinsic::masked_load: { 4197 Assert(CS.getType()->isVectorTy(), "masked_load: must return a vector", CS); 4198 4199 Value *Ptr = CS.getArgOperand(0); 4200 //Value *Alignment = CS.getArgOperand(1); 4201 Value *Mask = CS.getArgOperand(2); 4202 Value *PassThru = CS.getArgOperand(3); 4203 Assert(Mask->getType()->isVectorTy(), 4204 "masked_load: mask must be vector", CS); 4205 4206 // DataTy is the overloaded type 4207 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 4208 Assert(DataTy == CS.getType(), 4209 "masked_load: return must match pointer type", CS); 4210 Assert(PassThru->getType() == DataTy, 4211 "masked_load: pass through and data type must match", CS); 4212 Assert(Mask->getType()->getVectorNumElements() == 4213 DataTy->getVectorNumElements(), 4214 "masked_load: vector mask must be same length as data", CS); 4215 break; 4216 } 4217 case Intrinsic::masked_store: { 4218 Value *Val = CS.getArgOperand(0); 4219 Value *Ptr = CS.getArgOperand(1); 4220 //Value *Alignment = CS.getArgOperand(2); 4221 Value *Mask = CS.getArgOperand(3); 4222 Assert(Mask->getType()->isVectorTy(), 4223 "masked_store: mask must be vector", CS); 4224 4225 // DataTy is the overloaded type 4226 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType(); 4227 Assert(DataTy == Val->getType(), 4228 "masked_store: storee must match pointer type", CS); 4229 Assert(Mask->getType()->getVectorNumElements() == 4230 DataTy->getVectorNumElements(), 4231 "masked_store: vector mask must be same length as data", CS); 4232 break; 4233 } 4234 4235 case Intrinsic::experimental_guard: { 4236 Assert(CS.isCall(), "experimental_guard cannot be invoked", CS); 4237 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 4238 "experimental_guard must have exactly one " 4239 "\"deopt\" operand bundle"); 4240 break; 4241 } 4242 4243 case Intrinsic::experimental_deoptimize: { 4244 Assert(CS.isCall(), "experimental_deoptimize cannot be invoked", CS); 4245 Assert(CS.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 4246 "experimental_deoptimize must have exactly one " 4247 "\"deopt\" operand bundle"); 4248 Assert(CS.getType() == CS.getInstruction()->getFunction()->getReturnType(), 4249 "experimental_deoptimize return type must match caller return type"); 4250 4251 if (CS.isCall()) { 4252 auto *DeoptCI = CS.getInstruction(); 4253 auto *RI = dyn_cast<ReturnInst>(DeoptCI->getNextNode()); 4254 Assert(RI, 4255 "calls to experimental_deoptimize must be followed by a return"); 4256 4257 if (!CS.getType()->isVoidTy() && RI) 4258 Assert(RI->getReturnValue() == DeoptCI, 4259 "calls to experimental_deoptimize must be followed by a return " 4260 "of the value computed by experimental_deoptimize"); 4261 } 4262 4263 break; 4264 } 4265 }; 4266 } 4267 4268 /// \brief Carefully grab the subprogram from a local scope. 4269 /// 4270 /// This carefully grabs the subprogram from a local scope, avoiding the 4271 /// built-in assertions that would typically fire. 4272 static DISubprogram *getSubprogram(Metadata *LocalScope) { 4273 if (!LocalScope) 4274 return nullptr; 4275 4276 if (auto *SP = dyn_cast<DISubprogram>(LocalScope)) 4277 return SP; 4278 4279 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope)) 4280 return getSubprogram(LB->getRawScope()); 4281 4282 // Just return null; broken scope chains are checked elsewhere. 4283 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope"); 4284 return nullptr; 4285 } 4286 4287 template <class DbgIntrinsicTy> 4288 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) { 4289 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata(); 4290 AssertDI(isa<ValueAsMetadata>(MD) || 4291 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()), 4292 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD); 4293 AssertDI(isa<DILocalVariable>(DII.getRawVariable()), 4294 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII, 4295 DII.getRawVariable()); 4296 AssertDI(isa<DIExpression>(DII.getRawExpression()), 4297 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII, 4298 DII.getRawExpression()); 4299 4300 // Ignore broken !dbg attachments; they're checked elsewhere. 4301 if (MDNode *N = DII.getDebugLoc().getAsMDNode()) 4302 if (!isa<DILocation>(N)) 4303 return; 4304 4305 BasicBlock *BB = DII.getParent(); 4306 Function *F = BB ? BB->getParent() : nullptr; 4307 4308 // The scopes for variables and !dbg attachments must agree. 4309 DILocalVariable *Var = DII.getVariable(); 4310 DILocation *Loc = DII.getDebugLoc(); 4311 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 4312 &DII, BB, F); 4313 4314 DISubprogram *VarSP = getSubprogram(Var->getRawScope()); 4315 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 4316 if (!VarSP || !LocSP) 4317 return; // Broken scope chains are checked elsewhere. 4318 4319 Assert(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 4320 " variable and !dbg attachment", 4321 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc, 4322 Loc->getScope()->getSubprogram()); 4323 } 4324 4325 static uint64_t getVariableSize(const DILocalVariable &V) { 4326 // Be careful of broken types (checked elsewhere). 4327 const Metadata *RawType = V.getRawType(); 4328 while (RawType) { 4329 // Try to get the size directly. 4330 if (auto *T = dyn_cast<DIType>(RawType)) 4331 if (uint64_t Size = T->getSizeInBits()) 4332 return Size; 4333 4334 if (auto *DT = dyn_cast<DIDerivedType>(RawType)) { 4335 // Look at the base type. 4336 RawType = DT->getRawBaseType(); 4337 continue; 4338 } 4339 4340 // Missing type or size. 4341 break; 4342 } 4343 4344 // Fail gracefully. 4345 return 0; 4346 } 4347 4348 void Verifier::verifyBitPieceExpression(const DbgInfoIntrinsic &I) { 4349 DILocalVariable *V; 4350 DIExpression *E; 4351 if (auto *DVI = dyn_cast<DbgValueInst>(&I)) { 4352 V = dyn_cast_or_null<DILocalVariable>(DVI->getRawVariable()); 4353 E = dyn_cast_or_null<DIExpression>(DVI->getRawExpression()); 4354 } else { 4355 auto *DDI = cast<DbgDeclareInst>(&I); 4356 V = dyn_cast_or_null<DILocalVariable>(DDI->getRawVariable()); 4357 E = dyn_cast_or_null<DIExpression>(DDI->getRawExpression()); 4358 } 4359 4360 // We don't know whether this intrinsic verified correctly. 4361 if (!V || !E || !E->isValid()) 4362 return; 4363 4364 // Nothing to do if this isn't a bit piece expression. 4365 if (!E->isBitPiece()) 4366 return; 4367 4368 // The frontend helps out GDB by emitting the members of local anonymous 4369 // unions as artificial local variables with shared storage. When SROA splits 4370 // the storage for artificial local variables that are smaller than the entire 4371 // union, the overhang piece will be outside of the allotted space for the 4372 // variable and this check fails. 4373 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs. 4374 if (V->isArtificial()) 4375 return; 4376 4377 // If there's no size, the type is broken, but that should be checked 4378 // elsewhere. 4379 uint64_t VarSize = getVariableSize(*V); 4380 if (!VarSize) 4381 return; 4382 4383 unsigned PieceSize = E->getBitPieceSize(); 4384 unsigned PieceOffset = E->getBitPieceOffset(); 4385 Assert(PieceSize + PieceOffset <= VarSize, 4386 "piece is larger than or outside of variable", &I, V, E); 4387 Assert(PieceSize != VarSize, "piece covers entire variable", &I, V, E); 4388 } 4389 4390 void Verifier::verifyCompileUnits() { 4391 auto *CUs = M->getNamedMetadata("llvm.dbg.cu"); 4392 SmallPtrSet<const Metadata *, 2> Listed; 4393 if (CUs) 4394 Listed.insert(CUs->op_begin(), CUs->op_end()); 4395 Assert( 4396 std::all_of(CUVisited.begin(), CUVisited.end(), 4397 [&Listed](const Metadata *CU) { return Listed.count(CU); }), 4398 "All DICompileUnits must be listed in llvm.dbg.cu"); 4399 CUVisited.clear(); 4400 } 4401 4402 void Verifier::verifyDeoptimizeCallingConvs() { 4403 if (DeoptimizeDeclarations.empty()) 4404 return; 4405 4406 const Function *First = DeoptimizeDeclarations[0]; 4407 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) { 4408 Assert(First->getCallingConv() == F->getCallingConv(), 4409 "All llvm.experimental.deoptimize declarations must have the same " 4410 "calling convention", 4411 First, F); 4412 } 4413 } 4414 4415 //===----------------------------------------------------------------------===// 4416 // Implement the public interfaces to this file... 4417 //===----------------------------------------------------------------------===// 4418 4419 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) { 4420 Function &F = const_cast<Function &>(f); 4421 4422 // Don't use a raw_null_ostream. Printing IR is expensive. 4423 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true); 4424 4425 // Note that this function's return value is inverted from what you would 4426 // expect of a function called "verify". 4427 return !V.verify(F); 4428 } 4429 4430 bool llvm::verifyModule(const Module &M, raw_ostream *OS, 4431 bool *BrokenDebugInfo) { 4432 // Don't use a raw_null_ostream. Printing IR is expensive. 4433 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo); 4434 4435 bool Broken = false; 4436 for (const Function &F : M) 4437 Broken |= !V.verify(F); 4438 4439 Broken |= !V.verify(M); 4440 if (BrokenDebugInfo) 4441 *BrokenDebugInfo = V.hasBrokenDebugInfo(); 4442 // Note that this function's return value is inverted from what you would 4443 // expect of a function called "verify". 4444 return Broken; 4445 } 4446 4447 namespace { 4448 struct VerifierLegacyPass : public FunctionPass { 4449 static char ID; 4450 4451 Verifier V; 4452 bool FatalErrors = true; 4453 4454 VerifierLegacyPass() 4455 : FunctionPass(ID), 4456 V(&dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false) { 4457 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 4458 } 4459 explicit VerifierLegacyPass(bool FatalErrors) 4460 : FunctionPass(ID), 4461 V(&dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false), 4462 FatalErrors(FatalErrors) { 4463 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 4464 } 4465 4466 bool runOnFunction(Function &F) override { 4467 if (!V.verify(F) && FatalErrors) 4468 report_fatal_error("Broken function found, compilation aborted!"); 4469 4470 return false; 4471 } 4472 4473 bool doFinalization(Module &M) override { 4474 bool HasErrors = false; 4475 for (Function &F : M) 4476 if (F.isDeclaration()) 4477 HasErrors |= !V.verify(F); 4478 4479 HasErrors |= !V.verify(M); 4480 if (FatalErrors) { 4481 if (HasErrors) 4482 report_fatal_error("Broken module found, compilation aborted!"); 4483 assert(!V.hasBrokenDebugInfo() && "Module contains invalid debug info"); 4484 } 4485 4486 // Strip broken debug info. 4487 if (V.hasBrokenDebugInfo()) { 4488 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M); 4489 M.getContext().diagnose(DiagInvalid); 4490 if (!StripDebugInfo(M)) 4491 report_fatal_error("Failed to strip malformed debug info"); 4492 } 4493 return false; 4494 } 4495 4496 void getAnalysisUsage(AnalysisUsage &AU) const override { 4497 AU.setPreservesAll(); 4498 } 4499 }; 4500 } 4501 4502 char VerifierLegacyPass::ID = 0; 4503 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false) 4504 4505 FunctionPass *llvm::createVerifierPass(bool FatalErrors) { 4506 return new VerifierLegacyPass(FatalErrors); 4507 } 4508 4509 char VerifierAnalysis::PassID; 4510 VerifierAnalysis::Result VerifierAnalysis::run(Module &M) { 4511 Result Res; 4512 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken); 4513 return Res; 4514 } 4515 4516 VerifierAnalysis::Result VerifierAnalysis::run(Function &F) { 4517 return { llvm::verifyFunction(F, &dbgs()), false }; 4518 } 4519 4520 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) { 4521 auto Res = AM.getResult<VerifierAnalysis>(M); 4522 if (FatalErrors) { 4523 if (Res.IRBroken) 4524 report_fatal_error("Broken module found, compilation aborted!"); 4525 assert(!Res.DebugInfoBroken && "Module contains invalid debug info"); 4526 } 4527 4528 // Strip broken debug info. 4529 if (Res.DebugInfoBroken) { 4530 DiagnosticInfoIgnoringInvalidDebugMetadata DiagInvalid(M); 4531 M.getContext().diagnose(DiagInvalid); 4532 if (!StripDebugInfo(M)) 4533 report_fatal_error("Failed to strip malformed debug info"); 4534 } 4535 return PreservedAnalyses::all(); 4536 } 4537 4538 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 4539 auto res = AM.getResult<VerifierAnalysis>(F); 4540 if (res.IRBroken && FatalErrors) 4541 report_fatal_error("Broken function found, compilation aborted!"); 4542 4543 return PreservedAnalyses::all(); 4544 } 4545