1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the function verifier interface, that can be used for some 10 // sanity checking of input to the system. 11 // 12 // Note that this does not provide full `Java style' security and verifications, 13 // instead it just tries to ensure that code is well-formed. 14 // 15 // * Both of a binary operator's parameters are of the same type 16 // * Verify that the indices of mem access instructions match other operands 17 // * Verify that arithmetic and other things are only performed on first-class 18 // types. Verify that shifts & logicals only happen on integrals f.e. 19 // * All of the constants in a switch statement are of the correct type 20 // * The code is in valid SSA form 21 // * It should be illegal to put a label into any other type (like a structure) 22 // or to return one. [except constant arrays!] 23 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad 24 // * PHI nodes must have an entry for each predecessor, with no extras. 25 // * PHI nodes must be the first thing in a basic block, all grouped together 26 // * PHI nodes must have at least one entry 27 // * All basic blocks should only end with terminator insts, not contain them 28 // * The entry node to a function must not have predecessors 29 // * All Instructions must be embedded into a basic block 30 // * Functions cannot take a void-typed parameter 31 // * Verify that a function's argument list agrees with it's declared type. 32 // * It is illegal to specify a name for a void value. 33 // * It is illegal to have a internal global value with no initializer 34 // * It is illegal to have a ret instruction that returns a value that does not 35 // agree with the function return value type. 36 // * Function call argument types match the function prototype 37 // * A landing pad is defined by a landingpad instruction, and can be jumped to 38 // only by the unwind edge of an invoke instruction. 39 // * A landingpad instruction must be the first non-PHI instruction in the 40 // block. 41 // * Landingpad instructions must be in a function with a personality function. 42 // * All other things that are tested by asserts spread about the code... 43 // 44 //===----------------------------------------------------------------------===// 45 46 #include "llvm/IR/Verifier.h" 47 #include "llvm/ADT/APFloat.h" 48 #include "llvm/ADT/APInt.h" 49 #include "llvm/ADT/ArrayRef.h" 50 #include "llvm/ADT/DenseMap.h" 51 #include "llvm/ADT/MapVector.h" 52 #include "llvm/ADT/Optional.h" 53 #include "llvm/ADT/STLExtras.h" 54 #include "llvm/ADT/SmallPtrSet.h" 55 #include "llvm/ADT/SmallSet.h" 56 #include "llvm/ADT/SmallVector.h" 57 #include "llvm/ADT/StringExtras.h" 58 #include "llvm/ADT/StringMap.h" 59 #include "llvm/ADT/StringRef.h" 60 #include "llvm/ADT/Twine.h" 61 #include "llvm/ADT/ilist.h" 62 #include "llvm/BinaryFormat/Dwarf.h" 63 #include "llvm/IR/Argument.h" 64 #include "llvm/IR/Attributes.h" 65 #include "llvm/IR/BasicBlock.h" 66 #include "llvm/IR/CFG.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/Dominators.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GlobalAlias.h" 80 #include "llvm/IR/GlobalValue.h" 81 #include "llvm/IR/GlobalVariable.h" 82 #include "llvm/IR/InlineAsm.h" 83 #include "llvm/IR/InstVisitor.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/IntrinsicInst.h" 88 #include "llvm/IR/Intrinsics.h" 89 #include "llvm/IR/IntrinsicsWebAssembly.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/InitializePasses.h" 101 #include "llvm/Pass.h" 102 #include "llvm/Support/AtomicOrdering.h" 103 #include "llvm/Support/Casting.h" 104 #include "llvm/Support/CommandLine.h" 105 #include "llvm/Support/Debug.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> VerifyNoAliasScopeDomination( 119 "verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), 120 cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " 121 "scopes are not dominating")); 122 123 namespace llvm { 124 125 struct VerifierSupport { 126 raw_ostream *OS; 127 const Module &M; 128 ModuleSlotTracker MST; 129 Triple TT; 130 const DataLayout &DL; 131 LLVMContext &Context; 132 133 /// Track the brokenness of the module while recursively visiting. 134 bool Broken = false; 135 /// Broken debug info can be "recovered" from by stripping the debug info. 136 bool BrokenDebugInfo = false; 137 /// Whether to treat broken debug info as an error. 138 bool TreatBrokenDebugInfoAsError = true; 139 140 explicit VerifierSupport(raw_ostream *OS, const Module &M) 141 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()), 142 Context(M.getContext()) {} 143 144 private: 145 void Write(const Module *M) { 146 *OS << "; ModuleID = '" << M->getModuleIdentifier() << "'\n"; 147 } 148 149 void Write(const Value *V) { 150 if (V) 151 Write(*V); 152 } 153 154 void Write(const Value &V) { 155 if (isa<Instruction>(V)) { 156 V.print(*OS, MST); 157 *OS << '\n'; 158 } else { 159 V.printAsOperand(*OS, true, MST); 160 *OS << '\n'; 161 } 162 } 163 164 void Write(const Metadata *MD) { 165 if (!MD) 166 return; 167 MD->print(*OS, MST, &M); 168 *OS << '\n'; 169 } 170 171 template <class T> void Write(const MDTupleTypedArrayWrapper<T> &MD) { 172 Write(MD.get()); 173 } 174 175 void Write(const NamedMDNode *NMD) { 176 if (!NMD) 177 return; 178 NMD->print(*OS, MST); 179 *OS << '\n'; 180 } 181 182 void Write(Type *T) { 183 if (!T) 184 return; 185 *OS << ' ' << *T; 186 } 187 188 void Write(const Comdat *C) { 189 if (!C) 190 return; 191 *OS << *C; 192 } 193 194 void Write(const APInt *AI) { 195 if (!AI) 196 return; 197 *OS << *AI << '\n'; 198 } 199 200 void Write(const unsigned i) { *OS << i << '\n'; } 201 202 // NOLINTNEXTLINE(readability-identifier-naming) 203 void Write(const Attribute *A) { 204 if (!A) 205 return; 206 *OS << A->getAsString() << '\n'; 207 } 208 209 // NOLINTNEXTLINE(readability-identifier-naming) 210 void Write(const AttributeSet *AS) { 211 if (!AS) 212 return; 213 *OS << AS->getAsString() << '\n'; 214 } 215 216 // NOLINTNEXTLINE(readability-identifier-naming) 217 void Write(const AttributeList *AL) { 218 if (!AL) 219 return; 220 AL->print(*OS); 221 } 222 223 template <typename T> void Write(ArrayRef<T> Vs) { 224 for (const T &V : Vs) 225 Write(V); 226 } 227 228 template <typename T1, typename... Ts> 229 void WriteTs(const T1 &V1, const Ts &... Vs) { 230 Write(V1); 231 WriteTs(Vs...); 232 } 233 234 template <typename... Ts> void WriteTs() {} 235 236 public: 237 /// A check failed, so printout out the condition and the message. 238 /// 239 /// This provides a nice place to put a breakpoint if you want to see why 240 /// something is not correct. 241 void CheckFailed(const Twine &Message) { 242 if (OS) 243 *OS << Message << '\n'; 244 Broken = true; 245 } 246 247 /// A check failed (with values to print). 248 /// 249 /// This calls the Message-only version so that the above is easier to set a 250 /// breakpoint on. 251 template <typename T1, typename... Ts> 252 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) { 253 CheckFailed(Message); 254 if (OS) 255 WriteTs(V1, Vs...); 256 } 257 258 /// A debug info check failed. 259 void DebugInfoCheckFailed(const Twine &Message) { 260 if (OS) 261 *OS << Message << '\n'; 262 Broken |= TreatBrokenDebugInfoAsError; 263 BrokenDebugInfo = true; 264 } 265 266 /// A debug info check failed (with values to print). 267 template <typename T1, typename... Ts> 268 void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, 269 const Ts &... Vs) { 270 DebugInfoCheckFailed(Message); 271 if (OS) 272 WriteTs(V1, Vs...); 273 } 274 }; 275 276 } // namespace llvm 277 278 namespace { 279 280 class Verifier : public InstVisitor<Verifier>, VerifierSupport { 281 friend class InstVisitor<Verifier>; 282 283 DominatorTree DT; 284 285 /// When verifying a basic block, keep track of all of the 286 /// instructions we have seen so far. 287 /// 288 /// This allows us to do efficient dominance checks for the case when an 289 /// instruction has an operand that is an instruction in the same block. 290 SmallPtrSet<Instruction *, 16> InstsInThisBlock; 291 292 /// Keep track of the metadata nodes that have been checked already. 293 SmallPtrSet<const Metadata *, 32> MDNodes; 294 295 /// Keep track which DISubprogram is attached to which function. 296 DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments; 297 298 /// Track all DICompileUnits visited. 299 SmallPtrSet<const Metadata *, 2> CUVisited; 300 301 /// The result type for a landingpad. 302 Type *LandingPadResultTy; 303 304 /// Whether we've seen a call to @llvm.localescape in this function 305 /// already. 306 bool SawFrameEscape; 307 308 /// Whether the current function has a DISubprogram attached to it. 309 bool HasDebugInfo = false; 310 311 /// The current source language. 312 dwarf::SourceLanguage CurrentSourceLang = dwarf::DW_LANG_lo_user; 313 314 /// Whether source was present on the first DIFile encountered in each CU. 315 DenseMap<const DICompileUnit *, bool> HasSourceDebugInfo; 316 317 /// Stores the count of how many objects were passed to llvm.localescape for a 318 /// given function and the largest index passed to llvm.localrecover. 319 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo; 320 321 // Maps catchswitches and cleanuppads that unwind to siblings to the 322 // terminators that indicate the unwind, used to detect cycles therein. 323 MapVector<Instruction *, Instruction *> SiblingFuncletInfo; 324 325 /// Cache of constants visited in search of ConstantExprs. 326 SmallPtrSet<const Constant *, 32> ConstantExprVisited; 327 328 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic. 329 SmallVector<const Function *, 4> DeoptimizeDeclarations; 330 331 /// Cache of attribute lists verified. 332 SmallPtrSet<const void *, 32> AttributeListsVisited; 333 334 // Verify that this GlobalValue is only used in this module. 335 // This map is used to avoid visiting uses twice. We can arrive at a user 336 // twice, if they have multiple operands. In particular for very large 337 // constant expressions, we can arrive at a particular user many times. 338 SmallPtrSet<const Value *, 32> GlobalValueVisited; 339 340 // Keeps track of duplicate function argument debug info. 341 SmallVector<const DILocalVariable *, 16> DebugFnArgs; 342 343 TBAAVerifier TBAAVerifyHelper; 344 345 SmallVector<IntrinsicInst *, 4> NoAliasScopeDecls; 346 347 void checkAtomicMemAccessSize(Type *Ty, const Instruction *I); 348 349 public: 350 explicit Verifier(raw_ostream *OS, bool ShouldTreatBrokenDebugInfoAsError, 351 const Module &M) 352 : VerifierSupport(OS, M), LandingPadResultTy(nullptr), 353 SawFrameEscape(false), TBAAVerifyHelper(this) { 354 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError; 355 } 356 357 bool hasBrokenDebugInfo() const { return BrokenDebugInfo; } 358 359 bool verify(const Function &F) { 360 assert(F.getParent() == &M && 361 "An instance of this class only works with a specific module!"); 362 363 // First ensure the function is well-enough formed to compute dominance 364 // information, and directly compute a dominance tree. We don't rely on the 365 // pass manager to provide this as it isolates us from a potentially 366 // out-of-date dominator tree and makes it significantly more complex to run 367 // this code outside of a pass manager. 368 // FIXME: It's really gross that we have to cast away constness here. 369 if (!F.empty()) 370 DT.recalculate(const_cast<Function &>(F)); 371 372 for (const BasicBlock &BB : F) { 373 if (!BB.empty() && BB.back().isTerminator()) 374 continue; 375 376 if (OS) { 377 *OS << "Basic Block in function '" << F.getName() 378 << "' does not have terminator!\n"; 379 BB.printAsOperand(*OS, true, MST); 380 *OS << "\n"; 381 } 382 return false; 383 } 384 385 Broken = false; 386 // FIXME: We strip const here because the inst visitor strips const. 387 visit(const_cast<Function &>(F)); 388 verifySiblingFuncletUnwinds(); 389 InstsInThisBlock.clear(); 390 DebugFnArgs.clear(); 391 LandingPadResultTy = nullptr; 392 SawFrameEscape = false; 393 SiblingFuncletInfo.clear(); 394 verifyNoAliasScopeDecl(); 395 NoAliasScopeDecls.clear(); 396 397 return !Broken; 398 } 399 400 /// Verify the module that this instance of \c Verifier was initialized with. 401 bool verify() { 402 Broken = false; 403 404 // Collect all declarations of the llvm.experimental.deoptimize intrinsic. 405 for (const Function &F : M) 406 if (F.getIntrinsicID() == Intrinsic::experimental_deoptimize) 407 DeoptimizeDeclarations.push_back(&F); 408 409 // Now that we've visited every function, verify that we never asked to 410 // recover a frame index that wasn't escaped. 411 verifyFrameRecoverIndices(); 412 for (const GlobalVariable &GV : M.globals()) 413 visitGlobalVariable(GV); 414 415 for (const GlobalAlias &GA : M.aliases()) 416 visitGlobalAlias(GA); 417 418 for (const NamedMDNode &NMD : M.named_metadata()) 419 visitNamedMDNode(NMD); 420 421 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable()) 422 visitComdat(SMEC.getValue()); 423 424 visitModuleFlags(M); 425 visitModuleIdents(M); 426 visitModuleCommandLines(M); 427 428 verifyCompileUnits(); 429 430 verifyDeoptimizeCallingConvs(); 431 DISubprogramAttachments.clear(); 432 return !Broken; 433 } 434 435 private: 436 /// Whether a metadata node is allowed to be, or contain, a DILocation. 437 enum class AreDebugLocsAllowed { No, Yes }; 438 439 // Verification methods... 440 void visitGlobalValue(const GlobalValue &GV); 441 void visitGlobalVariable(const GlobalVariable &GV); 442 void visitGlobalAlias(const GlobalAlias &GA); 443 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C); 444 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited, 445 const GlobalAlias &A, const Constant &C); 446 void visitNamedMDNode(const NamedMDNode &NMD); 447 void visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs); 448 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F); 449 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F); 450 void visitComdat(const Comdat &C); 451 void visitModuleIdents(const Module &M); 452 void visitModuleCommandLines(const Module &M); 453 void visitModuleFlags(const Module &M); 454 void visitModuleFlag(const MDNode *Op, 455 DenseMap<const MDString *, const MDNode *> &SeenIDs, 456 SmallVectorImpl<const MDNode *> &Requirements); 457 void visitModuleFlagCGProfileEntry(const MDOperand &MDO); 458 void visitFunction(const Function &F); 459 void visitBasicBlock(BasicBlock &BB); 460 void visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty); 461 void visitDereferenceableMetadata(Instruction &I, MDNode *MD); 462 void visitProfMetadata(Instruction &I, MDNode *MD); 463 void visitAnnotationMetadata(MDNode *Annotation); 464 465 template <class Ty> bool isValidMetadataArray(const MDTuple &N); 466 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N); 467 #include "llvm/IR/Metadata.def" 468 void visitDIScope(const DIScope &N); 469 void visitDIVariable(const DIVariable &N); 470 void visitDILexicalBlockBase(const DILexicalBlockBase &N); 471 void visitDITemplateParameter(const DITemplateParameter &N); 472 473 void visitTemplateParams(const MDNode &N, const Metadata &RawParams); 474 475 // InstVisitor overrides... 476 using InstVisitor<Verifier>::visit; 477 void visit(Instruction &I); 478 479 void visitTruncInst(TruncInst &I); 480 void visitZExtInst(ZExtInst &I); 481 void visitSExtInst(SExtInst &I); 482 void visitFPTruncInst(FPTruncInst &I); 483 void visitFPExtInst(FPExtInst &I); 484 void visitFPToUIInst(FPToUIInst &I); 485 void visitFPToSIInst(FPToSIInst &I); 486 void visitUIToFPInst(UIToFPInst &I); 487 void visitSIToFPInst(SIToFPInst &I); 488 void visitIntToPtrInst(IntToPtrInst &I); 489 void visitPtrToIntInst(PtrToIntInst &I); 490 void visitBitCastInst(BitCastInst &I); 491 void visitAddrSpaceCastInst(AddrSpaceCastInst &I); 492 void visitPHINode(PHINode &PN); 493 void visitCallBase(CallBase &Call); 494 void visitUnaryOperator(UnaryOperator &U); 495 void visitBinaryOperator(BinaryOperator &B); 496 void visitICmpInst(ICmpInst &IC); 497 void visitFCmpInst(FCmpInst &FC); 498 void visitExtractElementInst(ExtractElementInst &EI); 499 void visitInsertElementInst(InsertElementInst &EI); 500 void visitShuffleVectorInst(ShuffleVectorInst &EI); 501 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); } 502 void visitCallInst(CallInst &CI); 503 void visitInvokeInst(InvokeInst &II); 504 void visitGetElementPtrInst(GetElementPtrInst &GEP); 505 void visitLoadInst(LoadInst &LI); 506 void visitStoreInst(StoreInst &SI); 507 void verifyDominatesUse(Instruction &I, unsigned i); 508 void visitInstruction(Instruction &I); 509 void visitTerminator(Instruction &I); 510 void visitBranchInst(BranchInst &BI); 511 void visitReturnInst(ReturnInst &RI); 512 void visitSwitchInst(SwitchInst &SI); 513 void visitIndirectBrInst(IndirectBrInst &BI); 514 void visitCallBrInst(CallBrInst &CBI); 515 void visitSelectInst(SelectInst &SI); 516 void visitUserOp1(Instruction &I); 517 void visitUserOp2(Instruction &I) { visitUserOp1(I); } 518 void visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call); 519 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI); 520 void visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII); 521 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI); 522 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI); 523 void visitAtomicRMWInst(AtomicRMWInst &RMWI); 524 void visitFenceInst(FenceInst &FI); 525 void visitAllocaInst(AllocaInst &AI); 526 void visitExtractValueInst(ExtractValueInst &EVI); 527 void visitInsertValueInst(InsertValueInst &IVI); 528 void visitEHPadPredecessors(Instruction &I); 529 void visitLandingPadInst(LandingPadInst &LPI); 530 void visitResumeInst(ResumeInst &RI); 531 void visitCatchPadInst(CatchPadInst &CPI); 532 void visitCatchReturnInst(CatchReturnInst &CatchReturn); 533 void visitCleanupPadInst(CleanupPadInst &CPI); 534 void visitFuncletPadInst(FuncletPadInst &FPI); 535 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch); 536 void visitCleanupReturnInst(CleanupReturnInst &CRI); 537 538 void verifySwiftErrorCall(CallBase &Call, const Value *SwiftErrorVal); 539 void verifySwiftErrorValue(const Value *SwiftErrorVal); 540 void verifyTailCCMustTailAttrs(AttrBuilder Attrs, StringRef Context); 541 void verifyMustTailCall(CallInst &CI); 542 bool verifyAttributeCount(AttributeList Attrs, unsigned Params); 543 void verifyAttributeTypes(AttributeSet Attrs, bool IsFunction, 544 const Value *V); 545 void verifyParameterAttrs(AttributeSet Attrs, Type *Ty, const Value *V); 546 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr, 547 const Value *V); 548 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs, 549 const Value *V, bool IsIntrinsic); 550 void verifyFunctionMetadata(ArrayRef<std::pair<unsigned, MDNode *>> MDs); 551 552 void visitConstantExprsRecursively(const Constant *EntryC); 553 void visitConstantExpr(const ConstantExpr *CE); 554 void verifyStatepoint(const CallBase &Call); 555 void verifyFrameRecoverIndices(); 556 void verifySiblingFuncletUnwinds(); 557 558 void verifyFragmentExpression(const DbgVariableIntrinsic &I); 559 template <typename ValueOrMetadata> 560 void verifyFragmentExpression(const DIVariable &V, 561 DIExpression::FragmentInfo Fragment, 562 ValueOrMetadata *Desc); 563 void verifyFnArgs(const DbgVariableIntrinsic &I); 564 void verifyNotEntryValue(const DbgVariableIntrinsic &I); 565 566 /// Module-level debug info verification... 567 void verifyCompileUnits(); 568 569 /// Module-level verification that all @llvm.experimental.deoptimize 570 /// declarations share the same calling convention. 571 void verifyDeoptimizeCallingConvs(); 572 573 /// Verify all-or-nothing property of DIFile source attribute within a CU. 574 void verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F); 575 576 /// Verify the llvm.experimental.noalias.scope.decl declarations 577 void verifyNoAliasScopeDecl(); 578 }; 579 580 } // end anonymous namespace 581 582 /// We know that cond should be true, if not print an error message. 583 #define Assert(C, ...) \ 584 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false) 585 586 /// We know that a debug info condition should be true, if not print 587 /// an error message. 588 #define AssertDI(C, ...) \ 589 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false) 590 591 void Verifier::visit(Instruction &I) { 592 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 593 Assert(I.getOperand(i) != nullptr, "Operand is null", &I); 594 InstVisitor<Verifier>::visit(I); 595 } 596 597 // Helper to recursively iterate over indirect users. By 598 // returning false, the callback can ask to stop recursing 599 // further. 600 static void forEachUser(const Value *User, 601 SmallPtrSet<const Value *, 32> &Visited, 602 llvm::function_ref<bool(const Value *)> Callback) { 603 if (!Visited.insert(User).second) 604 return; 605 for (const Value *TheNextUser : User->materialized_users()) 606 if (Callback(TheNextUser)) 607 forEachUser(TheNextUser, Visited, Callback); 608 } 609 610 void Verifier::visitGlobalValue(const GlobalValue &GV) { 611 Assert(!GV.isDeclaration() || GV.hasValidDeclarationLinkage(), 612 "Global is external, but doesn't have external or weak linkage!", &GV); 613 614 if (const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) 615 Assert(GO->getAlignment() <= Value::MaximumAlignment, 616 "huge alignment values are unsupported", GO); 617 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV), 618 "Only global variables can have appending linkage!", &GV); 619 620 if (GV.hasAppendingLinkage()) { 621 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV); 622 Assert(GVar && GVar->getValueType()->isArrayTy(), 623 "Only global arrays can have appending linkage!", GVar); 624 } 625 626 if (GV.isDeclarationForLinker()) 627 Assert(!GV.hasComdat(), "Declaration may not be in a Comdat!", &GV); 628 629 if (GV.hasDLLImportStorageClass()) { 630 Assert(!GV.isDSOLocal(), 631 "GlobalValue with DLLImport Storage is dso_local!", &GV); 632 633 Assert((GV.isDeclaration() && 634 (GV.hasExternalLinkage() || GV.hasExternalWeakLinkage())) || 635 GV.hasAvailableExternallyLinkage(), 636 "Global is marked as dllimport, but not external", &GV); 637 } 638 639 if (GV.isImplicitDSOLocal()) 640 Assert(GV.isDSOLocal(), 641 "GlobalValue with local linkage or non-default " 642 "visibility must be dso_local!", 643 &GV); 644 645 forEachUser(&GV, GlobalValueVisited, [&](const Value *V) -> bool { 646 if (const Instruction *I = dyn_cast<Instruction>(V)) { 647 if (!I->getParent() || !I->getParent()->getParent()) 648 CheckFailed("Global is referenced by parentless instruction!", &GV, &M, 649 I); 650 else if (I->getParent()->getParent()->getParent() != &M) 651 CheckFailed("Global is referenced in a different module!", &GV, &M, I, 652 I->getParent()->getParent(), 653 I->getParent()->getParent()->getParent()); 654 return false; 655 } else if (const Function *F = dyn_cast<Function>(V)) { 656 if (F->getParent() != &M) 657 CheckFailed("Global is used by function in a different module", &GV, &M, 658 F, F->getParent()); 659 return false; 660 } 661 return true; 662 }); 663 } 664 665 void Verifier::visitGlobalVariable(const GlobalVariable &GV) { 666 if (GV.hasInitializer()) { 667 Assert(GV.getInitializer()->getType() == GV.getValueType(), 668 "Global variable initializer type does not match global " 669 "variable type!", 670 &GV); 671 // If the global has common linkage, it must have a zero initializer and 672 // cannot be constant. 673 if (GV.hasCommonLinkage()) { 674 Assert(GV.getInitializer()->isNullValue(), 675 "'common' global must have a zero initializer!", &GV); 676 Assert(!GV.isConstant(), "'common' global may not be marked constant!", 677 &GV); 678 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV); 679 } 680 } 681 682 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" || 683 GV.getName() == "llvm.global_dtors")) { 684 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 685 "invalid linkage for intrinsic global variable", &GV); 686 // Don't worry about emitting an error for it not being an array, 687 // visitGlobalValue will complain on appending non-array. 688 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getValueType())) { 689 StructType *STy = dyn_cast<StructType>(ATy->getElementType()); 690 PointerType *FuncPtrTy = 691 FunctionType::get(Type::getVoidTy(Context), false)-> 692 getPointerTo(DL.getProgramAddressSpace()); 693 Assert(STy && 694 (STy->getNumElements() == 2 || STy->getNumElements() == 3) && 695 STy->getTypeAtIndex(0u)->isIntegerTy(32) && 696 STy->getTypeAtIndex(1) == FuncPtrTy, 697 "wrong type for intrinsic global variable", &GV); 698 Assert(STy->getNumElements() == 3, 699 "the third field of the element type is mandatory, " 700 "specify i8* null to migrate from the obsoleted 2-field form"); 701 Type *ETy = STy->getTypeAtIndex(2); 702 Type *Int8Ty = Type::getInt8Ty(ETy->getContext()); 703 Assert(ETy->isPointerTy() && 704 cast<PointerType>(ETy)->isOpaqueOrPointeeTypeMatches(Int8Ty), 705 "wrong type for intrinsic global variable", &GV); 706 } 707 } 708 709 if (GV.hasName() && (GV.getName() == "llvm.used" || 710 GV.getName() == "llvm.compiler.used")) { 711 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(), 712 "invalid linkage for intrinsic global variable", &GV); 713 Type *GVType = GV.getValueType(); 714 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) { 715 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType()); 716 Assert(PTy, "wrong type for intrinsic global variable", &GV); 717 if (GV.hasInitializer()) { 718 const Constant *Init = GV.getInitializer(); 719 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init); 720 Assert(InitArray, "wrong initalizer for intrinsic global variable", 721 Init); 722 for (Value *Op : InitArray->operands()) { 723 Value *V = Op->stripPointerCasts(); 724 Assert(isa<GlobalVariable>(V) || isa<Function>(V) || 725 isa<GlobalAlias>(V), 726 "invalid llvm.used member", V); 727 Assert(V->hasName(), "members of llvm.used must be named", V); 728 } 729 } 730 } 731 } 732 733 // Visit any debug info attachments. 734 SmallVector<MDNode *, 1> MDs; 735 GV.getMetadata(LLVMContext::MD_dbg, MDs); 736 for (auto *MD : MDs) { 737 if (auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD)) 738 visitDIGlobalVariableExpression(*GVE); 739 else 740 AssertDI(false, "!dbg attachment of global variable must be a " 741 "DIGlobalVariableExpression"); 742 } 743 744 // Scalable vectors cannot be global variables, since we don't know 745 // the runtime size. If the global is an array containing scalable vectors, 746 // that will be caught by the isValidElementType methods in StructType or 747 // ArrayType instead. 748 Assert(!isa<ScalableVectorType>(GV.getValueType()), 749 "Globals cannot contain scalable vectors", &GV); 750 751 if (auto *STy = dyn_cast<StructType>(GV.getValueType())) 752 Assert(!STy->containsScalableVectorType(), 753 "Globals cannot contain scalable vectors", &GV); 754 755 if (!GV.hasInitializer()) { 756 visitGlobalValue(GV); 757 return; 758 } 759 760 // Walk any aggregate initializers looking for bitcasts between address spaces 761 visitConstantExprsRecursively(GV.getInitializer()); 762 763 visitGlobalValue(GV); 764 } 765 766 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) { 767 SmallPtrSet<const GlobalAlias*, 4> Visited; 768 Visited.insert(&GA); 769 visitAliaseeSubExpr(Visited, GA, C); 770 } 771 772 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited, 773 const GlobalAlias &GA, const Constant &C) { 774 if (const auto *GV = dyn_cast<GlobalValue>(&C)) { 775 Assert(!GV->isDeclarationForLinker(), "Alias must point to a definition", 776 &GA); 777 778 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) { 779 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA); 780 781 Assert(!GA2->isInterposable(), "Alias cannot point to an interposable alias", 782 &GA); 783 } else { 784 // Only continue verifying subexpressions of GlobalAliases. 785 // Do not recurse into global initializers. 786 return; 787 } 788 } 789 790 if (const auto *CE = dyn_cast<ConstantExpr>(&C)) 791 visitConstantExprsRecursively(CE); 792 793 for (const Use &U : C.operands()) { 794 Value *V = &*U; 795 if (const auto *GA2 = dyn_cast<GlobalAlias>(V)) 796 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee()); 797 else if (const auto *C2 = dyn_cast<Constant>(V)) 798 visitAliaseeSubExpr(Visited, GA, *C2); 799 } 800 } 801 802 void Verifier::visitGlobalAlias(const GlobalAlias &GA) { 803 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()), 804 "Alias should have private, internal, linkonce, weak, linkonce_odr, " 805 "weak_odr, or external linkage!", 806 &GA); 807 const Constant *Aliasee = GA.getAliasee(); 808 Assert(Aliasee, "Aliasee cannot be NULL!", &GA); 809 Assert(GA.getType() == Aliasee->getType(), 810 "Alias and aliasee types should match!", &GA); 811 812 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee), 813 "Aliasee should be either GlobalValue or ConstantExpr", &GA); 814 815 visitAliaseeSubExpr(GA, *Aliasee); 816 817 visitGlobalValue(GA); 818 } 819 820 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) { 821 // There used to be various other llvm.dbg.* nodes, but we don't support 822 // upgrading them and we want to reserve the namespace for future uses. 823 if (NMD.getName().startswith("llvm.dbg.")) 824 AssertDI(NMD.getName() == "llvm.dbg.cu", 825 "unrecognized named metadata node in the llvm.dbg namespace", 826 &NMD); 827 for (const MDNode *MD : NMD.operands()) { 828 if (NMD.getName() == "llvm.dbg.cu") 829 AssertDI(MD && isa<DICompileUnit>(MD), "invalid compile unit", &NMD, MD); 830 831 if (!MD) 832 continue; 833 834 visitMDNode(*MD, AreDebugLocsAllowed::Yes); 835 } 836 } 837 838 void Verifier::visitMDNode(const MDNode &MD, AreDebugLocsAllowed AllowLocs) { 839 // Only visit each node once. Metadata can be mutually recursive, so this 840 // avoids infinite recursion here, as well as being an optimization. 841 if (!MDNodes.insert(&MD).second) 842 return; 843 844 Assert(&MD.getContext() == &Context, 845 "MDNode context does not match Module context!", &MD); 846 847 switch (MD.getMetadataID()) { 848 default: 849 llvm_unreachable("Invalid MDNode subclass"); 850 case Metadata::MDTupleKind: 851 break; 852 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 853 case Metadata::CLASS##Kind: \ 854 visit##CLASS(cast<CLASS>(MD)); \ 855 break; 856 #include "llvm/IR/Metadata.def" 857 } 858 859 for (const Metadata *Op : MD.operands()) { 860 if (!Op) 861 continue; 862 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!", 863 &MD, Op); 864 AssertDI(!isa<DILocation>(Op) || AllowLocs == AreDebugLocsAllowed::Yes, 865 "DILocation not allowed within this metadata node", &MD, Op); 866 if (auto *N = dyn_cast<MDNode>(Op)) { 867 visitMDNode(*N, AllowLocs); 868 continue; 869 } 870 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) { 871 visitValueAsMetadata(*V, nullptr); 872 continue; 873 } 874 } 875 876 // Check these last, so we diagnose problems in operands first. 877 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD); 878 Assert(MD.isResolved(), "All nodes should be resolved!", &MD); 879 } 880 881 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) { 882 Assert(MD.getValue(), "Expected valid value", &MD); 883 Assert(!MD.getValue()->getType()->isMetadataTy(), 884 "Unexpected metadata round-trip through values", &MD, MD.getValue()); 885 886 auto *L = dyn_cast<LocalAsMetadata>(&MD); 887 if (!L) 888 return; 889 890 Assert(F, "function-local metadata used outside a function", L); 891 892 // If this was an instruction, bb, or argument, verify that it is in the 893 // function that we expect. 894 Function *ActualF = nullptr; 895 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) { 896 Assert(I->getParent(), "function-local metadata not in basic block", L, I); 897 ActualF = I->getParent()->getParent(); 898 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue())) 899 ActualF = BB->getParent(); 900 else if (Argument *A = dyn_cast<Argument>(L->getValue())) 901 ActualF = A->getParent(); 902 assert(ActualF && "Unimplemented function local metadata case!"); 903 904 Assert(ActualF == F, "function-local metadata used in wrong function", L); 905 } 906 907 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) { 908 Metadata *MD = MDV.getMetadata(); 909 if (auto *N = dyn_cast<MDNode>(MD)) { 910 visitMDNode(*N, AreDebugLocsAllowed::No); 911 return; 912 } 913 914 // Only visit each node once. Metadata can be mutually recursive, so this 915 // avoids infinite recursion here, as well as being an optimization. 916 if (!MDNodes.insert(MD).second) 917 return; 918 919 if (auto *V = dyn_cast<ValueAsMetadata>(MD)) 920 visitValueAsMetadata(*V, F); 921 } 922 923 static bool isType(const Metadata *MD) { return !MD || isa<DIType>(MD); } 924 static bool isScope(const Metadata *MD) { return !MD || isa<DIScope>(MD); } 925 static bool isDINode(const Metadata *MD) { return !MD || isa<DINode>(MD); } 926 927 void Verifier::visitDILocation(const DILocation &N) { 928 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 929 "location requires a valid scope", &N, N.getRawScope()); 930 if (auto *IA = N.getRawInlinedAt()) 931 AssertDI(isa<DILocation>(IA), "inlined-at should be a location", &N, IA); 932 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope())) 933 AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N); 934 } 935 936 void Verifier::visitGenericDINode(const GenericDINode &N) { 937 AssertDI(N.getTag(), "invalid tag", &N); 938 } 939 940 void Verifier::visitDIScope(const DIScope &N) { 941 if (auto *F = N.getRawFile()) 942 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 943 } 944 945 void Verifier::visitDISubrange(const DISubrange &N) { 946 AssertDI(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N); 947 bool HasAssumedSizedArraySupport = dwarf::isFortran(CurrentSourceLang); 948 AssertDI(HasAssumedSizedArraySupport || N.getRawCountNode() || 949 N.getRawUpperBound(), 950 "Subrange must contain count or upperBound", &N); 951 AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(), 952 "Subrange can have any one of count or upperBound", &N); 953 auto *CBound = N.getRawCountNode(); 954 AssertDI(!CBound || isa<ConstantAsMetadata>(CBound) || 955 isa<DIVariable>(CBound) || isa<DIExpression>(CBound), 956 "Count must be signed constant or DIVariable or DIExpression", &N); 957 auto Count = N.getCount(); 958 AssertDI(!Count || !Count.is<ConstantInt *>() || 959 Count.get<ConstantInt *>()->getSExtValue() >= -1, 960 "invalid subrange count", &N); 961 auto *LBound = N.getRawLowerBound(); 962 AssertDI(!LBound || isa<ConstantAsMetadata>(LBound) || 963 isa<DIVariable>(LBound) || isa<DIExpression>(LBound), 964 "LowerBound must be signed constant or DIVariable or DIExpression", 965 &N); 966 auto *UBound = N.getRawUpperBound(); 967 AssertDI(!UBound || isa<ConstantAsMetadata>(UBound) || 968 isa<DIVariable>(UBound) || isa<DIExpression>(UBound), 969 "UpperBound must be signed constant or DIVariable or DIExpression", 970 &N); 971 auto *Stride = N.getRawStride(); 972 AssertDI(!Stride || isa<ConstantAsMetadata>(Stride) || 973 isa<DIVariable>(Stride) || isa<DIExpression>(Stride), 974 "Stride must be signed constant or DIVariable or DIExpression", &N); 975 } 976 977 void Verifier::visitDIGenericSubrange(const DIGenericSubrange &N) { 978 AssertDI(N.getTag() == dwarf::DW_TAG_generic_subrange, "invalid tag", &N); 979 AssertDI(N.getRawCountNode() || N.getRawUpperBound(), 980 "GenericSubrange must contain count or upperBound", &N); 981 AssertDI(!N.getRawCountNode() || !N.getRawUpperBound(), 982 "GenericSubrange can have any one of count or upperBound", &N); 983 auto *CBound = N.getRawCountNode(); 984 AssertDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound), 985 "Count must be signed constant or DIVariable or DIExpression", &N); 986 auto *LBound = N.getRawLowerBound(); 987 AssertDI(LBound, "GenericSubrange must contain lowerBound", &N); 988 AssertDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound), 989 "LowerBound must be signed constant or DIVariable or DIExpression", 990 &N); 991 auto *UBound = N.getRawUpperBound(); 992 AssertDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound), 993 "UpperBound must be signed constant or DIVariable or DIExpression", 994 &N); 995 auto *Stride = N.getRawStride(); 996 AssertDI(Stride, "GenericSubrange must contain stride", &N); 997 AssertDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride), 998 "Stride must be signed constant or DIVariable or DIExpression", &N); 999 } 1000 1001 void Verifier::visitDIEnumerator(const DIEnumerator &N) { 1002 AssertDI(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N); 1003 } 1004 1005 void Verifier::visitDIBasicType(const DIBasicType &N) { 1006 AssertDI(N.getTag() == dwarf::DW_TAG_base_type || 1007 N.getTag() == dwarf::DW_TAG_unspecified_type || 1008 N.getTag() == dwarf::DW_TAG_string_type, 1009 "invalid tag", &N); 1010 } 1011 1012 void Verifier::visitDIStringType(const DIStringType &N) { 1013 AssertDI(N.getTag() == dwarf::DW_TAG_string_type, "invalid tag", &N); 1014 AssertDI(!(N.isBigEndian() && N.isLittleEndian()) , 1015 "has conflicting flags", &N); 1016 } 1017 1018 void Verifier::visitDIDerivedType(const DIDerivedType &N) { 1019 // Common scope checks. 1020 visitDIScope(N); 1021 1022 AssertDI(N.getTag() == dwarf::DW_TAG_typedef || 1023 N.getTag() == dwarf::DW_TAG_pointer_type || 1024 N.getTag() == dwarf::DW_TAG_ptr_to_member_type || 1025 N.getTag() == dwarf::DW_TAG_reference_type || 1026 N.getTag() == dwarf::DW_TAG_rvalue_reference_type || 1027 N.getTag() == dwarf::DW_TAG_const_type || 1028 N.getTag() == dwarf::DW_TAG_volatile_type || 1029 N.getTag() == dwarf::DW_TAG_restrict_type || 1030 N.getTag() == dwarf::DW_TAG_atomic_type || 1031 N.getTag() == dwarf::DW_TAG_member || 1032 N.getTag() == dwarf::DW_TAG_inheritance || 1033 N.getTag() == dwarf::DW_TAG_friend || 1034 N.getTag() == dwarf::DW_TAG_set_type, 1035 "invalid tag", &N); 1036 if (N.getTag() == dwarf::DW_TAG_ptr_to_member_type) { 1037 AssertDI(isType(N.getRawExtraData()), "invalid pointer to member type", &N, 1038 N.getRawExtraData()); 1039 } 1040 1041 if (N.getTag() == dwarf::DW_TAG_set_type) { 1042 if (auto *T = N.getRawBaseType()) { 1043 auto *Enum = dyn_cast_or_null<DICompositeType>(T); 1044 auto *Basic = dyn_cast_or_null<DIBasicType>(T); 1045 AssertDI( 1046 (Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type) || 1047 (Basic && (Basic->getEncoding() == dwarf::DW_ATE_unsigned || 1048 Basic->getEncoding() == dwarf::DW_ATE_signed || 1049 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char || 1050 Basic->getEncoding() == dwarf::DW_ATE_signed_char || 1051 Basic->getEncoding() == dwarf::DW_ATE_boolean)), 1052 "invalid set base type", &N, T); 1053 } 1054 } 1055 1056 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 1057 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 1058 N.getRawBaseType()); 1059 1060 if (N.getDWARFAddressSpace()) { 1061 AssertDI(N.getTag() == dwarf::DW_TAG_pointer_type || 1062 N.getTag() == dwarf::DW_TAG_reference_type || 1063 N.getTag() == dwarf::DW_TAG_rvalue_reference_type, 1064 "DWARF address space only applies to pointer or reference types", 1065 &N); 1066 } 1067 } 1068 1069 /// Detect mutually exclusive flags. 1070 static bool hasConflictingReferenceFlags(unsigned Flags) { 1071 return ((Flags & DINode::FlagLValueReference) && 1072 (Flags & DINode::FlagRValueReference)) || 1073 ((Flags & DINode::FlagTypePassByValue) && 1074 (Flags & DINode::FlagTypePassByReference)); 1075 } 1076 1077 void Verifier::visitTemplateParams(const MDNode &N, const Metadata &RawParams) { 1078 auto *Params = dyn_cast<MDTuple>(&RawParams); 1079 AssertDI(Params, "invalid template params", &N, &RawParams); 1080 for (Metadata *Op : Params->operands()) { 1081 AssertDI(Op && isa<DITemplateParameter>(Op), "invalid template parameter", 1082 &N, Params, Op); 1083 } 1084 } 1085 1086 void Verifier::visitDICompositeType(const DICompositeType &N) { 1087 // Common scope checks. 1088 visitDIScope(N); 1089 1090 AssertDI(N.getTag() == dwarf::DW_TAG_array_type || 1091 N.getTag() == dwarf::DW_TAG_structure_type || 1092 N.getTag() == dwarf::DW_TAG_union_type || 1093 N.getTag() == dwarf::DW_TAG_enumeration_type || 1094 N.getTag() == dwarf::DW_TAG_class_type || 1095 N.getTag() == dwarf::DW_TAG_variant_part, 1096 "invalid tag", &N); 1097 1098 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 1099 AssertDI(isType(N.getRawBaseType()), "invalid base type", &N, 1100 N.getRawBaseType()); 1101 1102 AssertDI(!N.getRawElements() || isa<MDTuple>(N.getRawElements()), 1103 "invalid composite elements", &N, N.getRawElements()); 1104 AssertDI(isType(N.getRawVTableHolder()), "invalid vtable holder", &N, 1105 N.getRawVTableHolder()); 1106 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 1107 "invalid reference flags", &N); 1108 unsigned DIBlockByRefStruct = 1 << 4; 1109 AssertDI((N.getFlags() & DIBlockByRefStruct) == 0, 1110 "DIBlockByRefStruct on DICompositeType is no longer supported", &N); 1111 1112 if (N.isVector()) { 1113 const DINodeArray Elements = N.getElements(); 1114 AssertDI(Elements.size() == 1 && 1115 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type, 1116 "invalid vector, expected one element of type subrange", &N); 1117 } 1118 1119 if (auto *Params = N.getRawTemplateParams()) 1120 visitTemplateParams(N, *Params); 1121 1122 if (auto *D = N.getRawDiscriminator()) { 1123 AssertDI(isa<DIDerivedType>(D) && N.getTag() == dwarf::DW_TAG_variant_part, 1124 "discriminator can only appear on variant part"); 1125 } 1126 1127 if (N.getRawDataLocation()) { 1128 AssertDI(N.getTag() == dwarf::DW_TAG_array_type, 1129 "dataLocation can only appear in array type"); 1130 } 1131 1132 if (N.getRawAssociated()) { 1133 AssertDI(N.getTag() == dwarf::DW_TAG_array_type, 1134 "associated can only appear in array type"); 1135 } 1136 1137 if (N.getRawAllocated()) { 1138 AssertDI(N.getTag() == dwarf::DW_TAG_array_type, 1139 "allocated can only appear in array type"); 1140 } 1141 1142 if (N.getRawRank()) { 1143 AssertDI(N.getTag() == dwarf::DW_TAG_array_type, 1144 "rank can only appear in array type"); 1145 } 1146 } 1147 1148 void Verifier::visitDISubroutineType(const DISubroutineType &N) { 1149 AssertDI(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N); 1150 if (auto *Types = N.getRawTypeArray()) { 1151 AssertDI(isa<MDTuple>(Types), "invalid composite elements", &N, Types); 1152 for (Metadata *Ty : N.getTypeArray()->operands()) { 1153 AssertDI(isType(Ty), "invalid subroutine type ref", &N, Types, Ty); 1154 } 1155 } 1156 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 1157 "invalid reference flags", &N); 1158 } 1159 1160 void Verifier::visitDIFile(const DIFile &N) { 1161 AssertDI(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N); 1162 Optional<DIFile::ChecksumInfo<StringRef>> Checksum = N.getChecksum(); 1163 if (Checksum) { 1164 AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last, 1165 "invalid checksum kind", &N); 1166 size_t Size; 1167 switch (Checksum->Kind) { 1168 case DIFile::CSK_MD5: 1169 Size = 32; 1170 break; 1171 case DIFile::CSK_SHA1: 1172 Size = 40; 1173 break; 1174 case DIFile::CSK_SHA256: 1175 Size = 64; 1176 break; 1177 } 1178 AssertDI(Checksum->Value.size() == Size, "invalid checksum length", &N); 1179 AssertDI(Checksum->Value.find_if_not(llvm::isHexDigit) == StringRef::npos, 1180 "invalid checksum", &N); 1181 } 1182 } 1183 1184 void Verifier::visitDICompileUnit(const DICompileUnit &N) { 1185 AssertDI(N.isDistinct(), "compile units must be distinct", &N); 1186 AssertDI(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N); 1187 1188 // Don't bother verifying the compilation directory or producer string 1189 // as those could be empty. 1190 AssertDI(N.getRawFile() && isa<DIFile>(N.getRawFile()), "invalid file", &N, 1191 N.getRawFile()); 1192 AssertDI(!N.getFile()->getFilename().empty(), "invalid filename", &N, 1193 N.getFile()); 1194 1195 CurrentSourceLang = (dwarf::SourceLanguage)N.getSourceLanguage(); 1196 1197 verifySourceDebugInfo(N, *N.getFile()); 1198 1199 AssertDI((N.getEmissionKind() <= DICompileUnit::LastEmissionKind), 1200 "invalid emission kind", &N); 1201 1202 if (auto *Array = N.getRawEnumTypes()) { 1203 AssertDI(isa<MDTuple>(Array), "invalid enum list", &N, Array); 1204 for (Metadata *Op : N.getEnumTypes()->operands()) { 1205 auto *Enum = dyn_cast_or_null<DICompositeType>(Op); 1206 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type, 1207 "invalid enum type", &N, N.getEnumTypes(), Op); 1208 } 1209 } 1210 if (auto *Array = N.getRawRetainedTypes()) { 1211 AssertDI(isa<MDTuple>(Array), "invalid retained type list", &N, Array); 1212 for (Metadata *Op : N.getRetainedTypes()->operands()) { 1213 AssertDI(Op && (isa<DIType>(Op) || 1214 (isa<DISubprogram>(Op) && 1215 !cast<DISubprogram>(Op)->isDefinition())), 1216 "invalid retained type", &N, Op); 1217 } 1218 } 1219 if (auto *Array = N.getRawGlobalVariables()) { 1220 AssertDI(isa<MDTuple>(Array), "invalid global variable list", &N, Array); 1221 for (Metadata *Op : N.getGlobalVariables()->operands()) { 1222 AssertDI(Op && (isa<DIGlobalVariableExpression>(Op)), 1223 "invalid global variable ref", &N, Op); 1224 } 1225 } 1226 if (auto *Array = N.getRawImportedEntities()) { 1227 AssertDI(isa<MDTuple>(Array), "invalid imported entity list", &N, Array); 1228 for (Metadata *Op : N.getImportedEntities()->operands()) { 1229 AssertDI(Op && isa<DIImportedEntity>(Op), "invalid imported entity ref", 1230 &N, Op); 1231 } 1232 } 1233 if (auto *Array = N.getRawMacros()) { 1234 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1235 for (Metadata *Op : N.getMacros()->operands()) { 1236 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1237 } 1238 } 1239 CUVisited.insert(&N); 1240 } 1241 1242 void Verifier::visitDISubprogram(const DISubprogram &N) { 1243 AssertDI(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N); 1244 AssertDI(isScope(N.getRawScope()), "invalid scope", &N, N.getRawScope()); 1245 if (auto *F = N.getRawFile()) 1246 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1247 else 1248 AssertDI(N.getLine() == 0, "line specified with no file", &N, N.getLine()); 1249 if (auto *T = N.getRawType()) 1250 AssertDI(isa<DISubroutineType>(T), "invalid subroutine type", &N, T); 1251 AssertDI(isType(N.getRawContainingType()), "invalid containing type", &N, 1252 N.getRawContainingType()); 1253 if (auto *Params = N.getRawTemplateParams()) 1254 visitTemplateParams(N, *Params); 1255 if (auto *S = N.getRawDeclaration()) 1256 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(), 1257 "invalid subprogram declaration", &N, S); 1258 if (auto *RawNode = N.getRawRetainedNodes()) { 1259 auto *Node = dyn_cast<MDTuple>(RawNode); 1260 AssertDI(Node, "invalid retained nodes list", &N, RawNode); 1261 for (Metadata *Op : Node->operands()) { 1262 AssertDI(Op && (isa<DILocalVariable>(Op) || isa<DILabel>(Op)), 1263 "invalid retained nodes, expected DILocalVariable or DILabel", 1264 &N, Node, Op); 1265 } 1266 } 1267 AssertDI(!hasConflictingReferenceFlags(N.getFlags()), 1268 "invalid reference flags", &N); 1269 1270 auto *Unit = N.getRawUnit(); 1271 if (N.isDefinition()) { 1272 // Subprogram definitions (not part of the type hierarchy). 1273 AssertDI(N.isDistinct(), "subprogram definitions must be distinct", &N); 1274 AssertDI(Unit, "subprogram definitions must have a compile unit", &N); 1275 AssertDI(isa<DICompileUnit>(Unit), "invalid unit type", &N, Unit); 1276 if (N.getFile()) 1277 verifySourceDebugInfo(*N.getUnit(), *N.getFile()); 1278 } else { 1279 // Subprogram declarations (part of the type hierarchy). 1280 AssertDI(!Unit, "subprogram declarations must not have a compile unit", &N); 1281 } 1282 1283 if (auto *RawThrownTypes = N.getRawThrownTypes()) { 1284 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes); 1285 AssertDI(ThrownTypes, "invalid thrown types list", &N, RawThrownTypes); 1286 for (Metadata *Op : ThrownTypes->operands()) 1287 AssertDI(Op && isa<DIType>(Op), "invalid thrown type", &N, ThrownTypes, 1288 Op); 1289 } 1290 1291 if (N.areAllCallsDescribed()) 1292 AssertDI(N.isDefinition(), 1293 "DIFlagAllCallsDescribed must be attached to a definition"); 1294 } 1295 1296 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase &N) { 1297 AssertDI(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N); 1298 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1299 "invalid local scope", &N, N.getRawScope()); 1300 if (auto *SP = dyn_cast<DISubprogram>(N.getRawScope())) 1301 AssertDI(SP->isDefinition(), "scope points into the type hierarchy", &N); 1302 } 1303 1304 void Verifier::visitDILexicalBlock(const DILexicalBlock &N) { 1305 visitDILexicalBlockBase(N); 1306 1307 AssertDI(N.getLine() || !N.getColumn(), 1308 "cannot have column info without line info", &N); 1309 } 1310 1311 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile &N) { 1312 visitDILexicalBlockBase(N); 1313 } 1314 1315 void Verifier::visitDICommonBlock(const DICommonBlock &N) { 1316 AssertDI(N.getTag() == dwarf::DW_TAG_common_block, "invalid tag", &N); 1317 if (auto *S = N.getRawScope()) 1318 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S); 1319 if (auto *S = N.getRawDecl()) 1320 AssertDI(isa<DIGlobalVariable>(S), "invalid declaration", &N, S); 1321 } 1322 1323 void Verifier::visitDINamespace(const DINamespace &N) { 1324 AssertDI(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N); 1325 if (auto *S = N.getRawScope()) 1326 AssertDI(isa<DIScope>(S), "invalid scope ref", &N, S); 1327 } 1328 1329 void Verifier::visitDIMacro(const DIMacro &N) { 1330 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_define || 1331 N.getMacinfoType() == dwarf::DW_MACINFO_undef, 1332 "invalid macinfo type", &N); 1333 AssertDI(!N.getName().empty(), "anonymous macro", &N); 1334 if (!N.getValue().empty()) { 1335 assert(N.getValue().data()[0] != ' ' && "Macro value has a space prefix"); 1336 } 1337 } 1338 1339 void Verifier::visitDIMacroFile(const DIMacroFile &N) { 1340 AssertDI(N.getMacinfoType() == dwarf::DW_MACINFO_start_file, 1341 "invalid macinfo type", &N); 1342 if (auto *F = N.getRawFile()) 1343 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1344 1345 if (auto *Array = N.getRawElements()) { 1346 AssertDI(isa<MDTuple>(Array), "invalid macro list", &N, Array); 1347 for (Metadata *Op : N.getElements()->operands()) { 1348 AssertDI(Op && isa<DIMacroNode>(Op), "invalid macro ref", &N, Op); 1349 } 1350 } 1351 } 1352 1353 void Verifier::visitDIArgList(const DIArgList &N) { 1354 AssertDI(!N.getNumOperands(), 1355 "DIArgList should have no operands other than a list of " 1356 "ValueAsMetadata", 1357 &N); 1358 } 1359 1360 void Verifier::visitDIModule(const DIModule &N) { 1361 AssertDI(N.getTag() == dwarf::DW_TAG_module, "invalid tag", &N); 1362 AssertDI(!N.getName().empty(), "anonymous module", &N); 1363 } 1364 1365 void Verifier::visitDITemplateParameter(const DITemplateParameter &N) { 1366 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1367 } 1368 1369 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter &N) { 1370 visitDITemplateParameter(N); 1371 1372 AssertDI(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag", 1373 &N); 1374 } 1375 1376 void Verifier::visitDITemplateValueParameter( 1377 const DITemplateValueParameter &N) { 1378 visitDITemplateParameter(N); 1379 1380 AssertDI(N.getTag() == dwarf::DW_TAG_template_value_parameter || 1381 N.getTag() == dwarf::DW_TAG_GNU_template_template_param || 1382 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack, 1383 "invalid tag", &N); 1384 } 1385 1386 void Verifier::visitDIVariable(const DIVariable &N) { 1387 if (auto *S = N.getRawScope()) 1388 AssertDI(isa<DIScope>(S), "invalid scope", &N, S); 1389 if (auto *F = N.getRawFile()) 1390 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1391 } 1392 1393 void Verifier::visitDIGlobalVariable(const DIGlobalVariable &N) { 1394 // Checks common to all variables. 1395 visitDIVariable(N); 1396 1397 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1398 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1399 // Assert only if the global variable is not an extern 1400 if (N.isDefinition()) 1401 AssertDI(N.getType(), "missing global variable type", &N); 1402 if (auto *Member = N.getRawStaticDataMemberDeclaration()) { 1403 AssertDI(isa<DIDerivedType>(Member), 1404 "invalid static data member declaration", &N, Member); 1405 } 1406 } 1407 1408 void Verifier::visitDILocalVariable(const DILocalVariable &N) { 1409 // Checks common to all variables. 1410 visitDIVariable(N); 1411 1412 AssertDI(isType(N.getRawType()), "invalid type ref", &N, N.getRawType()); 1413 AssertDI(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N); 1414 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1415 "local variable requires a valid scope", &N, N.getRawScope()); 1416 if (auto Ty = N.getType()) 1417 AssertDI(!isa<DISubroutineType>(Ty), "invalid type", &N, N.getType()); 1418 } 1419 1420 void Verifier::visitDILabel(const DILabel &N) { 1421 if (auto *S = N.getRawScope()) 1422 AssertDI(isa<DIScope>(S), "invalid scope", &N, S); 1423 if (auto *F = N.getRawFile()) 1424 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1425 1426 AssertDI(N.getTag() == dwarf::DW_TAG_label, "invalid tag", &N); 1427 AssertDI(N.getRawScope() && isa<DILocalScope>(N.getRawScope()), 1428 "label requires a valid scope", &N, N.getRawScope()); 1429 } 1430 1431 void Verifier::visitDIExpression(const DIExpression &N) { 1432 AssertDI(N.isValid(), "invalid expression", &N); 1433 } 1434 1435 void Verifier::visitDIGlobalVariableExpression( 1436 const DIGlobalVariableExpression &GVE) { 1437 AssertDI(GVE.getVariable(), "missing variable"); 1438 if (auto *Var = GVE.getVariable()) 1439 visitDIGlobalVariable(*Var); 1440 if (auto *Expr = GVE.getExpression()) { 1441 visitDIExpression(*Expr); 1442 if (auto Fragment = Expr->getFragmentInfo()) 1443 verifyFragmentExpression(*GVE.getVariable(), *Fragment, &GVE); 1444 } 1445 } 1446 1447 void Verifier::visitDIObjCProperty(const DIObjCProperty &N) { 1448 AssertDI(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N); 1449 if (auto *T = N.getRawType()) 1450 AssertDI(isType(T), "invalid type ref", &N, T); 1451 if (auto *F = N.getRawFile()) 1452 AssertDI(isa<DIFile>(F), "invalid file", &N, F); 1453 } 1454 1455 void Verifier::visitDIImportedEntity(const DIImportedEntity &N) { 1456 AssertDI(N.getTag() == dwarf::DW_TAG_imported_module || 1457 N.getTag() == dwarf::DW_TAG_imported_declaration, 1458 "invalid tag", &N); 1459 if (auto *S = N.getRawScope()) 1460 AssertDI(isa<DIScope>(S), "invalid scope for imported entity", &N, S); 1461 AssertDI(isDINode(N.getRawEntity()), "invalid imported entity", &N, 1462 N.getRawEntity()); 1463 } 1464 1465 void Verifier::visitComdat(const Comdat &C) { 1466 // In COFF the Module is invalid if the GlobalValue has private linkage. 1467 // Entities with private linkage don't have entries in the symbol table. 1468 if (TT.isOSBinFormatCOFF()) 1469 if (const GlobalValue *GV = M.getNamedValue(C.getName())) 1470 Assert(!GV->hasPrivateLinkage(), 1471 "comdat global value has private linkage", GV); 1472 } 1473 1474 void Verifier::visitModuleIdents(const Module &M) { 1475 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident"); 1476 if (!Idents) 1477 return; 1478 1479 // llvm.ident takes a list of metadata entry. Each entry has only one string. 1480 // Scan each llvm.ident entry and make sure that this requirement is met. 1481 for (const MDNode *N : Idents->operands()) { 1482 Assert(N->getNumOperands() == 1, 1483 "incorrect number of operands in llvm.ident metadata", N); 1484 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)), 1485 ("invalid value for llvm.ident metadata entry operand" 1486 "(the operand should be a string)"), 1487 N->getOperand(0)); 1488 } 1489 } 1490 1491 void Verifier::visitModuleCommandLines(const Module &M) { 1492 const NamedMDNode *CommandLines = M.getNamedMetadata("llvm.commandline"); 1493 if (!CommandLines) 1494 return; 1495 1496 // llvm.commandline takes a list of metadata entry. Each entry has only one 1497 // string. Scan each llvm.commandline entry and make sure that this 1498 // requirement is met. 1499 for (const MDNode *N : CommandLines->operands()) { 1500 Assert(N->getNumOperands() == 1, 1501 "incorrect number of operands in llvm.commandline metadata", N); 1502 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)), 1503 ("invalid value for llvm.commandline metadata entry operand" 1504 "(the operand should be a string)"), 1505 N->getOperand(0)); 1506 } 1507 } 1508 1509 void Verifier::visitModuleFlags(const Module &M) { 1510 const NamedMDNode *Flags = M.getModuleFlagsMetadata(); 1511 if (!Flags) return; 1512 1513 // Scan each flag, and track the flags and requirements. 1514 DenseMap<const MDString*, const MDNode*> SeenIDs; 1515 SmallVector<const MDNode*, 16> Requirements; 1516 for (const MDNode *MDN : Flags->operands()) 1517 visitModuleFlag(MDN, SeenIDs, Requirements); 1518 1519 // Validate that the requirements in the module are valid. 1520 for (const MDNode *Requirement : Requirements) { 1521 const MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 1522 const Metadata *ReqValue = Requirement->getOperand(1); 1523 1524 const MDNode *Op = SeenIDs.lookup(Flag); 1525 if (!Op) { 1526 CheckFailed("invalid requirement on flag, flag is not present in module", 1527 Flag); 1528 continue; 1529 } 1530 1531 if (Op->getOperand(2) != ReqValue) { 1532 CheckFailed(("invalid requirement on flag, " 1533 "flag does not have the required value"), 1534 Flag); 1535 continue; 1536 } 1537 } 1538 } 1539 1540 void 1541 Verifier::visitModuleFlag(const MDNode *Op, 1542 DenseMap<const MDString *, const MDNode *> &SeenIDs, 1543 SmallVectorImpl<const MDNode *> &Requirements) { 1544 // Each module flag should have three arguments, the merge behavior (a 1545 // constant int), the flag ID (an MDString), and the value. 1546 Assert(Op->getNumOperands() == 3, 1547 "incorrect number of operands in module flag", Op); 1548 Module::ModFlagBehavior MFB; 1549 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) { 1550 Assert( 1551 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)), 1552 "invalid behavior operand in module flag (expected constant integer)", 1553 Op->getOperand(0)); 1554 Assert(false, 1555 "invalid behavior operand in module flag (unexpected constant)", 1556 Op->getOperand(0)); 1557 } 1558 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1)); 1559 Assert(ID, "invalid ID operand in module flag (expected metadata string)", 1560 Op->getOperand(1)); 1561 1562 // Sanity check the values for behaviors with additional requirements. 1563 switch (MFB) { 1564 case Module::Error: 1565 case Module::Warning: 1566 case Module::Override: 1567 // These behavior types accept any value. 1568 break; 1569 1570 case Module::Max: { 1571 Assert(mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)), 1572 "invalid value for 'max' module flag (expected constant integer)", 1573 Op->getOperand(2)); 1574 break; 1575 } 1576 1577 case Module::Require: { 1578 // The value should itself be an MDNode with two operands, a flag ID (an 1579 // MDString), and a value. 1580 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2)); 1581 Assert(Value && Value->getNumOperands() == 2, 1582 "invalid value for 'require' module flag (expected metadata pair)", 1583 Op->getOperand(2)); 1584 Assert(isa<MDString>(Value->getOperand(0)), 1585 ("invalid value for 'require' module flag " 1586 "(first value operand should be a string)"), 1587 Value->getOperand(0)); 1588 1589 // Append it to the list of requirements, to check once all module flags are 1590 // scanned. 1591 Requirements.push_back(Value); 1592 break; 1593 } 1594 1595 case Module::Append: 1596 case Module::AppendUnique: { 1597 // These behavior types require the operand be an MDNode. 1598 Assert(isa<MDNode>(Op->getOperand(2)), 1599 "invalid value for 'append'-type module flag " 1600 "(expected a metadata node)", 1601 Op->getOperand(2)); 1602 break; 1603 } 1604 } 1605 1606 // Unless this is a "requires" flag, check the ID is unique. 1607 if (MFB != Module::Require) { 1608 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second; 1609 Assert(Inserted, 1610 "module flag identifiers must be unique (or of 'require' type)", ID); 1611 } 1612 1613 if (ID->getString() == "wchar_size") { 1614 ConstantInt *Value 1615 = mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)); 1616 Assert(Value, "wchar_size metadata requires constant integer argument"); 1617 } 1618 1619 if (ID->getString() == "Linker Options") { 1620 // If the llvm.linker.options named metadata exists, we assume that the 1621 // bitcode reader has upgraded the module flag. Otherwise the flag might 1622 // have been created by a client directly. 1623 Assert(M.getNamedMetadata("llvm.linker.options"), 1624 "'Linker Options' named metadata no longer supported"); 1625 } 1626 1627 if (ID->getString() == "SemanticInterposition") { 1628 ConstantInt *Value = 1629 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(2)); 1630 Assert(Value, 1631 "SemanticInterposition metadata requires constant integer argument"); 1632 } 1633 1634 if (ID->getString() == "CG Profile") { 1635 for (const MDOperand &MDO : cast<MDNode>(Op->getOperand(2))->operands()) 1636 visitModuleFlagCGProfileEntry(MDO); 1637 } 1638 } 1639 1640 void Verifier::visitModuleFlagCGProfileEntry(const MDOperand &MDO) { 1641 auto CheckFunction = [&](const MDOperand &FuncMDO) { 1642 if (!FuncMDO) 1643 return; 1644 auto F = dyn_cast<ValueAsMetadata>(FuncMDO); 1645 Assert(F && isa<Function>(F->getValue()->stripPointerCasts()), 1646 "expected a Function or null", FuncMDO); 1647 }; 1648 auto Node = dyn_cast_or_null<MDNode>(MDO); 1649 Assert(Node && Node->getNumOperands() == 3, "expected a MDNode triple", MDO); 1650 CheckFunction(Node->getOperand(0)); 1651 CheckFunction(Node->getOperand(1)); 1652 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2)); 1653 Assert(Count && Count->getType()->isIntegerTy(), 1654 "expected an integer constant", Node->getOperand(2)); 1655 } 1656 1657 /// Return true if this attribute kind only applies to functions. 1658 static bool isFuncOnlyAttr(Attribute::AttrKind Kind) { 1659 switch (Kind) { 1660 case Attribute::NoMerge: 1661 case Attribute::NoReturn: 1662 case Attribute::NoSync: 1663 case Attribute::WillReturn: 1664 case Attribute::NoCallback: 1665 case Attribute::NoCfCheck: 1666 case Attribute::NoUnwind: 1667 case Attribute::NoInline: 1668 case Attribute::NoSanitizeCoverage: 1669 case Attribute::AlwaysInline: 1670 case Attribute::OptimizeForSize: 1671 case Attribute::StackProtect: 1672 case Attribute::StackProtectReq: 1673 case Attribute::StackProtectStrong: 1674 case Attribute::SafeStack: 1675 case Attribute::ShadowCallStack: 1676 case Attribute::NoRedZone: 1677 case Attribute::NoImplicitFloat: 1678 case Attribute::Naked: 1679 case Attribute::InlineHint: 1680 case Attribute::UWTable: 1681 case Attribute::VScaleRange: 1682 case Attribute::NonLazyBind: 1683 case Attribute::ReturnsTwice: 1684 case Attribute::SanitizeAddress: 1685 case Attribute::SanitizeHWAddress: 1686 case Attribute::SanitizeMemTag: 1687 case Attribute::SanitizeThread: 1688 case Attribute::SanitizeMemory: 1689 case Attribute::MinSize: 1690 case Attribute::NoDuplicate: 1691 case Attribute::Builtin: 1692 case Attribute::NoBuiltin: 1693 case Attribute::Cold: 1694 case Attribute::Hot: 1695 case Attribute::OptForFuzzing: 1696 case Attribute::OptimizeNone: 1697 case Attribute::JumpTable: 1698 case Attribute::Convergent: 1699 case Attribute::ArgMemOnly: 1700 case Attribute::NoRecurse: 1701 case Attribute::InaccessibleMemOnly: 1702 case Attribute::InaccessibleMemOrArgMemOnly: 1703 case Attribute::AllocSize: 1704 case Attribute::SpeculativeLoadHardening: 1705 case Attribute::Speculatable: 1706 case Attribute::StrictFP: 1707 case Attribute::NullPointerIsValid: 1708 case Attribute::MustProgress: 1709 case Attribute::NoProfile: 1710 return true; 1711 default: 1712 break; 1713 } 1714 return false; 1715 } 1716 1717 /// Return true if this is a function attribute that can also appear on 1718 /// arguments. 1719 static bool isFuncOrArgAttr(Attribute::AttrKind Kind) { 1720 return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly || 1721 Kind == Attribute::ReadNone || Kind == Attribute::NoFree || 1722 Kind == Attribute::Preallocated || Kind == Attribute::StackAlignment; 1723 } 1724 1725 void Verifier::verifyAttributeTypes(AttributeSet Attrs, bool IsFunction, 1726 const Value *V) { 1727 for (Attribute A : Attrs) { 1728 1729 if (A.isStringAttribute()) { 1730 #define GET_ATTR_NAMES 1731 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) 1732 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \ 1733 if (A.getKindAsString() == #DISPLAY_NAME) { \ 1734 auto V = A.getValueAsString(); \ 1735 if (!(V.empty() || V == "true" || V == "false")) \ 1736 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \ 1737 ""); \ 1738 } 1739 1740 #include "llvm/IR/Attributes.inc" 1741 continue; 1742 } 1743 1744 if (A.isIntAttribute() != 1745 Attribute::doesAttrKindHaveArgument(A.getKindAsEnum())) { 1746 CheckFailed("Attribute '" + A.getAsString() + "' should have an Argument", 1747 V); 1748 return; 1749 } 1750 1751 if (isFuncOnlyAttr(A.getKindAsEnum())) { 1752 if (!IsFunction) { 1753 CheckFailed("Attribute '" + A.getAsString() + 1754 "' only applies to functions!", 1755 V); 1756 return; 1757 } 1758 } else if (IsFunction && !isFuncOrArgAttr(A.getKindAsEnum())) { 1759 CheckFailed("Attribute '" + A.getAsString() + 1760 "' does not apply to functions!", 1761 V); 1762 return; 1763 } 1764 } 1765 } 1766 1767 // VerifyParameterAttrs - Check the given attributes for an argument or return 1768 // value of the specified type. The value V is printed in error messages. 1769 void Verifier::verifyParameterAttrs(AttributeSet Attrs, Type *Ty, 1770 const Value *V) { 1771 if (!Attrs.hasAttributes()) 1772 return; 1773 1774 verifyAttributeTypes(Attrs, /*IsFunction=*/false, V); 1775 1776 if (Attrs.hasAttribute(Attribute::ImmArg)) { 1777 Assert(Attrs.getNumAttributes() == 1, 1778 "Attribute 'immarg' is incompatible with other attributes", V); 1779 } 1780 1781 // Check for mutually incompatible attributes. Only inreg is compatible with 1782 // sret. 1783 unsigned AttrCount = 0; 1784 AttrCount += Attrs.hasAttribute(Attribute::ByVal); 1785 AttrCount += Attrs.hasAttribute(Attribute::InAlloca); 1786 AttrCount += Attrs.hasAttribute(Attribute::Preallocated); 1787 AttrCount += Attrs.hasAttribute(Attribute::StructRet) || 1788 Attrs.hasAttribute(Attribute::InReg); 1789 AttrCount += Attrs.hasAttribute(Attribute::Nest); 1790 AttrCount += Attrs.hasAttribute(Attribute::ByRef); 1791 Assert(AttrCount <= 1, 1792 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', " 1793 "'byref', and 'sret' are incompatible!", 1794 V); 1795 1796 Assert(!(Attrs.hasAttribute(Attribute::InAlloca) && 1797 Attrs.hasAttribute(Attribute::ReadOnly)), 1798 "Attributes " 1799 "'inalloca and readonly' are incompatible!", 1800 V); 1801 1802 Assert(!(Attrs.hasAttribute(Attribute::StructRet) && 1803 Attrs.hasAttribute(Attribute::Returned)), 1804 "Attributes " 1805 "'sret and returned' are incompatible!", 1806 V); 1807 1808 Assert(!(Attrs.hasAttribute(Attribute::ZExt) && 1809 Attrs.hasAttribute(Attribute::SExt)), 1810 "Attributes " 1811 "'zeroext and signext' are incompatible!", 1812 V); 1813 1814 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) && 1815 Attrs.hasAttribute(Attribute::ReadOnly)), 1816 "Attributes " 1817 "'readnone and readonly' are incompatible!", 1818 V); 1819 1820 Assert(!(Attrs.hasAttribute(Attribute::ReadNone) && 1821 Attrs.hasAttribute(Attribute::WriteOnly)), 1822 "Attributes " 1823 "'readnone and writeonly' are incompatible!", 1824 V); 1825 1826 Assert(!(Attrs.hasAttribute(Attribute::ReadOnly) && 1827 Attrs.hasAttribute(Attribute::WriteOnly)), 1828 "Attributes " 1829 "'readonly and writeonly' are incompatible!", 1830 V); 1831 1832 Assert(!(Attrs.hasAttribute(Attribute::NoInline) && 1833 Attrs.hasAttribute(Attribute::AlwaysInline)), 1834 "Attributes " 1835 "'noinline and alwaysinline' are incompatible!", 1836 V); 1837 1838 AttrBuilder IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty); 1839 Assert(!AttrBuilder(Attrs).overlaps(IncompatibleAttrs), 1840 "Wrong types for attribute: " + 1841 AttributeSet::get(Context, IncompatibleAttrs).getAsString(), 1842 V); 1843 1844 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) { 1845 if (Attrs.hasAttribute(Attribute::ByVal)) { 1846 SmallPtrSet<Type *, 4> Visited; 1847 Assert(Attrs.getByValType()->isSized(&Visited), 1848 "Attribute 'byval' does not support unsized types!", V); 1849 } 1850 if (Attrs.hasAttribute(Attribute::ByRef)) { 1851 SmallPtrSet<Type *, 4> Visited; 1852 Assert(Attrs.getByRefType()->isSized(&Visited), 1853 "Attribute 'byref' does not support unsized types!", V); 1854 } 1855 if (Attrs.hasAttribute(Attribute::InAlloca)) { 1856 SmallPtrSet<Type *, 4> Visited; 1857 Assert(Attrs.getInAllocaType()->isSized(&Visited), 1858 "Attribute 'inalloca' does not support unsized types!", V); 1859 } 1860 if (Attrs.hasAttribute(Attribute::Preallocated)) { 1861 SmallPtrSet<Type *, 4> Visited; 1862 Assert(Attrs.getPreallocatedType()->isSized(&Visited), 1863 "Attribute 'preallocated' does not support unsized types!", V); 1864 } 1865 if (!PTy->isOpaque()) { 1866 if (!isa<PointerType>(PTy->getElementType())) 1867 Assert(!Attrs.hasAttribute(Attribute::SwiftError), 1868 "Attribute 'swifterror' only applies to parameters " 1869 "with pointer to pointer type!", 1870 V); 1871 if (Attrs.hasAttribute(Attribute::ByRef)) { 1872 Assert(Attrs.getByRefType() == PTy->getElementType(), 1873 "Attribute 'byref' type does not match parameter!", V); 1874 } 1875 1876 if (Attrs.hasAttribute(Attribute::ByVal) && Attrs.getByValType()) { 1877 Assert(Attrs.getByValType() == PTy->getElementType(), 1878 "Attribute 'byval' type does not match parameter!", V); 1879 } 1880 1881 if (Attrs.hasAttribute(Attribute::Preallocated)) { 1882 Assert(Attrs.getPreallocatedType() == PTy->getElementType(), 1883 "Attribute 'preallocated' type does not match parameter!", V); 1884 } 1885 1886 if (Attrs.hasAttribute(Attribute::InAlloca)) { 1887 Assert(Attrs.getInAllocaType() == PTy->getElementType(), 1888 "Attribute 'inalloca' type does not match parameter!", V); 1889 } 1890 } 1891 } else { 1892 Assert(!Attrs.hasAttribute(Attribute::ByVal), 1893 "Attribute 'byval' only applies to parameters with pointer type!", 1894 V); 1895 Assert(!Attrs.hasAttribute(Attribute::ByRef), 1896 "Attribute 'byref' only applies to parameters with pointer type!", 1897 V); 1898 Assert(!Attrs.hasAttribute(Attribute::SwiftError), 1899 "Attribute 'swifterror' only applies to parameters " 1900 "with pointer type!", 1901 V); 1902 } 1903 } 1904 1905 void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr, 1906 const Value *V) { 1907 if (Attrs.hasFnAttribute(Attr)) { 1908 StringRef S = Attrs.getAttribute(AttributeList::FunctionIndex, Attr) 1909 .getValueAsString(); 1910 unsigned N; 1911 if (S.getAsInteger(10, N)) 1912 CheckFailed("\"" + Attr + "\" takes an unsigned integer: " + S, V); 1913 } 1914 } 1915 1916 // Check parameter attributes against a function type. 1917 // The value V is printed in error messages. 1918 void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs, 1919 const Value *V, bool IsIntrinsic) { 1920 if (Attrs.isEmpty()) 1921 return; 1922 1923 if (AttributeListsVisited.insert(Attrs.getRawPointer()).second) { 1924 Assert(Attrs.hasParentContext(Context), 1925 "Attribute list does not match Module context!", &Attrs, V); 1926 for (const auto &AttrSet : Attrs) { 1927 Assert(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context), 1928 "Attribute set does not match Module context!", &AttrSet, V); 1929 for (const auto &A : AttrSet) { 1930 Assert(A.hasParentContext(Context), 1931 "Attribute does not match Module context!", &A, V); 1932 } 1933 } 1934 } 1935 1936 bool SawNest = false; 1937 bool SawReturned = false; 1938 bool SawSRet = false; 1939 bool SawSwiftSelf = false; 1940 bool SawSwiftAsync = false; 1941 bool SawSwiftError = false; 1942 1943 // Verify return value attributes. 1944 AttributeSet RetAttrs = Attrs.getRetAttributes(); 1945 Assert((!RetAttrs.hasAttribute(Attribute::ByVal) && 1946 !RetAttrs.hasAttribute(Attribute::Nest) && 1947 !RetAttrs.hasAttribute(Attribute::StructRet) && 1948 !RetAttrs.hasAttribute(Attribute::NoCapture) && 1949 !RetAttrs.hasAttribute(Attribute::NoFree) && 1950 !RetAttrs.hasAttribute(Attribute::Returned) && 1951 !RetAttrs.hasAttribute(Attribute::InAlloca) && 1952 !RetAttrs.hasAttribute(Attribute::Preallocated) && 1953 !RetAttrs.hasAttribute(Attribute::ByRef) && 1954 !RetAttrs.hasAttribute(Attribute::SwiftSelf) && 1955 !RetAttrs.hasAttribute(Attribute::SwiftAsync) && 1956 !RetAttrs.hasAttribute(Attribute::SwiftError)), 1957 "Attributes 'byval', 'inalloca', 'preallocated', 'byref', " 1958 "'nest', 'sret', 'nocapture', 'nofree', " 1959 "'returned', 'swiftself', 'swiftasync', and 'swifterror'" 1960 " do not apply to return values!", 1961 V); 1962 Assert((!RetAttrs.hasAttribute(Attribute::ReadOnly) && 1963 !RetAttrs.hasAttribute(Attribute::WriteOnly) && 1964 !RetAttrs.hasAttribute(Attribute::ReadNone)), 1965 "Attribute '" + RetAttrs.getAsString() + 1966 "' does not apply to function returns", 1967 V); 1968 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V); 1969 1970 // Verify parameter attributes. 1971 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1972 Type *Ty = FT->getParamType(i); 1973 AttributeSet ArgAttrs = Attrs.getParamAttributes(i); 1974 1975 if (!IsIntrinsic) { 1976 Assert(!ArgAttrs.hasAttribute(Attribute::ImmArg), 1977 "immarg attribute only applies to intrinsics",V); 1978 } 1979 1980 verifyParameterAttrs(ArgAttrs, Ty, V); 1981 1982 if (ArgAttrs.hasAttribute(Attribute::Nest)) { 1983 Assert(!SawNest, "More than one parameter has attribute nest!", V); 1984 SawNest = true; 1985 } 1986 1987 if (ArgAttrs.hasAttribute(Attribute::Returned)) { 1988 Assert(!SawReturned, "More than one parameter has attribute returned!", 1989 V); 1990 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()), 1991 "Incompatible argument and return types for 'returned' attribute", 1992 V); 1993 SawReturned = true; 1994 } 1995 1996 if (ArgAttrs.hasAttribute(Attribute::StructRet)) { 1997 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V); 1998 Assert(i == 0 || i == 1, 1999 "Attribute 'sret' is not on first or second parameter!", V); 2000 SawSRet = true; 2001 } 2002 2003 if (ArgAttrs.hasAttribute(Attribute::SwiftSelf)) { 2004 Assert(!SawSwiftSelf, "Cannot have multiple 'swiftself' parameters!", V); 2005 SawSwiftSelf = true; 2006 } 2007 2008 if (ArgAttrs.hasAttribute(Attribute::SwiftAsync)) { 2009 Assert(!SawSwiftAsync, "Cannot have multiple 'swiftasync' parameters!", V); 2010 SawSwiftAsync = true; 2011 } 2012 2013 if (ArgAttrs.hasAttribute(Attribute::SwiftError)) { 2014 Assert(!SawSwiftError, "Cannot have multiple 'swifterror' parameters!", 2015 V); 2016 SawSwiftError = true; 2017 } 2018 2019 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) { 2020 Assert(i == FT->getNumParams() - 1, 2021 "inalloca isn't on the last parameter!", V); 2022 } 2023 } 2024 2025 if (!Attrs.hasAttributes(AttributeList::FunctionIndex)) 2026 return; 2027 2028 verifyAttributeTypes(Attrs.getFnAttributes(), /*IsFunction=*/true, V); 2029 2030 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 2031 Attrs.hasFnAttribute(Attribute::ReadOnly)), 2032 "Attributes 'readnone and readonly' are incompatible!", V); 2033 2034 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 2035 Attrs.hasFnAttribute(Attribute::WriteOnly)), 2036 "Attributes 'readnone and writeonly' are incompatible!", V); 2037 2038 Assert(!(Attrs.hasFnAttribute(Attribute::ReadOnly) && 2039 Attrs.hasFnAttribute(Attribute::WriteOnly)), 2040 "Attributes 'readonly and writeonly' are incompatible!", V); 2041 2042 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 2043 Attrs.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly)), 2044 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are " 2045 "incompatible!", 2046 V); 2047 2048 Assert(!(Attrs.hasFnAttribute(Attribute::ReadNone) && 2049 Attrs.hasFnAttribute(Attribute::InaccessibleMemOnly)), 2050 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V); 2051 2052 Assert(!(Attrs.hasFnAttribute(Attribute::NoInline) && 2053 Attrs.hasFnAttribute(Attribute::AlwaysInline)), 2054 "Attributes 'noinline and alwaysinline' are incompatible!", V); 2055 2056 if (Attrs.hasFnAttribute(Attribute::OptimizeNone)) { 2057 Assert(Attrs.hasFnAttribute(Attribute::NoInline), 2058 "Attribute 'optnone' requires 'noinline'!", V); 2059 2060 Assert(!Attrs.hasFnAttribute(Attribute::OptimizeForSize), 2061 "Attributes 'optsize and optnone' are incompatible!", V); 2062 2063 Assert(!Attrs.hasFnAttribute(Attribute::MinSize), 2064 "Attributes 'minsize and optnone' are incompatible!", V); 2065 } 2066 2067 if (Attrs.hasFnAttribute(Attribute::JumpTable)) { 2068 const GlobalValue *GV = cast<GlobalValue>(V); 2069 Assert(GV->hasGlobalUnnamedAddr(), 2070 "Attribute 'jumptable' requires 'unnamed_addr'", V); 2071 } 2072 2073 if (Attrs.hasFnAttribute(Attribute::AllocSize)) { 2074 std::pair<unsigned, Optional<unsigned>> Args = 2075 Attrs.getAllocSizeArgs(AttributeList::FunctionIndex); 2076 2077 auto CheckParam = [&](StringRef Name, unsigned ParamNo) { 2078 if (ParamNo >= FT->getNumParams()) { 2079 CheckFailed("'allocsize' " + Name + " argument is out of bounds", V); 2080 return false; 2081 } 2082 2083 if (!FT->getParamType(ParamNo)->isIntegerTy()) { 2084 CheckFailed("'allocsize' " + Name + 2085 " argument must refer to an integer parameter", 2086 V); 2087 return false; 2088 } 2089 2090 return true; 2091 }; 2092 2093 if (!CheckParam("element size", Args.first)) 2094 return; 2095 2096 if (Args.second && !CheckParam("number of elements", *Args.second)) 2097 return; 2098 } 2099 2100 if (Attrs.hasFnAttribute(Attribute::VScaleRange)) { 2101 std::pair<unsigned, unsigned> Args = 2102 Attrs.getVScaleRangeArgs(AttributeList::FunctionIndex); 2103 2104 if (Args.first > Args.second && Args.second != 0) 2105 CheckFailed("'vscale_range' minimum cannot be greater than maximum", V); 2106 } 2107 2108 if (Attrs.hasFnAttribute("frame-pointer")) { 2109 StringRef FP = Attrs.getAttribute(AttributeList::FunctionIndex, 2110 "frame-pointer").getValueAsString(); 2111 if (FP != "all" && FP != "non-leaf" && FP != "none") 2112 CheckFailed("invalid value for 'frame-pointer' attribute: " + FP, V); 2113 } 2114 2115 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-prefix", V); 2116 checkUnsignedBaseTenFuncAttr(Attrs, "patchable-function-entry", V); 2117 checkUnsignedBaseTenFuncAttr(Attrs, "warn-stack-size", V); 2118 } 2119 2120 void Verifier::verifyFunctionMetadata( 2121 ArrayRef<std::pair<unsigned, MDNode *>> MDs) { 2122 for (const auto &Pair : MDs) { 2123 if (Pair.first == LLVMContext::MD_prof) { 2124 MDNode *MD = Pair.second; 2125 Assert(MD->getNumOperands() >= 2, 2126 "!prof annotations should have no less than 2 operands", MD); 2127 2128 // Check first operand. 2129 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", 2130 MD); 2131 Assert(isa<MDString>(MD->getOperand(0)), 2132 "expected string with name of the !prof annotation", MD); 2133 MDString *MDS = cast<MDString>(MD->getOperand(0)); 2134 StringRef ProfName = MDS->getString(); 2135 Assert(ProfName.equals("function_entry_count") || 2136 ProfName.equals("synthetic_function_entry_count"), 2137 "first operand should be 'function_entry_count'" 2138 " or 'synthetic_function_entry_count'", 2139 MD); 2140 2141 // Check second operand. 2142 Assert(MD->getOperand(1) != nullptr, "second operand should not be null", 2143 MD); 2144 Assert(isa<ConstantAsMetadata>(MD->getOperand(1)), 2145 "expected integer argument to function_entry_count", MD); 2146 } 2147 } 2148 } 2149 2150 void Verifier::visitConstantExprsRecursively(const Constant *EntryC) { 2151 if (!ConstantExprVisited.insert(EntryC).second) 2152 return; 2153 2154 SmallVector<const Constant *, 16> Stack; 2155 Stack.push_back(EntryC); 2156 2157 while (!Stack.empty()) { 2158 const Constant *C = Stack.pop_back_val(); 2159 2160 // Check this constant expression. 2161 if (const auto *CE = dyn_cast<ConstantExpr>(C)) 2162 visitConstantExpr(CE); 2163 2164 if (const auto *GV = dyn_cast<GlobalValue>(C)) { 2165 // Global Values get visited separately, but we do need to make sure 2166 // that the global value is in the correct module 2167 Assert(GV->getParent() == &M, "Referencing global in another module!", 2168 EntryC, &M, GV, GV->getParent()); 2169 continue; 2170 } 2171 2172 // Visit all sub-expressions. 2173 for (const Use &U : C->operands()) { 2174 const auto *OpC = dyn_cast<Constant>(U); 2175 if (!OpC) 2176 continue; 2177 if (!ConstantExprVisited.insert(OpC).second) 2178 continue; 2179 Stack.push_back(OpC); 2180 } 2181 } 2182 } 2183 2184 void Verifier::visitConstantExpr(const ConstantExpr *CE) { 2185 if (CE->getOpcode() == Instruction::BitCast) 2186 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0), 2187 CE->getType()), 2188 "Invalid bitcast", CE); 2189 } 2190 2191 bool Verifier::verifyAttributeCount(AttributeList Attrs, unsigned Params) { 2192 // There shouldn't be more attribute sets than there are parameters plus the 2193 // function and return value. 2194 return Attrs.getNumAttrSets() <= Params + 2; 2195 } 2196 2197 /// Verify that statepoint intrinsic is well formed. 2198 void Verifier::verifyStatepoint(const CallBase &Call) { 2199 assert(Call.getCalledFunction() && 2200 Call.getCalledFunction()->getIntrinsicID() == 2201 Intrinsic::experimental_gc_statepoint); 2202 2203 Assert(!Call.doesNotAccessMemory() && !Call.onlyReadsMemory() && 2204 !Call.onlyAccessesArgMemory(), 2205 "gc.statepoint must read and write all memory to preserve " 2206 "reordering restrictions required by safepoint semantics", 2207 Call); 2208 2209 const int64_t NumPatchBytes = 2210 cast<ConstantInt>(Call.getArgOperand(1))->getSExtValue(); 2211 assert(isInt<32>(NumPatchBytes) && "NumPatchBytesV is an i32!"); 2212 Assert(NumPatchBytes >= 0, 2213 "gc.statepoint number of patchable bytes must be " 2214 "positive", 2215 Call); 2216 2217 const Value *Target = Call.getArgOperand(2); 2218 auto *PT = dyn_cast<PointerType>(Target->getType()); 2219 Assert(PT && PT->getElementType()->isFunctionTy(), 2220 "gc.statepoint callee must be of function pointer type", Call, Target); 2221 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType()); 2222 2223 const int NumCallArgs = cast<ConstantInt>(Call.getArgOperand(3))->getZExtValue(); 2224 Assert(NumCallArgs >= 0, 2225 "gc.statepoint number of arguments to underlying call " 2226 "must be positive", 2227 Call); 2228 const int NumParams = (int)TargetFuncType->getNumParams(); 2229 if (TargetFuncType->isVarArg()) { 2230 Assert(NumCallArgs >= NumParams, 2231 "gc.statepoint mismatch in number of vararg call args", Call); 2232 2233 // TODO: Remove this limitation 2234 Assert(TargetFuncType->getReturnType()->isVoidTy(), 2235 "gc.statepoint doesn't support wrapping non-void " 2236 "vararg functions yet", 2237 Call); 2238 } else 2239 Assert(NumCallArgs == NumParams, 2240 "gc.statepoint mismatch in number of call args", Call); 2241 2242 const uint64_t Flags 2243 = cast<ConstantInt>(Call.getArgOperand(4))->getZExtValue(); 2244 Assert((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0, 2245 "unknown flag used in gc.statepoint flags argument", Call); 2246 2247 // Verify that the types of the call parameter arguments match 2248 // the type of the wrapped callee. 2249 AttributeList Attrs = Call.getAttributes(); 2250 for (int i = 0; i < NumParams; i++) { 2251 Type *ParamType = TargetFuncType->getParamType(i); 2252 Type *ArgType = Call.getArgOperand(5 + i)->getType(); 2253 Assert(ArgType == ParamType, 2254 "gc.statepoint call argument does not match wrapped " 2255 "function type", 2256 Call); 2257 2258 if (TargetFuncType->isVarArg()) { 2259 AttributeSet ArgAttrs = Attrs.getParamAttributes(5 + i); 2260 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet), 2261 "Attribute 'sret' cannot be used for vararg call arguments!", 2262 Call); 2263 } 2264 } 2265 2266 const int EndCallArgsInx = 4 + NumCallArgs; 2267 2268 const Value *NumTransitionArgsV = Call.getArgOperand(EndCallArgsInx + 1); 2269 Assert(isa<ConstantInt>(NumTransitionArgsV), 2270 "gc.statepoint number of transition arguments " 2271 "must be constant integer", 2272 Call); 2273 const int NumTransitionArgs = 2274 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue(); 2275 Assert(NumTransitionArgs == 0, 2276 "gc.statepoint w/inline transition bundle is deprecated", Call); 2277 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs; 2278 2279 const Value *NumDeoptArgsV = Call.getArgOperand(EndTransitionArgsInx + 1); 2280 Assert(isa<ConstantInt>(NumDeoptArgsV), 2281 "gc.statepoint number of deoptimization arguments " 2282 "must be constant integer", 2283 Call); 2284 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue(); 2285 Assert(NumDeoptArgs == 0, 2286 "gc.statepoint w/inline deopt operands is deprecated", Call); 2287 2288 const int ExpectedNumArgs = 7 + NumCallArgs; 2289 Assert(ExpectedNumArgs == (int)Call.arg_size(), 2290 "gc.statepoint too many arguments", Call); 2291 2292 // Check that the only uses of this gc.statepoint are gc.result or 2293 // gc.relocate calls which are tied to this statepoint and thus part 2294 // of the same statepoint sequence 2295 for (const User *U : Call.users()) { 2296 const CallInst *UserCall = dyn_cast<const CallInst>(U); 2297 Assert(UserCall, "illegal use of statepoint token", Call, U); 2298 if (!UserCall) 2299 continue; 2300 Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall), 2301 "gc.result or gc.relocate are the only value uses " 2302 "of a gc.statepoint", 2303 Call, U); 2304 if (isa<GCResultInst>(UserCall)) { 2305 Assert(UserCall->getArgOperand(0) == &Call, 2306 "gc.result connected to wrong gc.statepoint", Call, UserCall); 2307 } else if (isa<GCRelocateInst>(Call)) { 2308 Assert(UserCall->getArgOperand(0) == &Call, 2309 "gc.relocate connected to wrong gc.statepoint", Call, UserCall); 2310 } 2311 } 2312 2313 // Note: It is legal for a single derived pointer to be listed multiple 2314 // times. It's non-optimal, but it is legal. It can also happen after 2315 // insertion if we strip a bitcast away. 2316 // Note: It is really tempting to check that each base is relocated and 2317 // that a derived pointer is never reused as a base pointer. This turns 2318 // out to be problematic since optimizations run after safepoint insertion 2319 // can recognize equality properties that the insertion logic doesn't know 2320 // about. See example statepoint.ll in the verifier subdirectory 2321 } 2322 2323 void Verifier::verifyFrameRecoverIndices() { 2324 for (auto &Counts : FrameEscapeInfo) { 2325 Function *F = Counts.first; 2326 unsigned EscapedObjectCount = Counts.second.first; 2327 unsigned MaxRecoveredIndex = Counts.second.second; 2328 Assert(MaxRecoveredIndex <= EscapedObjectCount, 2329 "all indices passed to llvm.localrecover must be less than the " 2330 "number of arguments passed to llvm.localescape in the parent " 2331 "function", 2332 F); 2333 } 2334 } 2335 2336 static Instruction *getSuccPad(Instruction *Terminator) { 2337 BasicBlock *UnwindDest; 2338 if (auto *II = dyn_cast<InvokeInst>(Terminator)) 2339 UnwindDest = II->getUnwindDest(); 2340 else if (auto *CSI = dyn_cast<CatchSwitchInst>(Terminator)) 2341 UnwindDest = CSI->getUnwindDest(); 2342 else 2343 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest(); 2344 return UnwindDest->getFirstNonPHI(); 2345 } 2346 2347 void Verifier::verifySiblingFuncletUnwinds() { 2348 SmallPtrSet<Instruction *, 8> Visited; 2349 SmallPtrSet<Instruction *, 8> Active; 2350 for (const auto &Pair : SiblingFuncletInfo) { 2351 Instruction *PredPad = Pair.first; 2352 if (Visited.count(PredPad)) 2353 continue; 2354 Active.insert(PredPad); 2355 Instruction *Terminator = Pair.second; 2356 do { 2357 Instruction *SuccPad = getSuccPad(Terminator); 2358 if (Active.count(SuccPad)) { 2359 // Found a cycle; report error 2360 Instruction *CyclePad = SuccPad; 2361 SmallVector<Instruction *, 8> CycleNodes; 2362 do { 2363 CycleNodes.push_back(CyclePad); 2364 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad]; 2365 if (CycleTerminator != CyclePad) 2366 CycleNodes.push_back(CycleTerminator); 2367 CyclePad = getSuccPad(CycleTerminator); 2368 } while (CyclePad != SuccPad); 2369 Assert(false, "EH pads can't handle each other's exceptions", 2370 ArrayRef<Instruction *>(CycleNodes)); 2371 } 2372 // Don't re-walk a node we've already checked 2373 if (!Visited.insert(SuccPad).second) 2374 break; 2375 // Walk to this successor if it has a map entry. 2376 PredPad = SuccPad; 2377 auto TermI = SiblingFuncletInfo.find(PredPad); 2378 if (TermI == SiblingFuncletInfo.end()) 2379 break; 2380 Terminator = TermI->second; 2381 Active.insert(PredPad); 2382 } while (true); 2383 // Each node only has one successor, so we've walked all the active 2384 // nodes' successors. 2385 Active.clear(); 2386 } 2387 } 2388 2389 // visitFunction - Verify that a function is ok. 2390 // 2391 void Verifier::visitFunction(const Function &F) { 2392 visitGlobalValue(F); 2393 2394 // Check function arguments. 2395 FunctionType *FT = F.getFunctionType(); 2396 unsigned NumArgs = F.arg_size(); 2397 2398 Assert(&Context == &F.getContext(), 2399 "Function context does not match Module context!", &F); 2400 2401 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F); 2402 Assert(FT->getNumParams() == NumArgs, 2403 "# formal arguments must match # of arguments for function type!", &F, 2404 FT); 2405 Assert(F.getReturnType()->isFirstClassType() || 2406 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(), 2407 "Functions cannot return aggregate values!", &F); 2408 2409 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(), 2410 "Invalid struct return type!", &F); 2411 2412 AttributeList Attrs = F.getAttributes(); 2413 2414 Assert(verifyAttributeCount(Attrs, FT->getNumParams()), 2415 "Attribute after last parameter!", &F); 2416 2417 bool isLLVMdotName = F.getName().size() >= 5 && 2418 F.getName().substr(0, 5) == "llvm."; 2419 2420 // Check function attributes. 2421 verifyFunctionAttrs(FT, Attrs, &F, isLLVMdotName); 2422 2423 // On function declarations/definitions, we do not support the builtin 2424 // attribute. We do not check this in VerifyFunctionAttrs since that is 2425 // checking for Attributes that can/can not ever be on functions. 2426 Assert(!Attrs.hasFnAttribute(Attribute::Builtin), 2427 "Attribute 'builtin' can only be applied to a callsite.", &F); 2428 2429 // Check that this function meets the restrictions on this calling convention. 2430 // Sometimes varargs is used for perfectly forwarding thunks, so some of these 2431 // restrictions can be lifted. 2432 switch (F.getCallingConv()) { 2433 default: 2434 case CallingConv::C: 2435 break; 2436 case CallingConv::X86_INTR: { 2437 Assert(F.arg_empty() || Attrs.hasParamAttribute(0, Attribute::ByVal), 2438 "Calling convention parameter requires byval", &F); 2439 break; 2440 } 2441 case CallingConv::AMDGPU_KERNEL: 2442 case CallingConv::SPIR_KERNEL: 2443 Assert(F.getReturnType()->isVoidTy(), 2444 "Calling convention requires void return type", &F); 2445 LLVM_FALLTHROUGH; 2446 case CallingConv::AMDGPU_VS: 2447 case CallingConv::AMDGPU_HS: 2448 case CallingConv::AMDGPU_GS: 2449 case CallingConv::AMDGPU_PS: 2450 case CallingConv::AMDGPU_CS: 2451 Assert(!F.hasStructRetAttr(), 2452 "Calling convention does not allow sret", &F); 2453 if (F.getCallingConv() != CallingConv::SPIR_KERNEL) { 2454 const unsigned StackAS = DL.getAllocaAddrSpace(); 2455 unsigned i = 0; 2456 for (const Argument &Arg : F.args()) { 2457 Assert(!Attrs.hasParamAttribute(i, Attribute::ByVal), 2458 "Calling convention disallows byval", &F); 2459 Assert(!Attrs.hasParamAttribute(i, Attribute::Preallocated), 2460 "Calling convention disallows preallocated", &F); 2461 Assert(!Attrs.hasParamAttribute(i, Attribute::InAlloca), 2462 "Calling convention disallows inalloca", &F); 2463 2464 if (Attrs.hasParamAttribute(i, Attribute::ByRef)) { 2465 // FIXME: Should also disallow LDS and GDS, but we don't have the enum 2466 // value here. 2467 Assert(Arg.getType()->getPointerAddressSpace() != StackAS, 2468 "Calling convention disallows stack byref", &F); 2469 } 2470 2471 ++i; 2472 } 2473 } 2474 2475 LLVM_FALLTHROUGH; 2476 case CallingConv::Fast: 2477 case CallingConv::Cold: 2478 case CallingConv::Intel_OCL_BI: 2479 case CallingConv::PTX_Kernel: 2480 case CallingConv::PTX_Device: 2481 Assert(!F.isVarArg(), "Calling convention does not support varargs or " 2482 "perfect forwarding!", 2483 &F); 2484 break; 2485 } 2486 2487 // Check that the argument values match the function type for this function... 2488 unsigned i = 0; 2489 for (const Argument &Arg : F.args()) { 2490 Assert(Arg.getType() == FT->getParamType(i), 2491 "Argument value does not match function argument type!", &Arg, 2492 FT->getParamType(i)); 2493 Assert(Arg.getType()->isFirstClassType(), 2494 "Function arguments must have first-class types!", &Arg); 2495 if (!isLLVMdotName) { 2496 Assert(!Arg.getType()->isMetadataTy(), 2497 "Function takes metadata but isn't an intrinsic", &Arg, &F); 2498 Assert(!Arg.getType()->isTokenTy(), 2499 "Function takes token but isn't an intrinsic", &Arg, &F); 2500 Assert(!Arg.getType()->isX86_AMXTy(), 2501 "Function takes x86_amx but isn't an intrinsic", &Arg, &F); 2502 } 2503 2504 // Check that swifterror argument is only used by loads and stores. 2505 if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) { 2506 verifySwiftErrorValue(&Arg); 2507 } 2508 ++i; 2509 } 2510 2511 if (!isLLVMdotName) { 2512 Assert(!F.getReturnType()->isTokenTy(), 2513 "Function returns a token but isn't an intrinsic", &F); 2514 Assert(!F.getReturnType()->isX86_AMXTy(), 2515 "Function returns a x86_amx but isn't an intrinsic", &F); 2516 } 2517 2518 // Get the function metadata attachments. 2519 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 2520 F.getAllMetadata(MDs); 2521 assert(F.hasMetadata() != MDs.empty() && "Bit out-of-sync"); 2522 verifyFunctionMetadata(MDs); 2523 2524 // Check validity of the personality function 2525 if (F.hasPersonalityFn()) { 2526 auto *Per = dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()); 2527 if (Per) 2528 Assert(Per->getParent() == F.getParent(), 2529 "Referencing personality function in another module!", 2530 &F, F.getParent(), Per, Per->getParent()); 2531 } 2532 2533 if (F.isMaterializable()) { 2534 // Function has a body somewhere we can't see. 2535 Assert(MDs.empty(), "unmaterialized function cannot have metadata", &F, 2536 MDs.empty() ? nullptr : MDs.front().second); 2537 } else if (F.isDeclaration()) { 2538 for (const auto &I : MDs) { 2539 // This is used for call site debug information. 2540 AssertDI(I.first != LLVMContext::MD_dbg || 2541 !cast<DISubprogram>(I.second)->isDistinct(), 2542 "function declaration may only have a unique !dbg attachment", 2543 &F); 2544 Assert(I.first != LLVMContext::MD_prof, 2545 "function declaration may not have a !prof attachment", &F); 2546 2547 // Verify the metadata itself. 2548 visitMDNode(*I.second, AreDebugLocsAllowed::Yes); 2549 } 2550 Assert(!F.hasPersonalityFn(), 2551 "Function declaration shouldn't have a personality routine", &F); 2552 } else { 2553 // Verify that this function (which has a body) is not named "llvm.*". It 2554 // is not legal to define intrinsics. 2555 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F); 2556 2557 // Check the entry node 2558 const BasicBlock *Entry = &F.getEntryBlock(); 2559 Assert(pred_empty(Entry), 2560 "Entry block to function must not have predecessors!", Entry); 2561 2562 // The address of the entry block cannot be taken, unless it is dead. 2563 if (Entry->hasAddressTaken()) { 2564 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(), 2565 "blockaddress may not be used with the entry block!", Entry); 2566 } 2567 2568 unsigned NumDebugAttachments = 0, NumProfAttachments = 0; 2569 // Visit metadata attachments. 2570 for (const auto &I : MDs) { 2571 // Verify that the attachment is legal. 2572 auto AllowLocs = AreDebugLocsAllowed::No; 2573 switch (I.first) { 2574 default: 2575 break; 2576 case LLVMContext::MD_dbg: { 2577 ++NumDebugAttachments; 2578 AssertDI(NumDebugAttachments == 1, 2579 "function must have a single !dbg attachment", &F, I.second); 2580 AssertDI(isa<DISubprogram>(I.second), 2581 "function !dbg attachment must be a subprogram", &F, I.second); 2582 AssertDI(cast<DISubprogram>(I.second)->isDistinct(), 2583 "function definition may only have a distinct !dbg attachment", 2584 &F); 2585 2586 auto *SP = cast<DISubprogram>(I.second); 2587 const Function *&AttachedTo = DISubprogramAttachments[SP]; 2588 AssertDI(!AttachedTo || AttachedTo == &F, 2589 "DISubprogram attached to more than one function", SP, &F); 2590 AttachedTo = &F; 2591 AllowLocs = AreDebugLocsAllowed::Yes; 2592 break; 2593 } 2594 case LLVMContext::MD_prof: 2595 ++NumProfAttachments; 2596 Assert(NumProfAttachments == 1, 2597 "function must have a single !prof attachment", &F, I.second); 2598 break; 2599 } 2600 2601 // Verify the metadata itself. 2602 visitMDNode(*I.second, AllowLocs); 2603 } 2604 } 2605 2606 // If this function is actually an intrinsic, verify that it is only used in 2607 // direct call/invokes, never having its "address taken". 2608 // Only do this if the module is materialized, otherwise we don't have all the 2609 // uses. 2610 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) { 2611 const User *U; 2612 if (F.hasAddressTaken(&U)) 2613 Assert(false, "Invalid user of intrinsic instruction!", U); 2614 } 2615 2616 // Check intrinsics' signatures. 2617 switch (F.getIntrinsicID()) { 2618 case Intrinsic::experimental_gc_get_pointer_base: { 2619 FunctionType *FT = F.getFunctionType(); 2620 Assert(FT->getNumParams() == 1, "wrong number of parameters", F); 2621 Assert(isa<PointerType>(F.getReturnType()), 2622 "gc.get.pointer.base must return a pointer", F); 2623 Assert(FT->getParamType(0) == F.getReturnType(), 2624 "gc.get.pointer.base operand and result must be of the same type", 2625 F); 2626 break; 2627 } 2628 case Intrinsic::experimental_gc_get_pointer_offset: { 2629 FunctionType *FT = F.getFunctionType(); 2630 Assert(FT->getNumParams() == 1, "wrong number of parameters", F); 2631 Assert(isa<PointerType>(FT->getParamType(0)), 2632 "gc.get.pointer.offset operand must be a pointer", F); 2633 Assert(F.getReturnType()->isIntegerTy(), 2634 "gc.get.pointer.offset must return integer", F); 2635 break; 2636 } 2637 } 2638 2639 auto *N = F.getSubprogram(); 2640 HasDebugInfo = (N != nullptr); 2641 if (!HasDebugInfo) 2642 return; 2643 2644 // Check that all !dbg attachments lead to back to N. 2645 // 2646 // FIXME: Check this incrementally while visiting !dbg attachments. 2647 // FIXME: Only check when N is the canonical subprogram for F. 2648 SmallPtrSet<const MDNode *, 32> Seen; 2649 auto VisitDebugLoc = [&](const Instruction &I, const MDNode *Node) { 2650 // Be careful about using DILocation here since we might be dealing with 2651 // broken code (this is the Verifier after all). 2652 const DILocation *DL = dyn_cast_or_null<DILocation>(Node); 2653 if (!DL) 2654 return; 2655 if (!Seen.insert(DL).second) 2656 return; 2657 2658 Metadata *Parent = DL->getRawScope(); 2659 AssertDI(Parent && isa<DILocalScope>(Parent), 2660 "DILocation's scope must be a DILocalScope", N, &F, &I, DL, 2661 Parent); 2662 2663 DILocalScope *Scope = DL->getInlinedAtScope(); 2664 Assert(Scope, "Failed to find DILocalScope", DL); 2665 2666 if (!Seen.insert(Scope).second) 2667 return; 2668 2669 DISubprogram *SP = Scope->getSubprogram(); 2670 2671 // Scope and SP could be the same MDNode and we don't want to skip 2672 // validation in that case 2673 if (SP && ((Scope != SP) && !Seen.insert(SP).second)) 2674 return; 2675 2676 AssertDI(SP->describes(&F), 2677 "!dbg attachment points at wrong subprogram for function", N, &F, 2678 &I, DL, Scope, SP); 2679 }; 2680 for (auto &BB : F) 2681 for (auto &I : BB) { 2682 VisitDebugLoc(I, I.getDebugLoc().getAsMDNode()); 2683 // The llvm.loop annotations also contain two DILocations. 2684 if (auto MD = I.getMetadata(LLVMContext::MD_loop)) 2685 for (unsigned i = 1; i < MD->getNumOperands(); ++i) 2686 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i))); 2687 if (BrokenDebugInfo) 2688 return; 2689 } 2690 } 2691 2692 // verifyBasicBlock - Verify that a basic block is well formed... 2693 // 2694 void Verifier::visitBasicBlock(BasicBlock &BB) { 2695 InstsInThisBlock.clear(); 2696 2697 // Ensure that basic blocks have terminators! 2698 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB); 2699 2700 // Check constraints that this basic block imposes on all of the PHI nodes in 2701 // it. 2702 if (isa<PHINode>(BB.front())) { 2703 SmallVector<BasicBlock *, 8> Preds(predecessors(&BB)); 2704 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values; 2705 llvm::sort(Preds); 2706 for (const PHINode &PN : BB.phis()) { 2707 Assert(PN.getNumIncomingValues() == Preds.size(), 2708 "PHINode should have one entry for each predecessor of its " 2709 "parent basic block!", 2710 &PN); 2711 2712 // Get and sort all incoming values in the PHI node... 2713 Values.clear(); 2714 Values.reserve(PN.getNumIncomingValues()); 2715 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 2716 Values.push_back( 2717 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i))); 2718 llvm::sort(Values); 2719 2720 for (unsigned i = 0, e = Values.size(); i != e; ++i) { 2721 // Check to make sure that if there is more than one entry for a 2722 // particular basic block in this PHI node, that the incoming values are 2723 // all identical. 2724 // 2725 Assert(i == 0 || Values[i].first != Values[i - 1].first || 2726 Values[i].second == Values[i - 1].second, 2727 "PHI node has multiple entries for the same basic block with " 2728 "different incoming values!", 2729 &PN, Values[i].first, Values[i].second, Values[i - 1].second); 2730 2731 // Check to make sure that the predecessors and PHI node entries are 2732 // matched up. 2733 Assert(Values[i].first == Preds[i], 2734 "PHI node entries do not match predecessors!", &PN, 2735 Values[i].first, Preds[i]); 2736 } 2737 } 2738 } 2739 2740 // Check that all instructions have their parent pointers set up correctly. 2741 for (auto &I : BB) 2742 { 2743 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!"); 2744 } 2745 } 2746 2747 void Verifier::visitTerminator(Instruction &I) { 2748 // Ensure that terminators only exist at the end of the basic block. 2749 Assert(&I == I.getParent()->getTerminator(), 2750 "Terminator found in the middle of a basic block!", I.getParent()); 2751 visitInstruction(I); 2752 } 2753 2754 void Verifier::visitBranchInst(BranchInst &BI) { 2755 if (BI.isConditional()) { 2756 Assert(BI.getCondition()->getType()->isIntegerTy(1), 2757 "Branch condition is not 'i1' type!", &BI, BI.getCondition()); 2758 } 2759 visitTerminator(BI); 2760 } 2761 2762 void Verifier::visitReturnInst(ReturnInst &RI) { 2763 Function *F = RI.getParent()->getParent(); 2764 unsigned N = RI.getNumOperands(); 2765 if (F->getReturnType()->isVoidTy()) 2766 Assert(N == 0, 2767 "Found return instr that returns non-void in Function of void " 2768 "return type!", 2769 &RI, F->getReturnType()); 2770 else 2771 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(), 2772 "Function return type does not match operand " 2773 "type of return inst!", 2774 &RI, F->getReturnType()); 2775 2776 // Check to make sure that the return value has necessary properties for 2777 // terminators... 2778 visitTerminator(RI); 2779 } 2780 2781 void Verifier::visitSwitchInst(SwitchInst &SI) { 2782 // Check to make sure that all of the constants in the switch instruction 2783 // have the same type as the switched-on value. 2784 Type *SwitchTy = SI.getCondition()->getType(); 2785 SmallPtrSet<ConstantInt*, 32> Constants; 2786 for (auto &Case : SI.cases()) { 2787 Assert(Case.getCaseValue()->getType() == SwitchTy, 2788 "Switch constants must all be same type as switch value!", &SI); 2789 Assert(Constants.insert(Case.getCaseValue()).second, 2790 "Duplicate integer as switch case", &SI, Case.getCaseValue()); 2791 } 2792 2793 visitTerminator(SI); 2794 } 2795 2796 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) { 2797 Assert(BI.getAddress()->getType()->isPointerTy(), 2798 "Indirectbr operand must have pointer type!", &BI); 2799 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i) 2800 Assert(BI.getDestination(i)->getType()->isLabelTy(), 2801 "Indirectbr destinations must all have pointer type!", &BI); 2802 2803 visitTerminator(BI); 2804 } 2805 2806 void Verifier::visitCallBrInst(CallBrInst &CBI) { 2807 Assert(CBI.isInlineAsm(), "Callbr is currently only used for asm-goto!", 2808 &CBI); 2809 const InlineAsm *IA = cast<InlineAsm>(CBI.getCalledOperand()); 2810 Assert(!IA->canThrow(), "Unwinding from Callbr is not allowed"); 2811 for (unsigned i = 0, e = CBI.getNumSuccessors(); i != e; ++i) 2812 Assert(CBI.getSuccessor(i)->getType()->isLabelTy(), 2813 "Callbr successors must all have pointer type!", &CBI); 2814 for (unsigned i = 0, e = CBI.getNumOperands(); i != e; ++i) { 2815 Assert(i >= CBI.getNumArgOperands() || !isa<BasicBlock>(CBI.getOperand(i)), 2816 "Using an unescaped label as a callbr argument!", &CBI); 2817 if (isa<BasicBlock>(CBI.getOperand(i))) 2818 for (unsigned j = i + 1; j != e; ++j) 2819 Assert(CBI.getOperand(i) != CBI.getOperand(j), 2820 "Duplicate callbr destination!", &CBI); 2821 } 2822 { 2823 SmallPtrSet<BasicBlock *, 4> ArgBBs; 2824 for (Value *V : CBI.args()) 2825 if (auto *BA = dyn_cast<BlockAddress>(V)) 2826 ArgBBs.insert(BA->getBasicBlock()); 2827 for (BasicBlock *BB : CBI.getIndirectDests()) 2828 Assert(ArgBBs.count(BB), "Indirect label missing from arglist.", &CBI); 2829 } 2830 2831 visitTerminator(CBI); 2832 } 2833 2834 void Verifier::visitSelectInst(SelectInst &SI) { 2835 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1), 2836 SI.getOperand(2)), 2837 "Invalid operands for select instruction!", &SI); 2838 2839 Assert(SI.getTrueValue()->getType() == SI.getType(), 2840 "Select values must have same type as select instruction!", &SI); 2841 visitInstruction(SI); 2842 } 2843 2844 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of 2845 /// a pass, if any exist, it's an error. 2846 /// 2847 void Verifier::visitUserOp1(Instruction &I) { 2848 Assert(false, "User-defined operators should not live outside of a pass!", &I); 2849 } 2850 2851 void Verifier::visitTruncInst(TruncInst &I) { 2852 // Get the source and destination types 2853 Type *SrcTy = I.getOperand(0)->getType(); 2854 Type *DestTy = I.getType(); 2855 2856 // Get the size of the types in bits, we'll need this later 2857 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2858 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2859 2860 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I); 2861 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I); 2862 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2863 "trunc source and destination must both be a vector or neither", &I); 2864 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I); 2865 2866 visitInstruction(I); 2867 } 2868 2869 void Verifier::visitZExtInst(ZExtInst &I) { 2870 // Get the source and destination types 2871 Type *SrcTy = I.getOperand(0)->getType(); 2872 Type *DestTy = I.getType(); 2873 2874 // Get the size of the types in bits, we'll need this later 2875 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I); 2876 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I); 2877 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2878 "zext source and destination must both be a vector or neither", &I); 2879 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2880 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2881 2882 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I); 2883 2884 visitInstruction(I); 2885 } 2886 2887 void Verifier::visitSExtInst(SExtInst &I) { 2888 // Get the source and destination types 2889 Type *SrcTy = I.getOperand(0)->getType(); 2890 Type *DestTy = I.getType(); 2891 2892 // Get the size of the types in bits, we'll need this later 2893 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2894 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2895 2896 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I); 2897 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I); 2898 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2899 "sext source and destination must both be a vector or neither", &I); 2900 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I); 2901 2902 visitInstruction(I); 2903 } 2904 2905 void Verifier::visitFPTruncInst(FPTruncInst &I) { 2906 // Get the source and destination types 2907 Type *SrcTy = I.getOperand(0)->getType(); 2908 Type *DestTy = I.getType(); 2909 // Get the size of the types in bits, we'll need this later 2910 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2911 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2912 2913 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I); 2914 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I); 2915 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2916 "fptrunc source and destination must both be a vector or neither", &I); 2917 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I); 2918 2919 visitInstruction(I); 2920 } 2921 2922 void Verifier::visitFPExtInst(FPExtInst &I) { 2923 // Get the source and destination types 2924 Type *SrcTy = I.getOperand(0)->getType(); 2925 Type *DestTy = I.getType(); 2926 2927 // Get the size of the types in bits, we'll need this later 2928 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2929 unsigned DestBitSize = DestTy->getScalarSizeInBits(); 2930 2931 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I); 2932 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I); 2933 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), 2934 "fpext source and destination must both be a vector or neither", &I); 2935 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I); 2936 2937 visitInstruction(I); 2938 } 2939 2940 void Verifier::visitUIToFPInst(UIToFPInst &I) { 2941 // Get the source and destination types 2942 Type *SrcTy = I.getOperand(0)->getType(); 2943 Type *DestTy = I.getType(); 2944 2945 bool SrcVec = SrcTy->isVectorTy(); 2946 bool DstVec = DestTy->isVectorTy(); 2947 2948 Assert(SrcVec == DstVec, 2949 "UIToFP source and dest must both be vector or scalar", &I); 2950 Assert(SrcTy->isIntOrIntVectorTy(), 2951 "UIToFP source must be integer or integer vector", &I); 2952 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector", 2953 &I); 2954 2955 if (SrcVec && DstVec) 2956 Assert(cast<VectorType>(SrcTy)->getElementCount() == 2957 cast<VectorType>(DestTy)->getElementCount(), 2958 "UIToFP source and dest vector length mismatch", &I); 2959 2960 visitInstruction(I); 2961 } 2962 2963 void Verifier::visitSIToFPInst(SIToFPInst &I) { 2964 // Get the source and destination types 2965 Type *SrcTy = I.getOperand(0)->getType(); 2966 Type *DestTy = I.getType(); 2967 2968 bool SrcVec = SrcTy->isVectorTy(); 2969 bool DstVec = DestTy->isVectorTy(); 2970 2971 Assert(SrcVec == DstVec, 2972 "SIToFP source and dest must both be vector or scalar", &I); 2973 Assert(SrcTy->isIntOrIntVectorTy(), 2974 "SIToFP source must be integer or integer vector", &I); 2975 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector", 2976 &I); 2977 2978 if (SrcVec && DstVec) 2979 Assert(cast<VectorType>(SrcTy)->getElementCount() == 2980 cast<VectorType>(DestTy)->getElementCount(), 2981 "SIToFP source and dest vector length mismatch", &I); 2982 2983 visitInstruction(I); 2984 } 2985 2986 void Verifier::visitFPToUIInst(FPToUIInst &I) { 2987 // Get the source and destination types 2988 Type *SrcTy = I.getOperand(0)->getType(); 2989 Type *DestTy = I.getType(); 2990 2991 bool SrcVec = SrcTy->isVectorTy(); 2992 bool DstVec = DestTy->isVectorTy(); 2993 2994 Assert(SrcVec == DstVec, 2995 "FPToUI source and dest must both be vector or scalar", &I); 2996 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector", 2997 &I); 2998 Assert(DestTy->isIntOrIntVectorTy(), 2999 "FPToUI result must be integer or integer vector", &I); 3000 3001 if (SrcVec && DstVec) 3002 Assert(cast<VectorType>(SrcTy)->getElementCount() == 3003 cast<VectorType>(DestTy)->getElementCount(), 3004 "FPToUI source and dest vector length mismatch", &I); 3005 3006 visitInstruction(I); 3007 } 3008 3009 void Verifier::visitFPToSIInst(FPToSIInst &I) { 3010 // Get the source and destination types 3011 Type *SrcTy = I.getOperand(0)->getType(); 3012 Type *DestTy = I.getType(); 3013 3014 bool SrcVec = SrcTy->isVectorTy(); 3015 bool DstVec = DestTy->isVectorTy(); 3016 3017 Assert(SrcVec == DstVec, 3018 "FPToSI source and dest must both be vector or scalar", &I); 3019 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector", 3020 &I); 3021 Assert(DestTy->isIntOrIntVectorTy(), 3022 "FPToSI result must be integer or integer vector", &I); 3023 3024 if (SrcVec && DstVec) 3025 Assert(cast<VectorType>(SrcTy)->getElementCount() == 3026 cast<VectorType>(DestTy)->getElementCount(), 3027 "FPToSI source and dest vector length mismatch", &I); 3028 3029 visitInstruction(I); 3030 } 3031 3032 void Verifier::visitPtrToIntInst(PtrToIntInst &I) { 3033 // Get the source and destination types 3034 Type *SrcTy = I.getOperand(0)->getType(); 3035 Type *DestTy = I.getType(); 3036 3037 Assert(SrcTy->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I); 3038 3039 Assert(DestTy->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I); 3040 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch", 3041 &I); 3042 3043 if (SrcTy->isVectorTy()) { 3044 auto *VSrc = cast<VectorType>(SrcTy); 3045 auto *VDest = cast<VectorType>(DestTy); 3046 Assert(VSrc->getElementCount() == VDest->getElementCount(), 3047 "PtrToInt Vector width mismatch", &I); 3048 } 3049 3050 visitInstruction(I); 3051 } 3052 3053 void Verifier::visitIntToPtrInst(IntToPtrInst &I) { 3054 // Get the source and destination types 3055 Type *SrcTy = I.getOperand(0)->getType(); 3056 Type *DestTy = I.getType(); 3057 3058 Assert(SrcTy->isIntOrIntVectorTy(), 3059 "IntToPtr source must be an integral", &I); 3060 Assert(DestTy->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I); 3061 3062 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch", 3063 &I); 3064 if (SrcTy->isVectorTy()) { 3065 auto *VSrc = cast<VectorType>(SrcTy); 3066 auto *VDest = cast<VectorType>(DestTy); 3067 Assert(VSrc->getElementCount() == VDest->getElementCount(), 3068 "IntToPtr Vector width mismatch", &I); 3069 } 3070 visitInstruction(I); 3071 } 3072 3073 void Verifier::visitBitCastInst(BitCastInst &I) { 3074 Assert( 3075 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()), 3076 "Invalid bitcast", &I); 3077 visitInstruction(I); 3078 } 3079 3080 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) { 3081 Type *SrcTy = I.getOperand(0)->getType(); 3082 Type *DestTy = I.getType(); 3083 3084 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer", 3085 &I); 3086 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer", 3087 &I); 3088 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(), 3089 "AddrSpaceCast must be between different address spaces", &I); 3090 if (auto *SrcVTy = dyn_cast<VectorType>(SrcTy)) 3091 Assert(SrcVTy->getElementCount() == 3092 cast<VectorType>(DestTy)->getElementCount(), 3093 "AddrSpaceCast vector pointer number of elements mismatch", &I); 3094 visitInstruction(I); 3095 } 3096 3097 /// visitPHINode - Ensure that a PHI node is well formed. 3098 /// 3099 void Verifier::visitPHINode(PHINode &PN) { 3100 // Ensure that the PHI nodes are all grouped together at the top of the block. 3101 // This can be tested by checking whether the instruction before this is 3102 // either nonexistent (because this is begin()) or is a PHI node. If not, 3103 // then there is some other instruction before a PHI. 3104 Assert(&PN == &PN.getParent()->front() || 3105 isa<PHINode>(--BasicBlock::iterator(&PN)), 3106 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent()); 3107 3108 // Check that a PHI doesn't yield a Token. 3109 Assert(!PN.getType()->isTokenTy(), "PHI nodes cannot have token type!"); 3110 3111 // Check that all of the values of the PHI node have the same type as the 3112 // result, and that the incoming blocks are really basic blocks. 3113 for (Value *IncValue : PN.incoming_values()) { 3114 Assert(PN.getType() == IncValue->getType(), 3115 "PHI node operands are not the same type as the result!", &PN); 3116 } 3117 3118 // All other PHI node constraints are checked in the visitBasicBlock method. 3119 3120 visitInstruction(PN); 3121 } 3122 3123 void Verifier::visitCallBase(CallBase &Call) { 3124 Assert(Call.getCalledOperand()->getType()->isPointerTy(), 3125 "Called function must be a pointer!", Call); 3126 PointerType *FPTy = cast<PointerType>(Call.getCalledOperand()->getType()); 3127 3128 Assert(FPTy->isOpaqueOrPointeeTypeMatches(Call.getFunctionType()), 3129 "Called function is not the same type as the call!", Call); 3130 3131 FunctionType *FTy = Call.getFunctionType(); 3132 3133 // Verify that the correct number of arguments are being passed 3134 if (FTy->isVarArg()) 3135 Assert(Call.arg_size() >= FTy->getNumParams(), 3136 "Called function requires more parameters than were provided!", 3137 Call); 3138 else 3139 Assert(Call.arg_size() == FTy->getNumParams(), 3140 "Incorrect number of arguments passed to called function!", Call); 3141 3142 // Verify that all arguments to the call match the function type. 3143 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 3144 Assert(Call.getArgOperand(i)->getType() == FTy->getParamType(i), 3145 "Call parameter type does not match function signature!", 3146 Call.getArgOperand(i), FTy->getParamType(i), Call); 3147 3148 AttributeList Attrs = Call.getAttributes(); 3149 3150 Assert(verifyAttributeCount(Attrs, Call.arg_size()), 3151 "Attribute after last parameter!", Call); 3152 3153 bool IsIntrinsic = Call.getCalledFunction() && 3154 Call.getCalledFunction()->getName().startswith("llvm."); 3155 3156 Function *Callee = 3157 dyn_cast<Function>(Call.getCalledOperand()->stripPointerCasts()); 3158 3159 if (Attrs.hasFnAttribute(Attribute::Speculatable)) { 3160 // Don't allow speculatable on call sites, unless the underlying function 3161 // declaration is also speculatable. 3162 Assert(Callee && Callee->isSpeculatable(), 3163 "speculatable attribute may not apply to call sites", Call); 3164 } 3165 3166 if (Attrs.hasFnAttribute(Attribute::Preallocated)) { 3167 Assert(Call.getCalledFunction()->getIntrinsicID() == 3168 Intrinsic::call_preallocated_arg, 3169 "preallocated as a call site attribute can only be on " 3170 "llvm.call.preallocated.arg"); 3171 } 3172 3173 // Verify call attributes. 3174 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic); 3175 3176 // Conservatively check the inalloca argument. 3177 // We have a bug if we can find that there is an underlying alloca without 3178 // inalloca. 3179 if (Call.hasInAllocaArgument()) { 3180 Value *InAllocaArg = Call.getArgOperand(FTy->getNumParams() - 1); 3181 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets())) 3182 Assert(AI->isUsedWithInAlloca(), 3183 "inalloca argument for call has mismatched alloca", AI, Call); 3184 } 3185 3186 // For each argument of the callsite, if it has the swifterror argument, 3187 // make sure the underlying alloca/parameter it comes from has a swifterror as 3188 // well. 3189 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 3190 if (Call.paramHasAttr(i, Attribute::SwiftError)) { 3191 Value *SwiftErrorArg = Call.getArgOperand(i); 3192 if (auto AI = dyn_cast<AllocaInst>(SwiftErrorArg->stripInBoundsOffsets())) { 3193 Assert(AI->isSwiftError(), 3194 "swifterror argument for call has mismatched alloca", AI, Call); 3195 continue; 3196 } 3197 auto ArgI = dyn_cast<Argument>(SwiftErrorArg); 3198 Assert(ArgI, 3199 "swifterror argument should come from an alloca or parameter", 3200 SwiftErrorArg, Call); 3201 Assert(ArgI->hasSwiftErrorAttr(), 3202 "swifterror argument for call has mismatched parameter", ArgI, 3203 Call); 3204 } 3205 3206 if (Attrs.hasParamAttribute(i, Attribute::ImmArg)) { 3207 // Don't allow immarg on call sites, unless the underlying declaration 3208 // also has the matching immarg. 3209 Assert(Callee && Callee->hasParamAttribute(i, Attribute::ImmArg), 3210 "immarg may not apply only to call sites", 3211 Call.getArgOperand(i), Call); 3212 } 3213 3214 if (Call.paramHasAttr(i, Attribute::ImmArg)) { 3215 Value *ArgVal = Call.getArgOperand(i); 3216 Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal), 3217 "immarg operand has non-immediate parameter", ArgVal, Call); 3218 } 3219 3220 if (Call.paramHasAttr(i, Attribute::Preallocated)) { 3221 Value *ArgVal = Call.getArgOperand(i); 3222 bool hasOB = 3223 Call.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0; 3224 bool isMustTail = Call.isMustTailCall(); 3225 Assert(hasOB != isMustTail, 3226 "preallocated operand either requires a preallocated bundle or " 3227 "the call to be musttail (but not both)", 3228 ArgVal, Call); 3229 } 3230 } 3231 3232 if (FTy->isVarArg()) { 3233 // FIXME? is 'nest' even legal here? 3234 bool SawNest = false; 3235 bool SawReturned = false; 3236 3237 for (unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) { 3238 if (Attrs.hasParamAttribute(Idx, Attribute::Nest)) 3239 SawNest = true; 3240 if (Attrs.hasParamAttribute(Idx, Attribute::Returned)) 3241 SawReturned = true; 3242 } 3243 3244 // Check attributes on the varargs part. 3245 for (unsigned Idx = FTy->getNumParams(); Idx < Call.arg_size(); ++Idx) { 3246 Type *Ty = Call.getArgOperand(Idx)->getType(); 3247 AttributeSet ArgAttrs = Attrs.getParamAttributes(Idx); 3248 verifyParameterAttrs(ArgAttrs, Ty, &Call); 3249 3250 if (ArgAttrs.hasAttribute(Attribute::Nest)) { 3251 Assert(!SawNest, "More than one parameter has attribute nest!", Call); 3252 SawNest = true; 3253 } 3254 3255 if (ArgAttrs.hasAttribute(Attribute::Returned)) { 3256 Assert(!SawReturned, "More than one parameter has attribute returned!", 3257 Call); 3258 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()), 3259 "Incompatible argument and return types for 'returned' " 3260 "attribute", 3261 Call); 3262 SawReturned = true; 3263 } 3264 3265 // Statepoint intrinsic is vararg but the wrapped function may be not. 3266 // Allow sret here and check the wrapped function in verifyStatepoint. 3267 if (!Call.getCalledFunction() || 3268 Call.getCalledFunction()->getIntrinsicID() != 3269 Intrinsic::experimental_gc_statepoint) 3270 Assert(!ArgAttrs.hasAttribute(Attribute::StructRet), 3271 "Attribute 'sret' cannot be used for vararg call arguments!", 3272 Call); 3273 3274 if (ArgAttrs.hasAttribute(Attribute::InAlloca)) 3275 Assert(Idx == Call.arg_size() - 1, 3276 "inalloca isn't on the last argument!", Call); 3277 } 3278 } 3279 3280 // Verify that there's no metadata unless it's a direct call to an intrinsic. 3281 if (!IsIntrinsic) { 3282 for (Type *ParamTy : FTy->params()) { 3283 Assert(!ParamTy->isMetadataTy(), 3284 "Function has metadata parameter but isn't an intrinsic", Call); 3285 Assert(!ParamTy->isTokenTy(), 3286 "Function has token parameter but isn't an intrinsic", Call); 3287 } 3288 } 3289 3290 // Verify that indirect calls don't return tokens. 3291 if (!Call.getCalledFunction()) { 3292 Assert(!FTy->getReturnType()->isTokenTy(), 3293 "Return type cannot be token for indirect call!"); 3294 Assert(!FTy->getReturnType()->isX86_AMXTy(), 3295 "Return type cannot be x86_amx for indirect call!"); 3296 } 3297 3298 if (Function *F = Call.getCalledFunction()) 3299 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) 3300 visitIntrinsicCall(ID, Call); 3301 3302 // Verify that a callsite has at most one "deopt", at most one "funclet", at 3303 // most one "gc-transition", at most one "cfguardtarget", 3304 // and at most one "preallocated" operand bundle. 3305 bool FoundDeoptBundle = false, FoundFuncletBundle = false, 3306 FoundGCTransitionBundle = false, FoundCFGuardTargetBundle = false, 3307 FoundPreallocatedBundle = false, FoundGCLiveBundle = false, 3308 FoundAttachedCallBundle = false; 3309 for (unsigned i = 0, e = Call.getNumOperandBundles(); i < e; ++i) { 3310 OperandBundleUse BU = Call.getOperandBundleAt(i); 3311 uint32_t Tag = BU.getTagID(); 3312 if (Tag == LLVMContext::OB_deopt) { 3313 Assert(!FoundDeoptBundle, "Multiple deopt operand bundles", Call); 3314 FoundDeoptBundle = true; 3315 } else if (Tag == LLVMContext::OB_gc_transition) { 3316 Assert(!FoundGCTransitionBundle, "Multiple gc-transition operand bundles", 3317 Call); 3318 FoundGCTransitionBundle = true; 3319 } else if (Tag == LLVMContext::OB_funclet) { 3320 Assert(!FoundFuncletBundle, "Multiple funclet operand bundles", Call); 3321 FoundFuncletBundle = true; 3322 Assert(BU.Inputs.size() == 1, 3323 "Expected exactly one funclet bundle operand", Call); 3324 Assert(isa<FuncletPadInst>(BU.Inputs.front()), 3325 "Funclet bundle operands should correspond to a FuncletPadInst", 3326 Call); 3327 } else if (Tag == LLVMContext::OB_cfguardtarget) { 3328 Assert(!FoundCFGuardTargetBundle, 3329 "Multiple CFGuardTarget operand bundles", Call); 3330 FoundCFGuardTargetBundle = true; 3331 Assert(BU.Inputs.size() == 1, 3332 "Expected exactly one cfguardtarget bundle operand", Call); 3333 } else if (Tag == LLVMContext::OB_preallocated) { 3334 Assert(!FoundPreallocatedBundle, "Multiple preallocated operand bundles", 3335 Call); 3336 FoundPreallocatedBundle = true; 3337 Assert(BU.Inputs.size() == 1, 3338 "Expected exactly one preallocated bundle operand", Call); 3339 auto Input = dyn_cast<IntrinsicInst>(BU.Inputs.front()); 3340 Assert(Input && 3341 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup, 3342 "\"preallocated\" argument must be a token from " 3343 "llvm.call.preallocated.setup", 3344 Call); 3345 } else if (Tag == LLVMContext::OB_gc_live) { 3346 Assert(!FoundGCLiveBundle, "Multiple gc-live operand bundles", 3347 Call); 3348 FoundGCLiveBundle = true; 3349 } else if (Tag == LLVMContext::OB_clang_arc_attachedcall) { 3350 Assert(!FoundAttachedCallBundle, 3351 "Multiple \"clang.arc.attachedcall\" operand bundles", Call); 3352 FoundAttachedCallBundle = true; 3353 } 3354 } 3355 3356 if (FoundAttachedCallBundle) 3357 Assert((FTy->getReturnType()->isPointerTy() || 3358 (Call.doesNotReturn() && FTy->getReturnType()->isVoidTy())), 3359 "a call with operand bundle \"clang.arc.attachedcall\" must call a " 3360 "function returning a pointer or a non-returning function that has " 3361 "a void return type", 3362 Call); 3363 3364 // Verify that each inlinable callsite of a debug-info-bearing function in a 3365 // debug-info-bearing function has a debug location attached to it. Failure to 3366 // do so causes assertion failures when the inliner sets up inline scope info. 3367 if (Call.getFunction()->getSubprogram() && Call.getCalledFunction() && 3368 Call.getCalledFunction()->getSubprogram()) 3369 AssertDI(Call.getDebugLoc(), 3370 "inlinable function call in a function with " 3371 "debug info must have a !dbg location", 3372 Call); 3373 3374 visitInstruction(Call); 3375 } 3376 3377 void Verifier::verifyTailCCMustTailAttrs(AttrBuilder Attrs, 3378 StringRef Context) { 3379 Assert(!Attrs.contains(Attribute::InAlloca), 3380 Twine("inalloca attribute not allowed in ") + Context); 3381 Assert(!Attrs.contains(Attribute::InReg), 3382 Twine("inreg attribute not allowed in ") + Context); 3383 Assert(!Attrs.contains(Attribute::SwiftError), 3384 Twine("swifterror attribute not allowed in ") + Context); 3385 Assert(!Attrs.contains(Attribute::Preallocated), 3386 Twine("preallocated attribute not allowed in ") + Context); 3387 Assert(!Attrs.contains(Attribute::ByRef), 3388 Twine("byref attribute not allowed in ") + Context); 3389 } 3390 3391 /// Two types are "congruent" if they are identical, or if they are both pointer 3392 /// types with different pointee types and the same address space. 3393 static bool isTypeCongruent(Type *L, Type *R) { 3394 if (L == R) 3395 return true; 3396 PointerType *PL = dyn_cast<PointerType>(L); 3397 PointerType *PR = dyn_cast<PointerType>(R); 3398 if (!PL || !PR) 3399 return false; 3400 return PL->getAddressSpace() == PR->getAddressSpace(); 3401 } 3402 3403 static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs) { 3404 static const Attribute::AttrKind ABIAttrs[] = { 3405 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 3406 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf, 3407 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated, 3408 Attribute::ByRef}; 3409 AttrBuilder Copy; 3410 for (auto AK : ABIAttrs) { 3411 if (Attrs.hasParamAttribute(I, AK)) 3412 Copy.addAttribute(AK); 3413 } 3414 3415 // `align` is ABI-affecting only in combination with `byval` or `byref`. 3416 if (Attrs.hasParamAttribute(I, Attribute::Alignment) && 3417 (Attrs.hasParamAttribute(I, Attribute::ByVal) || 3418 Attrs.hasParamAttribute(I, Attribute::ByRef))) 3419 Copy.addAlignmentAttr(Attrs.getParamAlignment(I)); 3420 return Copy; 3421 } 3422 3423 void Verifier::verifyMustTailCall(CallInst &CI) { 3424 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI); 3425 3426 Function *F = CI.getParent()->getParent(); 3427 FunctionType *CallerTy = F->getFunctionType(); 3428 FunctionType *CalleeTy = CI.getFunctionType(); 3429 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(), 3430 "cannot guarantee tail call due to mismatched varargs", &CI); 3431 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()), 3432 "cannot guarantee tail call due to mismatched return types", &CI); 3433 3434 // - The calling conventions of the caller and callee must match. 3435 Assert(F->getCallingConv() == CI.getCallingConv(), 3436 "cannot guarantee tail call due to mismatched calling conv", &CI); 3437 3438 // - The call must immediately precede a :ref:`ret <i_ret>` instruction, 3439 // or a pointer bitcast followed by a ret instruction. 3440 // - The ret instruction must return the (possibly bitcasted) value 3441 // produced by the call or void. 3442 Value *RetVal = &CI; 3443 Instruction *Next = CI.getNextNode(); 3444 3445 // Handle the optional bitcast. 3446 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) { 3447 Assert(BI->getOperand(0) == RetVal, 3448 "bitcast following musttail call must use the call", BI); 3449 RetVal = BI; 3450 Next = BI->getNextNode(); 3451 } 3452 3453 // Check the return. 3454 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next); 3455 Assert(Ret, "musttail call must precede a ret with an optional bitcast", 3456 &CI); 3457 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal || 3458 isa<UndefValue>(Ret->getReturnValue()), 3459 "musttail call result must be returned", Ret); 3460 3461 AttributeList CallerAttrs = F->getAttributes(); 3462 AttributeList CalleeAttrs = CI.getAttributes(); 3463 if (CI.getCallingConv() == CallingConv::SwiftTail || 3464 CI.getCallingConv() == CallingConv::Tail) { 3465 StringRef CCName = 3466 CI.getCallingConv() == CallingConv::Tail ? "tailcc" : "swifttailcc"; 3467 3468 // - Only sret, byval, swiftself, and swiftasync ABI-impacting attributes 3469 // are allowed in swifttailcc call 3470 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 3471 AttrBuilder ABIAttrs = getParameterABIAttributes(I, CallerAttrs); 3472 SmallString<32> Context{CCName, StringRef(" musttail caller")}; 3473 verifyTailCCMustTailAttrs(ABIAttrs, Context); 3474 } 3475 for (int I = 0, E = CalleeTy->getNumParams(); I != E; ++I) { 3476 AttrBuilder ABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 3477 SmallString<32> Context{CCName, StringRef(" musttail callee")}; 3478 verifyTailCCMustTailAttrs(ABIAttrs, Context); 3479 } 3480 // - Varargs functions are not allowed 3481 Assert(!CallerTy->isVarArg(), Twine("cannot guarantee ") + CCName + 3482 " tail call for varargs function"); 3483 return; 3484 } 3485 3486 // - The caller and callee prototypes must match. Pointer types of 3487 // parameters or return types may differ in pointee type, but not 3488 // address space. 3489 if (!CI.getCalledFunction() || !CI.getCalledFunction()->isIntrinsic()) { 3490 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(), 3491 "cannot guarantee tail call due to mismatched parameter counts", 3492 &CI); 3493 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 3494 Assert( 3495 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)), 3496 "cannot guarantee tail call due to mismatched parameter types", &CI); 3497 } 3498 } 3499 3500 // - All ABI-impacting function attributes, such as sret, byval, inreg, 3501 // returned, preallocated, and inalloca, must match. 3502 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) { 3503 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs); 3504 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs); 3505 Assert(CallerABIAttrs == CalleeABIAttrs, 3506 "cannot guarantee tail call due to mismatched ABI impacting " 3507 "function attributes", 3508 &CI, CI.getOperand(I)); 3509 } 3510 } 3511 3512 void Verifier::visitCallInst(CallInst &CI) { 3513 visitCallBase(CI); 3514 3515 if (CI.isMustTailCall()) 3516 verifyMustTailCall(CI); 3517 } 3518 3519 void Verifier::visitInvokeInst(InvokeInst &II) { 3520 visitCallBase(II); 3521 3522 // Verify that the first non-PHI instruction of the unwind destination is an 3523 // exception handling instruction. 3524 Assert( 3525 II.getUnwindDest()->isEHPad(), 3526 "The unwind destination does not have an exception handling instruction!", 3527 &II); 3528 3529 visitTerminator(II); 3530 } 3531 3532 /// visitUnaryOperator - Check the argument to the unary operator. 3533 /// 3534 void Verifier::visitUnaryOperator(UnaryOperator &U) { 3535 Assert(U.getType() == U.getOperand(0)->getType(), 3536 "Unary operators must have same type for" 3537 "operands and result!", 3538 &U); 3539 3540 switch (U.getOpcode()) { 3541 // Check that floating-point arithmetic operators are only used with 3542 // floating-point operands. 3543 case Instruction::FNeg: 3544 Assert(U.getType()->isFPOrFPVectorTy(), 3545 "FNeg operator only works with float types!", &U); 3546 break; 3547 default: 3548 llvm_unreachable("Unknown UnaryOperator opcode!"); 3549 } 3550 3551 visitInstruction(U); 3552 } 3553 3554 /// visitBinaryOperator - Check that both arguments to the binary operator are 3555 /// of the same type! 3556 /// 3557 void Verifier::visitBinaryOperator(BinaryOperator &B) { 3558 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(), 3559 "Both operands to a binary operator are not of the same type!", &B); 3560 3561 switch (B.getOpcode()) { 3562 // Check that integer arithmetic operators are only used with 3563 // integral operands. 3564 case Instruction::Add: 3565 case Instruction::Sub: 3566 case Instruction::Mul: 3567 case Instruction::SDiv: 3568 case Instruction::UDiv: 3569 case Instruction::SRem: 3570 case Instruction::URem: 3571 Assert(B.getType()->isIntOrIntVectorTy(), 3572 "Integer arithmetic operators only work with integral types!", &B); 3573 Assert(B.getType() == B.getOperand(0)->getType(), 3574 "Integer arithmetic operators must have same type " 3575 "for operands and result!", 3576 &B); 3577 break; 3578 // Check that floating-point arithmetic operators are only used with 3579 // floating-point operands. 3580 case Instruction::FAdd: 3581 case Instruction::FSub: 3582 case Instruction::FMul: 3583 case Instruction::FDiv: 3584 case Instruction::FRem: 3585 Assert(B.getType()->isFPOrFPVectorTy(), 3586 "Floating-point arithmetic operators only work with " 3587 "floating-point types!", 3588 &B); 3589 Assert(B.getType() == B.getOperand(0)->getType(), 3590 "Floating-point arithmetic operators must have same type " 3591 "for operands and result!", 3592 &B); 3593 break; 3594 // Check that logical operators are only used with integral operands. 3595 case Instruction::And: 3596 case Instruction::Or: 3597 case Instruction::Xor: 3598 Assert(B.getType()->isIntOrIntVectorTy(), 3599 "Logical operators only work with integral types!", &B); 3600 Assert(B.getType() == B.getOperand(0)->getType(), 3601 "Logical operators must have same type for operands and result!", 3602 &B); 3603 break; 3604 case Instruction::Shl: 3605 case Instruction::LShr: 3606 case Instruction::AShr: 3607 Assert(B.getType()->isIntOrIntVectorTy(), 3608 "Shifts only work with integral types!", &B); 3609 Assert(B.getType() == B.getOperand(0)->getType(), 3610 "Shift return type must be same as operands!", &B); 3611 break; 3612 default: 3613 llvm_unreachable("Unknown BinaryOperator opcode!"); 3614 } 3615 3616 visitInstruction(B); 3617 } 3618 3619 void Verifier::visitICmpInst(ICmpInst &IC) { 3620 // Check that the operands are the same type 3621 Type *Op0Ty = IC.getOperand(0)->getType(); 3622 Type *Op1Ty = IC.getOperand(1)->getType(); 3623 Assert(Op0Ty == Op1Ty, 3624 "Both operands to ICmp instruction are not of the same type!", &IC); 3625 // Check that the operands are the right type 3626 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPtrOrPtrVectorTy(), 3627 "Invalid operand types for ICmp instruction", &IC); 3628 // Check that the predicate is valid. 3629 Assert(IC.isIntPredicate(), 3630 "Invalid predicate in ICmp instruction!", &IC); 3631 3632 visitInstruction(IC); 3633 } 3634 3635 void Verifier::visitFCmpInst(FCmpInst &FC) { 3636 // Check that the operands are the same type 3637 Type *Op0Ty = FC.getOperand(0)->getType(); 3638 Type *Op1Ty = FC.getOperand(1)->getType(); 3639 Assert(Op0Ty == Op1Ty, 3640 "Both operands to FCmp instruction are not of the same type!", &FC); 3641 // Check that the operands are the right type 3642 Assert(Op0Ty->isFPOrFPVectorTy(), 3643 "Invalid operand types for FCmp instruction", &FC); 3644 // Check that the predicate is valid. 3645 Assert(FC.isFPPredicate(), 3646 "Invalid predicate in FCmp instruction!", &FC); 3647 3648 visitInstruction(FC); 3649 } 3650 3651 void Verifier::visitExtractElementInst(ExtractElementInst &EI) { 3652 Assert( 3653 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)), 3654 "Invalid extractelement operands!", &EI); 3655 visitInstruction(EI); 3656 } 3657 3658 void Verifier::visitInsertElementInst(InsertElementInst &IE) { 3659 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1), 3660 IE.getOperand(2)), 3661 "Invalid insertelement operands!", &IE); 3662 visitInstruction(IE); 3663 } 3664 3665 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) { 3666 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1), 3667 SV.getShuffleMask()), 3668 "Invalid shufflevector operands!", &SV); 3669 visitInstruction(SV); 3670 } 3671 3672 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { 3673 Type *TargetTy = GEP.getPointerOperandType()->getScalarType(); 3674 3675 Assert(isa<PointerType>(TargetTy), 3676 "GEP base pointer is not a vector or a vector of pointers", &GEP); 3677 Assert(GEP.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP); 3678 3679 SmallVector<Value *, 16> Idxs(GEP.indices()); 3680 Assert(all_of( 3681 Idxs, [](Value* V) { return V->getType()->isIntOrIntVectorTy(); }), 3682 "GEP indexes must be integers", &GEP); 3683 Type *ElTy = 3684 GetElementPtrInst::getIndexedType(GEP.getSourceElementType(), Idxs); 3685 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP); 3686 3687 Assert(GEP.getType()->isPtrOrPtrVectorTy() && 3688 GEP.getResultElementType() == ElTy, 3689 "GEP is not of right type for indices!", &GEP, ElTy); 3690 3691 if (auto *GEPVTy = dyn_cast<VectorType>(GEP.getType())) { 3692 // Additional checks for vector GEPs. 3693 ElementCount GEPWidth = GEPVTy->getElementCount(); 3694 if (GEP.getPointerOperandType()->isVectorTy()) 3695 Assert( 3696 GEPWidth == 3697 cast<VectorType>(GEP.getPointerOperandType())->getElementCount(), 3698 "Vector GEP result width doesn't match operand's", &GEP); 3699 for (Value *Idx : Idxs) { 3700 Type *IndexTy = Idx->getType(); 3701 if (auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) { 3702 ElementCount IndexWidth = IndexVTy->getElementCount(); 3703 Assert(IndexWidth == GEPWidth, "Invalid GEP index vector width", &GEP); 3704 } 3705 Assert(IndexTy->isIntOrIntVectorTy(), 3706 "All GEP indices should be of integer type"); 3707 } 3708 } 3709 3710 if (auto *PTy = dyn_cast<PointerType>(GEP.getType())) { 3711 Assert(GEP.getAddressSpace() == PTy->getAddressSpace(), 3712 "GEP address space doesn't match type", &GEP); 3713 } 3714 3715 visitInstruction(GEP); 3716 } 3717 3718 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) { 3719 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper(); 3720 } 3721 3722 void Verifier::visitRangeMetadata(Instruction &I, MDNode *Range, Type *Ty) { 3723 assert(Range && Range == I.getMetadata(LLVMContext::MD_range) && 3724 "precondition violation"); 3725 3726 unsigned NumOperands = Range->getNumOperands(); 3727 Assert(NumOperands % 2 == 0, "Unfinished range!", Range); 3728 unsigned NumRanges = NumOperands / 2; 3729 Assert(NumRanges >= 1, "It should have at least one range!", Range); 3730 3731 ConstantRange LastRange(1, true); // Dummy initial value 3732 for (unsigned i = 0; i < NumRanges; ++i) { 3733 ConstantInt *Low = 3734 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i)); 3735 Assert(Low, "The lower limit must be an integer!", Low); 3736 ConstantInt *High = 3737 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1)); 3738 Assert(High, "The upper limit must be an integer!", High); 3739 Assert(High->getType() == Low->getType() && High->getType() == Ty, 3740 "Range types must match instruction type!", &I); 3741 3742 APInt HighV = High->getValue(); 3743 APInt LowV = Low->getValue(); 3744 ConstantRange CurRange(LowV, HighV); 3745 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(), 3746 "Range must not be empty!", Range); 3747 if (i != 0) { 3748 Assert(CurRange.intersectWith(LastRange).isEmptySet(), 3749 "Intervals are overlapping", Range); 3750 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order", 3751 Range); 3752 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous", 3753 Range); 3754 } 3755 LastRange = ConstantRange(LowV, HighV); 3756 } 3757 if (NumRanges > 2) { 3758 APInt FirstLow = 3759 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue(); 3760 APInt FirstHigh = 3761 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue(); 3762 ConstantRange FirstRange(FirstLow, FirstHigh); 3763 Assert(FirstRange.intersectWith(LastRange).isEmptySet(), 3764 "Intervals are overlapping", Range); 3765 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous", 3766 Range); 3767 } 3768 } 3769 3770 void Verifier::checkAtomicMemAccessSize(Type *Ty, const Instruction *I) { 3771 unsigned Size = DL.getTypeSizeInBits(Ty); 3772 Assert(Size >= 8, "atomic memory access' size must be byte-sized", Ty, I); 3773 Assert(!(Size & (Size - 1)), 3774 "atomic memory access' operand must have a power-of-two size", Ty, I); 3775 } 3776 3777 void Verifier::visitLoadInst(LoadInst &LI) { 3778 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType()); 3779 Assert(PTy, "Load operand must be a pointer.", &LI); 3780 Type *ElTy = LI.getType(); 3781 Assert(LI.getAlignment() <= Value::MaximumAlignment, 3782 "huge alignment values are unsupported", &LI); 3783 Assert(ElTy->isSized(), "loading unsized types is not allowed", &LI); 3784 if (LI.isAtomic()) { 3785 Assert(LI.getOrdering() != AtomicOrdering::Release && 3786 LI.getOrdering() != AtomicOrdering::AcquireRelease, 3787 "Load cannot have Release ordering", &LI); 3788 Assert(LI.getAlignment() != 0, 3789 "Atomic load must specify explicit alignment", &LI); 3790 Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(), 3791 "atomic load operand must have integer, pointer, or floating point " 3792 "type!", 3793 ElTy, &LI); 3794 checkAtomicMemAccessSize(ElTy, &LI); 3795 } else { 3796 Assert(LI.getSyncScopeID() == SyncScope::System, 3797 "Non-atomic load cannot have SynchronizationScope specified", &LI); 3798 } 3799 3800 visitInstruction(LI); 3801 } 3802 3803 void Verifier::visitStoreInst(StoreInst &SI) { 3804 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType()); 3805 Assert(PTy, "Store operand must be a pointer.", &SI); 3806 Type *ElTy = SI.getOperand(0)->getType(); 3807 Assert(PTy->isOpaqueOrPointeeTypeMatches(ElTy), 3808 "Stored value type does not match pointer operand type!", &SI, ElTy); 3809 Assert(SI.getAlignment() <= Value::MaximumAlignment, 3810 "huge alignment values are unsupported", &SI); 3811 Assert(ElTy->isSized(), "storing unsized types is not allowed", &SI); 3812 if (SI.isAtomic()) { 3813 Assert(SI.getOrdering() != AtomicOrdering::Acquire && 3814 SI.getOrdering() != AtomicOrdering::AcquireRelease, 3815 "Store cannot have Acquire ordering", &SI); 3816 Assert(SI.getAlignment() != 0, 3817 "Atomic store must specify explicit alignment", &SI); 3818 Assert(ElTy->isIntOrPtrTy() || ElTy->isFloatingPointTy(), 3819 "atomic store operand must have integer, pointer, or floating point " 3820 "type!", 3821 ElTy, &SI); 3822 checkAtomicMemAccessSize(ElTy, &SI); 3823 } else { 3824 Assert(SI.getSyncScopeID() == SyncScope::System, 3825 "Non-atomic store cannot have SynchronizationScope specified", &SI); 3826 } 3827 visitInstruction(SI); 3828 } 3829 3830 /// Check that SwiftErrorVal is used as a swifterror argument in CS. 3831 void Verifier::verifySwiftErrorCall(CallBase &Call, 3832 const Value *SwiftErrorVal) { 3833 for (const auto &I : llvm::enumerate(Call.args())) { 3834 if (I.value() == SwiftErrorVal) { 3835 Assert(Call.paramHasAttr(I.index(), Attribute::SwiftError), 3836 "swifterror value when used in a callsite should be marked " 3837 "with swifterror attribute", 3838 SwiftErrorVal, Call); 3839 } 3840 } 3841 } 3842 3843 void Verifier::verifySwiftErrorValue(const Value *SwiftErrorVal) { 3844 // Check that swifterror value is only used by loads, stores, or as 3845 // a swifterror argument. 3846 for (const User *U : SwiftErrorVal->users()) { 3847 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) || 3848 isa<InvokeInst>(U), 3849 "swifterror value can only be loaded and stored from, or " 3850 "as a swifterror argument!", 3851 SwiftErrorVal, U); 3852 // If it is used by a store, check it is the second operand. 3853 if (auto StoreI = dyn_cast<StoreInst>(U)) 3854 Assert(StoreI->getOperand(1) == SwiftErrorVal, 3855 "swifterror value should be the second operand when used " 3856 "by stores", SwiftErrorVal, U); 3857 if (auto *Call = dyn_cast<CallBase>(U)) 3858 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal); 3859 } 3860 } 3861 3862 void Verifier::visitAllocaInst(AllocaInst &AI) { 3863 SmallPtrSet<Type*, 4> Visited; 3864 Assert(AI.getAllocatedType()->isSized(&Visited), 3865 "Cannot allocate unsized type", &AI); 3866 Assert(AI.getArraySize()->getType()->isIntegerTy(), 3867 "Alloca array size must have integer type", &AI); 3868 Assert(AI.getAlignment() <= Value::MaximumAlignment, 3869 "huge alignment values are unsupported", &AI); 3870 3871 if (AI.isSwiftError()) { 3872 verifySwiftErrorValue(&AI); 3873 } 3874 3875 visitInstruction(AI); 3876 } 3877 3878 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) { 3879 Type *ElTy = CXI.getOperand(1)->getType(); 3880 Assert(ElTy->isIntOrPtrTy(), 3881 "cmpxchg operand must have integer or pointer type", ElTy, &CXI); 3882 checkAtomicMemAccessSize(ElTy, &CXI); 3883 visitInstruction(CXI); 3884 } 3885 3886 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) { 3887 Assert(RMWI.getOrdering() != AtomicOrdering::Unordered, 3888 "atomicrmw instructions cannot be unordered.", &RMWI); 3889 auto Op = RMWI.getOperation(); 3890 Type *ElTy = RMWI.getOperand(1)->getType(); 3891 if (Op == AtomicRMWInst::Xchg) { 3892 Assert(ElTy->isIntegerTy() || ElTy->isFloatingPointTy(), "atomicrmw " + 3893 AtomicRMWInst::getOperationName(Op) + 3894 " operand must have integer or floating point type!", 3895 &RMWI, ElTy); 3896 } else if (AtomicRMWInst::isFPOperation(Op)) { 3897 Assert(ElTy->isFloatingPointTy(), "atomicrmw " + 3898 AtomicRMWInst::getOperationName(Op) + 3899 " operand must have floating point type!", 3900 &RMWI, ElTy); 3901 } else { 3902 Assert(ElTy->isIntegerTy(), "atomicrmw " + 3903 AtomicRMWInst::getOperationName(Op) + 3904 " operand must have integer type!", 3905 &RMWI, ElTy); 3906 } 3907 checkAtomicMemAccessSize(ElTy, &RMWI); 3908 Assert(AtomicRMWInst::FIRST_BINOP <= Op && Op <= AtomicRMWInst::LAST_BINOP, 3909 "Invalid binary operation!", &RMWI); 3910 visitInstruction(RMWI); 3911 } 3912 3913 void Verifier::visitFenceInst(FenceInst &FI) { 3914 const AtomicOrdering Ordering = FI.getOrdering(); 3915 Assert(Ordering == AtomicOrdering::Acquire || 3916 Ordering == AtomicOrdering::Release || 3917 Ordering == AtomicOrdering::AcquireRelease || 3918 Ordering == AtomicOrdering::SequentiallyConsistent, 3919 "fence instructions may only have acquire, release, acq_rel, or " 3920 "seq_cst ordering.", 3921 &FI); 3922 visitInstruction(FI); 3923 } 3924 3925 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) { 3926 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(), 3927 EVI.getIndices()) == EVI.getType(), 3928 "Invalid ExtractValueInst operands!", &EVI); 3929 3930 visitInstruction(EVI); 3931 } 3932 3933 void Verifier::visitInsertValueInst(InsertValueInst &IVI) { 3934 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(), 3935 IVI.getIndices()) == 3936 IVI.getOperand(1)->getType(), 3937 "Invalid InsertValueInst operands!", &IVI); 3938 3939 visitInstruction(IVI); 3940 } 3941 3942 static Value *getParentPad(Value *EHPad) { 3943 if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) 3944 return FPI->getParentPad(); 3945 3946 return cast<CatchSwitchInst>(EHPad)->getParentPad(); 3947 } 3948 3949 void Verifier::visitEHPadPredecessors(Instruction &I) { 3950 assert(I.isEHPad()); 3951 3952 BasicBlock *BB = I.getParent(); 3953 Function *F = BB->getParent(); 3954 3955 Assert(BB != &F->getEntryBlock(), "EH pad cannot be in entry block.", &I); 3956 3957 if (auto *LPI = dyn_cast<LandingPadInst>(&I)) { 3958 // The landingpad instruction defines its parent as a landing pad block. The 3959 // landing pad block may be branched to only by the unwind edge of an 3960 // invoke. 3961 for (BasicBlock *PredBB : predecessors(BB)) { 3962 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator()); 3963 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB, 3964 "Block containing LandingPadInst must be jumped to " 3965 "only by the unwind edge of an invoke.", 3966 LPI); 3967 } 3968 return; 3969 } 3970 if (auto *CPI = dyn_cast<CatchPadInst>(&I)) { 3971 if (!pred_empty(BB)) 3972 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(), 3973 "Block containg CatchPadInst must be jumped to " 3974 "only by its catchswitch.", 3975 CPI); 3976 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(), 3977 "Catchswitch cannot unwind to one of its catchpads", 3978 CPI->getCatchSwitch(), CPI); 3979 return; 3980 } 3981 3982 // Verify that each pred has a legal terminator with a legal to/from EH 3983 // pad relationship. 3984 Instruction *ToPad = &I; 3985 Value *ToPadParent = getParentPad(ToPad); 3986 for (BasicBlock *PredBB : predecessors(BB)) { 3987 Instruction *TI = PredBB->getTerminator(); 3988 Value *FromPad; 3989 if (auto *II = dyn_cast<InvokeInst>(TI)) { 3990 Assert(II->getUnwindDest() == BB && II->getNormalDest() != BB, 3991 "EH pad must be jumped to via an unwind edge", ToPad, II); 3992 if (auto Bundle = II->getOperandBundle(LLVMContext::OB_funclet)) 3993 FromPad = Bundle->Inputs[0]; 3994 else 3995 FromPad = ConstantTokenNone::get(II->getContext()); 3996 } else if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) { 3997 FromPad = CRI->getOperand(0); 3998 Assert(FromPad != ToPadParent, "A cleanupret must exit its cleanup", CRI); 3999 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) { 4000 FromPad = CSI; 4001 } else { 4002 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad, TI); 4003 } 4004 4005 // The edge may exit from zero or more nested pads. 4006 SmallSet<Value *, 8> Seen; 4007 for (;; FromPad = getParentPad(FromPad)) { 4008 Assert(FromPad != ToPad, 4009 "EH pad cannot handle exceptions raised within it", FromPad, TI); 4010 if (FromPad == ToPadParent) { 4011 // This is a legal unwind edge. 4012 break; 4013 } 4014 Assert(!isa<ConstantTokenNone>(FromPad), 4015 "A single unwind edge may only enter one EH pad", TI); 4016 Assert(Seen.insert(FromPad).second, 4017 "EH pad jumps through a cycle of pads", FromPad); 4018 } 4019 } 4020 } 4021 4022 void Verifier::visitLandingPadInst(LandingPadInst &LPI) { 4023 // The landingpad instruction is ill-formed if it doesn't have any clauses and 4024 // isn't a cleanup. 4025 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(), 4026 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI); 4027 4028 visitEHPadPredecessors(LPI); 4029 4030 if (!LandingPadResultTy) 4031 LandingPadResultTy = LPI.getType(); 4032 else 4033 Assert(LandingPadResultTy == LPI.getType(), 4034 "The landingpad instruction should have a consistent result type " 4035 "inside a function.", 4036 &LPI); 4037 4038 Function *F = LPI.getParent()->getParent(); 4039 Assert(F->hasPersonalityFn(), 4040 "LandingPadInst needs to be in a function with a personality.", &LPI); 4041 4042 // The landingpad instruction must be the first non-PHI instruction in the 4043 // block. 4044 Assert(LPI.getParent()->getLandingPadInst() == &LPI, 4045 "LandingPadInst not the first non-PHI instruction in the block.", 4046 &LPI); 4047 4048 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) { 4049 Constant *Clause = LPI.getClause(i); 4050 if (LPI.isCatch(i)) { 4051 Assert(isa<PointerType>(Clause->getType()), 4052 "Catch operand does not have pointer type!", &LPI); 4053 } else { 4054 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI); 4055 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause), 4056 "Filter operand is not an array of constants!", &LPI); 4057 } 4058 } 4059 4060 visitInstruction(LPI); 4061 } 4062 4063 void Verifier::visitResumeInst(ResumeInst &RI) { 4064 Assert(RI.getFunction()->hasPersonalityFn(), 4065 "ResumeInst needs to be in a function with a personality.", &RI); 4066 4067 if (!LandingPadResultTy) 4068 LandingPadResultTy = RI.getValue()->getType(); 4069 else 4070 Assert(LandingPadResultTy == RI.getValue()->getType(), 4071 "The resume instruction should have a consistent result type " 4072 "inside a function.", 4073 &RI); 4074 4075 visitTerminator(RI); 4076 } 4077 4078 void Verifier::visitCatchPadInst(CatchPadInst &CPI) { 4079 BasicBlock *BB = CPI.getParent(); 4080 4081 Function *F = BB->getParent(); 4082 Assert(F->hasPersonalityFn(), 4083 "CatchPadInst needs to be in a function with a personality.", &CPI); 4084 4085 Assert(isa<CatchSwitchInst>(CPI.getParentPad()), 4086 "CatchPadInst needs to be directly nested in a CatchSwitchInst.", 4087 CPI.getParentPad()); 4088 4089 // The catchpad instruction must be the first non-PHI instruction in the 4090 // block. 4091 Assert(BB->getFirstNonPHI() == &CPI, 4092 "CatchPadInst not the first non-PHI instruction in the block.", &CPI); 4093 4094 visitEHPadPredecessors(CPI); 4095 visitFuncletPadInst(CPI); 4096 } 4097 4098 void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) { 4099 Assert(isa<CatchPadInst>(CatchReturn.getOperand(0)), 4100 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn, 4101 CatchReturn.getOperand(0)); 4102 4103 visitTerminator(CatchReturn); 4104 } 4105 4106 void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) { 4107 BasicBlock *BB = CPI.getParent(); 4108 4109 Function *F = BB->getParent(); 4110 Assert(F->hasPersonalityFn(), 4111 "CleanupPadInst needs to be in a function with a personality.", &CPI); 4112 4113 // The cleanuppad instruction must be the first non-PHI instruction in the 4114 // block. 4115 Assert(BB->getFirstNonPHI() == &CPI, 4116 "CleanupPadInst not the first non-PHI instruction in the block.", 4117 &CPI); 4118 4119 auto *ParentPad = CPI.getParentPad(); 4120 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 4121 "CleanupPadInst has an invalid parent.", &CPI); 4122 4123 visitEHPadPredecessors(CPI); 4124 visitFuncletPadInst(CPI); 4125 } 4126 4127 void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) { 4128 User *FirstUser = nullptr; 4129 Value *FirstUnwindPad = nullptr; 4130 SmallVector<FuncletPadInst *, 8> Worklist({&FPI}); 4131 SmallSet<FuncletPadInst *, 8> Seen; 4132 4133 while (!Worklist.empty()) { 4134 FuncletPadInst *CurrentPad = Worklist.pop_back_val(); 4135 Assert(Seen.insert(CurrentPad).second, 4136 "FuncletPadInst must not be nested within itself", CurrentPad); 4137 Value *UnresolvedAncestorPad = nullptr; 4138 for (User *U : CurrentPad->users()) { 4139 BasicBlock *UnwindDest; 4140 if (auto *CRI = dyn_cast<CleanupReturnInst>(U)) { 4141 UnwindDest = CRI->getUnwindDest(); 4142 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(U)) { 4143 // We allow catchswitch unwind to caller to nest 4144 // within an outer pad that unwinds somewhere else, 4145 // because catchswitch doesn't have a nounwind variant. 4146 // See e.g. SimplifyCFGOpt::SimplifyUnreachable. 4147 if (CSI->unwindsToCaller()) 4148 continue; 4149 UnwindDest = CSI->getUnwindDest(); 4150 } else if (auto *II = dyn_cast<InvokeInst>(U)) { 4151 UnwindDest = II->getUnwindDest(); 4152 } else if (isa<CallInst>(U)) { 4153 // Calls which don't unwind may be found inside funclet 4154 // pads that unwind somewhere else. We don't *require* 4155 // such calls to be annotated nounwind. 4156 continue; 4157 } else if (auto *CPI = dyn_cast<CleanupPadInst>(U)) { 4158 // The unwind dest for a cleanup can only be found by 4159 // recursive search. Add it to the worklist, and we'll 4160 // search for its first use that determines where it unwinds. 4161 Worklist.push_back(CPI); 4162 continue; 4163 } else { 4164 Assert(isa<CatchReturnInst>(U), "Bogus funclet pad use", U); 4165 continue; 4166 } 4167 4168 Value *UnwindPad; 4169 bool ExitsFPI; 4170 if (UnwindDest) { 4171 UnwindPad = UnwindDest->getFirstNonPHI(); 4172 if (!cast<Instruction>(UnwindPad)->isEHPad()) 4173 continue; 4174 Value *UnwindParent = getParentPad(UnwindPad); 4175 // Ignore unwind edges that don't exit CurrentPad. 4176 if (UnwindParent == CurrentPad) 4177 continue; 4178 // Determine whether the original funclet pad is exited, 4179 // and if we are scanning nested pads determine how many 4180 // of them are exited so we can stop searching their 4181 // children. 4182 Value *ExitedPad = CurrentPad; 4183 ExitsFPI = false; 4184 do { 4185 if (ExitedPad == &FPI) { 4186 ExitsFPI = true; 4187 // Now we can resolve any ancestors of CurrentPad up to 4188 // FPI, but not including FPI since we need to make sure 4189 // to check all direct users of FPI for consistency. 4190 UnresolvedAncestorPad = &FPI; 4191 break; 4192 } 4193 Value *ExitedParent = getParentPad(ExitedPad); 4194 if (ExitedParent == UnwindParent) { 4195 // ExitedPad is the ancestor-most pad which this unwind 4196 // edge exits, so we can resolve up to it, meaning that 4197 // ExitedParent is the first ancestor still unresolved. 4198 UnresolvedAncestorPad = ExitedParent; 4199 break; 4200 } 4201 ExitedPad = ExitedParent; 4202 } while (!isa<ConstantTokenNone>(ExitedPad)); 4203 } else { 4204 // Unwinding to caller exits all pads. 4205 UnwindPad = ConstantTokenNone::get(FPI.getContext()); 4206 ExitsFPI = true; 4207 UnresolvedAncestorPad = &FPI; 4208 } 4209 4210 if (ExitsFPI) { 4211 // This unwind edge exits FPI. Make sure it agrees with other 4212 // such edges. 4213 if (FirstUser) { 4214 Assert(UnwindPad == FirstUnwindPad, "Unwind edges out of a funclet " 4215 "pad must have the same unwind " 4216 "dest", 4217 &FPI, U, FirstUser); 4218 } else { 4219 FirstUser = U; 4220 FirstUnwindPad = UnwindPad; 4221 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds 4222 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) && 4223 getParentPad(UnwindPad) == getParentPad(&FPI)) 4224 SiblingFuncletInfo[&FPI] = cast<Instruction>(U); 4225 } 4226 } 4227 // Make sure we visit all uses of FPI, but for nested pads stop as 4228 // soon as we know where they unwind to. 4229 if (CurrentPad != &FPI) 4230 break; 4231 } 4232 if (UnresolvedAncestorPad) { 4233 if (CurrentPad == UnresolvedAncestorPad) { 4234 // When CurrentPad is FPI itself, we don't mark it as resolved even if 4235 // we've found an unwind edge that exits it, because we need to verify 4236 // all direct uses of FPI. 4237 assert(CurrentPad == &FPI); 4238 continue; 4239 } 4240 // Pop off the worklist any nested pads that we've found an unwind 4241 // destination for. The pads on the worklist are the uncles, 4242 // great-uncles, etc. of CurrentPad. We've found an unwind destination 4243 // for all ancestors of CurrentPad up to but not including 4244 // UnresolvedAncestorPad. 4245 Value *ResolvedPad = CurrentPad; 4246 while (!Worklist.empty()) { 4247 Value *UnclePad = Worklist.back(); 4248 Value *AncestorPad = getParentPad(UnclePad); 4249 // Walk ResolvedPad up the ancestor list until we either find the 4250 // uncle's parent or the last resolved ancestor. 4251 while (ResolvedPad != AncestorPad) { 4252 Value *ResolvedParent = getParentPad(ResolvedPad); 4253 if (ResolvedParent == UnresolvedAncestorPad) { 4254 break; 4255 } 4256 ResolvedPad = ResolvedParent; 4257 } 4258 // If the resolved ancestor search didn't find the uncle's parent, 4259 // then the uncle is not yet resolved. 4260 if (ResolvedPad != AncestorPad) 4261 break; 4262 // This uncle is resolved, so pop it from the worklist. 4263 Worklist.pop_back(); 4264 } 4265 } 4266 } 4267 4268 if (FirstUnwindPad) { 4269 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.getParentPad())) { 4270 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest(); 4271 Value *SwitchUnwindPad; 4272 if (SwitchUnwindDest) 4273 SwitchUnwindPad = SwitchUnwindDest->getFirstNonPHI(); 4274 else 4275 SwitchUnwindPad = ConstantTokenNone::get(FPI.getContext()); 4276 Assert(SwitchUnwindPad == FirstUnwindPad, 4277 "Unwind edges out of a catch must have the same unwind dest as " 4278 "the parent catchswitch", 4279 &FPI, FirstUser, CatchSwitch); 4280 } 4281 } 4282 4283 visitInstruction(FPI); 4284 } 4285 4286 void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) { 4287 BasicBlock *BB = CatchSwitch.getParent(); 4288 4289 Function *F = BB->getParent(); 4290 Assert(F->hasPersonalityFn(), 4291 "CatchSwitchInst needs to be in a function with a personality.", 4292 &CatchSwitch); 4293 4294 // The catchswitch instruction must be the first non-PHI instruction in the 4295 // block. 4296 Assert(BB->getFirstNonPHI() == &CatchSwitch, 4297 "CatchSwitchInst not the first non-PHI instruction in the block.", 4298 &CatchSwitch); 4299 4300 auto *ParentPad = CatchSwitch.getParentPad(); 4301 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad), 4302 "CatchSwitchInst has an invalid parent.", ParentPad); 4303 4304 if (BasicBlock *UnwindDest = CatchSwitch.getUnwindDest()) { 4305 Instruction *I = UnwindDest->getFirstNonPHI(); 4306 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 4307 "CatchSwitchInst must unwind to an EH block which is not a " 4308 "landingpad.", 4309 &CatchSwitch); 4310 4311 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds 4312 if (getParentPad(I) == ParentPad) 4313 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch; 4314 } 4315 4316 Assert(CatchSwitch.getNumHandlers() != 0, 4317 "CatchSwitchInst cannot have empty handler list", &CatchSwitch); 4318 4319 for (BasicBlock *Handler : CatchSwitch.handlers()) { 4320 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()), 4321 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler); 4322 } 4323 4324 visitEHPadPredecessors(CatchSwitch); 4325 visitTerminator(CatchSwitch); 4326 } 4327 4328 void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) { 4329 Assert(isa<CleanupPadInst>(CRI.getOperand(0)), 4330 "CleanupReturnInst needs to be provided a CleanupPad", &CRI, 4331 CRI.getOperand(0)); 4332 4333 if (BasicBlock *UnwindDest = CRI.getUnwindDest()) { 4334 Instruction *I = UnwindDest->getFirstNonPHI(); 4335 Assert(I->isEHPad() && !isa<LandingPadInst>(I), 4336 "CleanupReturnInst must unwind to an EH block which is not a " 4337 "landingpad.", 4338 &CRI); 4339 } 4340 4341 visitTerminator(CRI); 4342 } 4343 4344 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) { 4345 Instruction *Op = cast<Instruction>(I.getOperand(i)); 4346 // If the we have an invalid invoke, don't try to compute the dominance. 4347 // We already reject it in the invoke specific checks and the dominance 4348 // computation doesn't handle multiple edges. 4349 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) { 4350 if (II->getNormalDest() == II->getUnwindDest()) 4351 return; 4352 } 4353 4354 // Quick check whether the def has already been encountered in the same block. 4355 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI 4356 // uses are defined to happen on the incoming edge, not at the instruction. 4357 // 4358 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata) 4359 // wrapping an SSA value, assert that we've already encountered it. See 4360 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp. 4361 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op)) 4362 return; 4363 4364 const Use &U = I.getOperandUse(i); 4365 Assert(DT.dominates(Op, U), 4366 "Instruction does not dominate all uses!", Op, &I); 4367 } 4368 4369 void Verifier::visitDereferenceableMetadata(Instruction& I, MDNode* MD) { 4370 Assert(I.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null " 4371 "apply only to pointer types", &I); 4372 Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)), 4373 "dereferenceable, dereferenceable_or_null apply only to load" 4374 " and inttoptr instructions, use attributes for calls or invokes", &I); 4375 Assert(MD->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null " 4376 "take one operand!", &I); 4377 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 4378 Assert(CI && CI->getType()->isIntegerTy(64), "dereferenceable, " 4379 "dereferenceable_or_null metadata value must be an i64!", &I); 4380 } 4381 4382 void Verifier::visitProfMetadata(Instruction &I, MDNode *MD) { 4383 Assert(MD->getNumOperands() >= 2, 4384 "!prof annotations should have no less than 2 operands", MD); 4385 4386 // Check first operand. 4387 Assert(MD->getOperand(0) != nullptr, "first operand should not be null", MD); 4388 Assert(isa<MDString>(MD->getOperand(0)), 4389 "expected string with name of the !prof annotation", MD); 4390 MDString *MDS = cast<MDString>(MD->getOperand(0)); 4391 StringRef ProfName = MDS->getString(); 4392 4393 // Check consistency of !prof branch_weights metadata. 4394 if (ProfName.equals("branch_weights")) { 4395 if (isa<InvokeInst>(&I)) { 4396 Assert(MD->getNumOperands() == 2 || MD->getNumOperands() == 3, 4397 "Wrong number of InvokeInst branch_weights operands", MD); 4398 } else { 4399 unsigned ExpectedNumOperands = 0; 4400 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 4401 ExpectedNumOperands = BI->getNumSuccessors(); 4402 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 4403 ExpectedNumOperands = SI->getNumSuccessors(); 4404 else if (isa<CallInst>(&I)) 4405 ExpectedNumOperands = 1; 4406 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 4407 ExpectedNumOperands = IBI->getNumDestinations(); 4408 else if (isa<SelectInst>(&I)) 4409 ExpectedNumOperands = 2; 4410 else 4411 CheckFailed("!prof branch_weights are not allowed for this instruction", 4412 MD); 4413 4414 Assert(MD->getNumOperands() == 1 + ExpectedNumOperands, 4415 "Wrong number of operands", MD); 4416 } 4417 for (unsigned i = 1; i < MD->getNumOperands(); ++i) { 4418 auto &MDO = MD->getOperand(i); 4419 Assert(MDO, "second operand should not be null", MD); 4420 Assert(mdconst::dyn_extract<ConstantInt>(MDO), 4421 "!prof brunch_weights operand is not a const int"); 4422 } 4423 } 4424 } 4425 4426 void Verifier::visitAnnotationMetadata(MDNode *Annotation) { 4427 Assert(isa<MDTuple>(Annotation), "annotation must be a tuple"); 4428 Assert(Annotation->getNumOperands() >= 1, 4429 "annotation must have at least one operand"); 4430 for (const MDOperand &Op : Annotation->operands()) 4431 Assert(isa<MDString>(Op.get()), "operands must be strings"); 4432 } 4433 4434 /// verifyInstruction - Verify that an instruction is well formed. 4435 /// 4436 void Verifier::visitInstruction(Instruction &I) { 4437 BasicBlock *BB = I.getParent(); 4438 Assert(BB, "Instruction not embedded in basic block!", &I); 4439 4440 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential 4441 for (User *U : I.users()) { 4442 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB), 4443 "Only PHI nodes may reference their own value!", &I); 4444 } 4445 } 4446 4447 // Check that void typed values don't have names 4448 Assert(!I.getType()->isVoidTy() || !I.hasName(), 4449 "Instruction has a name, but provides a void value!", &I); 4450 4451 // Check that the return value of the instruction is either void or a legal 4452 // value type. 4453 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(), 4454 "Instruction returns a non-scalar type!", &I); 4455 4456 // Check that the instruction doesn't produce metadata. Calls are already 4457 // checked against the callee type. 4458 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I), 4459 "Invalid use of metadata!", &I); 4460 4461 // Check that all uses of the instruction, if they are instructions 4462 // themselves, actually have parent basic blocks. If the use is not an 4463 // instruction, it is an error! 4464 for (Use &U : I.uses()) { 4465 if (Instruction *Used = dyn_cast<Instruction>(U.getUser())) 4466 Assert(Used->getParent() != nullptr, 4467 "Instruction referencing" 4468 " instruction not embedded in a basic block!", 4469 &I, Used); 4470 else { 4471 CheckFailed("Use of instruction is not an instruction!", U); 4472 return; 4473 } 4474 } 4475 4476 // Get a pointer to the call base of the instruction if it is some form of 4477 // call. 4478 const CallBase *CBI = dyn_cast<CallBase>(&I); 4479 4480 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 4481 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I); 4482 4483 // Check to make sure that only first-class-values are operands to 4484 // instructions. 4485 if (!I.getOperand(i)->getType()->isFirstClassType()) { 4486 Assert(false, "Instruction operands must be first-class values!", &I); 4487 } 4488 4489 if (Function *F = dyn_cast<Function>(I.getOperand(i))) { 4490 // Check to make sure that the "address of" an intrinsic function is never 4491 // taken. 4492 Assert(!F->isIntrinsic() || 4493 (CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i)), 4494 "Cannot take the address of an intrinsic!", &I); 4495 Assert( 4496 !F->isIntrinsic() || isa<CallInst>(I) || 4497 F->getIntrinsicID() == Intrinsic::donothing || 4498 F->getIntrinsicID() == Intrinsic::seh_try_begin || 4499 F->getIntrinsicID() == Intrinsic::seh_try_end || 4500 F->getIntrinsicID() == Intrinsic::seh_scope_begin || 4501 F->getIntrinsicID() == Intrinsic::seh_scope_end || 4502 F->getIntrinsicID() == Intrinsic::coro_resume || 4503 F->getIntrinsicID() == Intrinsic::coro_destroy || 4504 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void || 4505 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 || 4506 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint || 4507 F->getIntrinsicID() == Intrinsic::wasm_rethrow, 4508 "Cannot invoke an intrinsic other than donothing, patchpoint, " 4509 "statepoint, coro_resume or coro_destroy", 4510 &I); 4511 Assert(F->getParent() == &M, "Referencing function in another module!", 4512 &I, &M, F, F->getParent()); 4513 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) { 4514 Assert(OpBB->getParent() == BB->getParent(), 4515 "Referring to a basic block in another function!", &I); 4516 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) { 4517 Assert(OpArg->getParent() == BB->getParent(), 4518 "Referring to an argument in another function!", &I); 4519 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) { 4520 Assert(GV->getParent() == &M, "Referencing global in another module!", &I, 4521 &M, GV, GV->getParent()); 4522 } else if (isa<Instruction>(I.getOperand(i))) { 4523 verifyDominatesUse(I, i); 4524 } else if (isa<InlineAsm>(I.getOperand(i))) { 4525 Assert(CBI && &CBI->getCalledOperandUse() == &I.getOperandUse(i), 4526 "Cannot take the address of an inline asm!", &I); 4527 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) { 4528 if (CE->getType()->isPtrOrPtrVectorTy()) { 4529 // If we have a ConstantExpr pointer, we need to see if it came from an 4530 // illegal bitcast. 4531 visitConstantExprsRecursively(CE); 4532 } 4533 } 4534 } 4535 4536 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) { 4537 Assert(I.getType()->isFPOrFPVectorTy(), 4538 "fpmath requires a floating point result!", &I); 4539 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I); 4540 if (ConstantFP *CFP0 = 4541 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) { 4542 const APFloat &Accuracy = CFP0->getValueAPF(); 4543 Assert(&Accuracy.getSemantics() == &APFloat::IEEEsingle(), 4544 "fpmath accuracy must have float type", &I); 4545 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(), 4546 "fpmath accuracy not a positive number!", &I); 4547 } else { 4548 Assert(false, "invalid fpmath accuracy!", &I); 4549 } 4550 } 4551 4552 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) { 4553 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I), 4554 "Ranges are only for loads, calls and invokes!", &I); 4555 visitRangeMetadata(I, Range, I.getType()); 4556 } 4557 4558 if (I.getMetadata(LLVMContext::MD_nonnull)) { 4559 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types", 4560 &I); 4561 Assert(isa<LoadInst>(I), 4562 "nonnull applies only to load instructions, use attributes" 4563 " for calls or invokes", 4564 &I); 4565 } 4566 4567 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable)) 4568 visitDereferenceableMetadata(I, MD); 4569 4570 if (MDNode *MD = I.getMetadata(LLVMContext::MD_dereferenceable_or_null)) 4571 visitDereferenceableMetadata(I, MD); 4572 4573 if (MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa)) 4574 TBAAVerifyHelper.visitTBAAMetadata(I, TBAA); 4575 4576 if (MDNode *AlignMD = I.getMetadata(LLVMContext::MD_align)) { 4577 Assert(I.getType()->isPointerTy(), "align applies only to pointer types", 4578 &I); 4579 Assert(isa<LoadInst>(I), "align applies only to load instructions, " 4580 "use attributes for calls or invokes", &I); 4581 Assert(AlignMD->getNumOperands() == 1, "align takes one operand!", &I); 4582 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0)); 4583 Assert(CI && CI->getType()->isIntegerTy(64), 4584 "align metadata value must be an i64!", &I); 4585 uint64_t Align = CI->getZExtValue(); 4586 Assert(isPowerOf2_64(Align), 4587 "align metadata value must be a power of 2!", &I); 4588 Assert(Align <= Value::MaximumAlignment, 4589 "alignment is larger that implementation defined limit", &I); 4590 } 4591 4592 if (MDNode *MD = I.getMetadata(LLVMContext::MD_prof)) 4593 visitProfMetadata(I, MD); 4594 4595 if (MDNode *Annotation = I.getMetadata(LLVMContext::MD_annotation)) 4596 visitAnnotationMetadata(Annotation); 4597 4598 if (MDNode *N = I.getDebugLoc().getAsMDNode()) { 4599 AssertDI(isa<DILocation>(N), "invalid !dbg metadata attachment", &I, N); 4600 visitMDNode(*N, AreDebugLocsAllowed::Yes); 4601 } 4602 4603 if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) { 4604 verifyFragmentExpression(*DII); 4605 verifyNotEntryValue(*DII); 4606 } 4607 4608 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; 4609 I.getAllMetadata(MDs); 4610 for (auto Attachment : MDs) { 4611 unsigned Kind = Attachment.first; 4612 auto AllowLocs = 4613 (Kind == LLVMContext::MD_dbg || Kind == LLVMContext::MD_loop) 4614 ? AreDebugLocsAllowed::Yes 4615 : AreDebugLocsAllowed::No; 4616 visitMDNode(*Attachment.second, AllowLocs); 4617 } 4618 4619 InstsInThisBlock.insert(&I); 4620 } 4621 4622 /// Allow intrinsics to be verified in different ways. 4623 void Verifier::visitIntrinsicCall(Intrinsic::ID ID, CallBase &Call) { 4624 Function *IF = Call.getCalledFunction(); 4625 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!", 4626 IF); 4627 4628 // Verify that the intrinsic prototype lines up with what the .td files 4629 // describe. 4630 FunctionType *IFTy = IF->getFunctionType(); 4631 bool IsVarArg = IFTy->isVarArg(); 4632 4633 SmallVector<Intrinsic::IITDescriptor, 8> Table; 4634 getIntrinsicInfoTableEntries(ID, Table); 4635 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 4636 4637 // Walk the descriptors to extract overloaded types. 4638 SmallVector<Type *, 4> ArgTys; 4639 Intrinsic::MatchIntrinsicTypesResult Res = 4640 Intrinsic::matchIntrinsicSignature(IFTy, TableRef, ArgTys); 4641 Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchRet, 4642 "Intrinsic has incorrect return type!", IF); 4643 Assert(Res != Intrinsic::MatchIntrinsicTypes_NoMatchArg, 4644 "Intrinsic has incorrect argument type!", IF); 4645 4646 // Verify if the intrinsic call matches the vararg property. 4647 if (IsVarArg) 4648 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 4649 "Intrinsic was not defined with variable arguments!", IF); 4650 else 4651 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg, TableRef), 4652 "Callsite was not defined with variable arguments!", IF); 4653 4654 // All descriptors should be absorbed by now. 4655 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF); 4656 4657 // Now that we have the intrinsic ID and the actual argument types (and we 4658 // know they are legal for the intrinsic!) get the intrinsic name through the 4659 // usual means. This allows us to verify the mangling of argument types into 4660 // the name. 4661 const std::string ExpectedName = 4662 Intrinsic::getName(ID, ArgTys, IF->getParent(), IFTy); 4663 Assert(ExpectedName == IF->getName(), 4664 "Intrinsic name not mangled correctly for type arguments! " 4665 "Should be: " + 4666 ExpectedName, 4667 IF); 4668 4669 // If the intrinsic takes MDNode arguments, verify that they are either global 4670 // or are local to *this* function. 4671 for (Value *V : Call.args()) { 4672 if (auto *MD = dyn_cast<MetadataAsValue>(V)) 4673 visitMetadataAsValue(*MD, Call.getCaller()); 4674 if (auto *Const = dyn_cast<Constant>(V)) 4675 Assert(!Const->getType()->isX86_AMXTy(), 4676 "const x86_amx is not allowed in argument!"); 4677 } 4678 4679 switch (ID) { 4680 default: 4681 break; 4682 case Intrinsic::assume: { 4683 for (auto &Elem : Call.bundle_op_infos()) { 4684 Assert(Elem.Tag->getKey() == "ignore" || 4685 Attribute::isExistingAttribute(Elem.Tag->getKey()), 4686 "tags must be valid attribute names"); 4687 Attribute::AttrKind Kind = 4688 Attribute::getAttrKindFromName(Elem.Tag->getKey()); 4689 unsigned ArgCount = Elem.End - Elem.Begin; 4690 if (Kind == Attribute::Alignment) { 4691 Assert(ArgCount <= 3 && ArgCount >= 2, 4692 "alignment assumptions should have 2 or 3 arguments"); 4693 Assert(Call.getOperand(Elem.Begin)->getType()->isPointerTy(), 4694 "first argument should be a pointer"); 4695 Assert(Call.getOperand(Elem.Begin + 1)->getType()->isIntegerTy(), 4696 "second argument should be an integer"); 4697 if (ArgCount == 3) 4698 Assert(Call.getOperand(Elem.Begin + 2)->getType()->isIntegerTy(), 4699 "third argument should be an integer if present"); 4700 return; 4701 } 4702 Assert(ArgCount <= 2, "to many arguments"); 4703 if (Kind == Attribute::None) 4704 break; 4705 if (Attribute::doesAttrKindHaveArgument(Kind)) { 4706 Assert(ArgCount == 2, "this attribute should have 2 arguments"); 4707 Assert(isa<ConstantInt>(Call.getOperand(Elem.Begin + 1)), 4708 "the second argument should be a constant integral value"); 4709 } else if (isFuncOnlyAttr(Kind)) { 4710 Assert((ArgCount) == 0, "this attribute has no argument"); 4711 } else if (!isFuncOrArgAttr(Kind)) { 4712 Assert((ArgCount) == 1, "this attribute should have one argument"); 4713 } 4714 } 4715 break; 4716 } 4717 case Intrinsic::coro_id: { 4718 auto *InfoArg = Call.getArgOperand(3)->stripPointerCasts(); 4719 if (isa<ConstantPointerNull>(InfoArg)) 4720 break; 4721 auto *GV = dyn_cast<GlobalVariable>(InfoArg); 4722 Assert(GV && GV->isConstant() && GV->hasDefinitiveInitializer(), 4723 "info argument of llvm.coro.id must refer to an initialized " 4724 "constant"); 4725 Constant *Init = GV->getInitializer(); 4726 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init), 4727 "info argument of llvm.coro.id must refer to either a struct or " 4728 "an array"); 4729 break; 4730 } 4731 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \ 4732 case Intrinsic::INTRINSIC: 4733 #include "llvm/IR/ConstrainedOps.def" 4734 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call)); 4735 break; 4736 case Intrinsic::dbg_declare: // llvm.dbg.declare 4737 Assert(isa<MetadataAsValue>(Call.getArgOperand(0)), 4738 "invalid llvm.dbg.declare intrinsic call 1", Call); 4739 visitDbgIntrinsic("declare", cast<DbgVariableIntrinsic>(Call)); 4740 break; 4741 case Intrinsic::dbg_addr: // llvm.dbg.addr 4742 visitDbgIntrinsic("addr", cast<DbgVariableIntrinsic>(Call)); 4743 break; 4744 case Intrinsic::dbg_value: // llvm.dbg.value 4745 visitDbgIntrinsic("value", cast<DbgVariableIntrinsic>(Call)); 4746 break; 4747 case Intrinsic::dbg_label: // llvm.dbg.label 4748 visitDbgLabelIntrinsic("label", cast<DbgLabelInst>(Call)); 4749 break; 4750 case Intrinsic::memcpy: 4751 case Intrinsic::memcpy_inline: 4752 case Intrinsic::memmove: 4753 case Intrinsic::memset: { 4754 const auto *MI = cast<MemIntrinsic>(&Call); 4755 auto IsValidAlignment = [&](unsigned Alignment) -> bool { 4756 return Alignment == 0 || isPowerOf2_32(Alignment); 4757 }; 4758 Assert(IsValidAlignment(MI->getDestAlignment()), 4759 "alignment of arg 0 of memory intrinsic must be 0 or a power of 2", 4760 Call); 4761 if (const auto *MTI = dyn_cast<MemTransferInst>(MI)) { 4762 Assert(IsValidAlignment(MTI->getSourceAlignment()), 4763 "alignment of arg 1 of memory intrinsic must be 0 or a power of 2", 4764 Call); 4765 } 4766 4767 break; 4768 } 4769 case Intrinsic::memcpy_element_unordered_atomic: 4770 case Intrinsic::memmove_element_unordered_atomic: 4771 case Intrinsic::memset_element_unordered_atomic: { 4772 const auto *AMI = cast<AtomicMemIntrinsic>(&Call); 4773 4774 ConstantInt *ElementSizeCI = 4775 cast<ConstantInt>(AMI->getRawElementSizeInBytes()); 4776 const APInt &ElementSizeVal = ElementSizeCI->getValue(); 4777 Assert(ElementSizeVal.isPowerOf2(), 4778 "element size of the element-wise atomic memory intrinsic " 4779 "must be a power of 2", 4780 Call); 4781 4782 auto IsValidAlignment = [&](uint64_t Alignment) { 4783 return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment); 4784 }; 4785 uint64_t DstAlignment = AMI->getDestAlignment(); 4786 Assert(IsValidAlignment(DstAlignment), 4787 "incorrect alignment of the destination argument", Call); 4788 if (const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) { 4789 uint64_t SrcAlignment = AMT->getSourceAlignment(); 4790 Assert(IsValidAlignment(SrcAlignment), 4791 "incorrect alignment of the source argument", Call); 4792 } 4793 break; 4794 } 4795 case Intrinsic::call_preallocated_setup: { 4796 auto *NumArgs = dyn_cast<ConstantInt>(Call.getArgOperand(0)); 4797 Assert(NumArgs != nullptr, 4798 "llvm.call.preallocated.setup argument must be a constant"); 4799 bool FoundCall = false; 4800 for (User *U : Call.users()) { 4801 auto *UseCall = dyn_cast<CallBase>(U); 4802 Assert(UseCall != nullptr, 4803 "Uses of llvm.call.preallocated.setup must be calls"); 4804 const Function *Fn = UseCall->getCalledFunction(); 4805 if (Fn && Fn->getIntrinsicID() == Intrinsic::call_preallocated_arg) { 4806 auto *AllocArgIndex = dyn_cast<ConstantInt>(UseCall->getArgOperand(1)); 4807 Assert(AllocArgIndex != nullptr, 4808 "llvm.call.preallocated.alloc arg index must be a constant"); 4809 auto AllocArgIndexInt = AllocArgIndex->getValue(); 4810 Assert(AllocArgIndexInt.sge(0) && 4811 AllocArgIndexInt.slt(NumArgs->getValue()), 4812 "llvm.call.preallocated.alloc arg index must be between 0 and " 4813 "corresponding " 4814 "llvm.call.preallocated.setup's argument count"); 4815 } else if (Fn && Fn->getIntrinsicID() == 4816 Intrinsic::call_preallocated_teardown) { 4817 // nothing to do 4818 } else { 4819 Assert(!FoundCall, "Can have at most one call corresponding to a " 4820 "llvm.call.preallocated.setup"); 4821 FoundCall = true; 4822 size_t NumPreallocatedArgs = 0; 4823 for (unsigned i = 0; i < UseCall->getNumArgOperands(); i++) { 4824 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) { 4825 ++NumPreallocatedArgs; 4826 } 4827 } 4828 Assert(NumPreallocatedArgs != 0, 4829 "cannot use preallocated intrinsics on a call without " 4830 "preallocated arguments"); 4831 Assert(NumArgs->equalsInt(NumPreallocatedArgs), 4832 "llvm.call.preallocated.setup arg size must be equal to number " 4833 "of preallocated arguments " 4834 "at call site", 4835 Call, *UseCall); 4836 // getOperandBundle() cannot be called if more than one of the operand 4837 // bundle exists. There is already a check elsewhere for this, so skip 4838 // here if we see more than one. 4839 if (UseCall->countOperandBundlesOfType(LLVMContext::OB_preallocated) > 4840 1) { 4841 return; 4842 } 4843 auto PreallocatedBundle = 4844 UseCall->getOperandBundle(LLVMContext::OB_preallocated); 4845 Assert(PreallocatedBundle, 4846 "Use of llvm.call.preallocated.setup outside intrinsics " 4847 "must be in \"preallocated\" operand bundle"); 4848 Assert(PreallocatedBundle->Inputs.front().get() == &Call, 4849 "preallocated bundle must have token from corresponding " 4850 "llvm.call.preallocated.setup"); 4851 } 4852 } 4853 break; 4854 } 4855 case Intrinsic::call_preallocated_arg: { 4856 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0)); 4857 Assert(Token && Token->getCalledFunction()->getIntrinsicID() == 4858 Intrinsic::call_preallocated_setup, 4859 "llvm.call.preallocated.arg token argument must be a " 4860 "llvm.call.preallocated.setup"); 4861 Assert(Call.hasFnAttr(Attribute::Preallocated), 4862 "llvm.call.preallocated.arg must be called with a \"preallocated\" " 4863 "call site attribute"); 4864 break; 4865 } 4866 case Intrinsic::call_preallocated_teardown: { 4867 auto *Token = dyn_cast<CallBase>(Call.getArgOperand(0)); 4868 Assert(Token && Token->getCalledFunction()->getIntrinsicID() == 4869 Intrinsic::call_preallocated_setup, 4870 "llvm.call.preallocated.teardown token argument must be a " 4871 "llvm.call.preallocated.setup"); 4872 break; 4873 } 4874 case Intrinsic::gcroot: 4875 case Intrinsic::gcwrite: 4876 case Intrinsic::gcread: 4877 if (ID == Intrinsic::gcroot) { 4878 AllocaInst *AI = 4879 dyn_cast<AllocaInst>(Call.getArgOperand(0)->stripPointerCasts()); 4880 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", Call); 4881 Assert(isa<Constant>(Call.getArgOperand(1)), 4882 "llvm.gcroot parameter #2 must be a constant.", Call); 4883 if (!AI->getAllocatedType()->isPointerTy()) { 4884 Assert(!isa<ConstantPointerNull>(Call.getArgOperand(1)), 4885 "llvm.gcroot parameter #1 must either be a pointer alloca, " 4886 "or argument #2 must be a non-null constant.", 4887 Call); 4888 } 4889 } 4890 4891 Assert(Call.getParent()->getParent()->hasGC(), 4892 "Enclosing function does not use GC.", Call); 4893 break; 4894 case Intrinsic::init_trampoline: 4895 Assert(isa<Function>(Call.getArgOperand(1)->stripPointerCasts()), 4896 "llvm.init_trampoline parameter #2 must resolve to a function.", 4897 Call); 4898 break; 4899 case Intrinsic::prefetch: 4900 Assert(cast<ConstantInt>(Call.getArgOperand(1))->getZExtValue() < 2 && 4901 cast<ConstantInt>(Call.getArgOperand(2))->getZExtValue() < 4, 4902 "invalid arguments to llvm.prefetch", Call); 4903 break; 4904 case Intrinsic::stackprotector: 4905 Assert(isa<AllocaInst>(Call.getArgOperand(1)->stripPointerCasts()), 4906 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call); 4907 break; 4908 case Intrinsic::localescape: { 4909 BasicBlock *BB = Call.getParent(); 4910 Assert(BB == &BB->getParent()->front(), 4911 "llvm.localescape used outside of entry block", Call); 4912 Assert(!SawFrameEscape, 4913 "multiple calls to llvm.localescape in one function", Call); 4914 for (Value *Arg : Call.args()) { 4915 if (isa<ConstantPointerNull>(Arg)) 4916 continue; // Null values are allowed as placeholders. 4917 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts()); 4918 Assert(AI && AI->isStaticAlloca(), 4919 "llvm.localescape only accepts static allocas", Call); 4920 } 4921 FrameEscapeInfo[BB->getParent()].first = Call.getNumArgOperands(); 4922 SawFrameEscape = true; 4923 break; 4924 } 4925 case Intrinsic::localrecover: { 4926 Value *FnArg = Call.getArgOperand(0)->stripPointerCasts(); 4927 Function *Fn = dyn_cast<Function>(FnArg); 4928 Assert(Fn && !Fn->isDeclaration(), 4929 "llvm.localrecover first " 4930 "argument must be function defined in this module", 4931 Call); 4932 auto *IdxArg = cast<ConstantInt>(Call.getArgOperand(2)); 4933 auto &Entry = FrameEscapeInfo[Fn]; 4934 Entry.second = unsigned( 4935 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1)); 4936 break; 4937 } 4938 4939 case Intrinsic::experimental_gc_statepoint: 4940 if (auto *CI = dyn_cast<CallInst>(&Call)) 4941 Assert(!CI->isInlineAsm(), 4942 "gc.statepoint support for inline assembly unimplemented", CI); 4943 Assert(Call.getParent()->getParent()->hasGC(), 4944 "Enclosing function does not use GC.", Call); 4945 4946 verifyStatepoint(Call); 4947 break; 4948 case Intrinsic::experimental_gc_result: { 4949 Assert(Call.getParent()->getParent()->hasGC(), 4950 "Enclosing function does not use GC.", Call); 4951 // Are we tied to a statepoint properly? 4952 const auto *StatepointCall = dyn_cast<CallBase>(Call.getArgOperand(0)); 4953 const Function *StatepointFn = 4954 StatepointCall ? StatepointCall->getCalledFunction() : nullptr; 4955 Assert(StatepointFn && StatepointFn->isDeclaration() && 4956 StatepointFn->getIntrinsicID() == 4957 Intrinsic::experimental_gc_statepoint, 4958 "gc.result operand #1 must be from a statepoint", Call, 4959 Call.getArgOperand(0)); 4960 4961 // Assert that result type matches wrapped callee. 4962 const Value *Target = StatepointCall->getArgOperand(2); 4963 auto *PT = cast<PointerType>(Target->getType()); 4964 auto *TargetFuncType = cast<FunctionType>(PT->getElementType()); 4965 Assert(Call.getType() == TargetFuncType->getReturnType(), 4966 "gc.result result type does not match wrapped callee", Call); 4967 break; 4968 } 4969 case Intrinsic::experimental_gc_relocate: { 4970 Assert(Call.getNumArgOperands() == 3, "wrong number of arguments", Call); 4971 4972 Assert(isa<PointerType>(Call.getType()->getScalarType()), 4973 "gc.relocate must return a pointer or a vector of pointers", Call); 4974 4975 // Check that this relocate is correctly tied to the statepoint 4976 4977 // This is case for relocate on the unwinding path of an invoke statepoint 4978 if (LandingPadInst *LandingPad = 4979 dyn_cast<LandingPadInst>(Call.getArgOperand(0))) { 4980 4981 const BasicBlock *InvokeBB = 4982 LandingPad->getParent()->getUniquePredecessor(); 4983 4984 // Landingpad relocates should have only one predecessor with invoke 4985 // statepoint terminator 4986 Assert(InvokeBB, "safepoints should have unique landingpads", 4987 LandingPad->getParent()); 4988 Assert(InvokeBB->getTerminator(), "safepoint block should be well formed", 4989 InvokeBB); 4990 Assert(isa<GCStatepointInst>(InvokeBB->getTerminator()), 4991 "gc relocate should be linked to a statepoint", InvokeBB); 4992 } else { 4993 // In all other cases relocate should be tied to the statepoint directly. 4994 // This covers relocates on a normal return path of invoke statepoint and 4995 // relocates of a call statepoint. 4996 auto Token = Call.getArgOperand(0); 4997 Assert(isa<GCStatepointInst>(Token), 4998 "gc relocate is incorrectly tied to the statepoint", Call, Token); 4999 } 5000 5001 // Verify rest of the relocate arguments. 5002 const CallBase &StatepointCall = 5003 *cast<GCRelocateInst>(Call).getStatepoint(); 5004 5005 // Both the base and derived must be piped through the safepoint. 5006 Value *Base = Call.getArgOperand(1); 5007 Assert(isa<ConstantInt>(Base), 5008 "gc.relocate operand #2 must be integer offset", Call); 5009 5010 Value *Derived = Call.getArgOperand(2); 5011 Assert(isa<ConstantInt>(Derived), 5012 "gc.relocate operand #3 must be integer offset", Call); 5013 5014 const uint64_t BaseIndex = cast<ConstantInt>(Base)->getZExtValue(); 5015 const uint64_t DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue(); 5016 5017 // Check the bounds 5018 if (auto Opt = StatepointCall.getOperandBundle(LLVMContext::OB_gc_live)) { 5019 Assert(BaseIndex < Opt->Inputs.size(), 5020 "gc.relocate: statepoint base index out of bounds", Call); 5021 Assert(DerivedIndex < Opt->Inputs.size(), 5022 "gc.relocate: statepoint derived index out of bounds", Call); 5023 } 5024 5025 // Relocated value must be either a pointer type or vector-of-pointer type, 5026 // but gc_relocate does not need to return the same pointer type as the 5027 // relocated pointer. It can be casted to the correct type later if it's 5028 // desired. However, they must have the same address space and 'vectorness' 5029 GCRelocateInst &Relocate = cast<GCRelocateInst>(Call); 5030 Assert(Relocate.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(), 5031 "gc.relocate: relocated value must be a gc pointer", Call); 5032 5033 auto ResultType = Call.getType(); 5034 auto DerivedType = Relocate.getDerivedPtr()->getType(); 5035 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(), 5036 "gc.relocate: vector relocates to vector and pointer to pointer", 5037 Call); 5038 Assert( 5039 ResultType->getPointerAddressSpace() == 5040 DerivedType->getPointerAddressSpace(), 5041 "gc.relocate: relocating a pointer shouldn't change its address space", 5042 Call); 5043 break; 5044 } 5045 case Intrinsic::eh_exceptioncode: 5046 case Intrinsic::eh_exceptionpointer: { 5047 Assert(isa<CatchPadInst>(Call.getArgOperand(0)), 5048 "eh.exceptionpointer argument must be a catchpad", Call); 5049 break; 5050 } 5051 case Intrinsic::get_active_lane_mask: { 5052 Assert(Call.getType()->isVectorTy(), "get_active_lane_mask: must return a " 5053 "vector", Call); 5054 auto *ElemTy = Call.getType()->getScalarType(); 5055 Assert(ElemTy->isIntegerTy(1), "get_active_lane_mask: element type is not " 5056 "i1", Call); 5057 break; 5058 } 5059 case Intrinsic::masked_load: { 5060 Assert(Call.getType()->isVectorTy(), "masked_load: must return a vector", 5061 Call); 5062 5063 Value *Ptr = Call.getArgOperand(0); 5064 ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(1)); 5065 Value *Mask = Call.getArgOperand(2); 5066 Value *PassThru = Call.getArgOperand(3); 5067 Assert(Mask->getType()->isVectorTy(), "masked_load: mask must be vector", 5068 Call); 5069 Assert(Alignment->getValue().isPowerOf2(), 5070 "masked_load: alignment must be a power of 2", Call); 5071 5072 PointerType *PtrTy = cast<PointerType>(Ptr->getType()); 5073 Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Call.getType()), 5074 "masked_load: return must match pointer type", Call); 5075 Assert(PassThru->getType() == Call.getType(), 5076 "masked_load: pass through and return type must match", Call); 5077 Assert(cast<VectorType>(Mask->getType())->getElementCount() == 5078 cast<VectorType>(Call.getType())->getElementCount(), 5079 "masked_load: vector mask must be same length as return", Call); 5080 break; 5081 } 5082 case Intrinsic::masked_store: { 5083 Value *Val = Call.getArgOperand(0); 5084 Value *Ptr = Call.getArgOperand(1); 5085 ConstantInt *Alignment = cast<ConstantInt>(Call.getArgOperand(2)); 5086 Value *Mask = Call.getArgOperand(3); 5087 Assert(Mask->getType()->isVectorTy(), "masked_store: mask must be vector", 5088 Call); 5089 Assert(Alignment->getValue().isPowerOf2(), 5090 "masked_store: alignment must be a power of 2", Call); 5091 5092 PointerType *PtrTy = cast<PointerType>(Ptr->getType()); 5093 Assert(PtrTy->isOpaqueOrPointeeTypeMatches(Val->getType()), 5094 "masked_store: storee must match pointer type", Call); 5095 Assert(cast<VectorType>(Mask->getType())->getElementCount() == 5096 cast<VectorType>(Val->getType())->getElementCount(), 5097 "masked_store: vector mask must be same length as value", Call); 5098 break; 5099 } 5100 5101 case Intrinsic::masked_gather: { 5102 const APInt &Alignment = 5103 cast<ConstantInt>(Call.getArgOperand(1))->getValue(); 5104 Assert(Alignment.isNullValue() || Alignment.isPowerOf2(), 5105 "masked_gather: alignment must be 0 or a power of 2", Call); 5106 break; 5107 } 5108 case Intrinsic::masked_scatter: { 5109 const APInt &Alignment = 5110 cast<ConstantInt>(Call.getArgOperand(2))->getValue(); 5111 Assert(Alignment.isNullValue() || Alignment.isPowerOf2(), 5112 "masked_scatter: alignment must be 0 or a power of 2", Call); 5113 break; 5114 } 5115 5116 case Intrinsic::experimental_guard: { 5117 Assert(isa<CallInst>(Call), "experimental_guard cannot be invoked", Call); 5118 Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 5119 "experimental_guard must have exactly one " 5120 "\"deopt\" operand bundle"); 5121 break; 5122 } 5123 5124 case Intrinsic::experimental_deoptimize: { 5125 Assert(isa<CallInst>(Call), "experimental_deoptimize cannot be invoked", 5126 Call); 5127 Assert(Call.countOperandBundlesOfType(LLVMContext::OB_deopt) == 1, 5128 "experimental_deoptimize must have exactly one " 5129 "\"deopt\" operand bundle"); 5130 Assert(Call.getType() == Call.getFunction()->getReturnType(), 5131 "experimental_deoptimize return type must match caller return type"); 5132 5133 if (isa<CallInst>(Call)) { 5134 auto *RI = dyn_cast<ReturnInst>(Call.getNextNode()); 5135 Assert(RI, 5136 "calls to experimental_deoptimize must be followed by a return"); 5137 5138 if (!Call.getType()->isVoidTy() && RI) 5139 Assert(RI->getReturnValue() == &Call, 5140 "calls to experimental_deoptimize must be followed by a return " 5141 "of the value computed by experimental_deoptimize"); 5142 } 5143 5144 break; 5145 } 5146 case Intrinsic::vector_reduce_and: 5147 case Intrinsic::vector_reduce_or: 5148 case Intrinsic::vector_reduce_xor: 5149 case Intrinsic::vector_reduce_add: 5150 case Intrinsic::vector_reduce_mul: 5151 case Intrinsic::vector_reduce_smax: 5152 case Intrinsic::vector_reduce_smin: 5153 case Intrinsic::vector_reduce_umax: 5154 case Intrinsic::vector_reduce_umin: { 5155 Type *ArgTy = Call.getArgOperand(0)->getType(); 5156 Assert(ArgTy->isIntOrIntVectorTy() && ArgTy->isVectorTy(), 5157 "Intrinsic has incorrect argument type!"); 5158 break; 5159 } 5160 case Intrinsic::vector_reduce_fmax: 5161 case Intrinsic::vector_reduce_fmin: { 5162 Type *ArgTy = Call.getArgOperand(0)->getType(); 5163 Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(), 5164 "Intrinsic has incorrect argument type!"); 5165 break; 5166 } 5167 case Intrinsic::vector_reduce_fadd: 5168 case Intrinsic::vector_reduce_fmul: { 5169 // Unlike the other reductions, the first argument is a start value. The 5170 // second argument is the vector to be reduced. 5171 Type *ArgTy = Call.getArgOperand(1)->getType(); 5172 Assert(ArgTy->isFPOrFPVectorTy() && ArgTy->isVectorTy(), 5173 "Intrinsic has incorrect argument type!"); 5174 break; 5175 } 5176 case Intrinsic::smul_fix: 5177 case Intrinsic::smul_fix_sat: 5178 case Intrinsic::umul_fix: 5179 case Intrinsic::umul_fix_sat: 5180 case Intrinsic::sdiv_fix: 5181 case Intrinsic::sdiv_fix_sat: 5182 case Intrinsic::udiv_fix: 5183 case Intrinsic::udiv_fix_sat: { 5184 Value *Op1 = Call.getArgOperand(0); 5185 Value *Op2 = Call.getArgOperand(1); 5186 Assert(Op1->getType()->isIntOrIntVectorTy(), 5187 "first operand of [us][mul|div]_fix[_sat] must be an int type or " 5188 "vector of ints"); 5189 Assert(Op2->getType()->isIntOrIntVectorTy(), 5190 "second operand of [us][mul|div]_fix[_sat] must be an int type or " 5191 "vector of ints"); 5192 5193 auto *Op3 = cast<ConstantInt>(Call.getArgOperand(2)); 5194 Assert(Op3->getType()->getBitWidth() <= 32, 5195 "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits"); 5196 5197 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat || 5198 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) { 5199 Assert( 5200 Op3->getZExtValue() < Op1->getType()->getScalarSizeInBits(), 5201 "the scale of s[mul|div]_fix[_sat] must be less than the width of " 5202 "the operands"); 5203 } else { 5204 Assert(Op3->getZExtValue() <= Op1->getType()->getScalarSizeInBits(), 5205 "the scale of u[mul|div]_fix[_sat] must be less than or equal " 5206 "to the width of the operands"); 5207 } 5208 break; 5209 } 5210 case Intrinsic::lround: 5211 case Intrinsic::llround: 5212 case Intrinsic::lrint: 5213 case Intrinsic::llrint: { 5214 Type *ValTy = Call.getArgOperand(0)->getType(); 5215 Type *ResultTy = Call.getType(); 5216 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5217 "Intrinsic does not support vectors", &Call); 5218 break; 5219 } 5220 case Intrinsic::bswap: { 5221 Type *Ty = Call.getType(); 5222 unsigned Size = Ty->getScalarSizeInBits(); 5223 Assert(Size % 16 == 0, "bswap must be an even number of bytes", &Call); 5224 break; 5225 } 5226 case Intrinsic::invariant_start: { 5227 ConstantInt *InvariantSize = dyn_cast<ConstantInt>(Call.getArgOperand(0)); 5228 Assert(InvariantSize && 5229 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()), 5230 "invariant_start parameter must be -1, 0 or a positive number", 5231 &Call); 5232 break; 5233 } 5234 case Intrinsic::matrix_multiply: 5235 case Intrinsic::matrix_transpose: 5236 case Intrinsic::matrix_column_major_load: 5237 case Intrinsic::matrix_column_major_store: { 5238 Function *IF = Call.getCalledFunction(); 5239 ConstantInt *Stride = nullptr; 5240 ConstantInt *NumRows; 5241 ConstantInt *NumColumns; 5242 VectorType *ResultTy; 5243 Type *Op0ElemTy = nullptr; 5244 Type *Op1ElemTy = nullptr; 5245 switch (ID) { 5246 case Intrinsic::matrix_multiply: 5247 NumRows = cast<ConstantInt>(Call.getArgOperand(2)); 5248 NumColumns = cast<ConstantInt>(Call.getArgOperand(4)); 5249 ResultTy = cast<VectorType>(Call.getType()); 5250 Op0ElemTy = 5251 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5252 Op1ElemTy = 5253 cast<VectorType>(Call.getArgOperand(1)->getType())->getElementType(); 5254 break; 5255 case Intrinsic::matrix_transpose: 5256 NumRows = cast<ConstantInt>(Call.getArgOperand(1)); 5257 NumColumns = cast<ConstantInt>(Call.getArgOperand(2)); 5258 ResultTy = cast<VectorType>(Call.getType()); 5259 Op0ElemTy = 5260 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5261 break; 5262 case Intrinsic::matrix_column_major_load: 5263 Stride = dyn_cast<ConstantInt>(Call.getArgOperand(1)); 5264 NumRows = cast<ConstantInt>(Call.getArgOperand(3)); 5265 NumColumns = cast<ConstantInt>(Call.getArgOperand(4)); 5266 ResultTy = cast<VectorType>(Call.getType()); 5267 Op0ElemTy = 5268 cast<PointerType>(Call.getArgOperand(0)->getType())->getElementType(); 5269 break; 5270 case Intrinsic::matrix_column_major_store: 5271 Stride = dyn_cast<ConstantInt>(Call.getArgOperand(2)); 5272 NumRows = cast<ConstantInt>(Call.getArgOperand(4)); 5273 NumColumns = cast<ConstantInt>(Call.getArgOperand(5)); 5274 ResultTy = cast<VectorType>(Call.getArgOperand(0)->getType()); 5275 Op0ElemTy = 5276 cast<VectorType>(Call.getArgOperand(0)->getType())->getElementType(); 5277 Op1ElemTy = 5278 cast<PointerType>(Call.getArgOperand(1)->getType())->getElementType(); 5279 break; 5280 default: 5281 llvm_unreachable("unexpected intrinsic"); 5282 } 5283 5284 Assert(ResultTy->getElementType()->isIntegerTy() || 5285 ResultTy->getElementType()->isFloatingPointTy(), 5286 "Result type must be an integer or floating-point type!", IF); 5287 5288 Assert(ResultTy->getElementType() == Op0ElemTy, 5289 "Vector element type mismatch of the result and first operand " 5290 "vector!", IF); 5291 5292 if (Op1ElemTy) 5293 Assert(ResultTy->getElementType() == Op1ElemTy, 5294 "Vector element type mismatch of the result and second operand " 5295 "vector!", IF); 5296 5297 Assert(cast<FixedVectorType>(ResultTy)->getNumElements() == 5298 NumRows->getZExtValue() * NumColumns->getZExtValue(), 5299 "Result of a matrix operation does not fit in the returned vector!"); 5300 5301 if (Stride) 5302 Assert(Stride->getZExtValue() >= NumRows->getZExtValue(), 5303 "Stride must be greater or equal than the number of rows!", IF); 5304 5305 break; 5306 } 5307 case Intrinsic::experimental_stepvector: { 5308 VectorType *VecTy = dyn_cast<VectorType>(Call.getType()); 5309 Assert(VecTy && VecTy->getScalarType()->isIntegerTy() && 5310 VecTy->getScalarSizeInBits() >= 8, 5311 "experimental_stepvector only supported for vectors of integers " 5312 "with a bitwidth of at least 8.", 5313 &Call); 5314 break; 5315 } 5316 case Intrinsic::experimental_vector_insert: { 5317 Value *Vec = Call.getArgOperand(0); 5318 Value *SubVec = Call.getArgOperand(1); 5319 Value *Idx = Call.getArgOperand(2); 5320 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 5321 5322 VectorType *VecTy = cast<VectorType>(Vec->getType()); 5323 VectorType *SubVecTy = cast<VectorType>(SubVec->getType()); 5324 5325 ElementCount VecEC = VecTy->getElementCount(); 5326 ElementCount SubVecEC = SubVecTy->getElementCount(); 5327 Assert(VecTy->getElementType() == SubVecTy->getElementType(), 5328 "experimental_vector_insert parameters must have the same element " 5329 "type.", 5330 &Call); 5331 Assert(IdxN % SubVecEC.getKnownMinValue() == 0, 5332 "experimental_vector_insert index must be a constant multiple of " 5333 "the subvector's known minimum vector length."); 5334 5335 // If this insertion is not the 'mixed' case where a fixed vector is 5336 // inserted into a scalable vector, ensure that the insertion of the 5337 // subvector does not overrun the parent vector. 5338 if (VecEC.isScalable() == SubVecEC.isScalable()) { 5339 Assert( 5340 IdxN < VecEC.getKnownMinValue() && 5341 IdxN + SubVecEC.getKnownMinValue() <= VecEC.getKnownMinValue(), 5342 "subvector operand of experimental_vector_insert would overrun the " 5343 "vector being inserted into."); 5344 } 5345 break; 5346 } 5347 case Intrinsic::experimental_vector_extract: { 5348 Value *Vec = Call.getArgOperand(0); 5349 Value *Idx = Call.getArgOperand(1); 5350 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 5351 5352 VectorType *ResultTy = cast<VectorType>(Call.getType()); 5353 VectorType *VecTy = cast<VectorType>(Vec->getType()); 5354 5355 ElementCount VecEC = VecTy->getElementCount(); 5356 ElementCount ResultEC = ResultTy->getElementCount(); 5357 5358 Assert(ResultTy->getElementType() == VecTy->getElementType(), 5359 "experimental_vector_extract result must have the same element " 5360 "type as the input vector.", 5361 &Call); 5362 Assert(IdxN % ResultEC.getKnownMinValue() == 0, 5363 "experimental_vector_extract index must be a constant multiple of " 5364 "the result type's known minimum vector length."); 5365 5366 // If this extraction is not the 'mixed' case where a fixed vector is is 5367 // extracted from a scalable vector, ensure that the extraction does not 5368 // overrun the parent vector. 5369 if (VecEC.isScalable() == ResultEC.isScalable()) { 5370 Assert(IdxN < VecEC.getKnownMinValue() && 5371 IdxN + ResultEC.getKnownMinValue() <= VecEC.getKnownMinValue(), 5372 "experimental_vector_extract would overrun."); 5373 } 5374 break; 5375 } 5376 case Intrinsic::experimental_noalias_scope_decl: { 5377 NoAliasScopeDecls.push_back(cast<IntrinsicInst>(&Call)); 5378 break; 5379 } 5380 }; 5381 } 5382 5383 /// Carefully grab the subprogram from a local scope. 5384 /// 5385 /// This carefully grabs the subprogram from a local scope, avoiding the 5386 /// built-in assertions that would typically fire. 5387 static DISubprogram *getSubprogram(Metadata *LocalScope) { 5388 if (!LocalScope) 5389 return nullptr; 5390 5391 if (auto *SP = dyn_cast<DISubprogram>(LocalScope)) 5392 return SP; 5393 5394 if (auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope)) 5395 return getSubprogram(LB->getRawScope()); 5396 5397 // Just return null; broken scope chains are checked elsewhere. 5398 assert(!isa<DILocalScope>(LocalScope) && "Unknown type of local scope"); 5399 return nullptr; 5400 } 5401 5402 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) { 5403 unsigned NumOperands; 5404 bool HasRoundingMD; 5405 switch (FPI.getIntrinsicID()) { 5406 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 5407 case Intrinsic::INTRINSIC: \ 5408 NumOperands = NARG; \ 5409 HasRoundingMD = ROUND_MODE; \ 5410 break; 5411 #include "llvm/IR/ConstrainedOps.def" 5412 default: 5413 llvm_unreachable("Invalid constrained FP intrinsic!"); 5414 } 5415 NumOperands += (1 + HasRoundingMD); 5416 // Compare intrinsics carry an extra predicate metadata operand. 5417 if (isa<ConstrainedFPCmpIntrinsic>(FPI)) 5418 NumOperands += 1; 5419 Assert((FPI.getNumArgOperands() == NumOperands), 5420 "invalid arguments for constrained FP intrinsic", &FPI); 5421 5422 switch (FPI.getIntrinsicID()) { 5423 case Intrinsic::experimental_constrained_lrint: 5424 case Intrinsic::experimental_constrained_llrint: { 5425 Type *ValTy = FPI.getArgOperand(0)->getType(); 5426 Type *ResultTy = FPI.getType(); 5427 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5428 "Intrinsic does not support vectors", &FPI); 5429 } 5430 break; 5431 5432 case Intrinsic::experimental_constrained_lround: 5433 case Intrinsic::experimental_constrained_llround: { 5434 Type *ValTy = FPI.getArgOperand(0)->getType(); 5435 Type *ResultTy = FPI.getType(); 5436 Assert(!ValTy->isVectorTy() && !ResultTy->isVectorTy(), 5437 "Intrinsic does not support vectors", &FPI); 5438 break; 5439 } 5440 5441 case Intrinsic::experimental_constrained_fcmp: 5442 case Intrinsic::experimental_constrained_fcmps: { 5443 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->getPredicate(); 5444 Assert(CmpInst::isFPPredicate(Pred), 5445 "invalid predicate for constrained FP comparison intrinsic", &FPI); 5446 break; 5447 } 5448 5449 case Intrinsic::experimental_constrained_fptosi: 5450 case Intrinsic::experimental_constrained_fptoui: { 5451 Value *Operand = FPI.getArgOperand(0); 5452 uint64_t NumSrcElem = 0; 5453 Assert(Operand->getType()->isFPOrFPVectorTy(), 5454 "Intrinsic first argument must be floating point", &FPI); 5455 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5456 NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements(); 5457 } 5458 5459 Operand = &FPI; 5460 Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(), 5461 "Intrinsic first argument and result disagree on vector use", &FPI); 5462 Assert(Operand->getType()->isIntOrIntVectorTy(), 5463 "Intrinsic result must be an integer", &FPI); 5464 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5465 Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(), 5466 "Intrinsic first argument and result vector lengths must be equal", 5467 &FPI); 5468 } 5469 } 5470 break; 5471 5472 case Intrinsic::experimental_constrained_sitofp: 5473 case Intrinsic::experimental_constrained_uitofp: { 5474 Value *Operand = FPI.getArgOperand(0); 5475 uint64_t NumSrcElem = 0; 5476 Assert(Operand->getType()->isIntOrIntVectorTy(), 5477 "Intrinsic first argument must be integer", &FPI); 5478 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5479 NumSrcElem = cast<FixedVectorType>(OperandT)->getNumElements(); 5480 } 5481 5482 Operand = &FPI; 5483 Assert((NumSrcElem > 0) == Operand->getType()->isVectorTy(), 5484 "Intrinsic first argument and result disagree on vector use", &FPI); 5485 Assert(Operand->getType()->isFPOrFPVectorTy(), 5486 "Intrinsic result must be a floating point", &FPI); 5487 if (auto *OperandT = dyn_cast<VectorType>(Operand->getType())) { 5488 Assert(NumSrcElem == cast<FixedVectorType>(OperandT)->getNumElements(), 5489 "Intrinsic first argument and result vector lengths must be equal", 5490 &FPI); 5491 } 5492 } break; 5493 5494 case Intrinsic::experimental_constrained_fptrunc: 5495 case Intrinsic::experimental_constrained_fpext: { 5496 Value *Operand = FPI.getArgOperand(0); 5497 Type *OperandTy = Operand->getType(); 5498 Value *Result = &FPI; 5499 Type *ResultTy = Result->getType(); 5500 Assert(OperandTy->isFPOrFPVectorTy(), 5501 "Intrinsic first argument must be FP or FP vector", &FPI); 5502 Assert(ResultTy->isFPOrFPVectorTy(), 5503 "Intrinsic result must be FP or FP vector", &FPI); 5504 Assert(OperandTy->isVectorTy() == ResultTy->isVectorTy(), 5505 "Intrinsic first argument and result disagree on vector use", &FPI); 5506 if (OperandTy->isVectorTy()) { 5507 Assert(cast<FixedVectorType>(OperandTy)->getNumElements() == 5508 cast<FixedVectorType>(ResultTy)->getNumElements(), 5509 "Intrinsic first argument and result vector lengths must be equal", 5510 &FPI); 5511 } 5512 if (FPI.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) { 5513 Assert(OperandTy->getScalarSizeInBits() > ResultTy->getScalarSizeInBits(), 5514 "Intrinsic first argument's type must be larger than result type", 5515 &FPI); 5516 } else { 5517 Assert(OperandTy->getScalarSizeInBits() < ResultTy->getScalarSizeInBits(), 5518 "Intrinsic first argument's type must be smaller than result type", 5519 &FPI); 5520 } 5521 } 5522 break; 5523 5524 default: 5525 break; 5526 } 5527 5528 // If a non-metadata argument is passed in a metadata slot then the 5529 // error will be caught earlier when the incorrect argument doesn't 5530 // match the specification in the intrinsic call table. Thus, no 5531 // argument type check is needed here. 5532 5533 Assert(FPI.getExceptionBehavior().hasValue(), 5534 "invalid exception behavior argument", &FPI); 5535 if (HasRoundingMD) { 5536 Assert(FPI.getRoundingMode().hasValue(), 5537 "invalid rounding mode argument", &FPI); 5538 } 5539 } 5540 5541 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgVariableIntrinsic &DII) { 5542 auto *MD = DII.getRawLocation(); 5543 AssertDI(isa<ValueAsMetadata>(MD) || isa<DIArgList>(MD) || 5544 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()), 5545 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD); 5546 AssertDI(isa<DILocalVariable>(DII.getRawVariable()), 5547 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII, 5548 DII.getRawVariable()); 5549 AssertDI(isa<DIExpression>(DII.getRawExpression()), 5550 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII, 5551 DII.getRawExpression()); 5552 5553 // Ignore broken !dbg attachments; they're checked elsewhere. 5554 if (MDNode *N = DII.getDebugLoc().getAsMDNode()) 5555 if (!isa<DILocation>(N)) 5556 return; 5557 5558 BasicBlock *BB = DII.getParent(); 5559 Function *F = BB ? BB->getParent() : nullptr; 5560 5561 // The scopes for variables and !dbg attachments must agree. 5562 DILocalVariable *Var = DII.getVariable(); 5563 DILocation *Loc = DII.getDebugLoc(); 5564 AssertDI(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 5565 &DII, BB, F); 5566 5567 DISubprogram *VarSP = getSubprogram(Var->getRawScope()); 5568 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 5569 if (!VarSP || !LocSP) 5570 return; // Broken scope chains are checked elsewhere. 5571 5572 AssertDI(VarSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 5573 " variable and !dbg attachment", 5574 &DII, BB, F, Var, Var->getScope()->getSubprogram(), Loc, 5575 Loc->getScope()->getSubprogram()); 5576 5577 // This check is redundant with one in visitLocalVariable(). 5578 AssertDI(isType(Var->getRawType()), "invalid type ref", Var, 5579 Var->getRawType()); 5580 verifyFnArgs(DII); 5581 } 5582 5583 void Verifier::visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI) { 5584 AssertDI(isa<DILabel>(DLI.getRawLabel()), 5585 "invalid llvm.dbg." + Kind + " intrinsic variable", &DLI, 5586 DLI.getRawLabel()); 5587 5588 // Ignore broken !dbg attachments; they're checked elsewhere. 5589 if (MDNode *N = DLI.getDebugLoc().getAsMDNode()) 5590 if (!isa<DILocation>(N)) 5591 return; 5592 5593 BasicBlock *BB = DLI.getParent(); 5594 Function *F = BB ? BB->getParent() : nullptr; 5595 5596 // The scopes for variables and !dbg attachments must agree. 5597 DILabel *Label = DLI.getLabel(); 5598 DILocation *Loc = DLI.getDebugLoc(); 5599 Assert(Loc, "llvm.dbg." + Kind + " intrinsic requires a !dbg attachment", 5600 &DLI, BB, F); 5601 5602 DISubprogram *LabelSP = getSubprogram(Label->getRawScope()); 5603 DISubprogram *LocSP = getSubprogram(Loc->getRawScope()); 5604 if (!LabelSP || !LocSP) 5605 return; 5606 5607 AssertDI(LabelSP == LocSP, "mismatched subprogram between llvm.dbg." + Kind + 5608 " label and !dbg attachment", 5609 &DLI, BB, F, Label, Label->getScope()->getSubprogram(), Loc, 5610 Loc->getScope()->getSubprogram()); 5611 } 5612 5613 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic &I) { 5614 DILocalVariable *V = dyn_cast_or_null<DILocalVariable>(I.getRawVariable()); 5615 DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression()); 5616 5617 // We don't know whether this intrinsic verified correctly. 5618 if (!V || !E || !E->isValid()) 5619 return; 5620 5621 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression. 5622 auto Fragment = E->getFragmentInfo(); 5623 if (!Fragment) 5624 return; 5625 5626 // The frontend helps out GDB by emitting the members of local anonymous 5627 // unions as artificial local variables with shared storage. When SROA splits 5628 // the storage for artificial local variables that are smaller than the entire 5629 // union, the overhang piece will be outside of the allotted space for the 5630 // variable and this check fails. 5631 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs. 5632 if (V->isArtificial()) 5633 return; 5634 5635 verifyFragmentExpression(*V, *Fragment, &I); 5636 } 5637 5638 template <typename ValueOrMetadata> 5639 void Verifier::verifyFragmentExpression(const DIVariable &V, 5640 DIExpression::FragmentInfo Fragment, 5641 ValueOrMetadata *Desc) { 5642 // If there's no size, the type is broken, but that should be checked 5643 // elsewhere. 5644 auto VarSize = V.getSizeInBits(); 5645 if (!VarSize) 5646 return; 5647 5648 unsigned FragSize = Fragment.SizeInBits; 5649 unsigned FragOffset = Fragment.OffsetInBits; 5650 AssertDI(FragSize + FragOffset <= *VarSize, 5651 "fragment is larger than or outside of variable", Desc, &V); 5652 AssertDI(FragSize != *VarSize, "fragment covers entire variable", Desc, &V); 5653 } 5654 5655 void Verifier::verifyFnArgs(const DbgVariableIntrinsic &I) { 5656 // This function does not take the scope of noninlined function arguments into 5657 // account. Don't run it if current function is nodebug, because it may 5658 // contain inlined debug intrinsics. 5659 if (!HasDebugInfo) 5660 return; 5661 5662 // For performance reasons only check non-inlined ones. 5663 if (I.getDebugLoc()->getInlinedAt()) 5664 return; 5665 5666 DILocalVariable *Var = I.getVariable(); 5667 AssertDI(Var, "dbg intrinsic without variable"); 5668 5669 unsigned ArgNo = Var->getArg(); 5670 if (!ArgNo) 5671 return; 5672 5673 // Verify there are no duplicate function argument debug info entries. 5674 // These will cause hard-to-debug assertions in the DWARF backend. 5675 if (DebugFnArgs.size() < ArgNo) 5676 DebugFnArgs.resize(ArgNo, nullptr); 5677 5678 auto *Prev = DebugFnArgs[ArgNo - 1]; 5679 DebugFnArgs[ArgNo - 1] = Var; 5680 AssertDI(!Prev || (Prev == Var), "conflicting debug info for argument", &I, 5681 Prev, Var); 5682 } 5683 5684 void Verifier::verifyNotEntryValue(const DbgVariableIntrinsic &I) { 5685 DIExpression *E = dyn_cast_or_null<DIExpression>(I.getRawExpression()); 5686 5687 // We don't know whether this intrinsic verified correctly. 5688 if (!E || !E->isValid()) 5689 return; 5690 5691 AssertDI(!E->isEntryValue(), "Entry values are only allowed in MIR", &I); 5692 } 5693 5694 void Verifier::verifyCompileUnits() { 5695 // When more than one Module is imported into the same context, such as during 5696 // an LTO build before linking the modules, ODR type uniquing may cause types 5697 // to point to a different CU. This check does not make sense in this case. 5698 if (M.getContext().isODRUniquingDebugTypes()) 5699 return; 5700 auto *CUs = M.getNamedMetadata("llvm.dbg.cu"); 5701 SmallPtrSet<const Metadata *, 2> Listed; 5702 if (CUs) 5703 Listed.insert(CUs->op_begin(), CUs->op_end()); 5704 for (auto *CU : CUVisited) 5705 AssertDI(Listed.count(CU), "DICompileUnit not listed in llvm.dbg.cu", CU); 5706 CUVisited.clear(); 5707 } 5708 5709 void Verifier::verifyDeoptimizeCallingConvs() { 5710 if (DeoptimizeDeclarations.empty()) 5711 return; 5712 5713 const Function *First = DeoptimizeDeclarations[0]; 5714 for (auto *F : makeArrayRef(DeoptimizeDeclarations).slice(1)) { 5715 Assert(First->getCallingConv() == F->getCallingConv(), 5716 "All llvm.experimental.deoptimize declarations must have the same " 5717 "calling convention", 5718 First, F); 5719 } 5720 } 5721 5722 void Verifier::verifySourceDebugInfo(const DICompileUnit &U, const DIFile &F) { 5723 bool HasSource = F.getSource().hasValue(); 5724 if (!HasSourceDebugInfo.count(&U)) 5725 HasSourceDebugInfo[&U] = HasSource; 5726 AssertDI(HasSource == HasSourceDebugInfo[&U], 5727 "inconsistent use of embedded source"); 5728 } 5729 5730 void Verifier::verifyNoAliasScopeDecl() { 5731 if (NoAliasScopeDecls.empty()) 5732 return; 5733 5734 // only a single scope must be declared at a time. 5735 for (auto *II : NoAliasScopeDecls) { 5736 assert(II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl && 5737 "Not a llvm.experimental.noalias.scope.decl ?"); 5738 const auto *ScopeListMV = dyn_cast<MetadataAsValue>( 5739 II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg)); 5740 Assert(ScopeListMV != nullptr, 5741 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue " 5742 "argument", 5743 II); 5744 5745 const auto *ScopeListMD = dyn_cast<MDNode>(ScopeListMV->getMetadata()); 5746 Assert(ScopeListMD != nullptr, "!id.scope.list must point to an MDNode", 5747 II); 5748 Assert(ScopeListMD->getNumOperands() == 1, 5749 "!id.scope.list must point to a list with a single scope", II); 5750 } 5751 5752 // Only check the domination rule when requested. Once all passes have been 5753 // adapted this option can go away. 5754 if (!VerifyNoAliasScopeDomination) 5755 return; 5756 5757 // Now sort the intrinsics based on the scope MDNode so that declarations of 5758 // the same scopes are next to each other. 5759 auto GetScope = [](IntrinsicInst *II) { 5760 const auto *ScopeListMV = cast<MetadataAsValue>( 5761 II->getOperand(Intrinsic::NoAliasScopeDeclScopeArg)); 5762 return &cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0); 5763 }; 5764 5765 // We are sorting on MDNode pointers here. For valid input IR this is ok. 5766 // TODO: Sort on Metadata ID to avoid non-deterministic error messages. 5767 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) { 5768 return GetScope(Lhs) < GetScope(Rhs); 5769 }; 5770 5771 llvm::sort(NoAliasScopeDecls, Compare); 5772 5773 // Go over the intrinsics and check that for the same scope, they are not 5774 // dominating each other. 5775 auto ItCurrent = NoAliasScopeDecls.begin(); 5776 while (ItCurrent != NoAliasScopeDecls.end()) { 5777 auto CurScope = GetScope(*ItCurrent); 5778 auto ItNext = ItCurrent; 5779 do { 5780 ++ItNext; 5781 } while (ItNext != NoAliasScopeDecls.end() && 5782 GetScope(*ItNext) == CurScope); 5783 5784 // [ItCurrent, ItNext) represents the declarations for the same scope. 5785 // Ensure they are not dominating each other.. but only if it is not too 5786 // expensive. 5787 if (ItNext - ItCurrent < 32) 5788 for (auto *I : llvm::make_range(ItCurrent, ItNext)) 5789 for (auto *J : llvm::make_range(ItCurrent, ItNext)) 5790 if (I != J) 5791 Assert(!DT.dominates(I, J), 5792 "llvm.experimental.noalias.scope.decl dominates another one " 5793 "with the same scope", 5794 I); 5795 ItCurrent = ItNext; 5796 } 5797 } 5798 5799 //===----------------------------------------------------------------------===// 5800 // Implement the public interfaces to this file... 5801 //===----------------------------------------------------------------------===// 5802 5803 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) { 5804 Function &F = const_cast<Function &>(f); 5805 5806 // Don't use a raw_null_ostream. Printing IR is expensive. 5807 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f.getParent()); 5808 5809 // Note that this function's return value is inverted from what you would 5810 // expect of a function called "verify". 5811 return !V.verify(F); 5812 } 5813 5814 bool llvm::verifyModule(const Module &M, raw_ostream *OS, 5815 bool *BrokenDebugInfo) { 5816 // Don't use a raw_null_ostream. Printing IR is expensive. 5817 Verifier V(OS, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo, M); 5818 5819 bool Broken = false; 5820 for (const Function &F : M) 5821 Broken |= !V.verify(F); 5822 5823 Broken |= !V.verify(); 5824 if (BrokenDebugInfo) 5825 *BrokenDebugInfo = V.hasBrokenDebugInfo(); 5826 // Note that this function's return value is inverted from what you would 5827 // expect of a function called "verify". 5828 return Broken; 5829 } 5830 5831 namespace { 5832 5833 struct VerifierLegacyPass : public FunctionPass { 5834 static char ID; 5835 5836 std::unique_ptr<Verifier> V; 5837 bool FatalErrors = true; 5838 5839 VerifierLegacyPass() : FunctionPass(ID) { 5840 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 5841 } 5842 explicit VerifierLegacyPass(bool FatalErrors) 5843 : FunctionPass(ID), 5844 FatalErrors(FatalErrors) { 5845 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry()); 5846 } 5847 5848 bool doInitialization(Module &M) override { 5849 V = std::make_unique<Verifier>( 5850 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M); 5851 return false; 5852 } 5853 5854 bool runOnFunction(Function &F) override { 5855 if (!V->verify(F) && FatalErrors) { 5856 errs() << "in function " << F.getName() << '\n'; 5857 report_fatal_error("Broken function found, compilation aborted!"); 5858 } 5859 return false; 5860 } 5861 5862 bool doFinalization(Module &M) override { 5863 bool HasErrors = false; 5864 for (Function &F : M) 5865 if (F.isDeclaration()) 5866 HasErrors |= !V->verify(F); 5867 5868 HasErrors |= !V->verify(); 5869 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo())) 5870 report_fatal_error("Broken module found, compilation aborted!"); 5871 return false; 5872 } 5873 5874 void getAnalysisUsage(AnalysisUsage &AU) const override { 5875 AU.setPreservesAll(); 5876 } 5877 }; 5878 5879 } // end anonymous namespace 5880 5881 /// Helper to issue failure from the TBAA verification 5882 template <typename... Tys> void TBAAVerifier::CheckFailed(Tys &&... Args) { 5883 if (Diagnostic) 5884 return Diagnostic->CheckFailed(Args...); 5885 } 5886 5887 #define AssertTBAA(C, ...) \ 5888 do { \ 5889 if (!(C)) { \ 5890 CheckFailed(__VA_ARGS__); \ 5891 return false; \ 5892 } \ 5893 } while (false) 5894 5895 /// Verify that \p BaseNode can be used as the "base type" in the struct-path 5896 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a 5897 /// struct-type node describing an aggregate data structure (like a struct). 5898 TBAAVerifier::TBAABaseNodeSummary 5899 TBAAVerifier::verifyTBAABaseNode(Instruction &I, const MDNode *BaseNode, 5900 bool IsNewFormat) { 5901 if (BaseNode->getNumOperands() < 2) { 5902 CheckFailed("Base nodes must have at least two operands", &I, BaseNode); 5903 return {true, ~0u}; 5904 } 5905 5906 auto Itr = TBAABaseNodes.find(BaseNode); 5907 if (Itr != TBAABaseNodes.end()) 5908 return Itr->second; 5909 5910 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat); 5911 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result}); 5912 (void)InsertResult; 5913 assert(InsertResult.second && "We just checked!"); 5914 return Result; 5915 } 5916 5917 TBAAVerifier::TBAABaseNodeSummary 5918 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction &I, const MDNode *BaseNode, 5919 bool IsNewFormat) { 5920 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {true, ~0u}; 5921 5922 if (BaseNode->getNumOperands() == 2) { 5923 // Scalar nodes can only be accessed at offset 0. 5924 return isValidScalarTBAANode(BaseNode) 5925 ? TBAAVerifier::TBAABaseNodeSummary({false, 0}) 5926 : InvalidNode; 5927 } 5928 5929 if (IsNewFormat) { 5930 if (BaseNode->getNumOperands() % 3 != 0) { 5931 CheckFailed("Access tag nodes must have the number of operands that is a " 5932 "multiple of 3!", BaseNode); 5933 return InvalidNode; 5934 } 5935 } else { 5936 if (BaseNode->getNumOperands() % 2 != 1) { 5937 CheckFailed("Struct tag nodes must have an odd number of operands!", 5938 BaseNode); 5939 return InvalidNode; 5940 } 5941 } 5942 5943 // Check the type size field. 5944 if (IsNewFormat) { 5945 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 5946 BaseNode->getOperand(1)); 5947 if (!TypeSizeNode) { 5948 CheckFailed("Type size nodes must be constants!", &I, BaseNode); 5949 return InvalidNode; 5950 } 5951 } 5952 5953 // Check the type name field. In the new format it can be anything. 5954 if (!IsNewFormat && !isa<MDString>(BaseNode->getOperand(0))) { 5955 CheckFailed("Struct tag nodes have a string as their first operand", 5956 BaseNode); 5957 return InvalidNode; 5958 } 5959 5960 bool Failed = false; 5961 5962 Optional<APInt> PrevOffset; 5963 unsigned BitWidth = ~0u; 5964 5965 // We've already checked that BaseNode is not a degenerate root node with one 5966 // operand in \c verifyTBAABaseNode, so this loop should run at least once. 5967 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1; 5968 unsigned NumOpsPerField = IsNewFormat ? 3 : 2; 5969 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands(); 5970 Idx += NumOpsPerField) { 5971 const MDOperand &FieldTy = BaseNode->getOperand(Idx); 5972 const MDOperand &FieldOffset = BaseNode->getOperand(Idx + 1); 5973 if (!isa<MDNode>(FieldTy)) { 5974 CheckFailed("Incorrect field entry in struct type node!", &I, BaseNode); 5975 Failed = true; 5976 continue; 5977 } 5978 5979 auto *OffsetEntryCI = 5980 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset); 5981 if (!OffsetEntryCI) { 5982 CheckFailed("Offset entries must be constants!", &I, BaseNode); 5983 Failed = true; 5984 continue; 5985 } 5986 5987 if (BitWidth == ~0u) 5988 BitWidth = OffsetEntryCI->getBitWidth(); 5989 5990 if (OffsetEntryCI->getBitWidth() != BitWidth) { 5991 CheckFailed( 5992 "Bitwidth between the offsets and struct type entries must match", &I, 5993 BaseNode); 5994 Failed = true; 5995 continue; 5996 } 5997 5998 // NB! As far as I can tell, we generate a non-strictly increasing offset 5999 // sequence only from structs that have zero size bit fields. When 6000 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we 6001 // pick the field lexically the latest in struct type metadata node. This 6002 // mirrors the actual behavior of the alias analysis implementation. 6003 bool IsAscending = 6004 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue()); 6005 6006 if (!IsAscending) { 6007 CheckFailed("Offsets must be increasing!", &I, BaseNode); 6008 Failed = true; 6009 } 6010 6011 PrevOffset = OffsetEntryCI->getValue(); 6012 6013 if (IsNewFormat) { 6014 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 6015 BaseNode->getOperand(Idx + 2)); 6016 if (!MemberSizeNode) { 6017 CheckFailed("Member size entries must be constants!", &I, BaseNode); 6018 Failed = true; 6019 continue; 6020 } 6021 } 6022 } 6023 6024 return Failed ? InvalidNode 6025 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth); 6026 } 6027 6028 static bool IsRootTBAANode(const MDNode *MD) { 6029 return MD->getNumOperands() < 2; 6030 } 6031 6032 static bool IsScalarTBAANodeImpl(const MDNode *MD, 6033 SmallPtrSetImpl<const MDNode *> &Visited) { 6034 if (MD->getNumOperands() != 2 && MD->getNumOperands() != 3) 6035 return false; 6036 6037 if (!isa<MDString>(MD->getOperand(0))) 6038 return false; 6039 6040 if (MD->getNumOperands() == 3) { 6041 auto *Offset = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); 6042 if (!(Offset && Offset->isZero() && isa<MDString>(MD->getOperand(0)))) 6043 return false; 6044 } 6045 6046 auto *Parent = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 6047 return Parent && Visited.insert(Parent).second && 6048 (IsRootTBAANode(Parent) || IsScalarTBAANodeImpl(Parent, Visited)); 6049 } 6050 6051 bool TBAAVerifier::isValidScalarTBAANode(const MDNode *MD) { 6052 auto ResultIt = TBAAScalarNodes.find(MD); 6053 if (ResultIt != TBAAScalarNodes.end()) 6054 return ResultIt->second; 6055 6056 SmallPtrSet<const MDNode *, 4> Visited; 6057 bool Result = IsScalarTBAANodeImpl(MD, Visited); 6058 auto InsertResult = TBAAScalarNodes.insert({MD, Result}); 6059 (void)InsertResult; 6060 assert(InsertResult.second && "Just checked!"); 6061 6062 return Result; 6063 } 6064 6065 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p 6066 /// Offset in place to be the offset within the field node returned. 6067 /// 6068 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode. 6069 MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction &I, 6070 const MDNode *BaseNode, 6071 APInt &Offset, 6072 bool IsNewFormat) { 6073 assert(BaseNode->getNumOperands() >= 2 && "Invalid base node!"); 6074 6075 // Scalar nodes have only one possible "field" -- their parent in the access 6076 // hierarchy. Offset must be zero at this point, but our caller is supposed 6077 // to Assert that. 6078 if (BaseNode->getNumOperands() == 2) 6079 return cast<MDNode>(BaseNode->getOperand(1)); 6080 6081 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1; 6082 unsigned NumOpsPerField = IsNewFormat ? 3 : 2; 6083 for (unsigned Idx = FirstFieldOpNo; Idx < BaseNode->getNumOperands(); 6084 Idx += NumOpsPerField) { 6085 auto *OffsetEntryCI = 6086 mdconst::extract<ConstantInt>(BaseNode->getOperand(Idx + 1)); 6087 if (OffsetEntryCI->getValue().ugt(Offset)) { 6088 if (Idx == FirstFieldOpNo) { 6089 CheckFailed("Could not find TBAA parent in struct type node", &I, 6090 BaseNode, &Offset); 6091 return nullptr; 6092 } 6093 6094 unsigned PrevIdx = Idx - NumOpsPerField; 6095 auto *PrevOffsetEntryCI = 6096 mdconst::extract<ConstantInt>(BaseNode->getOperand(PrevIdx + 1)); 6097 Offset -= PrevOffsetEntryCI->getValue(); 6098 return cast<MDNode>(BaseNode->getOperand(PrevIdx)); 6099 } 6100 } 6101 6102 unsigned LastIdx = BaseNode->getNumOperands() - NumOpsPerField; 6103 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>( 6104 BaseNode->getOperand(LastIdx + 1)); 6105 Offset -= LastOffsetEntryCI->getValue(); 6106 return cast<MDNode>(BaseNode->getOperand(LastIdx)); 6107 } 6108 6109 static bool isNewFormatTBAATypeNode(llvm::MDNode *Type) { 6110 if (!Type || Type->getNumOperands() < 3) 6111 return false; 6112 6113 // In the new format type nodes shall have a reference to the parent type as 6114 // its first operand. 6115 MDNode *Parent = dyn_cast_or_null<MDNode>(Type->getOperand(0)); 6116 if (!Parent) 6117 return false; 6118 6119 return true; 6120 } 6121 6122 bool TBAAVerifier::visitTBAAMetadata(Instruction &I, const MDNode *MD) { 6123 AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) || 6124 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) || 6125 isa<AtomicCmpXchgInst>(I), 6126 "This instruction shall not have a TBAA access tag!", &I); 6127 6128 bool IsStructPathTBAA = 6129 isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3; 6130 6131 AssertTBAA( 6132 IsStructPathTBAA, 6133 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I); 6134 6135 MDNode *BaseNode = dyn_cast_or_null<MDNode>(MD->getOperand(0)); 6136 MDNode *AccessType = dyn_cast_or_null<MDNode>(MD->getOperand(1)); 6137 6138 bool IsNewFormat = isNewFormatTBAATypeNode(AccessType); 6139 6140 if (IsNewFormat) { 6141 AssertTBAA(MD->getNumOperands() == 4 || MD->getNumOperands() == 5, 6142 "Access tag metadata must have either 4 or 5 operands", &I, MD); 6143 } else { 6144 AssertTBAA(MD->getNumOperands() < 5, 6145 "Struct tag metadata must have either 3 or 4 operands", &I, MD); 6146 } 6147 6148 // Check the access size field. 6149 if (IsNewFormat) { 6150 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>( 6151 MD->getOperand(3)); 6152 AssertTBAA(AccessSizeNode, "Access size field must be a constant", &I, MD); 6153 } 6154 6155 // Check the immutability flag. 6156 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3; 6157 if (MD->getNumOperands() == ImmutabilityFlagOpNo + 1) { 6158 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>( 6159 MD->getOperand(ImmutabilityFlagOpNo)); 6160 AssertTBAA(IsImmutableCI, 6161 "Immutability tag on struct tag metadata must be a constant", 6162 &I, MD); 6163 AssertTBAA( 6164 IsImmutableCI->isZero() || IsImmutableCI->isOne(), 6165 "Immutability part of the struct tag metadata must be either 0 or 1", 6166 &I, MD); 6167 } 6168 6169 AssertTBAA(BaseNode && AccessType, 6170 "Malformed struct tag metadata: base and access-type " 6171 "should be non-null and point to Metadata nodes", 6172 &I, MD, BaseNode, AccessType); 6173 6174 if (!IsNewFormat) { 6175 AssertTBAA(isValidScalarTBAANode(AccessType), 6176 "Access type node must be a valid scalar type", &I, MD, 6177 AccessType); 6178 } 6179 6180 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->getOperand(2)); 6181 AssertTBAA(OffsetCI, "Offset must be constant integer", &I, MD); 6182 6183 APInt Offset = OffsetCI->getValue(); 6184 bool SeenAccessTypeInPath = false; 6185 6186 SmallPtrSet<MDNode *, 4> StructPath; 6187 6188 for (/* empty */; BaseNode && !IsRootTBAANode(BaseNode); 6189 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset, 6190 IsNewFormat)) { 6191 if (!StructPath.insert(BaseNode).second) { 6192 CheckFailed("Cycle detected in struct path", &I, MD); 6193 return false; 6194 } 6195 6196 bool Invalid; 6197 unsigned BaseNodeBitWidth; 6198 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode, 6199 IsNewFormat); 6200 6201 // If the base node is invalid in itself, then we've already printed all the 6202 // errors we wanted to print. 6203 if (Invalid) 6204 return false; 6205 6206 SeenAccessTypeInPath |= BaseNode == AccessType; 6207 6208 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType) 6209 AssertTBAA(Offset == 0, "Offset not zero at the point of scalar access", 6210 &I, MD, &Offset); 6211 6212 AssertTBAA(BaseNodeBitWidth == Offset.getBitWidth() || 6213 (BaseNodeBitWidth == 0 && Offset == 0) || 6214 (IsNewFormat && BaseNodeBitWidth == ~0u), 6215 "Access bit-width not the same as description bit-width", &I, MD, 6216 BaseNodeBitWidth, Offset.getBitWidth()); 6217 6218 if (IsNewFormat && SeenAccessTypeInPath) 6219 break; 6220 } 6221 6222 AssertTBAA(SeenAccessTypeInPath, "Did not see access type in access path!", 6223 &I, MD); 6224 return true; 6225 } 6226 6227 char VerifierLegacyPass::ID = 0; 6228 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false) 6229 6230 FunctionPass *llvm::createVerifierPass(bool FatalErrors) { 6231 return new VerifierLegacyPass(FatalErrors); 6232 } 6233 6234 AnalysisKey VerifierAnalysis::Key; 6235 VerifierAnalysis::Result VerifierAnalysis::run(Module &M, 6236 ModuleAnalysisManager &) { 6237 Result Res; 6238 Res.IRBroken = llvm::verifyModule(M, &dbgs(), &Res.DebugInfoBroken); 6239 return Res; 6240 } 6241 6242 VerifierAnalysis::Result VerifierAnalysis::run(Function &F, 6243 FunctionAnalysisManager &) { 6244 return { llvm::verifyFunction(F, &dbgs()), false }; 6245 } 6246 6247 PreservedAnalyses VerifierPass::run(Module &M, ModuleAnalysisManager &AM) { 6248 auto Res = AM.getResult<VerifierAnalysis>(M); 6249 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken)) 6250 report_fatal_error("Broken module found, compilation aborted!"); 6251 6252 return PreservedAnalyses::all(); 6253 } 6254 6255 PreservedAnalyses VerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 6256 auto res = AM.getResult<VerifierAnalysis>(F); 6257 if (res.IRBroken && FatalErrors) 6258 report_fatal_error("Broken function found, compilation aborted!"); 6259 6260 return PreservedAnalyses::all(); 6261 } 6262