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