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