1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===// 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 #include "MetadataLoader.h" 10 #include "ValueList.h" 11 12 #include "llvm/ADT/APFloat.h" 13 #include "llvm/ADT/APInt.h" 14 #include "llvm/ADT/ArrayRef.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/None.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallString.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Bitcode/BitcodeReader.h" 24 #include "llvm/Bitcode/LLVMBitCodes.h" 25 #include "llvm/Bitstream/BitstreamReader.h" 26 #include "llvm/IR/Argument.h" 27 #include "llvm/IR/Attributes.h" 28 #include "llvm/IR/AutoUpgrade.h" 29 #include "llvm/IR/BasicBlock.h" 30 #include "llvm/IR/CallingConv.h" 31 #include "llvm/IR/Comdat.h" 32 #include "llvm/IR/Constant.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DebugInfo.h" 35 #include "llvm/IR/DebugInfoMetadata.h" 36 #include "llvm/IR/DebugLoc.h" 37 #include "llvm/IR/DerivedTypes.h" 38 #include "llvm/IR/DiagnosticPrinter.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GVMaterializer.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalIFunc.h" 43 #include "llvm/IR/GlobalObject.h" 44 #include "llvm/IR/GlobalValue.h" 45 #include "llvm/IR/GlobalVariable.h" 46 #include "llvm/IR/InlineAsm.h" 47 #include "llvm/IR/InstrTypes.h" 48 #include "llvm/IR/Instruction.h" 49 #include "llvm/IR/Instructions.h" 50 #include "llvm/IR/IntrinsicInst.h" 51 #include "llvm/IR/Intrinsics.h" 52 #include "llvm/IR/LLVMContext.h" 53 #include "llvm/IR/Module.h" 54 #include "llvm/IR/ModuleSummaryIndex.h" 55 #include "llvm/IR/OperandTraits.h" 56 #include "llvm/IR/TrackingMDRef.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/ValueHandle.h" 59 #include "llvm/Support/AtomicOrdering.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/Compiler.h" 63 #include "llvm/Support/Debug.h" 64 #include "llvm/Support/ErrorHandling.h" 65 #include "llvm/Support/ManagedStatic.h" 66 #include "llvm/Support/MemoryBuffer.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include <algorithm> 69 #include <cassert> 70 #include <cstddef> 71 #include <cstdint> 72 #include <deque> 73 #include <limits> 74 #include <map> 75 #include <string> 76 #include <system_error> 77 #include <tuple> 78 #include <utility> 79 #include <vector> 80 81 using namespace llvm; 82 83 #define DEBUG_TYPE "bitcode-reader" 84 85 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded"); 86 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created"); 87 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded"); 88 89 /// Flag whether we need to import full type definitions for ThinLTO. 90 /// Currently needed for Darwin and LLDB. 91 static cl::opt<bool> ImportFullTypeDefinitions( 92 "import-full-type-definitions", cl::init(false), cl::Hidden, 93 cl::desc("Import full type definitions for ThinLTO.")); 94 95 static cl::opt<bool> DisableLazyLoading( 96 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden, 97 cl::desc("Force disable the lazy-loading on-demand of metadata when " 98 "loading bitcode for importing.")); 99 100 namespace { 101 102 static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; } 103 104 class BitcodeReaderMetadataList { 105 /// Array of metadata references. 106 /// 107 /// Don't use std::vector here. Some versions of libc++ copy (instead of 108 /// move) on resize, and TrackingMDRef is very expensive to copy. 109 SmallVector<TrackingMDRef, 1> MetadataPtrs; 110 111 /// The set of indices in MetadataPtrs above of forward references that were 112 /// generated. 113 SmallDenseSet<unsigned, 1> ForwardReference; 114 115 /// The set of indices in MetadataPtrs above of Metadata that need to be 116 /// resolved. 117 SmallDenseSet<unsigned, 1> UnresolvedNodes; 118 119 /// Structures for resolving old type refs. 120 struct { 121 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown; 122 SmallDenseMap<MDString *, DICompositeType *, 1> Final; 123 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls; 124 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays; 125 } OldTypeRefs; 126 127 LLVMContext &Context; 128 129 /// Maximum number of valid references. Forward references exceeding the 130 /// maximum must be invalid. 131 unsigned RefsUpperBound; 132 133 public: 134 BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound) 135 : Context(C), 136 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(), 137 RefsUpperBound)) {} 138 139 // vector compatibility methods 140 unsigned size() const { return MetadataPtrs.size(); } 141 void resize(unsigned N) { MetadataPtrs.resize(N); } 142 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); } 143 void clear() { MetadataPtrs.clear(); } 144 Metadata *back() const { return MetadataPtrs.back(); } 145 void pop_back() { MetadataPtrs.pop_back(); } 146 bool empty() const { return MetadataPtrs.empty(); } 147 148 Metadata *operator[](unsigned i) const { 149 assert(i < MetadataPtrs.size()); 150 return MetadataPtrs[i]; 151 } 152 153 Metadata *lookup(unsigned I) const { 154 if (I < MetadataPtrs.size()) 155 return MetadataPtrs[I]; 156 return nullptr; 157 } 158 159 void shrinkTo(unsigned N) { 160 assert(N <= size() && "Invalid shrinkTo request!"); 161 assert(ForwardReference.empty() && "Unexpected forward refs"); 162 assert(UnresolvedNodes.empty() && "Unexpected unresolved node"); 163 MetadataPtrs.resize(N); 164 } 165 166 /// Return the given metadata, creating a replaceable forward reference if 167 /// necessary. 168 Metadata *getMetadataFwdRef(unsigned Idx); 169 170 /// Return the given metadata only if it is fully resolved. 171 /// 172 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved() 173 /// would give \c false. 174 Metadata *getMetadataIfResolved(unsigned Idx); 175 176 MDNode *getMDNodeFwdRefOrNull(unsigned Idx); 177 void assignValue(Metadata *MD, unsigned Idx); 178 void tryToResolveCycles(); 179 bool hasFwdRefs() const { return !ForwardReference.empty(); } 180 int getNextFwdRef() { 181 assert(hasFwdRefs()); 182 return *ForwardReference.begin(); 183 } 184 185 /// Upgrade a type that had an MDString reference. 186 void addTypeRef(MDString &UUID, DICompositeType &CT); 187 188 /// Upgrade a type that had an MDString reference. 189 Metadata *upgradeTypeRef(Metadata *MaybeUUID); 190 191 /// Upgrade a type ref array that may have MDString references. 192 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple); 193 194 private: 195 Metadata *resolveTypeRefArray(Metadata *MaybeTuple); 196 }; 197 198 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) { 199 if (auto *MDN = dyn_cast<MDNode>(MD)) 200 if (!MDN->isResolved()) 201 UnresolvedNodes.insert(Idx); 202 203 if (Idx == size()) { 204 push_back(MD); 205 return; 206 } 207 208 if (Idx >= size()) 209 resize(Idx + 1); 210 211 TrackingMDRef &OldMD = MetadataPtrs[Idx]; 212 if (!OldMD) { 213 OldMD.reset(MD); 214 return; 215 } 216 217 // If there was a forward reference to this value, replace it. 218 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get())); 219 PrevMD->replaceAllUsesWith(MD); 220 ForwardReference.erase(Idx); 221 } 222 223 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) { 224 // Bail out for a clearly invalid value. 225 if (Idx >= RefsUpperBound) 226 return nullptr; 227 228 if (Idx >= size()) 229 resize(Idx + 1); 230 231 if (Metadata *MD = MetadataPtrs[Idx]) 232 return MD; 233 234 // Track forward refs to be resolved later. 235 ForwardReference.insert(Idx); 236 237 // Create and return a placeholder, which will later be RAUW'd. 238 ++NumMDNodeTemporary; 239 Metadata *MD = MDNode::getTemporary(Context, None).release(); 240 MetadataPtrs[Idx].reset(MD); 241 return MD; 242 } 243 244 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) { 245 Metadata *MD = lookup(Idx); 246 if (auto *N = dyn_cast_or_null<MDNode>(MD)) 247 if (!N->isResolved()) 248 return nullptr; 249 return MD; 250 } 251 252 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) { 253 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx)); 254 } 255 256 void BitcodeReaderMetadataList::tryToResolveCycles() { 257 if (!ForwardReference.empty()) 258 // Still forward references... can't resolve cycles. 259 return; 260 261 // Give up on finding a full definition for any forward decls that remain. 262 for (const auto &Ref : OldTypeRefs.FwdDecls) 263 OldTypeRefs.Final.insert(Ref); 264 OldTypeRefs.FwdDecls.clear(); 265 266 // Upgrade from old type ref arrays. In strange cases, this could add to 267 // OldTypeRefs.Unknown. 268 for (const auto &Array : OldTypeRefs.Arrays) 269 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get())); 270 OldTypeRefs.Arrays.clear(); 271 272 // Replace old string-based type refs with the resolved node, if possible. 273 // If we haven't seen the node, leave it to the verifier to complain about 274 // the invalid string reference. 275 for (const auto &Ref : OldTypeRefs.Unknown) { 276 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first)) 277 Ref.second->replaceAllUsesWith(CT); 278 else 279 Ref.second->replaceAllUsesWith(Ref.first); 280 } 281 OldTypeRefs.Unknown.clear(); 282 283 if (UnresolvedNodes.empty()) 284 // Nothing to do. 285 return; 286 287 // Resolve any cycles. 288 for (unsigned I : UnresolvedNodes) { 289 auto &MD = MetadataPtrs[I]; 290 auto *N = dyn_cast_or_null<MDNode>(MD); 291 if (!N) 292 continue; 293 294 assert(!N->isTemporary() && "Unexpected forward reference"); 295 N->resolveCycles(); 296 } 297 298 // Make sure we return early again until there's another unresolved ref. 299 UnresolvedNodes.clear(); 300 } 301 302 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID, 303 DICompositeType &CT) { 304 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID"); 305 if (CT.isForwardDecl()) 306 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT)); 307 else 308 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT)); 309 } 310 311 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) { 312 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID); 313 if (LLVM_LIKELY(!UUID)) 314 return MaybeUUID; 315 316 if (auto *CT = OldTypeRefs.Final.lookup(UUID)) 317 return CT; 318 319 auto &Ref = OldTypeRefs.Unknown[UUID]; 320 if (!Ref) 321 Ref = MDNode::getTemporary(Context, None); 322 return Ref.get(); 323 } 324 325 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) { 326 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple); 327 if (!Tuple || Tuple->isDistinct()) 328 return MaybeTuple; 329 330 // Look through the array immediately if possible. 331 if (!Tuple->isTemporary()) 332 return resolveTypeRefArray(Tuple); 333 334 // Create and return a placeholder to use for now. Eventually 335 // resolveTypeRefArrays() will be resolve this forward reference. 336 OldTypeRefs.Arrays.emplace_back( 337 std::piecewise_construct, std::forward_as_tuple(Tuple), 338 std::forward_as_tuple(MDTuple::getTemporary(Context, None))); 339 return OldTypeRefs.Arrays.back().second.get(); 340 } 341 342 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) { 343 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple); 344 if (!Tuple || Tuple->isDistinct()) 345 return MaybeTuple; 346 347 // Look through the DITypeRefArray, upgrading each DIType *. 348 SmallVector<Metadata *, 32> Ops; 349 Ops.reserve(Tuple->getNumOperands()); 350 for (Metadata *MD : Tuple->operands()) 351 Ops.push_back(upgradeTypeRef(MD)); 352 353 return MDTuple::get(Context, Ops); 354 } 355 356 namespace { 357 358 class PlaceholderQueue { 359 // Placeholders would thrash around when moved, so store in a std::deque 360 // instead of some sort of vector. 361 std::deque<DistinctMDOperandPlaceholder> PHs; 362 363 public: 364 ~PlaceholderQueue() { 365 assert(empty() && 366 "PlaceholderQueue hasn't been flushed before being destroyed"); 367 } 368 bool empty() const { return PHs.empty(); } 369 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID); 370 void flush(BitcodeReaderMetadataList &MetadataList); 371 372 /// Return the list of temporaries nodes in the queue, these need to be 373 /// loaded before we can flush the queue. 374 void getTemporaries(BitcodeReaderMetadataList &MetadataList, 375 DenseSet<unsigned> &Temporaries) { 376 for (auto &PH : PHs) { 377 auto ID = PH.getID(); 378 auto *MD = MetadataList.lookup(ID); 379 if (!MD) { 380 Temporaries.insert(ID); 381 continue; 382 } 383 auto *N = dyn_cast_or_null<MDNode>(MD); 384 if (N && N->isTemporary()) 385 Temporaries.insert(ID); 386 } 387 } 388 }; 389 390 } // end anonymous namespace 391 392 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) { 393 PHs.emplace_back(ID); 394 return PHs.back(); 395 } 396 397 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) { 398 while (!PHs.empty()) { 399 auto *MD = MetadataList.lookup(PHs.front().getID()); 400 assert(MD && "Flushing placeholder on unassigned MD"); 401 #ifndef NDEBUG 402 if (auto *MDN = dyn_cast<MDNode>(MD)) 403 assert(MDN->isResolved() && 404 "Flushing Placeholder while cycles aren't resolved"); 405 #endif 406 PHs.front().replaceUseWith(MD); 407 PHs.pop_front(); 408 } 409 } 410 411 } // anonymous namespace 412 413 static Error error(const Twine &Message) { 414 return make_error<StringError>( 415 Message, make_error_code(BitcodeError::CorruptedBitcode)); 416 } 417 418 class MetadataLoader::MetadataLoaderImpl { 419 BitcodeReaderMetadataList MetadataList; 420 BitcodeReaderValueList &ValueList; 421 BitstreamCursor &Stream; 422 LLVMContext &Context; 423 Module &TheModule; 424 std::function<Type *(unsigned)> getTypeByID; 425 426 /// Cursor associated with the lazy-loading of Metadata. This is the easy way 427 /// to keep around the right "context" (Abbrev list) to be able to jump in 428 /// the middle of the metadata block and load any record. 429 BitstreamCursor IndexCursor; 430 431 /// Index that keeps track of MDString values. 432 std::vector<StringRef> MDStringRef; 433 434 /// On-demand loading of a single MDString. Requires the index above to be 435 /// populated. 436 MDString *lazyLoadOneMDString(unsigned Idx); 437 438 /// Index that keeps track of where to find a metadata record in the stream. 439 std::vector<uint64_t> GlobalMetadataBitPosIndex; 440 441 /// Cursor position of the start of the global decl attachments, to enable 442 /// loading using the index built for lazy loading, instead of forward 443 /// references. 444 uint64_t GlobalDeclAttachmentPos = 0; 445 446 #ifndef NDEBUG 447 /// Sanity check that we end up parsing all of the global decl attachments. 448 unsigned NumGlobalDeclAttachSkipped = 0; 449 unsigned NumGlobalDeclAttachParsed = 0; 450 #endif 451 452 /// Load the global decl attachments, using the index built for lazy loading. 453 Expected<bool> loadGlobalDeclAttachments(); 454 455 /// Populate the index above to enable lazily loading of metadata, and load 456 /// the named metadata as well as the transitively referenced global 457 /// Metadata. 458 Expected<bool> lazyLoadModuleMetadataBlock(); 459 460 /// On-demand loading of a single metadata. Requires the index above to be 461 /// populated. 462 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders); 463 464 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to 465 // point from SP to CU after a block is completly parsed. 466 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms; 467 468 /// Functions that need to be matched with subprograms when upgrading old 469 /// metadata. 470 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs; 471 472 // Map the bitcode's custom MDKind ID to the Module's MDKind ID. 473 DenseMap<unsigned, unsigned> MDKindMap; 474 475 bool StripTBAA = false; 476 bool HasSeenOldLoopTags = false; 477 bool NeedUpgradeToDIGlobalVariableExpression = false; 478 bool NeedDeclareExpressionUpgrade = false; 479 480 /// True if metadata is being parsed for a module being ThinLTO imported. 481 bool IsImporting = false; 482 483 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code, 484 PlaceholderQueue &Placeholders, StringRef Blob, 485 unsigned &NextMetadataNo); 486 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob, 487 function_ref<void(StringRef)> CallBack); 488 Error parseGlobalObjectAttachment(GlobalObject &GO, 489 ArrayRef<uint64_t> Record); 490 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record); 491 492 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders); 493 494 /// Upgrade old-style CU <-> SP pointers to point from SP to CU. 495 void upgradeCUSubprograms() { 496 for (auto CU_SP : CUSubprograms) 497 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second)) 498 for (auto &Op : SPs->operands()) 499 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op)) 500 SP->replaceUnit(CU_SP.first); 501 CUSubprograms.clear(); 502 } 503 504 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions. 505 void upgradeCUVariables() { 506 if (!NeedUpgradeToDIGlobalVariableExpression) 507 return; 508 509 // Upgrade list of variables attached to the CUs. 510 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu")) 511 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) { 512 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I)); 513 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables())) 514 for (unsigned I = 0; I < GVs->getNumOperands(); I++) 515 if (auto *GV = 516 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) { 517 auto *DGVE = DIGlobalVariableExpression::getDistinct( 518 Context, GV, DIExpression::get(Context, {})); 519 GVs->replaceOperandWith(I, DGVE); 520 } 521 } 522 523 // Upgrade variables attached to globals. 524 for (auto &GV : TheModule.globals()) { 525 SmallVector<MDNode *, 1> MDs; 526 GV.getMetadata(LLVMContext::MD_dbg, MDs); 527 GV.eraseMetadata(LLVMContext::MD_dbg); 528 for (auto *MD : MDs) 529 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) { 530 auto *DGVE = DIGlobalVariableExpression::getDistinct( 531 Context, DGV, DIExpression::get(Context, {})); 532 GV.addMetadata(LLVMContext::MD_dbg, *DGVE); 533 } else 534 GV.addMetadata(LLVMContext::MD_dbg, *MD); 535 } 536 } 537 538 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that 539 /// describes a function argument. 540 void upgradeDeclareExpressions(Function &F) { 541 if (!NeedDeclareExpressionUpgrade) 542 return; 543 544 for (auto &BB : F) 545 for (auto &I : BB) 546 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I)) 547 if (auto *DIExpr = DDI->getExpression()) 548 if (DIExpr->startsWithDeref() && 549 isa_and_nonnull<Argument>(DDI->getAddress())) { 550 SmallVector<uint64_t, 8> Ops; 551 Ops.append(std::next(DIExpr->elements_begin()), 552 DIExpr->elements_end()); 553 DDI->setExpression(DIExpression::get(Context, Ops)); 554 } 555 } 556 557 /// Upgrade the expression from previous versions. 558 Error upgradeDIExpression(uint64_t FromVersion, 559 MutableArrayRef<uint64_t> &Expr, 560 SmallVectorImpl<uint64_t> &Buffer) { 561 auto N = Expr.size(); 562 switch (FromVersion) { 563 default: 564 return error("Invalid record"); 565 case 0: 566 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece) 567 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment; 568 LLVM_FALLTHROUGH; 569 case 1: 570 // Move DW_OP_deref to the end. 571 if (N && Expr[0] == dwarf::DW_OP_deref) { 572 auto End = Expr.end(); 573 if (Expr.size() >= 3 && 574 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment) 575 End = std::prev(End, 3); 576 std::move(std::next(Expr.begin()), End, Expr.begin()); 577 *std::prev(End) = dwarf::DW_OP_deref; 578 } 579 NeedDeclareExpressionUpgrade = true; 580 LLVM_FALLTHROUGH; 581 case 2: { 582 // Change DW_OP_plus to DW_OP_plus_uconst. 583 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus 584 auto SubExpr = ArrayRef<uint64_t>(Expr); 585 while (!SubExpr.empty()) { 586 // Skip past other operators with their operands 587 // for this version of the IR, obtained from 588 // from historic DIExpression::ExprOperand::getSize(). 589 size_t HistoricSize; 590 switch (SubExpr.front()) { 591 default: 592 HistoricSize = 1; 593 break; 594 case dwarf::DW_OP_constu: 595 case dwarf::DW_OP_minus: 596 case dwarf::DW_OP_plus: 597 HistoricSize = 2; 598 break; 599 case dwarf::DW_OP_LLVM_fragment: 600 HistoricSize = 3; 601 break; 602 } 603 604 // If the expression is malformed, make sure we don't 605 // copy more elements than we should. 606 HistoricSize = std::min(SubExpr.size(), HistoricSize); 607 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1); 608 609 switch (SubExpr.front()) { 610 case dwarf::DW_OP_plus: 611 Buffer.push_back(dwarf::DW_OP_plus_uconst); 612 Buffer.append(Args.begin(), Args.end()); 613 break; 614 case dwarf::DW_OP_minus: 615 Buffer.push_back(dwarf::DW_OP_constu); 616 Buffer.append(Args.begin(), Args.end()); 617 Buffer.push_back(dwarf::DW_OP_minus); 618 break; 619 default: 620 Buffer.push_back(*SubExpr.begin()); 621 Buffer.append(Args.begin(), Args.end()); 622 break; 623 } 624 625 // Continue with remaining elements. 626 SubExpr = SubExpr.slice(HistoricSize); 627 } 628 Expr = MutableArrayRef<uint64_t>(Buffer); 629 LLVM_FALLTHROUGH; 630 } 631 case 3: 632 // Up-to-date! 633 break; 634 } 635 636 return Error::success(); 637 } 638 639 void upgradeDebugInfo() { 640 upgradeCUSubprograms(); 641 upgradeCUVariables(); 642 } 643 644 public: 645 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule, 646 BitcodeReaderValueList &ValueList, 647 std::function<Type *(unsigned)> getTypeByID, 648 bool IsImporting) 649 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()), 650 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()), 651 TheModule(TheModule), getTypeByID(std::move(getTypeByID)), 652 IsImporting(IsImporting) {} 653 654 Error parseMetadata(bool ModuleLevel); 655 656 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); } 657 658 Metadata *getMetadataFwdRefOrLoad(unsigned ID) { 659 if (ID < MDStringRef.size()) 660 return lazyLoadOneMDString(ID); 661 if (auto *MD = MetadataList.lookup(ID)) 662 return MD; 663 // If lazy-loading is enabled, we try recursively to load the operand 664 // instead of creating a temporary. 665 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) { 666 PlaceholderQueue Placeholders; 667 lazyLoadOneMetadata(ID, Placeholders); 668 resolveForwardRefsAndPlaceholders(Placeholders); 669 return MetadataList.lookup(ID); 670 } 671 return MetadataList.getMetadataFwdRef(ID); 672 } 673 674 DISubprogram *lookupSubprogramForFunction(Function *F) { 675 return FunctionsWithSPs.lookup(F); 676 } 677 678 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; } 679 680 Error parseMetadataAttachment( 681 Function &F, const SmallVectorImpl<Instruction *> &InstructionList); 682 683 Error parseMetadataKinds(); 684 685 void setStripTBAA(bool Value) { StripTBAA = Value; } 686 bool isStrippingTBAA() const { return StripTBAA; } 687 688 unsigned size() const { return MetadataList.size(); } 689 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); } 690 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); } 691 }; 692 693 Expected<bool> 694 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() { 695 IndexCursor = Stream; 696 SmallVector<uint64_t, 64> Record; 697 GlobalDeclAttachmentPos = 0; 698 // Get the abbrevs, and preload record positions to make them lazy-loadable. 699 while (true) { 700 uint64_t SavedPos = IndexCursor.GetCurrentBitNo(); 701 BitstreamEntry Entry; 702 if (Error E = 703 IndexCursor 704 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd) 705 .moveInto(Entry)) 706 return std::move(E); 707 708 switch (Entry.Kind) { 709 case BitstreamEntry::SubBlock: // Handled for us already. 710 case BitstreamEntry::Error: 711 return error("Malformed block"); 712 case BitstreamEntry::EndBlock: { 713 return true; 714 } 715 case BitstreamEntry::Record: { 716 // The interesting case. 717 ++NumMDRecordLoaded; 718 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo(); 719 unsigned Code; 720 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code)) 721 return std::move(E); 722 switch (Code) { 723 case bitc::METADATA_STRINGS: { 724 // Rewind and parse the strings. 725 if (Error Err = IndexCursor.JumpToBit(CurrentPos)) 726 return std::move(Err); 727 StringRef Blob; 728 Record.clear(); 729 if (Expected<unsigned> MaybeRecord = 730 IndexCursor.readRecord(Entry.ID, Record, &Blob)) 731 ; 732 else 733 return MaybeRecord.takeError(); 734 unsigned NumStrings = Record[0]; 735 MDStringRef.reserve(NumStrings); 736 auto IndexNextMDString = [&](StringRef Str) { 737 MDStringRef.push_back(Str); 738 }; 739 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString)) 740 return std::move(Err); 741 break; 742 } 743 case bitc::METADATA_INDEX_OFFSET: { 744 // This is the offset to the index, when we see this we skip all the 745 // records and load only an index to these. 746 if (Error Err = IndexCursor.JumpToBit(CurrentPos)) 747 return std::move(Err); 748 Record.clear(); 749 if (Expected<unsigned> MaybeRecord = 750 IndexCursor.readRecord(Entry.ID, Record)) 751 ; 752 else 753 return MaybeRecord.takeError(); 754 if (Record.size() != 2) 755 return error("Invalid record"); 756 auto Offset = Record[0] + (Record[1] << 32); 757 auto BeginPos = IndexCursor.GetCurrentBitNo(); 758 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset)) 759 return std::move(Err); 760 Expected<BitstreamEntry> MaybeEntry = 761 IndexCursor.advanceSkippingSubblocks( 762 BitstreamCursor::AF_DontPopBlockAtEnd); 763 if (!MaybeEntry) 764 return MaybeEntry.takeError(); 765 Entry = MaybeEntry.get(); 766 assert(Entry.Kind == BitstreamEntry::Record && 767 "Corrupted bitcode: Expected `Record` when trying to find the " 768 "Metadata index"); 769 Record.clear(); 770 if (Expected<unsigned> MaybeCode = 771 IndexCursor.readRecord(Entry.ID, Record)) 772 assert(MaybeCode.get() == bitc::METADATA_INDEX && 773 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to " 774 "find the Metadata index"); 775 else 776 return MaybeCode.takeError(); 777 // Delta unpack 778 auto CurrentValue = BeginPos; 779 GlobalMetadataBitPosIndex.reserve(Record.size()); 780 for (auto &Elt : Record) { 781 CurrentValue += Elt; 782 GlobalMetadataBitPosIndex.push_back(CurrentValue); 783 } 784 break; 785 } 786 case bitc::METADATA_INDEX: 787 // We don't expect to get there, the Index is loaded when we encounter 788 // the offset. 789 return error("Corrupted Metadata block"); 790 case bitc::METADATA_NAME: { 791 // Named metadata need to be materialized now and aren't deferred. 792 if (Error Err = IndexCursor.JumpToBit(CurrentPos)) 793 return std::move(Err); 794 Record.clear(); 795 796 unsigned Code; 797 if (Expected<unsigned> MaybeCode = 798 IndexCursor.readRecord(Entry.ID, Record)) { 799 Code = MaybeCode.get(); 800 assert(Code == bitc::METADATA_NAME); 801 } else 802 return MaybeCode.takeError(); 803 804 // Read name of the named metadata. 805 SmallString<8> Name(Record.begin(), Record.end()); 806 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode()) 807 Code = MaybeCode.get(); 808 else 809 return MaybeCode.takeError(); 810 811 // Named Metadata comes in two parts, we expect the name to be followed 812 // by the node 813 Record.clear(); 814 if (Expected<unsigned> MaybeNextBitCode = 815 IndexCursor.readRecord(Code, Record)) 816 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE); 817 else 818 return MaybeNextBitCode.takeError(); 819 820 // Read named metadata elements. 821 unsigned Size = Record.size(); 822 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name); 823 for (unsigned i = 0; i != Size; ++i) { 824 // FIXME: We could use a placeholder here, however NamedMDNode are 825 // taking MDNode as operand and not using the Metadata infrastructure. 826 // It is acknowledged by 'TODO: Inherit from Metadata' in the 827 // NamedMDNode class definition. 828 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]); 829 assert(MD && "Invalid metadata: expect fwd ref to MDNode"); 830 NMD->addOperand(MD); 831 } 832 break; 833 } 834 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: { 835 if (!GlobalDeclAttachmentPos) 836 GlobalDeclAttachmentPos = SavedPos; 837 #ifndef NDEBUG 838 NumGlobalDeclAttachSkipped++; 839 #endif 840 break; 841 } 842 case bitc::METADATA_KIND: 843 case bitc::METADATA_STRING_OLD: 844 case bitc::METADATA_OLD_FN_NODE: 845 case bitc::METADATA_OLD_NODE: 846 case bitc::METADATA_VALUE: 847 case bitc::METADATA_DISTINCT_NODE: 848 case bitc::METADATA_NODE: 849 case bitc::METADATA_LOCATION: 850 case bitc::METADATA_GENERIC_DEBUG: 851 case bitc::METADATA_SUBRANGE: 852 case bitc::METADATA_ENUMERATOR: 853 case bitc::METADATA_BASIC_TYPE: 854 case bitc::METADATA_STRING_TYPE: 855 case bitc::METADATA_DERIVED_TYPE: 856 case bitc::METADATA_COMPOSITE_TYPE: 857 case bitc::METADATA_SUBROUTINE_TYPE: 858 case bitc::METADATA_MODULE: 859 case bitc::METADATA_FILE: 860 case bitc::METADATA_COMPILE_UNIT: 861 case bitc::METADATA_SUBPROGRAM: 862 case bitc::METADATA_LEXICAL_BLOCK: 863 case bitc::METADATA_LEXICAL_BLOCK_FILE: 864 case bitc::METADATA_NAMESPACE: 865 case bitc::METADATA_COMMON_BLOCK: 866 case bitc::METADATA_MACRO: 867 case bitc::METADATA_MACRO_FILE: 868 case bitc::METADATA_TEMPLATE_TYPE: 869 case bitc::METADATA_TEMPLATE_VALUE: 870 case bitc::METADATA_GLOBAL_VAR: 871 case bitc::METADATA_LOCAL_VAR: 872 case bitc::METADATA_LABEL: 873 case bitc::METADATA_EXPRESSION: 874 case bitc::METADATA_OBJC_PROPERTY: 875 case bitc::METADATA_IMPORTED_ENTITY: 876 case bitc::METADATA_GLOBAL_VAR_EXPR: 877 case bitc::METADATA_GENERIC_SUBRANGE: 878 // We don't expect to see any of these, if we see one, give up on 879 // lazy-loading and fallback. 880 MDStringRef.clear(); 881 GlobalMetadataBitPosIndex.clear(); 882 return false; 883 } 884 break; 885 } 886 } 887 } 888 } 889 890 // Load the global decl attachments after building the lazy loading index. 891 // We don't load them "lazily" - all global decl attachments must be 892 // parsed since they aren't materialized on demand. However, by delaying 893 // their parsing until after the index is created, we can use the index 894 // instead of creating temporaries. 895 Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() { 896 // Nothing to do if we didn't find any of these metadata records. 897 if (!GlobalDeclAttachmentPos) 898 return true; 899 // Use a temporary cursor so that we don't mess up the main Stream cursor or 900 // the lazy loading IndexCursor (which holds the necessary abbrev ids). 901 BitstreamCursor TempCursor = Stream; 902 SmallVector<uint64_t, 64> Record; 903 // Jump to the position before the first global decl attachment, so we can 904 // scan for the first BitstreamEntry record. 905 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos)) 906 return std::move(Err); 907 while (true) { 908 BitstreamEntry Entry; 909 if (Error E = 910 TempCursor 911 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd) 912 .moveInto(Entry)) 913 return std::move(E); 914 915 switch (Entry.Kind) { 916 case BitstreamEntry::SubBlock: // Handled for us already. 917 case BitstreamEntry::Error: 918 return error("Malformed block"); 919 case BitstreamEntry::EndBlock: 920 // Sanity check that we parsed them all. 921 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed); 922 return true; 923 case BitstreamEntry::Record: 924 break; 925 } 926 uint64_t CurrentPos = TempCursor.GetCurrentBitNo(); 927 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID); 928 if (!MaybeCode) 929 return MaybeCode.takeError(); 930 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) { 931 // Anything other than a global decl attachment signals the end of 932 // these records. sanity check that we parsed them all. 933 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed); 934 return true; 935 } 936 #ifndef NDEBUG 937 NumGlobalDeclAttachParsed++; 938 #endif 939 // FIXME: we need to do this early because we don't materialize global 940 // value explicitly. 941 if (Error Err = TempCursor.JumpToBit(CurrentPos)) 942 return std::move(Err); 943 Record.clear(); 944 if (Expected<unsigned> MaybeRecord = 945 TempCursor.readRecord(Entry.ID, Record)) 946 ; 947 else 948 return MaybeRecord.takeError(); 949 if (Record.size() % 2 == 0) 950 return error("Invalid record"); 951 unsigned ValueID = Record[0]; 952 if (ValueID >= ValueList.size()) 953 return error("Invalid record"); 954 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) { 955 // Need to save and restore the current position since 956 // parseGlobalObjectAttachment will resolve all forward references which 957 // would require parsing from locations stored in the index. 958 CurrentPos = TempCursor.GetCurrentBitNo(); 959 if (Error Err = parseGlobalObjectAttachment( 960 *GO, ArrayRef<uint64_t>(Record).slice(1))) 961 return std::move(Err); 962 if (Error Err = TempCursor.JumpToBit(CurrentPos)) 963 return std::move(Err); 964 } 965 } 966 } 967 968 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing 969 /// module level metadata. 970 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) { 971 if (!ModuleLevel && MetadataList.hasFwdRefs()) 972 return error("Invalid metadata: fwd refs into function blocks"); 973 974 // Record the entry position so that we can jump back here and efficiently 975 // skip the whole block in case we lazy-load. 976 auto EntryPos = Stream.GetCurrentBitNo(); 977 978 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 979 return Err; 980 981 SmallVector<uint64_t, 64> Record; 982 PlaceholderQueue Placeholders; 983 984 // We lazy-load module-level metadata: we build an index for each record, and 985 // then load individual record as needed, starting with the named metadata. 986 if (ModuleLevel && IsImporting && MetadataList.empty() && 987 !DisableLazyLoading) { 988 auto SuccessOrErr = lazyLoadModuleMetadataBlock(); 989 if (!SuccessOrErr) 990 return SuccessOrErr.takeError(); 991 if (SuccessOrErr.get()) { 992 // An index was successfully created and we will be able to load metadata 993 // on-demand. 994 MetadataList.resize(MDStringRef.size() + 995 GlobalMetadataBitPosIndex.size()); 996 997 // Now that we have built the index, load the global decl attachments 998 // that were deferred during that process. This avoids creating 999 // temporaries. 1000 SuccessOrErr = loadGlobalDeclAttachments(); 1001 if (!SuccessOrErr) 1002 return SuccessOrErr.takeError(); 1003 assert(SuccessOrErr.get()); 1004 1005 // Reading the named metadata created forward references and/or 1006 // placeholders, that we flush here. 1007 resolveForwardRefsAndPlaceholders(Placeholders); 1008 upgradeDebugInfo(); 1009 // Return at the beginning of the block, since it is easy to skip it 1010 // entirely from there. 1011 Stream.ReadBlockEnd(); // Pop the abbrev block context. 1012 if (Error Err = IndexCursor.JumpToBit(EntryPos)) 1013 return Err; 1014 if (Error Err = Stream.SkipBlock()) { 1015 // FIXME this drops the error on the floor, which 1016 // ThinLTO/X86/debuginfo-cu-import.ll relies on. 1017 consumeError(std::move(Err)); 1018 return Error::success(); 1019 } 1020 return Error::success(); 1021 } 1022 // Couldn't load an index, fallback to loading all the block "old-style". 1023 } 1024 1025 unsigned NextMetadataNo = MetadataList.size(); 1026 1027 // Read all the records. 1028 while (true) { 1029 BitstreamEntry Entry; 1030 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) 1031 return E; 1032 1033 switch (Entry.Kind) { 1034 case BitstreamEntry::SubBlock: // Handled for us already. 1035 case BitstreamEntry::Error: 1036 return error("Malformed block"); 1037 case BitstreamEntry::EndBlock: 1038 resolveForwardRefsAndPlaceholders(Placeholders); 1039 upgradeDebugInfo(); 1040 return Error::success(); 1041 case BitstreamEntry::Record: 1042 // The interesting case. 1043 break; 1044 } 1045 1046 // Read a record. 1047 Record.clear(); 1048 StringRef Blob; 1049 ++NumMDRecordLoaded; 1050 if (Expected<unsigned> MaybeCode = 1051 Stream.readRecord(Entry.ID, Record, &Blob)) { 1052 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders, 1053 Blob, NextMetadataNo)) 1054 return Err; 1055 } else 1056 return MaybeCode.takeError(); 1057 } 1058 } 1059 1060 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) { 1061 ++NumMDStringLoaded; 1062 if (Metadata *MD = MetadataList.lookup(ID)) 1063 return cast<MDString>(MD); 1064 auto MDS = MDString::get(Context, MDStringRef[ID]); 1065 MetadataList.assignValue(MDS, ID); 1066 return MDS; 1067 } 1068 1069 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata( 1070 unsigned ID, PlaceholderQueue &Placeholders) { 1071 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size()); 1072 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString"); 1073 // Lookup first if the metadata hasn't already been loaded. 1074 if (auto *MD = MetadataList.lookup(ID)) { 1075 auto *N = cast<MDNode>(MD); 1076 if (!N->isTemporary()) 1077 return; 1078 } 1079 SmallVector<uint64_t, 64> Record; 1080 StringRef Blob; 1081 if (Error Err = IndexCursor.JumpToBit( 1082 GlobalMetadataBitPosIndex[ID - MDStringRef.size()])) 1083 report_fatal_error("lazyLoadOneMetadata failed jumping: " + 1084 Twine(toString(std::move(Err)))); 1085 BitstreamEntry Entry; 1086 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry)) 1087 // FIXME this drops the error on the floor. 1088 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " + 1089 Twine(toString(std::move(E)))); 1090 ++NumMDRecordLoaded; 1091 if (Expected<unsigned> MaybeCode = 1092 IndexCursor.readRecord(Entry.ID, Record, &Blob)) { 1093 if (Error Err = 1094 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID)) 1095 report_fatal_error("Can't lazyload MD, parseOneMetadata: " + 1096 Twine(toString(std::move(Err)))); 1097 } else 1098 report_fatal_error("Can't lazyload MD: " + 1099 Twine(toString(MaybeCode.takeError()))); 1100 } 1101 1102 /// Ensure that all forward-references and placeholders are resolved. 1103 /// Iteratively lazy-loading metadata on-demand if needed. 1104 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders( 1105 PlaceholderQueue &Placeholders) { 1106 DenseSet<unsigned> Temporaries; 1107 while (1) { 1108 // Populate Temporaries with the placeholders that haven't been loaded yet. 1109 Placeholders.getTemporaries(MetadataList, Temporaries); 1110 1111 // If we don't have any temporary, or FwdReference, we're done! 1112 if (Temporaries.empty() && !MetadataList.hasFwdRefs()) 1113 break; 1114 1115 // First, load all the temporaries. This can add new placeholders or 1116 // forward references. 1117 for (auto ID : Temporaries) 1118 lazyLoadOneMetadata(ID, Placeholders); 1119 Temporaries.clear(); 1120 1121 // Second, load the forward-references. This can also add new placeholders 1122 // or forward references. 1123 while (MetadataList.hasFwdRefs()) 1124 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders); 1125 } 1126 // At this point we don't have any forward reference remaining, or temporary 1127 // that haven't been loaded. We can safely drop RAUW support and mark cycles 1128 // as resolved. 1129 MetadataList.tryToResolveCycles(); 1130 1131 // Finally, everything is in place, we can replace the placeholders operands 1132 // with the final node they refer to. 1133 Placeholders.flush(MetadataList); 1134 } 1135 1136 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata( 1137 SmallVectorImpl<uint64_t> &Record, unsigned Code, 1138 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) { 1139 1140 bool IsDistinct = false; 1141 auto getMD = [&](unsigned ID) -> Metadata * { 1142 if (ID < MDStringRef.size()) 1143 return lazyLoadOneMDString(ID); 1144 if (!IsDistinct) { 1145 if (auto *MD = MetadataList.lookup(ID)) 1146 return MD; 1147 // If lazy-loading is enabled, we try recursively to load the operand 1148 // instead of creating a temporary. 1149 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) { 1150 // Create a temporary for the node that is referencing the operand we 1151 // will lazy-load. It is needed before recursing in case there are 1152 // uniquing cycles. 1153 MetadataList.getMetadataFwdRef(NextMetadataNo); 1154 lazyLoadOneMetadata(ID, Placeholders); 1155 return MetadataList.lookup(ID); 1156 } 1157 // Return a temporary. 1158 return MetadataList.getMetadataFwdRef(ID); 1159 } 1160 if (auto *MD = MetadataList.getMetadataIfResolved(ID)) 1161 return MD; 1162 return &Placeholders.getPlaceholderOp(ID); 1163 }; 1164 auto getMDOrNull = [&](unsigned ID) -> Metadata * { 1165 if (ID) 1166 return getMD(ID - 1); 1167 return nullptr; 1168 }; 1169 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * { 1170 if (ID) 1171 return MetadataList.getMetadataFwdRef(ID - 1); 1172 return nullptr; 1173 }; 1174 auto getMDString = [&](unsigned ID) -> MDString * { 1175 // This requires that the ID is not really a forward reference. In 1176 // particular, the MDString must already have been resolved. 1177 auto MDS = getMDOrNull(ID); 1178 return cast_or_null<MDString>(MDS); 1179 }; 1180 1181 // Support for old type refs. 1182 auto getDITypeRefOrNull = [&](unsigned ID) { 1183 return MetadataList.upgradeTypeRef(getMDOrNull(ID)); 1184 }; 1185 1186 #define GET_OR_DISTINCT(CLASS, ARGS) \ 1187 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 1188 1189 switch (Code) { 1190 default: // Default behavior: ignore. 1191 break; 1192 case bitc::METADATA_NAME: { 1193 // Read name of the named metadata. 1194 SmallString<8> Name(Record.begin(), Record.end()); 1195 Record.clear(); 1196 if (Error E = Stream.ReadCode().moveInto(Code)) 1197 return E; 1198 1199 ++NumMDRecordLoaded; 1200 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) { 1201 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE) 1202 return error("METADATA_NAME not followed by METADATA_NAMED_NODE"); 1203 } else 1204 return MaybeNextBitCode.takeError(); 1205 1206 // Read named metadata elements. 1207 unsigned Size = Record.size(); 1208 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name); 1209 for (unsigned i = 0; i != Size; ++i) { 1210 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]); 1211 if (!MD) 1212 return error("Invalid named metadata: expect fwd ref to MDNode"); 1213 NMD->addOperand(MD); 1214 } 1215 break; 1216 } 1217 case bitc::METADATA_OLD_FN_NODE: { 1218 // Deprecated, but still needed to read old bitcode files. 1219 // This is a LocalAsMetadata record, the only type of function-local 1220 // metadata. 1221 if (Record.size() % 2 == 1) 1222 return error("Invalid record"); 1223 1224 // If this isn't a LocalAsMetadata record, we're dropping it. This used 1225 // to be legal, but there's no upgrade path. 1226 auto dropRecord = [&] { 1227 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo); 1228 NextMetadataNo++; 1229 }; 1230 if (Record.size() != 2) { 1231 dropRecord(); 1232 break; 1233 } 1234 1235 Type *Ty = getTypeByID(Record[0]); 1236 if (Ty->isMetadataTy() || Ty->isVoidTy()) { 1237 dropRecord(); 1238 break; 1239 } 1240 1241 MetadataList.assignValue( 1242 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 1243 NextMetadataNo); 1244 NextMetadataNo++; 1245 break; 1246 } 1247 case bitc::METADATA_OLD_NODE: { 1248 // Deprecated, but still needed to read old bitcode files. 1249 if (Record.size() % 2 == 1) 1250 return error("Invalid record"); 1251 1252 unsigned Size = Record.size(); 1253 SmallVector<Metadata *, 8> Elts; 1254 for (unsigned i = 0; i != Size; i += 2) { 1255 Type *Ty = getTypeByID(Record[i]); 1256 if (!Ty) 1257 return error("Invalid record"); 1258 if (Ty->isMetadataTy()) 1259 Elts.push_back(getMD(Record[i + 1])); 1260 else if (!Ty->isVoidTy()) { 1261 auto *MD = 1262 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 1263 assert(isa<ConstantAsMetadata>(MD) && 1264 "Expected non-function-local metadata"); 1265 Elts.push_back(MD); 1266 } else 1267 Elts.push_back(nullptr); 1268 } 1269 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo); 1270 NextMetadataNo++; 1271 break; 1272 } 1273 case bitc::METADATA_VALUE: { 1274 if (Record.size() != 2) 1275 return error("Invalid record"); 1276 1277 Type *Ty = getTypeByID(Record[0]); 1278 if (Ty->isMetadataTy() || Ty->isVoidTy()) 1279 return error("Invalid record"); 1280 1281 MetadataList.assignValue( 1282 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 1283 NextMetadataNo); 1284 NextMetadataNo++; 1285 break; 1286 } 1287 case bitc::METADATA_DISTINCT_NODE: 1288 IsDistinct = true; 1289 LLVM_FALLTHROUGH; 1290 case bitc::METADATA_NODE: { 1291 SmallVector<Metadata *, 8> Elts; 1292 Elts.reserve(Record.size()); 1293 for (unsigned ID : Record) 1294 Elts.push_back(getMDOrNull(ID)); 1295 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 1296 : MDNode::get(Context, Elts), 1297 NextMetadataNo); 1298 NextMetadataNo++; 1299 break; 1300 } 1301 case bitc::METADATA_LOCATION: { 1302 if (Record.size() != 5 && Record.size() != 6) 1303 return error("Invalid record"); 1304 1305 IsDistinct = Record[0]; 1306 unsigned Line = Record[1]; 1307 unsigned Column = Record[2]; 1308 Metadata *Scope = getMD(Record[3]); 1309 Metadata *InlinedAt = getMDOrNull(Record[4]); 1310 bool ImplicitCode = Record.size() == 6 && Record[5]; 1311 MetadataList.assignValue( 1312 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt, 1313 ImplicitCode)), 1314 NextMetadataNo); 1315 NextMetadataNo++; 1316 break; 1317 } 1318 case bitc::METADATA_GENERIC_DEBUG: { 1319 if (Record.size() < 4) 1320 return error("Invalid record"); 1321 1322 IsDistinct = Record[0]; 1323 unsigned Tag = Record[1]; 1324 unsigned Version = Record[2]; 1325 1326 if (Tag >= 1u << 16 || Version != 0) 1327 return error("Invalid record"); 1328 1329 auto *Header = getMDString(Record[3]); 1330 SmallVector<Metadata *, 8> DwarfOps; 1331 for (unsigned I = 4, E = Record.size(); I != E; ++I) 1332 DwarfOps.push_back(getMDOrNull(Record[I])); 1333 MetadataList.assignValue( 1334 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)), 1335 NextMetadataNo); 1336 NextMetadataNo++; 1337 break; 1338 } 1339 case bitc::METADATA_SUBRANGE: { 1340 Metadata *Val = nullptr; 1341 // Operand 'count' is interpreted as: 1342 // - Signed integer (version 0) 1343 // - Metadata node (version 1) 1344 // Operand 'lowerBound' is interpreted as: 1345 // - Signed integer (version 0 and 1) 1346 // - Metadata node (version 2) 1347 // Operands 'upperBound' and 'stride' are interpreted as: 1348 // - Metadata node (version 2) 1349 switch (Record[0] >> 1) { 1350 case 0: 1351 Val = GET_OR_DISTINCT(DISubrange, 1352 (Context, Record[1], unrotateSign(Record[2]))); 1353 break; 1354 case 1: 1355 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]), 1356 unrotateSign(Record[2]))); 1357 break; 1358 case 2: 1359 Val = GET_OR_DISTINCT( 1360 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]), 1361 getMDOrNull(Record[3]), getMDOrNull(Record[4]))); 1362 break; 1363 default: 1364 return error("Invalid record: Unsupported version of DISubrange"); 1365 } 1366 1367 MetadataList.assignValue(Val, NextMetadataNo); 1368 IsDistinct = Record[0] & 1; 1369 NextMetadataNo++; 1370 break; 1371 } 1372 case bitc::METADATA_GENERIC_SUBRANGE: { 1373 Metadata *Val = nullptr; 1374 Val = GET_OR_DISTINCT(DIGenericSubrange, 1375 (Context, getMDOrNull(Record[1]), 1376 getMDOrNull(Record[2]), getMDOrNull(Record[3]), 1377 getMDOrNull(Record[4]))); 1378 1379 MetadataList.assignValue(Val, NextMetadataNo); 1380 IsDistinct = Record[0] & 1; 1381 NextMetadataNo++; 1382 break; 1383 } 1384 case bitc::METADATA_ENUMERATOR: { 1385 if (Record.size() < 3) 1386 return error("Invalid record"); 1387 1388 IsDistinct = Record[0] & 1; 1389 bool IsUnsigned = Record[0] & 2; 1390 bool IsBigInt = Record[0] & 4; 1391 APInt Value; 1392 1393 if (IsBigInt) { 1394 const uint64_t BitWidth = Record[1]; 1395 const size_t NumWords = Record.size() - 3; 1396 Value = readWideAPInt(makeArrayRef(&Record[3], NumWords), BitWidth); 1397 } else 1398 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned); 1399 1400 MetadataList.assignValue( 1401 GET_OR_DISTINCT(DIEnumerator, 1402 (Context, Value, IsUnsigned, getMDString(Record[2]))), 1403 NextMetadataNo); 1404 NextMetadataNo++; 1405 break; 1406 } 1407 case bitc::METADATA_BASIC_TYPE: { 1408 if (Record.size() < 6 || Record.size() > 7) 1409 return error("Invalid record"); 1410 1411 IsDistinct = Record[0]; 1412 DINode::DIFlags Flags = (Record.size() > 6) 1413 ? static_cast<DINode::DIFlags>(Record[6]) 1414 : DINode::FlagZero; 1415 1416 MetadataList.assignValue( 1417 GET_OR_DISTINCT(DIBasicType, 1418 (Context, Record[1], getMDString(Record[2]), Record[3], 1419 Record[4], Record[5], Flags)), 1420 NextMetadataNo); 1421 NextMetadataNo++; 1422 break; 1423 } 1424 case bitc::METADATA_STRING_TYPE: { 1425 if (Record.size() != 8) 1426 return error("Invalid record"); 1427 1428 IsDistinct = Record[0]; 1429 MetadataList.assignValue( 1430 GET_OR_DISTINCT(DIStringType, 1431 (Context, Record[1], getMDString(Record[2]), 1432 getMDOrNull(Record[3]), getMDOrNull(Record[4]), 1433 Record[5], Record[6], Record[7])), 1434 NextMetadataNo); 1435 NextMetadataNo++; 1436 break; 1437 } 1438 case bitc::METADATA_DERIVED_TYPE: { 1439 if (Record.size() < 12 || Record.size() > 14) 1440 return error("Invalid record"); 1441 1442 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means 1443 // that there is no DWARF address space associated with DIDerivedType. 1444 Optional<unsigned> DWARFAddressSpace; 1445 if (Record.size() > 12 && Record[12]) 1446 DWARFAddressSpace = Record[12] - 1; 1447 1448 Metadata *Annotations = nullptr; 1449 if (Record.size() > 13 && Record[13]) 1450 Annotations = getMDOrNull(Record[13]); 1451 1452 IsDistinct = Record[0]; 1453 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 1454 MetadataList.assignValue( 1455 GET_OR_DISTINCT(DIDerivedType, 1456 (Context, Record[1], getMDString(Record[2]), 1457 getMDOrNull(Record[3]), Record[4], 1458 getDITypeRefOrNull(Record[5]), 1459 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1460 Record[9], DWARFAddressSpace, Flags, 1461 getDITypeRefOrNull(Record[11]), Annotations)), 1462 NextMetadataNo); 1463 NextMetadataNo++; 1464 break; 1465 } 1466 case bitc::METADATA_COMPOSITE_TYPE: { 1467 if (Record.size() < 16 || Record.size() > 22) 1468 return error("Invalid record"); 1469 1470 // If we have a UUID and this is not a forward declaration, lookup the 1471 // mapping. 1472 IsDistinct = Record[0] & 0x1; 1473 bool IsNotUsedInTypeRef = Record[0] >= 2; 1474 unsigned Tag = Record[1]; 1475 MDString *Name = getMDString(Record[2]); 1476 Metadata *File = getMDOrNull(Record[3]); 1477 unsigned Line = Record[4]; 1478 Metadata *Scope = getDITypeRefOrNull(Record[5]); 1479 Metadata *BaseType = nullptr; 1480 uint64_t SizeInBits = Record[7]; 1481 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1482 return error("Alignment value is too large"); 1483 uint32_t AlignInBits = Record[8]; 1484 uint64_t OffsetInBits = 0; 1485 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 1486 Metadata *Elements = nullptr; 1487 unsigned RuntimeLang = Record[12]; 1488 Metadata *VTableHolder = nullptr; 1489 Metadata *TemplateParams = nullptr; 1490 Metadata *Discriminator = nullptr; 1491 Metadata *DataLocation = nullptr; 1492 Metadata *Associated = nullptr; 1493 Metadata *Allocated = nullptr; 1494 Metadata *Rank = nullptr; 1495 Metadata *Annotations = nullptr; 1496 auto *Identifier = getMDString(Record[15]); 1497 // If this module is being parsed so that it can be ThinLTO imported 1498 // into another module, composite types only need to be imported 1499 // as type declarations (unless full type definitions requested). 1500 // Create type declarations up front to save memory. Also, buildODRType 1501 // handles the case where this is type ODRed with a definition needed 1502 // by the importing module, in which case the existing definition is 1503 // used. 1504 if (IsImporting && !ImportFullTypeDefinitions && Identifier && 1505 (Tag == dwarf::DW_TAG_enumeration_type || 1506 Tag == dwarf::DW_TAG_class_type || 1507 Tag == dwarf::DW_TAG_structure_type || 1508 Tag == dwarf::DW_TAG_union_type)) { 1509 Flags = Flags | DINode::FlagFwdDecl; 1510 } else { 1511 BaseType = getDITypeRefOrNull(Record[6]); 1512 OffsetInBits = Record[9]; 1513 Elements = getMDOrNull(Record[11]); 1514 VTableHolder = getDITypeRefOrNull(Record[13]); 1515 TemplateParams = getMDOrNull(Record[14]); 1516 if (Record.size() > 16) 1517 Discriminator = getMDOrNull(Record[16]); 1518 if (Record.size() > 17) 1519 DataLocation = getMDOrNull(Record[17]); 1520 if (Record.size() > 19) { 1521 Associated = getMDOrNull(Record[18]); 1522 Allocated = getMDOrNull(Record[19]); 1523 } 1524 if (Record.size() > 20) { 1525 Rank = getMDOrNull(Record[20]); 1526 } 1527 if (Record.size() > 21) { 1528 Annotations = getMDOrNull(Record[21]); 1529 } 1530 } 1531 DICompositeType *CT = nullptr; 1532 if (Identifier) 1533 CT = DICompositeType::buildODRType( 1534 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType, 1535 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 1536 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated, 1537 Allocated, Rank, Annotations); 1538 1539 // Create a node if we didn't get a lazy ODR type. 1540 if (!CT) 1541 CT = GET_OR_DISTINCT(DICompositeType, 1542 (Context, Tag, Name, File, Line, Scope, BaseType, 1543 SizeInBits, AlignInBits, OffsetInBits, Flags, 1544 Elements, RuntimeLang, VTableHolder, TemplateParams, 1545 Identifier, Discriminator, DataLocation, Associated, 1546 Allocated, Rank, Annotations)); 1547 if (!IsNotUsedInTypeRef && Identifier) 1548 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT)); 1549 1550 MetadataList.assignValue(CT, NextMetadataNo); 1551 NextMetadataNo++; 1552 break; 1553 } 1554 case bitc::METADATA_SUBROUTINE_TYPE: { 1555 if (Record.size() < 3 || Record.size() > 4) 1556 return error("Invalid record"); 1557 bool IsOldTypeRefArray = Record[0] < 2; 1558 unsigned CC = (Record.size() > 3) ? Record[3] : 0; 1559 1560 IsDistinct = Record[0] & 0x1; 1561 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]); 1562 Metadata *Types = getMDOrNull(Record[2]); 1563 if (LLVM_UNLIKELY(IsOldTypeRefArray)) 1564 Types = MetadataList.upgradeTypeRefArray(Types); 1565 1566 MetadataList.assignValue( 1567 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)), 1568 NextMetadataNo); 1569 NextMetadataNo++; 1570 break; 1571 } 1572 1573 case bitc::METADATA_MODULE: { 1574 if (Record.size() < 5 || Record.size() > 9) 1575 return error("Invalid record"); 1576 1577 unsigned Offset = Record.size() >= 8 ? 2 : 1; 1578 IsDistinct = Record[0]; 1579 MetadataList.assignValue( 1580 GET_OR_DISTINCT( 1581 DIModule, 1582 (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr, 1583 getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]), 1584 getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]), 1585 getMDString(Record[4 + Offset]), 1586 Record.size() <= 7 ? 0 : Record[7], 1587 Record.size() <= 8 ? false : Record[8])), 1588 NextMetadataNo); 1589 NextMetadataNo++; 1590 break; 1591 } 1592 1593 case bitc::METADATA_FILE: { 1594 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6) 1595 return error("Invalid record"); 1596 1597 IsDistinct = Record[0]; 1598 Optional<DIFile::ChecksumInfo<MDString *>> Checksum; 1599 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum 1600 // is not present. This matches up with the old internal representation, 1601 // and the old encoding for CSK_None in the ChecksumKind. The new 1602 // representation reserves the value 0 in the ChecksumKind to continue to 1603 // encode None in a backwards-compatible way. 1604 if (Record.size() > 4 && Record[3] && Record[4]) 1605 Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]), 1606 getMDString(Record[4])); 1607 MetadataList.assignValue( 1608 GET_OR_DISTINCT( 1609 DIFile, 1610 (Context, getMDString(Record[1]), getMDString(Record[2]), Checksum, 1611 Record.size() > 5 ? Optional<MDString *>(getMDString(Record[5])) 1612 : None)), 1613 NextMetadataNo); 1614 NextMetadataNo++; 1615 break; 1616 } 1617 case bitc::METADATA_COMPILE_UNIT: { 1618 if (Record.size() < 14 || Record.size() > 22) 1619 return error("Invalid record"); 1620 1621 // Ignore Record[0], which indicates whether this compile unit is 1622 // distinct. It's always distinct. 1623 IsDistinct = true; 1624 auto *CU = DICompileUnit::getDistinct( 1625 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]), 1626 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]), 1627 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]), 1628 getMDOrNull(Record[12]), getMDOrNull(Record[13]), 1629 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]), 1630 Record.size() <= 14 ? 0 : Record[14], 1631 Record.size() <= 16 ? true : Record[16], 1632 Record.size() <= 17 ? false : Record[17], 1633 Record.size() <= 18 ? 0 : Record[18], 1634 Record.size() <= 19 ? 0 : Record[19], 1635 Record.size() <= 20 ? nullptr : getMDString(Record[20]), 1636 Record.size() <= 21 ? nullptr : getMDString(Record[21])); 1637 1638 MetadataList.assignValue(CU, NextMetadataNo); 1639 NextMetadataNo++; 1640 1641 // Move the Upgrade the list of subprograms. 1642 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11])) 1643 CUSubprograms.push_back({CU, SPs}); 1644 break; 1645 } 1646 case bitc::METADATA_SUBPROGRAM: { 1647 if (Record.size() < 18 || Record.size() > 21) 1648 return error("Invalid record"); 1649 1650 bool HasSPFlags = Record[0] & 4; 1651 1652 DINode::DIFlags Flags; 1653 DISubprogram::DISPFlags SPFlags; 1654 if (!HasSPFlags) 1655 Flags = static_cast<DINode::DIFlags>(Record[11 + 2]); 1656 else { 1657 Flags = static_cast<DINode::DIFlags>(Record[11]); 1658 SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]); 1659 } 1660 1661 // Support for old metadata when 1662 // subprogram specific flags are placed in DIFlags. 1663 const unsigned DIFlagMainSubprogram = 1 << 21; 1664 bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram; 1665 if (HasOldMainSubprogramFlag) 1666 // Remove old DIFlagMainSubprogram from DIFlags. 1667 // Note: This assumes that any future use of bit 21 defaults to it 1668 // being 0. 1669 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram); 1670 1671 if (HasOldMainSubprogramFlag && HasSPFlags) 1672 SPFlags |= DISubprogram::SPFlagMainSubprogram; 1673 else if (!HasSPFlags) 1674 SPFlags = DISubprogram::toSPFlags( 1675 /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8], 1676 /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11], 1677 /*DIFlagMainSubprogram=*/HasOldMainSubprogramFlag); 1678 1679 // All definitions should be distinct. 1680 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition); 1681 // Version 1 has a Function as Record[15]. 1682 // Version 2 has removed Record[15]. 1683 // Version 3 has the Unit as Record[15]. 1684 // Version 4 added thisAdjustment. 1685 // Version 5 repacked flags into DISPFlags, changing many element numbers. 1686 bool HasUnit = Record[0] & 2; 1687 if (!HasSPFlags && HasUnit && Record.size() < 19) 1688 return error("Invalid record"); 1689 if (HasSPFlags && !HasUnit) 1690 return error("Invalid record"); 1691 // Accommodate older formats. 1692 bool HasFn = false; 1693 bool HasThisAdj = true; 1694 bool HasThrownTypes = true; 1695 bool HasAnnotations = false; 1696 unsigned OffsetA = 0; 1697 unsigned OffsetB = 0; 1698 if (!HasSPFlags) { 1699 OffsetA = 2; 1700 OffsetB = 2; 1701 if (Record.size() >= 19) { 1702 HasFn = !HasUnit; 1703 OffsetB++; 1704 } 1705 HasThisAdj = Record.size() >= 20; 1706 HasThrownTypes = Record.size() >= 21; 1707 } else { 1708 HasAnnotations = Record.size() >= 19; 1709 } 1710 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]); 1711 DISubprogram *SP = GET_OR_DISTINCT( 1712 DISubprogram, 1713 (Context, 1714 getDITypeRefOrNull(Record[1]), // scope 1715 getMDString(Record[2]), // name 1716 getMDString(Record[3]), // linkageName 1717 getMDOrNull(Record[4]), // file 1718 Record[5], // line 1719 getMDOrNull(Record[6]), // type 1720 Record[7 + OffsetA], // scopeLine 1721 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType 1722 Record[10 + OffsetA], // virtualIndex 1723 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment 1724 Flags, // flags 1725 SPFlags, // SPFlags 1726 HasUnit ? CUorFn : nullptr, // unit 1727 getMDOrNull(Record[13 + OffsetB]), // templateParams 1728 getMDOrNull(Record[14 + OffsetB]), // declaration 1729 getMDOrNull(Record[15 + OffsetB]), // retainedNodes 1730 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB]) 1731 : nullptr, // thrownTypes 1732 HasAnnotations ? getMDOrNull(Record[18 + OffsetB]) 1733 : nullptr // annotations 1734 )); 1735 MetadataList.assignValue(SP, NextMetadataNo); 1736 NextMetadataNo++; 1737 1738 // Upgrade sp->function mapping to function->sp mapping. 1739 if (HasFn) { 1740 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn)) 1741 if (auto *F = dyn_cast<Function>(CMD->getValue())) { 1742 if (F->isMaterializable()) 1743 // Defer until materialized; unmaterialized functions may not have 1744 // metadata. 1745 FunctionsWithSPs[F] = SP; 1746 else if (!F->empty()) 1747 F->setSubprogram(SP); 1748 } 1749 } 1750 break; 1751 } 1752 case bitc::METADATA_LEXICAL_BLOCK: { 1753 if (Record.size() != 5) 1754 return error("Invalid record"); 1755 1756 IsDistinct = Record[0]; 1757 MetadataList.assignValue( 1758 GET_OR_DISTINCT(DILexicalBlock, 1759 (Context, getMDOrNull(Record[1]), 1760 getMDOrNull(Record[2]), Record[3], Record[4])), 1761 NextMetadataNo); 1762 NextMetadataNo++; 1763 break; 1764 } 1765 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 1766 if (Record.size() != 4) 1767 return error("Invalid record"); 1768 1769 IsDistinct = Record[0]; 1770 MetadataList.assignValue( 1771 GET_OR_DISTINCT(DILexicalBlockFile, 1772 (Context, getMDOrNull(Record[1]), 1773 getMDOrNull(Record[2]), Record[3])), 1774 NextMetadataNo); 1775 NextMetadataNo++; 1776 break; 1777 } 1778 case bitc::METADATA_COMMON_BLOCK: { 1779 IsDistinct = Record[0] & 1; 1780 MetadataList.assignValue( 1781 GET_OR_DISTINCT(DICommonBlock, 1782 (Context, getMDOrNull(Record[1]), 1783 getMDOrNull(Record[2]), getMDString(Record[3]), 1784 getMDOrNull(Record[4]), Record[5])), 1785 NextMetadataNo); 1786 NextMetadataNo++; 1787 break; 1788 } 1789 case bitc::METADATA_NAMESPACE: { 1790 // Newer versions of DINamespace dropped file and line. 1791 MDString *Name; 1792 if (Record.size() == 3) 1793 Name = getMDString(Record[2]); 1794 else if (Record.size() == 5) 1795 Name = getMDString(Record[3]); 1796 else 1797 return error("Invalid record"); 1798 1799 IsDistinct = Record[0] & 1; 1800 bool ExportSymbols = Record[0] & 2; 1801 MetadataList.assignValue( 1802 GET_OR_DISTINCT(DINamespace, 1803 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)), 1804 NextMetadataNo); 1805 NextMetadataNo++; 1806 break; 1807 } 1808 case bitc::METADATA_MACRO: { 1809 if (Record.size() != 5) 1810 return error("Invalid record"); 1811 1812 IsDistinct = Record[0]; 1813 MetadataList.assignValue( 1814 GET_OR_DISTINCT(DIMacro, 1815 (Context, Record[1], Record[2], getMDString(Record[3]), 1816 getMDString(Record[4]))), 1817 NextMetadataNo); 1818 NextMetadataNo++; 1819 break; 1820 } 1821 case bitc::METADATA_MACRO_FILE: { 1822 if (Record.size() != 5) 1823 return error("Invalid record"); 1824 1825 IsDistinct = Record[0]; 1826 MetadataList.assignValue( 1827 GET_OR_DISTINCT(DIMacroFile, 1828 (Context, Record[1], Record[2], getMDOrNull(Record[3]), 1829 getMDOrNull(Record[4]))), 1830 NextMetadataNo); 1831 NextMetadataNo++; 1832 break; 1833 } 1834 case bitc::METADATA_TEMPLATE_TYPE: { 1835 if (Record.size() < 3 || Record.size() > 4) 1836 return error("Invalid record"); 1837 1838 IsDistinct = Record[0]; 1839 MetadataList.assignValue( 1840 GET_OR_DISTINCT(DITemplateTypeParameter, 1841 (Context, getMDString(Record[1]), 1842 getDITypeRefOrNull(Record[2]), 1843 (Record.size() == 4) ? getMDOrNull(Record[3]) 1844 : getMDOrNull(false))), 1845 NextMetadataNo); 1846 NextMetadataNo++; 1847 break; 1848 } 1849 case bitc::METADATA_TEMPLATE_VALUE: { 1850 if (Record.size() < 5 || Record.size() > 6) 1851 return error("Invalid record"); 1852 1853 IsDistinct = Record[0]; 1854 1855 MetadataList.assignValue( 1856 GET_OR_DISTINCT( 1857 DITemplateValueParameter, 1858 (Context, Record[1], getMDString(Record[2]), 1859 getDITypeRefOrNull(Record[3]), 1860 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false), 1861 (Record.size() == 6) ? getMDOrNull(Record[5]) 1862 : getMDOrNull(Record[4]))), 1863 NextMetadataNo); 1864 NextMetadataNo++; 1865 break; 1866 } 1867 case bitc::METADATA_GLOBAL_VAR: { 1868 if (Record.size() < 11 || Record.size() > 13) 1869 return error("Invalid record"); 1870 1871 IsDistinct = Record[0] & 1; 1872 unsigned Version = Record[0] >> 1; 1873 1874 if (Version == 2) { 1875 Metadata *Annotations = nullptr; 1876 if (Record.size() > 12) 1877 Annotations = getMDOrNull(Record[12]); 1878 1879 MetadataList.assignValue( 1880 GET_OR_DISTINCT(DIGlobalVariable, 1881 (Context, getMDOrNull(Record[1]), 1882 getMDString(Record[2]), getMDString(Record[3]), 1883 getMDOrNull(Record[4]), Record[5], 1884 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1885 getMDOrNull(Record[9]), getMDOrNull(Record[10]), 1886 Record[11], Annotations)), 1887 NextMetadataNo); 1888 1889 NextMetadataNo++; 1890 } else if (Version == 1) { 1891 // No upgrade necessary. A null field will be introduced to indicate 1892 // that no parameter information is available. 1893 MetadataList.assignValue( 1894 GET_OR_DISTINCT( 1895 DIGlobalVariable, 1896 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 1897 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 1898 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1899 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)), 1900 NextMetadataNo); 1901 1902 NextMetadataNo++; 1903 } else if (Version == 0) { 1904 // Upgrade old metadata, which stored a global variable reference or a 1905 // ConstantInt here. 1906 NeedUpgradeToDIGlobalVariableExpression = true; 1907 Metadata *Expr = getMDOrNull(Record[9]); 1908 uint32_t AlignInBits = 0; 1909 if (Record.size() > 11) { 1910 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1911 return error("Alignment value is too large"); 1912 AlignInBits = Record[11]; 1913 } 1914 GlobalVariable *Attach = nullptr; 1915 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) { 1916 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) { 1917 Attach = GV; 1918 Expr = nullptr; 1919 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) { 1920 Expr = DIExpression::get(Context, 1921 {dwarf::DW_OP_constu, CI->getZExtValue(), 1922 dwarf::DW_OP_stack_value}); 1923 } else { 1924 Expr = nullptr; 1925 } 1926 } 1927 DIGlobalVariable *DGV = GET_OR_DISTINCT( 1928 DIGlobalVariable, 1929 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 1930 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 1931 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1932 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr)); 1933 1934 DIGlobalVariableExpression *DGVE = nullptr; 1935 if (Attach || Expr) 1936 DGVE = DIGlobalVariableExpression::getDistinct( 1937 Context, DGV, Expr ? Expr : DIExpression::get(Context, {})); 1938 if (Attach) 1939 Attach->addDebugInfo(DGVE); 1940 1941 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV); 1942 MetadataList.assignValue(MDNode, NextMetadataNo); 1943 NextMetadataNo++; 1944 } else 1945 return error("Invalid record"); 1946 1947 break; 1948 } 1949 case bitc::METADATA_LOCAL_VAR: { 1950 // 10th field is for the obseleted 'inlinedAt:' field. 1951 if (Record.size() < 8 || Record.size() > 10) 1952 return error("Invalid record"); 1953 1954 IsDistinct = Record[0] & 1; 1955 bool HasAlignment = Record[0] & 2; 1956 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 1957 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that 1958 // this is newer version of record which doesn't have artificial tag. 1959 bool HasTag = !HasAlignment && Record.size() > 8; 1960 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]); 1961 uint32_t AlignInBits = 0; 1962 Metadata *Annotations = nullptr; 1963 if (HasAlignment) { 1964 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1965 return error("Alignment value is too large"); 1966 AlignInBits = Record[8]; 1967 if (Record.size() > 9) 1968 Annotations = getMDOrNull(Record[9]); 1969 } 1970 1971 MetadataList.assignValue( 1972 GET_OR_DISTINCT(DILocalVariable, 1973 (Context, getMDOrNull(Record[1 + HasTag]), 1974 getMDString(Record[2 + HasTag]), 1975 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 1976 getDITypeRefOrNull(Record[5 + HasTag]), 1977 Record[6 + HasTag], Flags, AlignInBits, Annotations)), 1978 NextMetadataNo); 1979 NextMetadataNo++; 1980 break; 1981 } 1982 case bitc::METADATA_LABEL: { 1983 if (Record.size() != 5) 1984 return error("Invalid record"); 1985 1986 IsDistinct = Record[0] & 1; 1987 MetadataList.assignValue( 1988 GET_OR_DISTINCT(DILabel, (Context, getMDOrNull(Record[1]), 1989 getMDString(Record[2]), 1990 getMDOrNull(Record[3]), Record[4])), 1991 NextMetadataNo); 1992 NextMetadataNo++; 1993 break; 1994 } 1995 case bitc::METADATA_EXPRESSION: { 1996 if (Record.size() < 1) 1997 return error("Invalid record"); 1998 1999 IsDistinct = Record[0] & 1; 2000 uint64_t Version = Record[0] >> 1; 2001 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1); 2002 2003 SmallVector<uint64_t, 6> Buffer; 2004 if (Error Err = upgradeDIExpression(Version, Elts, Buffer)) 2005 return Err; 2006 2007 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)), 2008 NextMetadataNo); 2009 NextMetadataNo++; 2010 break; 2011 } 2012 case bitc::METADATA_GLOBAL_VAR_EXPR: { 2013 if (Record.size() != 3) 2014 return error("Invalid record"); 2015 2016 IsDistinct = Record[0]; 2017 Metadata *Expr = getMDOrNull(Record[2]); 2018 if (!Expr) 2019 Expr = DIExpression::get(Context, {}); 2020 MetadataList.assignValue( 2021 GET_OR_DISTINCT(DIGlobalVariableExpression, 2022 (Context, getMDOrNull(Record[1]), Expr)), 2023 NextMetadataNo); 2024 NextMetadataNo++; 2025 break; 2026 } 2027 case bitc::METADATA_OBJC_PROPERTY: { 2028 if (Record.size() != 8) 2029 return error("Invalid record"); 2030 2031 IsDistinct = Record[0]; 2032 MetadataList.assignValue( 2033 GET_OR_DISTINCT(DIObjCProperty, 2034 (Context, getMDString(Record[1]), 2035 getMDOrNull(Record[2]), Record[3], 2036 getMDString(Record[4]), getMDString(Record[5]), 2037 Record[6], getDITypeRefOrNull(Record[7]))), 2038 NextMetadataNo); 2039 NextMetadataNo++; 2040 break; 2041 } 2042 case bitc::METADATA_IMPORTED_ENTITY: { 2043 if (Record.size() < 6 && Record.size() > 8) 2044 return error("Invalid record"); 2045 2046 IsDistinct = Record[0]; 2047 bool HasFile = (Record.size() >= 7); 2048 bool HasElements = (Record.size() >= 8); 2049 MetadataList.assignValue( 2050 GET_OR_DISTINCT(DIImportedEntity, 2051 (Context, Record[1], getMDOrNull(Record[2]), 2052 getDITypeRefOrNull(Record[3]), 2053 HasFile ? getMDOrNull(Record[6]) : nullptr, 2054 HasFile ? Record[4] : 0, getMDString(Record[5]), 2055 HasElements ? getMDOrNull(Record[7]) : nullptr)), 2056 NextMetadataNo); 2057 NextMetadataNo++; 2058 break; 2059 } 2060 case bitc::METADATA_STRING_OLD: { 2061 std::string String(Record.begin(), Record.end()); 2062 2063 // Test for upgrading !llvm.loop. 2064 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String); 2065 ++NumMDStringLoaded; 2066 Metadata *MD = MDString::get(Context, String); 2067 MetadataList.assignValue(MD, NextMetadataNo); 2068 NextMetadataNo++; 2069 break; 2070 } 2071 case bitc::METADATA_STRINGS: { 2072 auto CreateNextMDString = [&](StringRef Str) { 2073 ++NumMDStringLoaded; 2074 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo); 2075 NextMetadataNo++; 2076 }; 2077 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString)) 2078 return Err; 2079 break; 2080 } 2081 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: { 2082 if (Record.size() % 2 == 0) 2083 return error("Invalid record"); 2084 unsigned ValueID = Record[0]; 2085 if (ValueID >= ValueList.size()) 2086 return error("Invalid record"); 2087 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) 2088 if (Error Err = parseGlobalObjectAttachment( 2089 *GO, ArrayRef<uint64_t>(Record).slice(1))) 2090 return Err; 2091 break; 2092 } 2093 case bitc::METADATA_KIND: { 2094 // Support older bitcode files that had METADATA_KIND records in a 2095 // block with METADATA_BLOCK_ID. 2096 if (Error Err = parseMetadataKindRecord(Record)) 2097 return Err; 2098 break; 2099 } 2100 case bitc::METADATA_ARG_LIST: { 2101 SmallVector<ValueAsMetadata *, 4> Elts; 2102 Elts.reserve(Record.size()); 2103 for (uint64_t Elt : Record) { 2104 Metadata *MD = getMD(Elt); 2105 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) 2106 return error( 2107 "Invalid record: DIArgList should not contain forward refs"); 2108 if (!isa<ValueAsMetadata>(MD)) 2109 return error("Invalid record"); 2110 Elts.push_back(cast<ValueAsMetadata>(MD)); 2111 } 2112 2113 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo); 2114 NextMetadataNo++; 2115 break; 2116 } 2117 } 2118 return Error::success(); 2119 #undef GET_OR_DISTINCT 2120 } 2121 2122 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings( 2123 ArrayRef<uint64_t> Record, StringRef Blob, 2124 function_ref<void(StringRef)> CallBack) { 2125 // All the MDStrings in the block are emitted together in a single 2126 // record. The strings are concatenated and stored in a blob along with 2127 // their sizes. 2128 if (Record.size() != 2) 2129 return error("Invalid record: metadata strings layout"); 2130 2131 unsigned NumStrings = Record[0]; 2132 unsigned StringsOffset = Record[1]; 2133 if (!NumStrings) 2134 return error("Invalid record: metadata strings with no strings"); 2135 if (StringsOffset > Blob.size()) 2136 return error("Invalid record: metadata strings corrupt offset"); 2137 2138 StringRef Lengths = Blob.slice(0, StringsOffset); 2139 SimpleBitstreamCursor R(Lengths); 2140 2141 StringRef Strings = Blob.drop_front(StringsOffset); 2142 do { 2143 if (R.AtEndOfStream()) 2144 return error("Invalid record: metadata strings bad length"); 2145 2146 uint32_t Size; 2147 if (Error E = R.ReadVBR(6).moveInto(Size)) 2148 return E; 2149 if (Strings.size() < Size) 2150 return error("Invalid record: metadata strings truncated chars"); 2151 2152 CallBack(Strings.slice(0, Size)); 2153 Strings = Strings.drop_front(Size); 2154 } while (--NumStrings); 2155 2156 return Error::success(); 2157 } 2158 2159 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment( 2160 GlobalObject &GO, ArrayRef<uint64_t> Record) { 2161 assert(Record.size() % 2 == 0); 2162 for (unsigned I = 0, E = Record.size(); I != E; I += 2) { 2163 auto K = MDKindMap.find(Record[I]); 2164 if (K == MDKindMap.end()) 2165 return error("Invalid ID"); 2166 MDNode *MD = 2167 dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1])); 2168 if (!MD) 2169 return error("Invalid metadata attachment: expect fwd ref to MDNode"); 2170 GO.addMetadata(K->second, *MD); 2171 } 2172 return Error::success(); 2173 } 2174 2175 /// Parse metadata attachments. 2176 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment( 2177 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) { 2178 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 2179 return Err; 2180 2181 SmallVector<uint64_t, 64> Record; 2182 PlaceholderQueue Placeholders; 2183 2184 while (true) { 2185 BitstreamEntry Entry; 2186 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) 2187 return E; 2188 2189 switch (Entry.Kind) { 2190 case BitstreamEntry::SubBlock: // Handled for us already. 2191 case BitstreamEntry::Error: 2192 return error("Malformed block"); 2193 case BitstreamEntry::EndBlock: 2194 resolveForwardRefsAndPlaceholders(Placeholders); 2195 return Error::success(); 2196 case BitstreamEntry::Record: 2197 // The interesting case. 2198 break; 2199 } 2200 2201 // Read a metadata attachment record. 2202 Record.clear(); 2203 ++NumMDRecordLoaded; 2204 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2205 if (!MaybeRecord) 2206 return MaybeRecord.takeError(); 2207 switch (MaybeRecord.get()) { 2208 default: // Default behavior: ignore. 2209 break; 2210 case bitc::METADATA_ATTACHMENT: { 2211 unsigned RecordLength = Record.size(); 2212 if (Record.empty()) 2213 return error("Invalid record"); 2214 if (RecordLength % 2 == 0) { 2215 // A function attachment. 2216 if (Error Err = parseGlobalObjectAttachment(F, Record)) 2217 return Err; 2218 continue; 2219 } 2220 2221 // An instruction attachment. 2222 Instruction *Inst = InstructionList[Record[0]]; 2223 for (unsigned i = 1; i != RecordLength; i = i + 2) { 2224 unsigned Kind = Record[i]; 2225 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind); 2226 if (I == MDKindMap.end()) 2227 return error("Invalid ID"); 2228 if (I->second == LLVMContext::MD_tbaa && StripTBAA) 2229 continue; 2230 2231 auto Idx = Record[i + 1]; 2232 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) && 2233 !MetadataList.lookup(Idx)) { 2234 // Load the attachment if it is in the lazy-loadable range and hasn't 2235 // been loaded yet. 2236 lazyLoadOneMetadata(Idx, Placeholders); 2237 resolveForwardRefsAndPlaceholders(Placeholders); 2238 } 2239 2240 Metadata *Node = MetadataList.getMetadataFwdRef(Idx); 2241 if (isa<LocalAsMetadata>(Node)) 2242 // Drop the attachment. This used to be legal, but there's no 2243 // upgrade path. 2244 break; 2245 MDNode *MD = dyn_cast_or_null<MDNode>(Node); 2246 if (!MD) 2247 return error("Invalid metadata attachment"); 2248 2249 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop) 2250 MD = upgradeInstructionLoopAttachment(*MD); 2251 2252 if (I->second == LLVMContext::MD_tbaa) { 2253 assert(!MD->isTemporary() && "should load MDs before attachments"); 2254 MD = UpgradeTBAANode(*MD); 2255 } 2256 Inst->setMetadata(I->second, MD); 2257 } 2258 break; 2259 } 2260 } 2261 } 2262 } 2263 2264 /// Parse a single METADATA_KIND record, inserting result in MDKindMap. 2265 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord( 2266 SmallVectorImpl<uint64_t> &Record) { 2267 if (Record.size() < 2) 2268 return error("Invalid record"); 2269 2270 unsigned Kind = Record[0]; 2271 SmallString<8> Name(Record.begin() + 1, Record.end()); 2272 2273 unsigned NewKind = TheModule.getMDKindID(Name.str()); 2274 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 2275 return error("Conflicting METADATA_KIND records"); 2276 return Error::success(); 2277 } 2278 2279 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 2280 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() { 2281 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 2282 return Err; 2283 2284 SmallVector<uint64_t, 64> Record; 2285 2286 // Read all the records. 2287 while (true) { 2288 BitstreamEntry Entry; 2289 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) 2290 return E; 2291 2292 switch (Entry.Kind) { 2293 case BitstreamEntry::SubBlock: // Handled for us already. 2294 case BitstreamEntry::Error: 2295 return error("Malformed block"); 2296 case BitstreamEntry::EndBlock: 2297 return Error::success(); 2298 case BitstreamEntry::Record: 2299 // The interesting case. 2300 break; 2301 } 2302 2303 // Read a record. 2304 Record.clear(); 2305 ++NumMDRecordLoaded; 2306 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record); 2307 if (!MaybeCode) 2308 return MaybeCode.takeError(); 2309 switch (MaybeCode.get()) { 2310 default: // Default behavior: ignore. 2311 break; 2312 case bitc::METADATA_KIND: { 2313 if (Error Err = parseMetadataKindRecord(Record)) 2314 return Err; 2315 break; 2316 } 2317 } 2318 } 2319 } 2320 2321 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) { 2322 Pimpl = std::move(RHS.Pimpl); 2323 return *this; 2324 } 2325 MetadataLoader::MetadataLoader(MetadataLoader &&RHS) 2326 : Pimpl(std::move(RHS.Pimpl)) {} 2327 2328 MetadataLoader::~MetadataLoader() = default; 2329 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule, 2330 BitcodeReaderValueList &ValueList, 2331 bool IsImporting, 2332 std::function<Type *(unsigned)> getTypeByID) 2333 : Pimpl(std::make_unique<MetadataLoaderImpl>( 2334 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {} 2335 2336 Error MetadataLoader::parseMetadata(bool ModuleLevel) { 2337 return Pimpl->parseMetadata(ModuleLevel); 2338 } 2339 2340 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); } 2341 2342 /// Return the given metadata, creating a replaceable forward reference if 2343 /// necessary. 2344 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) { 2345 return Pimpl->getMetadataFwdRefOrLoad(Idx); 2346 } 2347 2348 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) { 2349 return Pimpl->lookupSubprogramForFunction(F); 2350 } 2351 2352 Error MetadataLoader::parseMetadataAttachment( 2353 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) { 2354 return Pimpl->parseMetadataAttachment(F, InstructionList); 2355 } 2356 2357 Error MetadataLoader::parseMetadataKinds() { 2358 return Pimpl->parseMetadataKinds(); 2359 } 2360 2361 void MetadataLoader::setStripTBAA(bool StripTBAA) { 2362 return Pimpl->setStripTBAA(StripTBAA); 2363 } 2364 2365 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); } 2366 2367 unsigned MetadataLoader::size() const { return Pimpl->size(); } 2368 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); } 2369 2370 void MetadataLoader::upgradeDebugIntrinsics(Function &F) { 2371 return Pimpl->upgradeDebugIntrinsics(F); 2372 } 2373