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