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