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