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