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