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