1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Bitcode/BitcodeReader.h"
27 #include "llvm/Bitcode/BitstreamReader.h"
28 #include "llvm/Bitcode/LLVMBitCodes.h"
29 #include "llvm/IR/Argument.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/AutoUpgrade.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Comdat.h"
36 #include "llvm/IR/Constant.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/DebugInfoMetadata.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/DiagnosticPrinter.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GVMaterializer.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalIFunc.h"
48 #include "llvm/IR/GlobalIndirectSymbol.h"
49 #include "llvm/IR/GlobalObject.h"
50 #include "llvm/IR/GlobalValue.h"
51 #include "llvm/IR/GlobalVariable.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/InstrTypes.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Intrinsics.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/ModuleSummaryIndex.h"
61 #include "llvm/IR/OperandTraits.h"
62 #include "llvm/IR/Operator.h"
63 #include "llvm/IR/TrackingMDRef.h"
64 #include "llvm/IR/Type.h"
65 #include "llvm/IR/ValueHandle.h"
66 #include "llvm/Support/AtomicOrdering.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/Error.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/ManagedStatic.h"
74 #include "llvm/Support/MemoryBuffer.h"
75 #include "llvm/Support/raw_ostream.h"
85 #include <system_error>
92 #define DEBUG_TYPE "bitcode-reader"
94 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
95 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
96 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
98 /// Flag whether we need to import full type definitions for ThinLTO.
99 /// Currently needed for Darwin and LLDB.
100 static cl::opt<bool> ImportFullTypeDefinitions(
101 "import-full-type-definitions", cl::init(false), cl::Hidden,
102 cl::desc("Import full type definitions for ThinLTO."));
104 static cl::opt<bool> DisableLazyLoading(
105 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
106 cl::desc("Force disable the lazy-loading on-demand of metadata when "
107 "loading bitcode for importing."));
111 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
113 class BitcodeReaderMetadataList {
114 /// Array of metadata references.
116 /// Don't use std::vector here. Some versions of libc++ copy (instead of
117 /// move) on resize, and TrackingMDRef is very expensive to copy.
118 SmallVector<TrackingMDRef, 1> MetadataPtrs;
120 /// The set of indices in MetadataPtrs above of forward references that were
122 SmallDenseSet<unsigned, 1> ForwardReference;
124 /// The set of indices in MetadataPtrs above of Metadata that need to be
126 SmallDenseSet<unsigned, 1> UnresolvedNodes;
128 /// Structures for resolving old type refs.
130 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
131 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
132 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
133 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
136 LLVMContext &Context;
139 BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
141 // vector compatibility methods
142 unsigned size() const { return MetadataPtrs.size(); }
143 void resize(unsigned N) { MetadataPtrs.resize(N); }
144 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
145 void clear() { MetadataPtrs.clear(); }
146 Metadata *back() const { return MetadataPtrs.back(); }
147 void pop_back() { MetadataPtrs.pop_back(); }
148 bool empty() const { return MetadataPtrs.empty(); }
150 Metadata *operator[](unsigned i) const {
151 assert(i < MetadataPtrs.size());
152 return MetadataPtrs[i];
155 Metadata *lookup(unsigned I) const {
156 if (I < MetadataPtrs.size())
157 return MetadataPtrs[I];
161 void shrinkTo(unsigned N) {
162 assert(N <= size() && "Invalid shrinkTo request!");
163 assert(ForwardReference.empty() && "Unexpected forward refs");
164 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
165 MetadataPtrs.resize(N);
168 /// Return the given metadata, creating a replaceable forward reference if
170 Metadata *getMetadataFwdRef(unsigned Idx);
172 /// Return the the given metadata only if it is fully resolved.
174 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
175 /// would give \c false.
176 Metadata *getMetadataIfResolved(unsigned Idx);
178 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
179 void assignValue(Metadata *MD, unsigned Idx);
180 void tryToResolveCycles();
181 bool hasFwdRefs() const { return !ForwardReference.empty(); }
182 int getNextFwdRef() {
183 assert(hasFwdRefs());
184 return *ForwardReference.begin();
187 /// Upgrade a type that had an MDString reference.
188 void addTypeRef(MDString &UUID, DICompositeType &CT);
190 /// Upgrade a type that had an MDString reference.
191 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
193 /// Upgrade a type ref array that may have MDString references.
194 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
197 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
200 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
201 if (auto *MDN = dyn_cast<MDNode>(MD))
202 if (!MDN->isResolved())
203 UnresolvedNodes.insert(Idx);
213 TrackingMDRef &OldMD = MetadataPtrs[Idx];
219 // If there was a forward reference to this value, replace it.
220 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
221 PrevMD->replaceAllUsesWith(MD);
222 ForwardReference.erase(Idx);
225 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
229 if (Metadata *MD = MetadataPtrs[Idx])
232 // Track forward refs to be resolved later.
233 ForwardReference.insert(Idx);
235 // Create and return a placeholder, which will later be RAUW'd.
236 ++NumMDNodeTemporary;
237 Metadata *MD = MDNode::getTemporary(Context, None).release();
238 MetadataPtrs[Idx].reset(MD);
242 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
243 Metadata *MD = lookup(Idx);
244 if (auto *N = dyn_cast_or_null<MDNode>(MD))
245 if (!N->isResolved())
250 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
251 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
254 void BitcodeReaderMetadataList::tryToResolveCycles() {
255 if (!ForwardReference.empty())
256 // Still forward references... can't resolve cycles.
259 // Give up on finding a full definition for any forward decls that remain.
260 for (const auto &Ref : OldTypeRefs.FwdDecls)
261 OldTypeRefs.Final.insert(Ref);
262 OldTypeRefs.FwdDecls.clear();
264 // Upgrade from old type ref arrays. In strange cases, this could add to
265 // OldTypeRefs.Unknown.
266 for (const auto &Array : OldTypeRefs.Arrays)
267 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
268 OldTypeRefs.Arrays.clear();
270 // Replace old string-based type refs with the resolved node, if possible.
271 // If we haven't seen the node, leave it to the verifier to complain about
272 // the invalid string reference.
273 for (const auto &Ref : OldTypeRefs.Unknown) {
274 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
275 Ref.second->replaceAllUsesWith(CT);
277 Ref.second->replaceAllUsesWith(Ref.first);
279 OldTypeRefs.Unknown.clear();
281 if (UnresolvedNodes.empty())
285 // Resolve any cycles.
286 for (unsigned I : UnresolvedNodes) {
287 auto &MD = MetadataPtrs[I];
288 auto *N = dyn_cast_or_null<MDNode>(MD);
292 assert(!N->isTemporary() && "Unexpected forward reference");
296 // Make sure we return early again until there's another unresolved ref.
297 UnresolvedNodes.clear();
300 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
301 DICompositeType &CT) {
302 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
303 if (CT.isForwardDecl())
304 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
306 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
309 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
310 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
311 if (LLVM_LIKELY(!UUID))
314 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
317 auto &Ref = OldTypeRefs.Unknown[UUID];
319 Ref = MDNode::getTemporary(Context, None);
323 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
324 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
325 if (!Tuple || Tuple->isDistinct())
328 // Look through the array immediately if possible.
329 if (!Tuple->isTemporary())
330 return resolveTypeRefArray(Tuple);
332 // Create and return a placeholder to use for now. Eventually
333 // resolveTypeRefArrays() will be resolve this forward reference.
334 OldTypeRefs.Arrays.emplace_back(
335 std::piecewise_construct, std::forward_as_tuple(Tuple),
336 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
337 return OldTypeRefs.Arrays.back().second.get();
340 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
341 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
342 if (!Tuple || Tuple->isDistinct())
345 // Look through the DITypeRefArray, upgrading each DITypeRef.
346 SmallVector<Metadata *, 32> Ops;
347 Ops.reserve(Tuple->getNumOperands());
348 for (Metadata *MD : Tuple->operands())
349 Ops.push_back(upgradeTypeRef(MD));
351 return MDTuple::get(Context, Ops);
356 class PlaceholderQueue {
357 // Placeholders would thrash around when moved, so store in a std::deque
358 // instead of some sort of vector.
359 std::deque<DistinctMDOperandPlaceholder> PHs;
362 ~PlaceholderQueue() {
363 assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed");
365 bool empty() { return PHs.empty(); }
366 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
367 void flush(BitcodeReaderMetadataList &MetadataList);
369 /// Return the list of temporaries nodes in the queue, these need to be
370 /// loaded before we can flush the queue.
371 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
372 DenseSet<unsigned> &Temporaries) {
373 for (auto &PH : PHs) {
374 auto ID = PH.getID();
375 auto *MD = MetadataList.lookup(ID);
377 Temporaries.insert(ID);
380 auto *N = dyn_cast_or_null<MDNode>(MD);
381 if (N && N->isTemporary())
382 Temporaries.insert(ID);
387 } // end anonymous namespace
389 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
390 PHs.emplace_back(ID);
394 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
395 while (!PHs.empty()) {
396 auto *MD = MetadataList.lookup(PHs.front().getID());
397 assert(MD && "Flushing placeholder on unassigned MD");
399 if (auto *MDN = dyn_cast<MDNode>(MD))
400 assert(MDN->isResolved() &&
401 "Flushing Placeholder while cycles aren't resolved");
403 PHs.front().replaceUseWith(MD);
408 } // anonynous namespace
410 static Error error(const Twine &Message) {
411 return make_error<StringError>(
412 Message, make_error_code(BitcodeError::CorruptedBitcode));
415 class MetadataLoader::MetadataLoaderImpl {
416 BitcodeReaderMetadataList MetadataList;
417 BitcodeReaderValueList &ValueList;
418 BitstreamCursor &Stream;
419 LLVMContext &Context;
421 std::function<Type *(unsigned)> getTypeByID;
423 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
424 /// to keep around the right "context" (Abbrev list) to be able to jump in
425 /// the middle of the metadata block and load any record.
426 BitstreamCursor IndexCursor;
428 /// Index that keeps track of MDString values.
429 std::vector<StringRef> MDStringRef;
431 /// On-demand loading of a single MDString. Requires the index above to be
433 MDString *lazyLoadOneMDString(unsigned Idx);
435 /// Index that keeps track of where to find a metadata record in the stream.
436 std::vector<uint64_t> GlobalMetadataBitPosIndex;
438 /// Populate the index above to enable lazily loading of metadata, and load
439 /// the named metadata as well as the transitively referenced global
441 Expected<bool> lazyLoadModuleMetadataBlock();
443 /// On-demand loading of a single metadata. Requires the index above to be
445 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
447 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
448 // point from SP to CU after a block is completly parsed.
449 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
451 /// Functions that need to be matched with subprograms when upgrading old
453 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
455 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
456 DenseMap<unsigned, unsigned> MDKindMap;
458 bool StripTBAA = false;
459 bool HasSeenOldLoopTags = false;
460 bool NeedUpgradeToDIGlobalVariableExpression = false;
461 bool NeedDeclareExpressionUpgrade = false;
463 /// True if metadata is being parsed for a module being ThinLTO imported.
464 bool IsImporting = false;
466 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
467 PlaceholderQueue &Placeholders, StringRef Blob,
468 unsigned &NextMetadataNo);
469 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
470 function_ref<void(StringRef)> CallBack);
471 Error parseGlobalObjectAttachment(GlobalObject &GO,
472 ArrayRef<uint64_t> Record);
473 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
475 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
477 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
478 void upgradeCUSubprograms() {
479 for (auto CU_SP : CUSubprograms)
480 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
481 for (auto &Op : SPs->operands())
482 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
483 SP->replaceUnit(CU_SP.first);
484 CUSubprograms.clear();
487 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
488 void upgradeCUVariables() {
489 if (!NeedUpgradeToDIGlobalVariableExpression)
492 // Upgrade list of variables attached to the CUs.
493 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
494 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
495 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
496 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
497 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
499 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
501 DIGlobalVariableExpression::getDistinct(Context, GV, nullptr);
502 GVs->replaceOperandWith(I, DGVE);
506 // Upgrade variables attached to globals.
507 for (auto &GV : TheModule.globals()) {
508 SmallVector<MDNode *, 1> MDs;
509 GV.getMetadata(LLVMContext::MD_dbg, MDs);
510 GV.eraseMetadata(LLVMContext::MD_dbg);
512 if (auto *DGV = dyn_cast_or_null<DIGlobalVariable>(MD)) {
514 DIGlobalVariableExpression::getDistinct(Context, DGV, nullptr);
515 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
517 GV.addMetadata(LLVMContext::MD_dbg, *MD);
521 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
522 /// describes a function argument.
523 void upgradeDeclareExpressions(Function &F) {
524 if (!NeedDeclareExpressionUpgrade)
529 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
530 if (auto *DIExpr = DDI->getExpression())
531 if (DIExpr->startsWithDeref() &&
532 dyn_cast_or_null<Argument>(DDI->getAddress())) {
533 SmallVector<uint64_t, 8> Ops;
534 Ops.append(std::next(DIExpr->elements_begin()),
535 DIExpr->elements_end());
536 auto *E = DIExpression::get(Context, Ops);
537 DDI->setOperand(2, MetadataAsValue::get(Context, E));
541 /// Upgrade the expression from previous versions.
542 Error upgradeDIExpression(uint64_t FromVersion,
543 MutableArrayRef<uint64_t> &Expr,
544 SmallVectorImpl<uint64_t> &Buffer) {
545 auto N = Expr.size();
546 switch (FromVersion) {
548 return error("Invalid record");
550 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
551 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
554 // Move DW_OP_deref to the end.
555 if (N && Expr[0] == dwarf::DW_OP_deref) {
556 auto End = Expr.end();
557 if (Expr.size() >= 3 &&
558 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
559 End = std::prev(End, 3);
560 std::move(std::next(Expr.begin()), End, Expr.begin());
561 *std::prev(End) = dwarf::DW_OP_deref;
563 NeedDeclareExpressionUpgrade = true;
566 // Change DW_OP_plus to DW_OP_plus_uconst.
567 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
568 auto SubExpr = ArrayRef<uint64_t>(Expr);
569 while (!SubExpr.empty()) {
570 // Skip past other operators with their operands
571 // for this version of the IR, obtained from
572 // from historic DIExpression::ExprOperand::getSize().
574 switch (SubExpr.front()) {
578 case dwarf::DW_OP_constu:
579 case dwarf::DW_OP_minus:
580 case dwarf::DW_OP_plus:
583 case dwarf::DW_OP_LLVM_fragment:
588 // If the expression is malformed, make sure we don't
589 // copy more elements than we should.
590 HistoricSize = std::min(SubExpr.size(), HistoricSize);
591 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize-1);
593 switch (SubExpr.front()) {
594 case dwarf::DW_OP_plus:
595 Buffer.push_back(dwarf::DW_OP_plus_uconst);
596 Buffer.append(Args.begin(), Args.end());
598 case dwarf::DW_OP_minus:
599 Buffer.push_back(dwarf::DW_OP_constu);
600 Buffer.append(Args.begin(), Args.end());
601 Buffer.push_back(dwarf::DW_OP_minus);
604 Buffer.push_back(*SubExpr.begin());
605 Buffer.append(Args.begin(), Args.end());
609 // Continue with remaining elements.
610 SubExpr = SubExpr.slice(HistoricSize);
612 Expr = MutableArrayRef<uint64_t>(Buffer);
620 return Error::success();
623 void upgradeDebugInfo() {
624 upgradeCUSubprograms();
625 upgradeCUVariables();
629 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
630 BitcodeReaderValueList &ValueList,
631 std::function<Type *(unsigned)> getTypeByID,
633 : MetadataList(TheModule.getContext()), ValueList(ValueList),
634 Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
635 getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
637 Error parseMetadata(bool ModuleLevel);
639 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
641 Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
642 if (ID < MDStringRef.size())
643 return lazyLoadOneMDString(ID);
644 if (auto *MD = MetadataList.lookup(ID))
646 // If lazy-loading is enabled, we try recursively to load the operand
647 // instead of creating a temporary.
648 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
649 PlaceholderQueue Placeholders;
650 lazyLoadOneMetadata(ID, Placeholders);
651 resolveForwardRefsAndPlaceholders(Placeholders);
652 return MetadataList.lookup(ID);
654 return MetadataList.getMetadataFwdRef(ID);
657 MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
658 return MetadataList.getMDNodeFwdRefOrNull(Idx);
661 DISubprogram *lookupSubprogramForFunction(Function *F) {
662 return FunctionsWithSPs.lookup(F);
665 bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
667 Error parseMetadataAttachment(
668 Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
670 Error parseMetadataKinds();
672 void setStripTBAA(bool Value) { StripTBAA = Value; }
673 bool isStrippingTBAA() { return StripTBAA; }
675 unsigned size() const { return MetadataList.size(); }
676 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
677 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
681 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
682 IndexCursor = Stream;
683 SmallVector<uint64_t, 64> Record;
684 // Get the abbrevs, and preload record positions to make them lazy-loadable.
686 BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
687 BitstreamCursor::AF_DontPopBlockAtEnd);
688 switch (Entry.Kind) {
689 case BitstreamEntry::SubBlock: // Handled for us already.
690 case BitstreamEntry::Error:
691 return error("Malformed block");
692 case BitstreamEntry::EndBlock: {
695 case BitstreamEntry::Record: {
696 // The interesting case.
698 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
699 auto Code = IndexCursor.skipRecord(Entry.ID);
701 case bitc::METADATA_STRINGS: {
702 // Rewind and parse the strings.
703 IndexCursor.JumpToBit(CurrentPos);
706 IndexCursor.readRecord(Entry.ID, Record, &Blob);
707 unsigned NumStrings = Record[0];
708 MDStringRef.reserve(NumStrings);
709 auto IndexNextMDString = [&](StringRef Str) {
710 MDStringRef.push_back(Str);
712 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
713 return std::move(Err);
716 case bitc::METADATA_INDEX_OFFSET: {
717 // This is the offset to the index, when we see this we skip all the
718 // records and load only an index to these.
719 IndexCursor.JumpToBit(CurrentPos);
721 IndexCursor.readRecord(Entry.ID, Record);
722 if (Record.size() != 2)
723 return error("Invalid record");
724 auto Offset = Record[0] + (Record[1] << 32);
725 auto BeginPos = IndexCursor.GetCurrentBitNo();
726 IndexCursor.JumpToBit(BeginPos + Offset);
727 Entry = IndexCursor.advanceSkippingSubblocks(
728 BitstreamCursor::AF_DontPopBlockAtEnd);
729 assert(Entry.Kind == BitstreamEntry::Record &&
730 "Corrupted bitcode: Expected `Record` when trying to find the "
733 auto Code = IndexCursor.readRecord(Entry.ID, Record);
735 assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
736 "`METADATA_INDEX` when trying "
737 "to find the Metadata index");
740 auto CurrentValue = BeginPos;
741 GlobalMetadataBitPosIndex.reserve(Record.size());
742 for (auto &Elt : Record) {
744 GlobalMetadataBitPosIndex.push_back(CurrentValue);
748 case bitc::METADATA_INDEX:
749 // We don't expect to get there, the Index is loaded when we encounter
751 return error("Corrupted Metadata block");
752 case bitc::METADATA_NAME: {
753 // Named metadata need to be materialized now and aren't deferred.
754 IndexCursor.JumpToBit(CurrentPos);
756 unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
757 assert(Code == bitc::METADATA_NAME);
759 // Read name of the named metadata.
760 SmallString<8> Name(Record.begin(), Record.end());
761 Code = IndexCursor.ReadCode();
763 // Named Metadata comes in two parts, we expect the name to be followed
766 unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
767 assert(NextBitCode == bitc::METADATA_NAMED_NODE);
770 // Read named metadata elements.
771 unsigned Size = Record.size();
772 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
773 for (unsigned i = 0; i != Size; ++i) {
774 // FIXME: We could use a placeholder here, however NamedMDNode are
775 // taking MDNode as operand and not using the Metadata infrastructure.
776 // It is acknowledged by 'TODO: Inherit from Metadata' in the
777 // NamedMDNode class definition.
778 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
779 assert(MD && "Invalid record");
784 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
785 // FIXME: we need to do this early because we don't materialize global
787 IndexCursor.JumpToBit(CurrentPos);
789 IndexCursor.readRecord(Entry.ID, Record);
790 if (Record.size() % 2 == 0)
791 return error("Invalid record");
792 unsigned ValueID = Record[0];
793 if (ValueID >= ValueList.size())
794 return error("Invalid record");
795 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
796 if (Error Err = parseGlobalObjectAttachment(
797 *GO, ArrayRef<uint64_t>(Record).slice(1)))
798 return std::move(Err);
801 case bitc::METADATA_KIND:
802 case bitc::METADATA_STRING_OLD:
803 case bitc::METADATA_OLD_FN_NODE:
804 case bitc::METADATA_OLD_NODE:
805 case bitc::METADATA_VALUE:
806 case bitc::METADATA_DISTINCT_NODE:
807 case bitc::METADATA_NODE:
808 case bitc::METADATA_LOCATION:
809 case bitc::METADATA_GENERIC_DEBUG:
810 case bitc::METADATA_SUBRANGE:
811 case bitc::METADATA_ENUMERATOR:
812 case bitc::METADATA_BASIC_TYPE:
813 case bitc::METADATA_DERIVED_TYPE:
814 case bitc::METADATA_COMPOSITE_TYPE:
815 case bitc::METADATA_SUBROUTINE_TYPE:
816 case bitc::METADATA_MODULE:
817 case bitc::METADATA_FILE:
818 case bitc::METADATA_COMPILE_UNIT:
819 case bitc::METADATA_SUBPROGRAM:
820 case bitc::METADATA_LEXICAL_BLOCK:
821 case bitc::METADATA_LEXICAL_BLOCK_FILE:
822 case bitc::METADATA_NAMESPACE:
823 case bitc::METADATA_MACRO:
824 case bitc::METADATA_MACRO_FILE:
825 case bitc::METADATA_TEMPLATE_TYPE:
826 case bitc::METADATA_TEMPLATE_VALUE:
827 case bitc::METADATA_GLOBAL_VAR:
828 case bitc::METADATA_LOCAL_VAR:
829 case bitc::METADATA_EXPRESSION:
830 case bitc::METADATA_OBJC_PROPERTY:
831 case bitc::METADATA_IMPORTED_ENTITY:
832 case bitc::METADATA_GLOBAL_VAR_EXPR:
833 // We don't expect to see any of these, if we see one, give up on
834 // lazy-loading and fallback.
836 GlobalMetadataBitPosIndex.clear();
845 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
846 /// module level metadata.
847 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
848 if (!ModuleLevel && MetadataList.hasFwdRefs())
849 return error("Invalid metadata: fwd refs into function blocks");
851 // Record the entry position so that we can jump back here and efficiently
852 // skip the whole block in case we lazy-load.
853 auto EntryPos = Stream.GetCurrentBitNo();
855 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
856 return error("Invalid record");
858 SmallVector<uint64_t, 64> Record;
859 PlaceholderQueue Placeholders;
861 // We lazy-load module-level metadata: we build an index for each record, and
862 // then load individual record as needed, starting with the named metadata.
863 if (ModuleLevel && IsImporting && MetadataList.empty() &&
864 !DisableLazyLoading) {
865 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
867 return SuccessOrErr.takeError();
868 if (SuccessOrErr.get()) {
869 // An index was successfully created and we will be able to load metadata
871 MetadataList.resize(MDStringRef.size() +
872 GlobalMetadataBitPosIndex.size());
874 // Reading the named metadata created forward references and/or
875 // placeholders, that we flush here.
876 resolveForwardRefsAndPlaceholders(Placeholders);
878 // Return at the beginning of the block, since it is easy to skip it
879 // entirely from there.
880 Stream.ReadBlockEnd(); // Pop the abbrev block context.
881 Stream.JumpToBit(EntryPos);
882 if (Stream.SkipBlock())
883 return error("Invalid record");
884 return Error::success();
886 // Couldn't load an index, fallback to loading all the block "old-style".
889 unsigned NextMetadataNo = MetadataList.size();
891 // Read all the records.
893 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
895 switch (Entry.Kind) {
896 case BitstreamEntry::SubBlock: // Handled for us already.
897 case BitstreamEntry::Error:
898 return error("Malformed block");
899 case BitstreamEntry::EndBlock:
900 resolveForwardRefsAndPlaceholders(Placeholders);
902 return Error::success();
903 case BitstreamEntry::Record:
904 // The interesting case.
912 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
914 parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
919 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
921 if (Metadata *MD = MetadataList.lookup(ID))
922 return cast<MDString>(MD);
923 auto MDS = MDString::get(Context, MDStringRef[ID]);
924 MetadataList.assignValue(MDS, ID);
928 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
929 unsigned ID, PlaceholderQueue &Placeholders) {
930 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
931 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
932 // Lookup first if the metadata hasn't already been loaded.
933 if (auto *MD = MetadataList.lookup(ID)) {
934 auto *N = dyn_cast_or_null<MDNode>(MD);
935 if (!N->isTemporary())
938 SmallVector<uint64_t, 64> Record;
940 IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
941 auto Entry = IndexCursor.advanceSkippingSubblocks();
943 unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
944 if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
945 report_fatal_error("Can't lazyload MD");
948 /// Ensure that all forward-references and placeholders are resolved.
949 /// Iteratively lazy-loading metadata on-demand if needed.
950 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
951 PlaceholderQueue &Placeholders) {
952 DenseSet<unsigned> Temporaries;
954 // Populate Temporaries with the placeholders that haven't been loaded yet.
955 Placeholders.getTemporaries(MetadataList, Temporaries);
957 // If we don't have any temporary, or FwdReference, we're done!
958 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
961 // First, load all the temporaries. This can add new placeholders or
962 // forward references.
963 for (auto ID : Temporaries)
964 lazyLoadOneMetadata(ID, Placeholders);
967 // Second, load the forward-references. This can also add new placeholders
968 // or forward references.
969 while (MetadataList.hasFwdRefs())
970 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
972 // At this point we don't have any forward reference remaining, or temporary
973 // that haven't been loaded. We can safely drop RAUW support and mark cycles
975 MetadataList.tryToResolveCycles();
977 // Finally, everything is in place, we can replace the placeholders operands
978 // with the final node they refer to.
979 Placeholders.flush(MetadataList);
982 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
983 SmallVectorImpl<uint64_t> &Record, unsigned Code,
984 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
986 bool IsDistinct = false;
987 auto getMD = [&](unsigned ID) -> Metadata * {
988 if (ID < MDStringRef.size())
989 return lazyLoadOneMDString(ID);
991 if (auto *MD = MetadataList.lookup(ID))
993 // If lazy-loading is enabled, we try recursively to load the operand
994 // instead of creating a temporary.
995 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
996 // Create a temporary for the node that is referencing the operand we
997 // will lazy-load. It is needed before recursing in case there are
999 MetadataList.getMetadataFwdRef(NextMetadataNo);
1000 lazyLoadOneMetadata(ID, Placeholders);
1001 return MetadataList.lookup(ID);
1003 // Return a temporary.
1004 return MetadataList.getMetadataFwdRef(ID);
1006 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1008 return &Placeholders.getPlaceholderOp(ID);
1010 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1012 return getMD(ID - 1);
1015 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1017 return MetadataList.getMetadataFwdRef(ID - 1);
1020 auto getMDString = [&](unsigned ID) -> MDString * {
1021 // This requires that the ID is not really a forward reference. In
1022 // particular, the MDString must already have been resolved.
1023 auto MDS = getMDOrNull(ID);
1024 return cast_or_null<MDString>(MDS);
1027 // Support for old type refs.
1028 auto getDITypeRefOrNull = [&](unsigned ID) {
1029 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1032 #define GET_OR_DISTINCT(CLASS, ARGS) \
1033 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1036 default: // Default behavior: ignore.
1038 case bitc::METADATA_NAME: {
1039 // Read name of the named metadata.
1040 SmallString<8> Name(Record.begin(), Record.end());
1042 Code = Stream.ReadCode();
1044 ++NumMDRecordLoaded;
1045 unsigned NextBitCode = Stream.readRecord(Code, Record);
1046 if (NextBitCode != bitc::METADATA_NAMED_NODE)
1047 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1049 // Read named metadata elements.
1050 unsigned Size = Record.size();
1051 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1052 for (unsigned i = 0; i != Size; ++i) {
1053 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1055 return error("Invalid record");
1056 NMD->addOperand(MD);
1060 case bitc::METADATA_OLD_FN_NODE: {
1061 // FIXME: Remove in 4.0.
1062 // This is a LocalAsMetadata record, the only type of function-local
1064 if (Record.size() % 2 == 1)
1065 return error("Invalid record");
1067 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1068 // to be legal, but there's no upgrade path.
1069 auto dropRecord = [&] {
1070 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
1073 if (Record.size() != 2) {
1078 Type *Ty = getTypeByID(Record[0]);
1079 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1084 MetadataList.assignValue(
1085 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1090 case bitc::METADATA_OLD_NODE: {
1091 // FIXME: Remove in 4.0.
1092 if (Record.size() % 2 == 1)
1093 return error("Invalid record");
1095 unsigned Size = Record.size();
1096 SmallVector<Metadata *, 8> Elts;
1097 for (unsigned i = 0; i != Size; i += 2) {
1098 Type *Ty = getTypeByID(Record[i]);
1100 return error("Invalid record");
1101 if (Ty->isMetadataTy())
1102 Elts.push_back(getMD(Record[i + 1]));
1103 else if (!Ty->isVoidTy()) {
1105 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1106 assert(isa<ConstantAsMetadata>(MD) &&
1107 "Expected non-function-local metadata");
1110 Elts.push_back(nullptr);
1112 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1116 case bitc::METADATA_VALUE: {
1117 if (Record.size() != 2)
1118 return error("Invalid record");
1120 Type *Ty = getTypeByID(Record[0]);
1121 if (Ty->isMetadataTy() || Ty->isVoidTy())
1122 return error("Invalid record");
1124 MetadataList.assignValue(
1125 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1130 case bitc::METADATA_DISTINCT_NODE:
1133 case bitc::METADATA_NODE: {
1134 SmallVector<Metadata *, 8> Elts;
1135 Elts.reserve(Record.size());
1136 for (unsigned ID : Record)
1137 Elts.push_back(getMDOrNull(ID));
1138 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1139 : MDNode::get(Context, Elts),
1144 case bitc::METADATA_LOCATION: {
1145 if (Record.size() != 5)
1146 return error("Invalid record");
1148 IsDistinct = Record[0];
1149 unsigned Line = Record[1];
1150 unsigned Column = Record[2];
1151 Metadata *Scope = getMD(Record[3]);
1152 Metadata *InlinedAt = getMDOrNull(Record[4]);
1153 MetadataList.assignValue(
1154 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
1159 case bitc::METADATA_GENERIC_DEBUG: {
1160 if (Record.size() < 4)
1161 return error("Invalid record");
1163 IsDistinct = Record[0];
1164 unsigned Tag = Record[1];
1165 unsigned Version = Record[2];
1167 if (Tag >= 1u << 16 || Version != 0)
1168 return error("Invalid record");
1170 auto *Header = getMDString(Record[3]);
1171 SmallVector<Metadata *, 8> DwarfOps;
1172 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1173 DwarfOps.push_back(getMDOrNull(Record[I]));
1174 MetadataList.assignValue(
1175 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1180 case bitc::METADATA_SUBRANGE: {
1181 if (Record.size() != 3)
1182 return error("Invalid record");
1184 IsDistinct = Record[0];
1185 MetadataList.assignValue(
1186 GET_OR_DISTINCT(DISubrange,
1187 (Context, Record[1], unrotateSign(Record[2]))),
1192 case bitc::METADATA_ENUMERATOR: {
1193 if (Record.size() != 3)
1194 return error("Invalid record");
1196 IsDistinct = Record[0];
1197 MetadataList.assignValue(
1198 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
1199 getMDString(Record[2]))),
1204 case bitc::METADATA_BASIC_TYPE: {
1205 if (Record.size() != 6)
1206 return error("Invalid record");
1208 IsDistinct = Record[0];
1209 MetadataList.assignValue(
1210 GET_OR_DISTINCT(DIBasicType,
1211 (Context, Record[1], getMDString(Record[2]), Record[3],
1212 Record[4], Record[5])),
1217 case bitc::METADATA_DERIVED_TYPE: {
1218 if (Record.size() < 12 || Record.size() > 13)
1219 return error("Invalid record");
1221 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1222 // that there is no DWARF address space associated with DIDerivedType.
1223 Optional<unsigned> DWARFAddressSpace;
1224 if (Record.size() > 12 && Record[12])
1225 DWARFAddressSpace = Record[12] - 1;
1227 IsDistinct = Record[0];
1228 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1229 MetadataList.assignValue(
1230 GET_OR_DISTINCT(DIDerivedType,
1231 (Context, Record[1], getMDString(Record[2]),
1232 getMDOrNull(Record[3]), Record[4],
1233 getDITypeRefOrNull(Record[5]),
1234 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1235 Record[9], DWARFAddressSpace, Flags,
1236 getDITypeRefOrNull(Record[11]))),
1241 case bitc::METADATA_COMPOSITE_TYPE: {
1242 if (Record.size() != 16)
1243 return error("Invalid record");
1245 // If we have a UUID and this is not a forward declaration, lookup the
1247 IsDistinct = Record[0] & 0x1;
1248 bool IsNotUsedInTypeRef = Record[0] >= 2;
1249 unsigned Tag = Record[1];
1250 MDString *Name = getMDString(Record[2]);
1251 Metadata *File = getMDOrNull(Record[3]);
1252 unsigned Line = Record[4];
1253 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1254 Metadata *BaseType = nullptr;
1255 uint64_t SizeInBits = Record[7];
1256 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1257 return error("Alignment value is too large");
1258 uint32_t AlignInBits = Record[8];
1259 uint64_t OffsetInBits = 0;
1260 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1261 Metadata *Elements = nullptr;
1262 unsigned RuntimeLang = Record[12];
1263 Metadata *VTableHolder = nullptr;
1264 Metadata *TemplateParams = nullptr;
1265 auto *Identifier = getMDString(Record[15]);
1266 // If this module is being parsed so that it can be ThinLTO imported
1267 // into another module, composite types only need to be imported
1268 // as type declarations (unless full type definitions requested).
1269 // Create type declarations up front to save memory. Also, buildODRType
1270 // handles the case where this is type ODRed with a definition needed
1271 // by the importing module, in which case the existing definition is
1273 if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1274 (Tag == dwarf::DW_TAG_enumeration_type ||
1275 Tag == dwarf::DW_TAG_class_type ||
1276 Tag == dwarf::DW_TAG_structure_type ||
1277 Tag == dwarf::DW_TAG_union_type)) {
1278 Flags = Flags | DINode::FlagFwdDecl;
1280 BaseType = getDITypeRefOrNull(Record[6]);
1281 OffsetInBits = Record[9];
1282 Elements = getMDOrNull(Record[11]);
1283 VTableHolder = getDITypeRefOrNull(Record[13]);
1284 TemplateParams = getMDOrNull(Record[14]);
1286 DICompositeType *CT = nullptr;
1288 CT = DICompositeType::buildODRType(
1289 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1290 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1291 VTableHolder, TemplateParams);
1293 // Create a node if we didn't get a lazy ODR type.
1295 CT = GET_OR_DISTINCT(DICompositeType,
1296 (Context, Tag, Name, File, Line, Scope, BaseType,
1297 SizeInBits, AlignInBits, OffsetInBits, Flags,
1298 Elements, RuntimeLang, VTableHolder, TemplateParams,
1300 if (!IsNotUsedInTypeRef && Identifier)
1301 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1303 MetadataList.assignValue(CT, NextMetadataNo);
1307 case bitc::METADATA_SUBROUTINE_TYPE: {
1308 if (Record.size() < 3 || Record.size() > 4)
1309 return error("Invalid record");
1310 bool IsOldTypeRefArray = Record[0] < 2;
1311 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1313 IsDistinct = Record[0] & 0x1;
1314 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1315 Metadata *Types = getMDOrNull(Record[2]);
1316 if (LLVM_UNLIKELY(IsOldTypeRefArray))
1317 Types = MetadataList.upgradeTypeRefArray(Types);
1319 MetadataList.assignValue(
1320 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1326 case bitc::METADATA_MODULE: {
1327 if (Record.size() != 6)
1328 return error("Invalid record");
1330 IsDistinct = Record[0];
1331 MetadataList.assignValue(
1332 GET_OR_DISTINCT(DIModule,
1333 (Context, getMDOrNull(Record[1]),
1334 getMDString(Record[2]), getMDString(Record[3]),
1335 getMDString(Record[4]), getMDString(Record[5]))),
1341 case bitc::METADATA_FILE: {
1342 if (Record.size() != 3 && Record.size() != 5)
1343 return error("Invalid record");
1345 IsDistinct = Record[0];
1346 MetadataList.assignValue(
1349 (Context, getMDString(Record[1]), getMDString(Record[2]),
1350 Record.size() == 3 ? DIFile::CSK_None
1351 : static_cast<DIFile::ChecksumKind>(Record[3]),
1352 Record.size() == 3 ? nullptr : getMDString(Record[4]))),
1357 case bitc::METADATA_COMPILE_UNIT: {
1358 if (Record.size() < 14 || Record.size() > 18)
1359 return error("Invalid record");
1361 // Ignore Record[0], which indicates whether this compile unit is
1362 // distinct. It's always distinct.
1364 auto *CU = DICompileUnit::getDistinct(
1365 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1366 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1367 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1368 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1369 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1370 Record.size() <= 14 ? 0 : Record[14],
1371 Record.size() <= 16 ? true : Record[16],
1372 Record.size() <= 17 ? false : Record[17]);
1374 MetadataList.assignValue(CU, NextMetadataNo);
1377 // Move the Upgrade the list of subprograms.
1378 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1379 CUSubprograms.push_back({CU, SPs});
1382 case bitc::METADATA_SUBPROGRAM: {
1383 if (Record.size() < 18 || Record.size() > 21)
1384 return error("Invalid record");
1387 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
1388 // Version 1 has a Function as Record[15].
1389 // Version 2 has removed Record[15].
1390 // Version 3 has the Unit as Record[15].
1391 // Version 4 added thisAdjustment.
1392 bool HasUnit = Record[0] >= 2;
1393 if (HasUnit && Record.size() < 19)
1394 return error("Invalid record");
1395 Metadata *CUorFn = getMDOrNull(Record[15]);
1396 unsigned Offset = Record.size() >= 19 ? 1 : 0;
1397 bool HasFn = Offset && !HasUnit;
1398 bool HasThisAdj = Record.size() >= 20;
1399 bool HasThrownTypes = Record.size() >= 21;
1400 DISubprogram *SP = GET_OR_DISTINCT(
1403 getDITypeRefOrNull(Record[1]), // scope
1404 getMDString(Record[2]), // name
1405 getMDString(Record[3]), // linkageName
1406 getMDOrNull(Record[4]), // file
1408 getMDOrNull(Record[6]), // type
1409 Record[7], // isLocal
1410 Record[8], // isDefinition
1411 Record[9], // scopeLine
1412 getDITypeRefOrNull(Record[10]), // containingType
1413 Record[11], // virtuality
1414 Record[12], // virtualIndex
1415 HasThisAdj ? Record[19] : 0, // thisAdjustment
1416 static_cast<DINode::DIFlags>(Record[13]), // flags
1417 Record[14], // isOptimized
1418 HasUnit ? CUorFn : nullptr, // unit
1419 getMDOrNull(Record[15 + Offset]), // templateParams
1420 getMDOrNull(Record[16 + Offset]), // declaration
1421 getMDOrNull(Record[17 + Offset]), // variables
1422 HasThrownTypes ? getMDOrNull(Record[20]) : nullptr // thrownTypes
1424 MetadataList.assignValue(SP, NextMetadataNo);
1427 // Upgrade sp->function mapping to function->sp mapping.
1429 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1430 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1431 if (F->isMaterializable())
1432 // Defer until materialized; unmaterialized functions may not have
1434 FunctionsWithSPs[F] = SP;
1435 else if (!F->empty())
1436 F->setSubprogram(SP);
1441 case bitc::METADATA_LEXICAL_BLOCK: {
1442 if (Record.size() != 5)
1443 return error("Invalid record");
1445 IsDistinct = Record[0];
1446 MetadataList.assignValue(
1447 GET_OR_DISTINCT(DILexicalBlock,
1448 (Context, getMDOrNull(Record[1]),
1449 getMDOrNull(Record[2]), Record[3], Record[4])),
1454 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1455 if (Record.size() != 4)
1456 return error("Invalid record");
1458 IsDistinct = Record[0];
1459 MetadataList.assignValue(
1460 GET_OR_DISTINCT(DILexicalBlockFile,
1461 (Context, getMDOrNull(Record[1]),
1462 getMDOrNull(Record[2]), Record[3])),
1467 case bitc::METADATA_NAMESPACE: {
1468 // Newer versions of DINamespace dropped file and line.
1470 if (Record.size() == 3)
1471 Name = getMDString(Record[2]);
1472 else if (Record.size() == 5)
1473 Name = getMDString(Record[3]);
1475 return error("Invalid record");
1477 IsDistinct = Record[0] & 1;
1478 bool ExportSymbols = Record[0] & 2;
1479 MetadataList.assignValue(
1480 GET_OR_DISTINCT(DINamespace,
1481 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
1486 case bitc::METADATA_MACRO: {
1487 if (Record.size() != 5)
1488 return error("Invalid record");
1490 IsDistinct = Record[0];
1491 MetadataList.assignValue(
1492 GET_OR_DISTINCT(DIMacro,
1493 (Context, Record[1], Record[2], getMDString(Record[3]),
1494 getMDString(Record[4]))),
1499 case bitc::METADATA_MACRO_FILE: {
1500 if (Record.size() != 5)
1501 return error("Invalid record");
1503 IsDistinct = Record[0];
1504 MetadataList.assignValue(
1505 GET_OR_DISTINCT(DIMacroFile,
1506 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1507 getMDOrNull(Record[4]))),
1512 case bitc::METADATA_TEMPLATE_TYPE: {
1513 if (Record.size() != 3)
1514 return error("Invalid record");
1516 IsDistinct = Record[0];
1517 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1518 (Context, getMDString(Record[1]),
1519 getDITypeRefOrNull(Record[2]))),
1524 case bitc::METADATA_TEMPLATE_VALUE: {
1525 if (Record.size() != 5)
1526 return error("Invalid record");
1528 IsDistinct = Record[0];
1529 MetadataList.assignValue(
1530 GET_OR_DISTINCT(DITemplateValueParameter,
1531 (Context, Record[1], getMDString(Record[2]),
1532 getDITypeRefOrNull(Record[3]),
1533 getMDOrNull(Record[4]))),
1538 case bitc::METADATA_GLOBAL_VAR: {
1539 if (Record.size() < 11 || Record.size() > 12)
1540 return error("Invalid record");
1542 IsDistinct = Record[0] & 1;
1543 unsigned Version = Record[0] >> 1;
1546 MetadataList.assignValue(
1547 GET_OR_DISTINCT(DIGlobalVariable,
1548 (Context, getMDOrNull(Record[1]),
1549 getMDString(Record[2]), getMDString(Record[3]),
1550 getMDOrNull(Record[4]), Record[5],
1551 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1552 getMDOrNull(Record[10]), Record[11])),
1555 } else if (Version == 0) {
1556 // Upgrade old metadata, which stored a global variable reference or a
1557 // ConstantInt here.
1558 NeedUpgradeToDIGlobalVariableExpression = true;
1559 Metadata *Expr = getMDOrNull(Record[9]);
1560 uint32_t AlignInBits = 0;
1561 if (Record.size() > 11) {
1562 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1563 return error("Alignment value is too large");
1564 AlignInBits = Record[11];
1566 GlobalVariable *Attach = nullptr;
1567 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1568 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1571 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1572 Expr = DIExpression::get(Context,
1573 {dwarf::DW_OP_constu, CI->getZExtValue(),
1574 dwarf::DW_OP_stack_value});
1579 DIGlobalVariable *DGV = GET_OR_DISTINCT(
1581 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1582 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1583 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1584 getMDOrNull(Record[10]), AlignInBits));
1586 DIGlobalVariableExpression *DGVE = nullptr;
1588 DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
1590 Attach->addDebugInfo(DGVE);
1592 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1593 MetadataList.assignValue(MDNode, NextMetadataNo);
1596 return error("Invalid record");
1600 case bitc::METADATA_LOCAL_VAR: {
1601 // 10th field is for the obseleted 'inlinedAt:' field.
1602 if (Record.size() < 8 || Record.size() > 10)
1603 return error("Invalid record");
1605 IsDistinct = Record[0] & 1;
1606 bool HasAlignment = Record[0] & 2;
1607 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1608 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1609 // this is newer version of record which doesn't have artificial tag.
1610 bool HasTag = !HasAlignment && Record.size() > 8;
1611 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1612 uint32_t AlignInBits = 0;
1614 if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1615 return error("Alignment value is too large");
1616 AlignInBits = Record[8 + HasTag];
1618 MetadataList.assignValue(
1619 GET_OR_DISTINCT(DILocalVariable,
1620 (Context, getMDOrNull(Record[1 + HasTag]),
1621 getMDString(Record[2 + HasTag]),
1622 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1623 getDITypeRefOrNull(Record[5 + HasTag]),
1624 Record[6 + HasTag], Flags, AlignInBits)),
1629 case bitc::METADATA_EXPRESSION: {
1630 if (Record.size() < 1)
1631 return error("Invalid record");
1633 IsDistinct = Record[0] & 1;
1634 uint64_t Version = Record[0] >> 1;
1635 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
1637 SmallVector<uint64_t, 6> Buffer;
1638 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
1641 MetadataList.assignValue(
1642 GET_OR_DISTINCT(DIExpression, (Context, Elts)), NextMetadataNo);
1646 case bitc::METADATA_GLOBAL_VAR_EXPR: {
1647 if (Record.size() != 3)
1648 return error("Invalid record");
1650 IsDistinct = Record[0];
1651 MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
1652 (Context, getMDOrNull(Record[1]),
1653 getMDOrNull(Record[2]))),
1658 case bitc::METADATA_OBJC_PROPERTY: {
1659 if (Record.size() != 8)
1660 return error("Invalid record");
1662 IsDistinct = Record[0];
1663 MetadataList.assignValue(
1664 GET_OR_DISTINCT(DIObjCProperty,
1665 (Context, getMDString(Record[1]),
1666 getMDOrNull(Record[2]), Record[3],
1667 getMDString(Record[4]), getMDString(Record[5]),
1668 Record[6], getDITypeRefOrNull(Record[7]))),
1673 case bitc::METADATA_IMPORTED_ENTITY: {
1674 if (Record.size() != 6)
1675 return error("Invalid record");
1677 IsDistinct = Record[0];
1678 MetadataList.assignValue(
1679 GET_OR_DISTINCT(DIImportedEntity,
1680 (Context, Record[1], getMDOrNull(Record[2]),
1681 getDITypeRefOrNull(Record[3]), Record[4],
1682 getMDString(Record[5]))),
1687 case bitc::METADATA_STRING_OLD: {
1688 std::string String(Record.begin(), Record.end());
1690 // Test for upgrading !llvm.loop.
1691 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
1692 ++NumMDStringLoaded;
1693 Metadata *MD = MDString::get(Context, String);
1694 MetadataList.assignValue(MD, NextMetadataNo);
1698 case bitc::METADATA_STRINGS: {
1699 auto CreateNextMDString = [&](StringRef Str) {
1700 ++NumMDStringLoaded;
1701 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
1704 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
1708 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1709 if (Record.size() % 2 == 0)
1710 return error("Invalid record");
1711 unsigned ValueID = Record[0];
1712 if (ValueID >= ValueList.size())
1713 return error("Invalid record");
1714 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1715 if (Error Err = parseGlobalObjectAttachment(
1716 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1720 case bitc::METADATA_KIND: {
1721 // Support older bitcode files that had METADATA_KIND records in a
1722 // block with METADATA_BLOCK_ID.
1723 if (Error Err = parseMetadataKindRecord(Record))
1728 return Error::success();
1729 #undef GET_OR_DISTINCT
1732 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
1733 ArrayRef<uint64_t> Record, StringRef Blob,
1734 function_ref<void(StringRef)> CallBack) {
1735 // All the MDStrings in the block are emitted together in a single
1736 // record. The strings are concatenated and stored in a blob along with
1738 if (Record.size() != 2)
1739 return error("Invalid record: metadata strings layout");
1741 unsigned NumStrings = Record[0];
1742 unsigned StringsOffset = Record[1];
1744 return error("Invalid record: metadata strings with no strings");
1745 if (StringsOffset > Blob.size())
1746 return error("Invalid record: metadata strings corrupt offset");
1748 StringRef Lengths = Blob.slice(0, StringsOffset);
1749 SimpleBitstreamCursor R(Lengths);
1751 StringRef Strings = Blob.drop_front(StringsOffset);
1753 if (R.AtEndOfStream())
1754 return error("Invalid record: metadata strings bad length");
1756 unsigned Size = R.ReadVBR(6);
1757 if (Strings.size() < Size)
1758 return error("Invalid record: metadata strings truncated chars");
1760 CallBack(Strings.slice(0, Size));
1761 Strings = Strings.drop_front(Size);
1762 } while (--NumStrings);
1764 return Error::success();
1767 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1768 GlobalObject &GO, ArrayRef<uint64_t> Record) {
1769 assert(Record.size() % 2 == 0);
1770 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1771 auto K = MDKindMap.find(Record[I]);
1772 if (K == MDKindMap.end())
1773 return error("Invalid ID");
1774 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1776 return error("Invalid metadata attachment");
1777 GO.addMetadata(K->second, *MD);
1779 return Error::success();
1782 /// Parse metadata attachments.
1783 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1784 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1785 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1786 return error("Invalid record");
1788 SmallVector<uint64_t, 64> Record;
1789 PlaceholderQueue Placeholders;
1792 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1794 switch (Entry.Kind) {
1795 case BitstreamEntry::SubBlock: // Handled for us already.
1796 case BitstreamEntry::Error:
1797 return error("Malformed block");
1798 case BitstreamEntry::EndBlock:
1799 resolveForwardRefsAndPlaceholders(Placeholders);
1800 return Error::success();
1801 case BitstreamEntry::Record:
1802 // The interesting case.
1806 // Read a metadata attachment record.
1808 ++NumMDRecordLoaded;
1809 switch (Stream.readRecord(Entry.ID, Record)) {
1810 default: // Default behavior: ignore.
1812 case bitc::METADATA_ATTACHMENT: {
1813 unsigned RecordLength = Record.size();
1815 return error("Invalid record");
1816 if (RecordLength % 2 == 0) {
1817 // A function attachment.
1818 if (Error Err = parseGlobalObjectAttachment(F, Record))
1823 // An instruction attachment.
1824 Instruction *Inst = InstructionList[Record[0]];
1825 for (unsigned i = 1; i != RecordLength; i = i + 2) {
1826 unsigned Kind = Record[i];
1827 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1828 if (I == MDKindMap.end())
1829 return error("Invalid ID");
1830 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1833 auto Idx = Record[i + 1];
1834 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
1835 !MetadataList.lookup(Idx)) {
1836 // Load the attachment if it is in the lazy-loadable range and hasn't
1838 lazyLoadOneMetadata(Idx, Placeholders);
1839 resolveForwardRefsAndPlaceholders(Placeholders);
1842 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
1843 if (isa<LocalAsMetadata>(Node))
1844 // Drop the attachment. This used to be legal, but there's no
1847 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1849 return error("Invalid metadata attachment");
1851 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1852 MD = upgradeInstructionLoopAttachment(*MD);
1854 if (I->second == LLVMContext::MD_tbaa) {
1855 assert(!MD->isTemporary() && "should load MDs before attachments");
1856 MD = UpgradeTBAANode(*MD);
1858 Inst->setMetadata(I->second, MD);
1866 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1867 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1868 SmallVectorImpl<uint64_t> &Record) {
1869 if (Record.size() < 2)
1870 return error("Invalid record");
1872 unsigned Kind = Record[0];
1873 SmallString<8> Name(Record.begin() + 1, Record.end());
1875 unsigned NewKind = TheModule.getMDKindID(Name.str());
1876 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1877 return error("Conflicting METADATA_KIND records");
1878 return Error::success();
1881 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1882 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1883 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1884 return error("Invalid record");
1886 SmallVector<uint64_t, 64> Record;
1888 // Read all the records.
1890 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1892 switch (Entry.Kind) {
1893 case BitstreamEntry::SubBlock: // Handled for us already.
1894 case BitstreamEntry::Error:
1895 return error("Malformed block");
1896 case BitstreamEntry::EndBlock:
1897 return Error::success();
1898 case BitstreamEntry::Record:
1899 // The interesting case.
1905 ++NumMDRecordLoaded;
1906 unsigned Code = Stream.readRecord(Entry.ID, Record);
1908 default: // Default behavior: ignore.
1910 case bitc::METADATA_KIND: {
1911 if (Error Err = parseMetadataKindRecord(Record))
1919 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1920 Pimpl = std::move(RHS.Pimpl);
1923 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
1924 : Pimpl(std::move(RHS.Pimpl)) {}
1926 MetadataLoader::~MetadataLoader() = default;
1927 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1928 BitcodeReaderValueList &ValueList,
1930 std::function<Type *(unsigned)> getTypeByID)
1931 : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
1932 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
1934 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
1935 return Pimpl->parseMetadata(ModuleLevel);
1938 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1940 /// Return the given metadata, creating a replaceable forward reference if
1942 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
1943 return Pimpl->getMetadataFwdRefOrLoad(Idx);
1946 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1947 return Pimpl->getMDNodeFwdRefOrNull(Idx);
1950 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1951 return Pimpl->lookupSubprogramForFunction(F);
1954 Error MetadataLoader::parseMetadataAttachment(
1955 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1956 return Pimpl->parseMetadataAttachment(F, InstructionList);
1959 Error MetadataLoader::parseMetadataKinds() {
1960 return Pimpl->parseMetadataKinds();
1963 void MetadataLoader::setStripTBAA(bool StripTBAA) {
1964 return Pimpl->setStripTBAA(StripTBAA);
1967 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1969 unsigned MetadataLoader::size() const { return Pimpl->size(); }
1970 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
1972 void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
1973 return Pimpl->upgradeDebugIntrinsics(F);