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