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