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