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