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