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