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