1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "MetadataLoader.h"
10 #include "ValueList.h"
12 #include "llvm/ADT/APInt.h"
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/BitmaskEnum.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLFunctionalExtras.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/ADT/ilist_iterator.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/BinaryFormat/Dwarf.h"
27 #include "llvm/Bitcode/BitcodeReader.h"
28 #include "llvm/Bitcode/LLVMBitCodes.h"
29 #include "llvm/Bitstream/BitstreamReader.h"
30 #include "llvm/IR/AutoUpgrade.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DebugInfoMetadata.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalObject.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/TrackingMDRef.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/type_traits.h"
61 #include <type_traits>
70 #define DEBUG_TYPE "bitcode-reader"
72 STATISTIC(NumMDStringLoaded
, "Number of MDStrings loaded");
73 STATISTIC(NumMDNodeTemporary
, "Number of MDNode::Temporary created");
74 STATISTIC(NumMDRecordLoaded
, "Number of Metadata records loaded");
76 /// Flag whether we need to import full type definitions for ThinLTO.
77 /// Currently needed for Darwin and LLDB.
78 static cl::opt
<bool> ImportFullTypeDefinitions(
79 "import-full-type-definitions", cl::init(false), cl::Hidden
,
80 cl::desc("Import full type definitions for ThinLTO."));
82 static cl::opt
<bool> DisableLazyLoading(
83 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden
,
84 cl::desc("Force disable the lazy-loading on-demand of metadata when "
85 "loading bitcode for importing."));
89 static int64_t unrotateSign(uint64_t U
) { return (U
& 1) ? ~(U
>> 1) : U
>> 1; }
91 class BitcodeReaderMetadataList
{
92 /// Array of metadata references.
94 /// Don't use std::vector here. Some versions of libc++ copy (instead of
95 /// move) on resize, and TrackingMDRef is very expensive to copy.
96 SmallVector
<TrackingMDRef
, 1> MetadataPtrs
;
98 /// The set of indices in MetadataPtrs above of forward references that were
100 SmallDenseSet
<unsigned, 1> ForwardReference
;
102 /// The set of indices in MetadataPtrs above of Metadata that need to be
104 SmallDenseSet
<unsigned, 1> UnresolvedNodes
;
106 /// Structures for resolving old type refs.
108 SmallDenseMap
<MDString
*, TempMDTuple
, 1> Unknown
;
109 SmallDenseMap
<MDString
*, DICompositeType
*, 1> Final
;
110 SmallDenseMap
<MDString
*, DICompositeType
*, 1> FwdDecls
;
111 SmallVector
<std::pair
<TrackingMDRef
, TempMDTuple
>, 1> Arrays
;
114 LLVMContext
&Context
;
116 /// Maximum number of valid references. Forward references exceeding the
117 /// maximum must be invalid.
118 unsigned RefsUpperBound
;
121 BitcodeReaderMetadataList(LLVMContext
&C
, size_t RefsUpperBound
)
123 RefsUpperBound(std::min((size_t)std::numeric_limits
<unsigned>::max(),
126 // vector compatibility methods
127 unsigned size() const { return MetadataPtrs
.size(); }
128 void resize(unsigned N
) { MetadataPtrs
.resize(N
); }
129 void push_back(Metadata
*MD
) { MetadataPtrs
.emplace_back(MD
); }
130 void clear() { MetadataPtrs
.clear(); }
131 Metadata
*back() const { return MetadataPtrs
.back(); }
132 void pop_back() { MetadataPtrs
.pop_back(); }
133 bool empty() const { return MetadataPtrs
.empty(); }
135 Metadata
*operator[](unsigned i
) const {
136 assert(i
< MetadataPtrs
.size());
137 return MetadataPtrs
[i
];
140 Metadata
*lookup(unsigned I
) const {
141 if (I
< MetadataPtrs
.size())
142 return MetadataPtrs
[I
];
146 void shrinkTo(unsigned N
) {
147 assert(N
<= size() && "Invalid shrinkTo request!");
148 assert(ForwardReference
.empty() && "Unexpected forward refs");
149 assert(UnresolvedNodes
.empty() && "Unexpected unresolved node");
150 MetadataPtrs
.resize(N
);
153 /// Return the given metadata, creating a replaceable forward reference if
155 Metadata
*getMetadataFwdRef(unsigned Idx
);
157 /// Return the given metadata only if it is fully resolved.
159 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
160 /// would give \c false.
161 Metadata
*getMetadataIfResolved(unsigned Idx
);
163 MDNode
*getMDNodeFwdRefOrNull(unsigned Idx
);
164 void assignValue(Metadata
*MD
, unsigned Idx
);
165 void tryToResolveCycles();
166 bool hasFwdRefs() const { return !ForwardReference
.empty(); }
167 int getNextFwdRef() {
168 assert(hasFwdRefs());
169 return *ForwardReference
.begin();
172 /// Upgrade a type that had an MDString reference.
173 void addTypeRef(MDString
&UUID
, DICompositeType
&CT
);
175 /// Upgrade a type that had an MDString reference.
176 Metadata
*upgradeTypeRef(Metadata
*MaybeUUID
);
178 /// Upgrade a type ref array that may have MDString references.
179 Metadata
*upgradeTypeRefArray(Metadata
*MaybeTuple
);
182 Metadata
*resolveTypeRefArray(Metadata
*MaybeTuple
);
185 void BitcodeReaderMetadataList::assignValue(Metadata
*MD
, unsigned Idx
) {
186 if (auto *MDN
= dyn_cast
<MDNode
>(MD
))
187 if (!MDN
->isResolved())
188 UnresolvedNodes
.insert(Idx
);
198 TrackingMDRef
&OldMD
= MetadataPtrs
[Idx
];
204 // If there was a forward reference to this value, replace it.
205 TempMDTuple
PrevMD(cast
<MDTuple
>(OldMD
.get()));
206 PrevMD
->replaceAllUsesWith(MD
);
207 ForwardReference
.erase(Idx
);
210 Metadata
*BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx
) {
211 // Bail out for a clearly invalid value.
212 if (Idx
>= RefsUpperBound
)
218 if (Metadata
*MD
= MetadataPtrs
[Idx
])
221 // Track forward refs to be resolved later.
222 ForwardReference
.insert(Idx
);
224 // Create and return a placeholder, which will later be RAUW'd.
225 ++NumMDNodeTemporary
;
226 Metadata
*MD
= MDNode::getTemporary(Context
, std::nullopt
).release();
227 MetadataPtrs
[Idx
].reset(MD
);
231 Metadata
*BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx
) {
232 Metadata
*MD
= lookup(Idx
);
233 if (auto *N
= dyn_cast_or_null
<MDNode
>(MD
))
234 if (!N
->isResolved())
239 MDNode
*BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx
) {
240 return dyn_cast_or_null
<MDNode
>(getMetadataFwdRef(Idx
));
243 void BitcodeReaderMetadataList::tryToResolveCycles() {
244 if (!ForwardReference
.empty())
245 // Still forward references... can't resolve cycles.
248 // Give up on finding a full definition for any forward decls that remain.
249 for (const auto &Ref
: OldTypeRefs
.FwdDecls
)
250 OldTypeRefs
.Final
.insert(Ref
);
251 OldTypeRefs
.FwdDecls
.clear();
253 // Upgrade from old type ref arrays. In strange cases, this could add to
254 // OldTypeRefs.Unknown.
255 for (const auto &Array
: OldTypeRefs
.Arrays
)
256 Array
.second
->replaceAllUsesWith(resolveTypeRefArray(Array
.first
.get()));
257 OldTypeRefs
.Arrays
.clear();
259 // Replace old string-based type refs with the resolved node, if possible.
260 // If we haven't seen the node, leave it to the verifier to complain about
261 // the invalid string reference.
262 for (const auto &Ref
: OldTypeRefs
.Unknown
) {
263 if (DICompositeType
*CT
= OldTypeRefs
.Final
.lookup(Ref
.first
))
264 Ref
.second
->replaceAllUsesWith(CT
);
266 Ref
.second
->replaceAllUsesWith(Ref
.first
);
268 OldTypeRefs
.Unknown
.clear();
270 if (UnresolvedNodes
.empty())
274 // Resolve any cycles.
275 for (unsigned I
: UnresolvedNodes
) {
276 auto &MD
= MetadataPtrs
[I
];
277 auto *N
= dyn_cast_or_null
<MDNode
>(MD
);
281 assert(!N
->isTemporary() && "Unexpected forward reference");
285 // Make sure we return early again until there's another unresolved ref.
286 UnresolvedNodes
.clear();
289 void BitcodeReaderMetadataList::addTypeRef(MDString
&UUID
,
290 DICompositeType
&CT
) {
291 assert(CT
.getRawIdentifier() == &UUID
&& "Mismatched UUID");
292 if (CT
.isForwardDecl())
293 OldTypeRefs
.FwdDecls
.insert(std::make_pair(&UUID
, &CT
));
295 OldTypeRefs
.Final
.insert(std::make_pair(&UUID
, &CT
));
298 Metadata
*BitcodeReaderMetadataList::upgradeTypeRef(Metadata
*MaybeUUID
) {
299 auto *UUID
= dyn_cast_or_null
<MDString
>(MaybeUUID
);
300 if (LLVM_LIKELY(!UUID
))
303 if (auto *CT
= OldTypeRefs
.Final
.lookup(UUID
))
306 auto &Ref
= OldTypeRefs
.Unknown
[UUID
];
308 Ref
= MDNode::getTemporary(Context
, std::nullopt
);
312 Metadata
*BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata
*MaybeTuple
) {
313 auto *Tuple
= dyn_cast_or_null
<MDTuple
>(MaybeTuple
);
314 if (!Tuple
|| Tuple
->isDistinct())
317 // Look through the array immediately if possible.
318 if (!Tuple
->isTemporary())
319 return resolveTypeRefArray(Tuple
);
321 // Create and return a placeholder to use for now. Eventually
322 // resolveTypeRefArrays() will be resolve this forward reference.
323 OldTypeRefs
.Arrays
.emplace_back(
324 std::piecewise_construct
, std::forward_as_tuple(Tuple
),
325 std::forward_as_tuple(MDTuple::getTemporary(Context
, std::nullopt
)));
326 return OldTypeRefs
.Arrays
.back().second
.get();
329 Metadata
*BitcodeReaderMetadataList::resolveTypeRefArray(Metadata
*MaybeTuple
) {
330 auto *Tuple
= dyn_cast_or_null
<MDTuple
>(MaybeTuple
);
331 if (!Tuple
|| Tuple
->isDistinct())
334 // Look through the DITypeRefArray, upgrading each DIType *.
335 SmallVector
<Metadata
*, 32> Ops
;
336 Ops
.reserve(Tuple
->getNumOperands());
337 for (Metadata
*MD
: Tuple
->operands())
338 Ops
.push_back(upgradeTypeRef(MD
));
340 return MDTuple::get(Context
, Ops
);
345 class PlaceholderQueue
{
346 // Placeholders would thrash around when moved, so store in a std::deque
347 // instead of some sort of vector.
348 std::deque
<DistinctMDOperandPlaceholder
> PHs
;
351 ~PlaceholderQueue() {
353 "PlaceholderQueue hasn't been flushed before being destroyed");
355 bool empty() const { return PHs
.empty(); }
356 DistinctMDOperandPlaceholder
&getPlaceholderOp(unsigned ID
);
357 void flush(BitcodeReaderMetadataList
&MetadataList
);
359 /// Return the list of temporaries nodes in the queue, these need to be
360 /// loaded before we can flush the queue.
361 void getTemporaries(BitcodeReaderMetadataList
&MetadataList
,
362 DenseSet
<unsigned> &Temporaries
) {
363 for (auto &PH
: PHs
) {
364 auto ID
= PH
.getID();
365 auto *MD
= MetadataList
.lookup(ID
);
367 Temporaries
.insert(ID
);
370 auto *N
= dyn_cast_or_null
<MDNode
>(MD
);
371 if (N
&& N
->isTemporary())
372 Temporaries
.insert(ID
);
377 } // end anonymous namespace
379 DistinctMDOperandPlaceholder
&PlaceholderQueue::getPlaceholderOp(unsigned ID
) {
380 PHs
.emplace_back(ID
);
384 void PlaceholderQueue::flush(BitcodeReaderMetadataList
&MetadataList
) {
385 while (!PHs
.empty()) {
386 auto *MD
= MetadataList
.lookup(PHs
.front().getID());
387 assert(MD
&& "Flushing placeholder on unassigned MD");
389 if (auto *MDN
= dyn_cast
<MDNode
>(MD
))
390 assert(MDN
->isResolved() &&
391 "Flushing Placeholder while cycles aren't resolved");
393 PHs
.front().replaceUseWith(MD
);
398 } // anonymous namespace
400 static Error
error(const Twine
&Message
) {
401 return make_error
<StringError
>(
402 Message
, make_error_code(BitcodeError::CorruptedBitcode
));
405 class MetadataLoader::MetadataLoaderImpl
{
406 BitcodeReaderMetadataList MetadataList
;
407 BitcodeReaderValueList
&ValueList
;
408 BitstreamCursor
&Stream
;
409 LLVMContext
&Context
;
411 MetadataLoaderCallbacks Callbacks
;
413 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
414 /// to keep around the right "context" (Abbrev list) to be able to jump in
415 /// the middle of the metadata block and load any record.
416 BitstreamCursor IndexCursor
;
418 /// Index that keeps track of MDString values.
419 std::vector
<StringRef
> MDStringRef
;
421 /// On-demand loading of a single MDString. Requires the index above to be
423 MDString
*lazyLoadOneMDString(unsigned Idx
);
425 /// Index that keeps track of where to find a metadata record in the stream.
426 std::vector
<uint64_t> GlobalMetadataBitPosIndex
;
428 /// Cursor position of the start of the global decl attachments, to enable
429 /// loading using the index built for lazy loading, instead of forward
431 uint64_t GlobalDeclAttachmentPos
= 0;
434 /// Baisic correctness check that we end up parsing all of the global decl
436 unsigned NumGlobalDeclAttachSkipped
= 0;
437 unsigned NumGlobalDeclAttachParsed
= 0;
440 /// Load the global decl attachments, using the index built for lazy loading.
441 Expected
<bool> loadGlobalDeclAttachments();
443 /// Populate the index above to enable lazily loading of metadata, and load
444 /// the named metadata as well as the transitively referenced global
446 Expected
<bool> lazyLoadModuleMetadataBlock();
448 /// On-demand loading of a single metadata. Requires the index above to be
450 void lazyLoadOneMetadata(unsigned Idx
, PlaceholderQueue
&Placeholders
);
452 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
453 // point from SP to CU after a block is completly parsed.
454 std::vector
<std::pair
<DICompileUnit
*, Metadata
*>> CUSubprograms
;
456 /// Functions that need to be matched with subprograms when upgrading old
458 SmallDenseMap
<Function
*, DISubprogram
*, 16> FunctionsWithSPs
;
460 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
461 DenseMap
<unsigned, unsigned> MDKindMap
;
463 bool StripTBAA
= false;
464 bool HasSeenOldLoopTags
= false;
465 bool NeedUpgradeToDIGlobalVariableExpression
= false;
466 bool NeedDeclareExpressionUpgrade
= false;
468 /// Map DILocalScope to the enclosing DISubprogram, if any.
469 DenseMap
<DILocalScope
*, DISubprogram
*> ParentSubprogram
;
471 /// True if metadata is being parsed for a module being ThinLTO imported.
472 bool IsImporting
= false;
474 Error
parseOneMetadata(SmallVectorImpl
<uint64_t> &Record
, unsigned Code
,
475 PlaceholderQueue
&Placeholders
, StringRef Blob
,
476 unsigned &NextMetadataNo
);
477 Error
parseMetadataStrings(ArrayRef
<uint64_t> Record
, StringRef Blob
,
478 function_ref
<void(StringRef
)> CallBack
);
479 Error
parseGlobalObjectAttachment(GlobalObject
&GO
,
480 ArrayRef
<uint64_t> Record
);
481 Error
parseMetadataKindRecord(SmallVectorImpl
<uint64_t> &Record
);
483 void resolveForwardRefsAndPlaceholders(PlaceholderQueue
&Placeholders
);
485 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
486 void upgradeCUSubprograms() {
487 for (auto CU_SP
: CUSubprograms
)
488 if (auto *SPs
= dyn_cast_or_null
<MDTuple
>(CU_SP
.second
))
489 for (auto &Op
: SPs
->operands())
490 if (auto *SP
= dyn_cast_or_null
<DISubprogram
>(Op
))
491 SP
->replaceUnit(CU_SP
.first
);
492 CUSubprograms
.clear();
495 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
496 void upgradeCUVariables() {
497 if (!NeedUpgradeToDIGlobalVariableExpression
)
500 // Upgrade list of variables attached to the CUs.
501 if (NamedMDNode
*CUNodes
= TheModule
.getNamedMetadata("llvm.dbg.cu"))
502 for (unsigned I
= 0, E
= CUNodes
->getNumOperands(); I
!= E
; ++I
) {
503 auto *CU
= cast
<DICompileUnit
>(CUNodes
->getOperand(I
));
504 if (auto *GVs
= dyn_cast_or_null
<MDTuple
>(CU
->getRawGlobalVariables()))
505 for (unsigned I
= 0; I
< GVs
->getNumOperands(); I
++)
507 dyn_cast_or_null
<DIGlobalVariable
>(GVs
->getOperand(I
))) {
508 auto *DGVE
= DIGlobalVariableExpression::getDistinct(
509 Context
, GV
, DIExpression::get(Context
, {}));
510 GVs
->replaceOperandWith(I
, DGVE
);
514 // Upgrade variables attached to globals.
515 for (auto &GV
: TheModule
.globals()) {
516 SmallVector
<MDNode
*, 1> MDs
;
517 GV
.getMetadata(LLVMContext::MD_dbg
, MDs
);
518 GV
.eraseMetadata(LLVMContext::MD_dbg
);
520 if (auto *DGV
= dyn_cast
<DIGlobalVariable
>(MD
)) {
521 auto *DGVE
= DIGlobalVariableExpression::getDistinct(
522 Context
, DGV
, DIExpression::get(Context
, {}));
523 GV
.addMetadata(LLVMContext::MD_dbg
, *DGVE
);
525 GV
.addMetadata(LLVMContext::MD_dbg
, *MD
);
529 DISubprogram
*findEnclosingSubprogram(DILocalScope
*S
) {
532 if (auto *SP
= ParentSubprogram
[S
]) {
536 DILocalScope
*InitialScope
= S
;
537 DenseSet
<DILocalScope
*> Visited
;
538 while (S
&& !isa
<DISubprogram
>(S
)) {
539 S
= dyn_cast_or_null
<DILocalScope
>(S
->getScope());
540 if (Visited
.contains(S
))
544 ParentSubprogram
[InitialScope
] = llvm::dyn_cast_or_null
<DISubprogram
>(S
);
546 return ParentSubprogram
[InitialScope
];
549 /// Move local imports from DICompileUnit's 'imports' field to
550 /// DISubprogram's retainedNodes.
551 /// Move fucntion-local enums from DICompileUnit's enums
552 /// to DISubprogram's retainedNodes.
553 void upgradeCULocals() {
554 if (NamedMDNode
*CUNodes
= TheModule
.getNamedMetadata("llvm.dbg.cu")) {
555 for (unsigned I
= 0, E
= CUNodes
->getNumOperands(); I
!= E
; ++I
) {
556 auto *CU
= dyn_cast
<DICompileUnit
>(CUNodes
->getOperand(I
));
560 SetVector
<Metadata
*> MetadataToRemove
;
561 // Collect imported entities to be moved.
562 if (CU
->getRawImportedEntities())
563 for (Metadata
*Op
: CU
->getImportedEntities()->operands()) {
564 auto *IE
= cast
<DIImportedEntity
>(Op
);
565 if (dyn_cast_or_null
<DILocalScope
>(IE
->getScope()))
566 MetadataToRemove
.insert(IE
);
568 // Collect enums to be moved.
569 if (CU
->getRawEnumTypes())
570 for (Metadata
*Op
: CU
->getEnumTypes()->operands()) {
571 auto *Enum
= cast
<DICompositeType
>(Op
);
572 if (dyn_cast_or_null
<DILocalScope
>(Enum
->getScope()))
573 MetadataToRemove
.insert(Enum
);
576 if (!MetadataToRemove
.empty()) {
577 // Make a new list of CU's 'imports'.
578 SmallVector
<Metadata
*> NewImports
;
579 if (CU
->getRawImportedEntities())
580 for (Metadata
*Op
: CU
->getImportedEntities()->operands())
581 if (!MetadataToRemove
.contains(Op
))
582 NewImports
.push_back(Op
);
584 // Make a new list of CU's 'enums'.
585 SmallVector
<Metadata
*> NewEnums
;
586 if (CU
->getRawEnumTypes())
587 for (Metadata
*Op
: CU
->getEnumTypes()->operands())
588 if (!MetadataToRemove
.contains(Op
))
589 NewEnums
.push_back(Op
);
591 // Find DISubprogram corresponding to each entity.
592 std::map
<DISubprogram
*, SmallVector
<Metadata
*>> SPToEntities
;
593 for (auto *I
: MetadataToRemove
) {
594 DILocalScope
*Scope
= nullptr;
595 if (auto *Entity
= dyn_cast
<DIImportedEntity
>(I
))
596 Scope
= cast
<DILocalScope
>(Entity
->getScope());
597 else if (auto *Enum
= dyn_cast
<DICompositeType
>(I
))
598 Scope
= cast
<DILocalScope
>(Enum
->getScope());
600 if (auto *SP
= findEnclosingSubprogram(Scope
))
601 SPToEntities
[SP
].push_back(I
);
604 // Update DISubprograms' retainedNodes.
605 for (auto I
= SPToEntities
.begin(); I
!= SPToEntities
.end(); ++I
) {
607 auto RetainedNodes
= SP
->getRetainedNodes();
608 SmallVector
<Metadata
*> MDs(RetainedNodes
.begin(),
609 RetainedNodes
.end());
610 MDs
.append(I
->second
);
611 SP
->replaceRetainedNodes(MDNode::get(Context
, MDs
));
614 // Remove entities with local scope from CU.
615 if (CU
->getRawImportedEntities())
616 CU
->replaceImportedEntities(MDTuple::get(Context
, NewImports
));
617 // Remove enums with local scope from CU.
618 if (CU
->getRawEnumTypes())
619 CU
->replaceEnumTypes(MDTuple::get(Context
, NewEnums
));
624 ParentSubprogram
.clear();
627 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
628 /// describes a function argument.
629 void upgradeDeclareExpressions(Function
&F
) {
630 if (!NeedDeclareExpressionUpgrade
)
635 if (auto *DDI
= dyn_cast
<DbgDeclareInst
>(&I
))
636 if (auto *DIExpr
= DDI
->getExpression())
637 if (DIExpr
->startsWithDeref() &&
638 isa_and_nonnull
<Argument
>(DDI
->getAddress())) {
639 SmallVector
<uint64_t, 8> Ops
;
640 Ops
.append(std::next(DIExpr
->elements_begin()),
641 DIExpr
->elements_end());
642 DDI
->setExpression(DIExpression::get(Context
, Ops
));
646 /// Upgrade the expression from previous versions.
647 Error
upgradeDIExpression(uint64_t FromVersion
,
648 MutableArrayRef
<uint64_t> &Expr
,
649 SmallVectorImpl
<uint64_t> &Buffer
) {
650 auto N
= Expr
.size();
651 switch (FromVersion
) {
653 return error("Invalid record");
655 if (N
>= 3 && Expr
[N
- 3] == dwarf::DW_OP_bit_piece
)
656 Expr
[N
- 3] = dwarf::DW_OP_LLVM_fragment
;
659 // Move DW_OP_deref to the end.
660 if (N
&& Expr
[0] == dwarf::DW_OP_deref
) {
661 auto End
= Expr
.end();
662 if (Expr
.size() >= 3 &&
663 *std::prev(End
, 3) == dwarf::DW_OP_LLVM_fragment
)
664 End
= std::prev(End
, 3);
665 std::move(std::next(Expr
.begin()), End
, Expr
.begin());
666 *std::prev(End
) = dwarf::DW_OP_deref
;
668 NeedDeclareExpressionUpgrade
= true;
671 // Change DW_OP_plus to DW_OP_plus_uconst.
672 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
673 auto SubExpr
= ArrayRef
<uint64_t>(Expr
);
674 while (!SubExpr
.empty()) {
675 // Skip past other operators with their operands
676 // for this version of the IR, obtained from
677 // from historic DIExpression::ExprOperand::getSize().
679 switch (SubExpr
.front()) {
683 case dwarf::DW_OP_constu
:
684 case dwarf::DW_OP_minus
:
685 case dwarf::DW_OP_plus
:
688 case dwarf::DW_OP_LLVM_fragment
:
693 // If the expression is malformed, make sure we don't
694 // copy more elements than we should.
695 HistoricSize
= std::min(SubExpr
.size(), HistoricSize
);
696 ArrayRef
<uint64_t> Args
= SubExpr
.slice(1, HistoricSize
- 1);
698 switch (SubExpr
.front()) {
699 case dwarf::DW_OP_plus
:
700 Buffer
.push_back(dwarf::DW_OP_plus_uconst
);
701 Buffer
.append(Args
.begin(), Args
.end());
703 case dwarf::DW_OP_minus
:
704 Buffer
.push_back(dwarf::DW_OP_constu
);
705 Buffer
.append(Args
.begin(), Args
.end());
706 Buffer
.push_back(dwarf::DW_OP_minus
);
709 Buffer
.push_back(*SubExpr
.begin());
710 Buffer
.append(Args
.begin(), Args
.end());
714 // Continue with remaining elements.
715 SubExpr
= SubExpr
.slice(HistoricSize
);
717 Expr
= MutableArrayRef
<uint64_t>(Buffer
);
725 return Error::success();
728 void upgradeDebugInfo() {
729 upgradeCUSubprograms();
730 upgradeCUVariables();
734 void callMDTypeCallback(Metadata
**Val
, unsigned TypeID
);
737 MetadataLoaderImpl(BitstreamCursor
&Stream
, Module
&TheModule
,
738 BitcodeReaderValueList
&ValueList
,
739 MetadataLoaderCallbacks Callbacks
, bool IsImporting
)
740 : MetadataList(TheModule
.getContext(), Stream
.SizeInBytes()),
741 ValueList(ValueList
), Stream(Stream
), Context(TheModule
.getContext()),
742 TheModule(TheModule
), Callbacks(std::move(Callbacks
)),
743 IsImporting(IsImporting
) {}
745 Error
parseMetadata(bool ModuleLevel
);
747 bool hasFwdRefs() const { return MetadataList
.hasFwdRefs(); }
749 Metadata
*getMetadataFwdRefOrLoad(unsigned ID
) {
750 if (ID
< MDStringRef
.size())
751 return lazyLoadOneMDString(ID
);
752 if (auto *MD
= MetadataList
.lookup(ID
))
754 // If lazy-loading is enabled, we try recursively to load the operand
755 // instead of creating a temporary.
756 if (ID
< (MDStringRef
.size() + GlobalMetadataBitPosIndex
.size())) {
757 PlaceholderQueue Placeholders
;
758 lazyLoadOneMetadata(ID
, Placeholders
);
759 resolveForwardRefsAndPlaceholders(Placeholders
);
760 return MetadataList
.lookup(ID
);
762 return MetadataList
.getMetadataFwdRef(ID
);
765 DISubprogram
*lookupSubprogramForFunction(Function
*F
) {
766 return FunctionsWithSPs
.lookup(F
);
769 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags
; }
771 Error
parseMetadataAttachment(Function
&F
,
772 ArrayRef
<Instruction
*> InstructionList
);
774 Error
parseMetadataKinds();
776 void setStripTBAA(bool Value
) { StripTBAA
= Value
; }
777 bool isStrippingTBAA() const { return StripTBAA
; }
779 unsigned size() const { return MetadataList
.size(); }
780 void shrinkTo(unsigned N
) { MetadataList
.shrinkTo(N
); }
781 void upgradeDebugIntrinsics(Function
&F
) { upgradeDeclareExpressions(F
); }
785 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
786 IndexCursor
= Stream
;
787 SmallVector
<uint64_t, 64> Record
;
788 GlobalDeclAttachmentPos
= 0;
789 // Get the abbrevs, and preload record positions to make them lazy-loadable.
791 uint64_t SavedPos
= IndexCursor
.GetCurrentBitNo();
792 BitstreamEntry Entry
;
795 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd
)
799 switch (Entry
.Kind
) {
800 case BitstreamEntry::SubBlock
: // Handled for us already.
801 case BitstreamEntry::Error
:
802 return error("Malformed block");
803 case BitstreamEntry::EndBlock
: {
806 case BitstreamEntry::Record
: {
807 // The interesting case.
809 uint64_t CurrentPos
= IndexCursor
.GetCurrentBitNo();
811 if (Error E
= IndexCursor
.skipRecord(Entry
.ID
).moveInto(Code
))
814 case bitc::METADATA_STRINGS
: {
815 // Rewind and parse the strings.
816 if (Error Err
= IndexCursor
.JumpToBit(CurrentPos
))
817 return std::move(Err
);
820 if (Expected
<unsigned> MaybeRecord
=
821 IndexCursor
.readRecord(Entry
.ID
, Record
, &Blob
))
824 return MaybeRecord
.takeError();
825 unsigned NumStrings
= Record
[0];
826 MDStringRef
.reserve(NumStrings
);
827 auto IndexNextMDString
= [&](StringRef Str
) {
828 MDStringRef
.push_back(Str
);
830 if (auto Err
= parseMetadataStrings(Record
, Blob
, IndexNextMDString
))
831 return std::move(Err
);
834 case bitc::METADATA_INDEX_OFFSET
: {
835 // This is the offset to the index, when we see this we skip all the
836 // records and load only an index to these.
837 if (Error Err
= IndexCursor
.JumpToBit(CurrentPos
))
838 return std::move(Err
);
840 if (Expected
<unsigned> MaybeRecord
=
841 IndexCursor
.readRecord(Entry
.ID
, Record
))
844 return MaybeRecord
.takeError();
845 if (Record
.size() != 2)
846 return error("Invalid record");
847 auto Offset
= Record
[0] + (Record
[1] << 32);
848 auto BeginPos
= IndexCursor
.GetCurrentBitNo();
849 if (Error Err
= IndexCursor
.JumpToBit(BeginPos
+ Offset
))
850 return std::move(Err
);
851 Expected
<BitstreamEntry
> MaybeEntry
=
852 IndexCursor
.advanceSkippingSubblocks(
853 BitstreamCursor::AF_DontPopBlockAtEnd
);
855 return MaybeEntry
.takeError();
856 Entry
= MaybeEntry
.get();
857 assert(Entry
.Kind
== BitstreamEntry::Record
&&
858 "Corrupted bitcode: Expected `Record` when trying to find the "
861 if (Expected
<unsigned> MaybeCode
=
862 IndexCursor
.readRecord(Entry
.ID
, Record
))
863 assert(MaybeCode
.get() == bitc::METADATA_INDEX
&&
864 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
865 "find the Metadata index");
867 return MaybeCode
.takeError();
869 auto CurrentValue
= BeginPos
;
870 GlobalMetadataBitPosIndex
.reserve(Record
.size());
871 for (auto &Elt
: Record
) {
873 GlobalMetadataBitPosIndex
.push_back(CurrentValue
);
877 case bitc::METADATA_INDEX
:
878 // We don't expect to get there, the Index is loaded when we encounter
880 return error("Corrupted Metadata block");
881 case bitc::METADATA_NAME
: {
882 // Named metadata need to be materialized now and aren't deferred.
883 if (Error Err
= IndexCursor
.JumpToBit(CurrentPos
))
884 return std::move(Err
);
888 if (Expected
<unsigned> MaybeCode
=
889 IndexCursor
.readRecord(Entry
.ID
, Record
)) {
890 Code
= MaybeCode
.get();
891 assert(Code
== bitc::METADATA_NAME
);
893 return MaybeCode
.takeError();
895 // Read name of the named metadata.
896 SmallString
<8> Name(Record
.begin(), Record
.end());
897 if (Expected
<unsigned> MaybeCode
= IndexCursor
.ReadCode())
898 Code
= MaybeCode
.get();
900 return MaybeCode
.takeError();
902 // Named Metadata comes in two parts, we expect the name to be followed
905 if (Expected
<unsigned> MaybeNextBitCode
=
906 IndexCursor
.readRecord(Code
, Record
))
907 assert(MaybeNextBitCode
.get() == bitc::METADATA_NAMED_NODE
);
909 return MaybeNextBitCode
.takeError();
911 // Read named metadata elements.
912 unsigned Size
= Record
.size();
913 NamedMDNode
*NMD
= TheModule
.getOrInsertNamedMetadata(Name
);
914 for (unsigned i
= 0; i
!= Size
; ++i
) {
915 // FIXME: We could use a placeholder here, however NamedMDNode are
916 // taking MDNode as operand and not using the Metadata infrastructure.
917 // It is acknowledged by 'TODO: Inherit from Metadata' in the
918 // NamedMDNode class definition.
919 MDNode
*MD
= MetadataList
.getMDNodeFwdRefOrNull(Record
[i
]);
920 assert(MD
&& "Invalid metadata: expect fwd ref to MDNode");
925 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT
: {
926 if (!GlobalDeclAttachmentPos
)
927 GlobalDeclAttachmentPos
= SavedPos
;
929 NumGlobalDeclAttachSkipped
++;
933 case bitc::METADATA_KIND
:
934 case bitc::METADATA_STRING_OLD
:
935 case bitc::METADATA_OLD_FN_NODE
:
936 case bitc::METADATA_OLD_NODE
:
937 case bitc::METADATA_VALUE
:
938 case bitc::METADATA_DISTINCT_NODE
:
939 case bitc::METADATA_NODE
:
940 case bitc::METADATA_LOCATION
:
941 case bitc::METADATA_GENERIC_DEBUG
:
942 case bitc::METADATA_SUBRANGE
:
943 case bitc::METADATA_ENUMERATOR
:
944 case bitc::METADATA_BASIC_TYPE
:
945 case bitc::METADATA_STRING_TYPE
:
946 case bitc::METADATA_DERIVED_TYPE
:
947 case bitc::METADATA_COMPOSITE_TYPE
:
948 case bitc::METADATA_SUBROUTINE_TYPE
:
949 case bitc::METADATA_MODULE
:
950 case bitc::METADATA_FILE
:
951 case bitc::METADATA_COMPILE_UNIT
:
952 case bitc::METADATA_SUBPROGRAM
:
953 case bitc::METADATA_LEXICAL_BLOCK
:
954 case bitc::METADATA_LEXICAL_BLOCK_FILE
:
955 case bitc::METADATA_NAMESPACE
:
956 case bitc::METADATA_COMMON_BLOCK
:
957 case bitc::METADATA_MACRO
:
958 case bitc::METADATA_MACRO_FILE
:
959 case bitc::METADATA_TEMPLATE_TYPE
:
960 case bitc::METADATA_TEMPLATE_VALUE
:
961 case bitc::METADATA_GLOBAL_VAR
:
962 case bitc::METADATA_LOCAL_VAR
:
963 case bitc::METADATA_ASSIGN_ID
:
964 case bitc::METADATA_LABEL
:
965 case bitc::METADATA_EXPRESSION
:
966 case bitc::METADATA_OBJC_PROPERTY
:
967 case bitc::METADATA_IMPORTED_ENTITY
:
968 case bitc::METADATA_GLOBAL_VAR_EXPR
:
969 case bitc::METADATA_GENERIC_SUBRANGE
:
970 // We don't expect to see any of these, if we see one, give up on
971 // lazy-loading and fallback.
973 GlobalMetadataBitPosIndex
.clear();
982 // Load the global decl attachments after building the lazy loading index.
983 // We don't load them "lazily" - all global decl attachments must be
984 // parsed since they aren't materialized on demand. However, by delaying
985 // their parsing until after the index is created, we can use the index
986 // instead of creating temporaries.
987 Expected
<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
988 // Nothing to do if we didn't find any of these metadata records.
989 if (!GlobalDeclAttachmentPos
)
991 // Use a temporary cursor so that we don't mess up the main Stream cursor or
992 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
993 BitstreamCursor TempCursor
= Stream
;
994 SmallVector
<uint64_t, 64> Record
;
995 // Jump to the position before the first global decl attachment, so we can
996 // scan for the first BitstreamEntry record.
997 if (Error Err
= TempCursor
.JumpToBit(GlobalDeclAttachmentPos
))
998 return std::move(Err
);
1000 BitstreamEntry Entry
;
1003 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd
)
1005 return std::move(E
);
1007 switch (Entry
.Kind
) {
1008 case BitstreamEntry::SubBlock
: // Handled for us already.
1009 case BitstreamEntry::Error
:
1010 return error("Malformed block");
1011 case BitstreamEntry::EndBlock
:
1012 // Check that we parsed them all.
1013 assert(NumGlobalDeclAttachSkipped
== NumGlobalDeclAttachParsed
);
1015 case BitstreamEntry::Record
:
1018 uint64_t CurrentPos
= TempCursor
.GetCurrentBitNo();
1019 Expected
<unsigned> MaybeCode
= TempCursor
.skipRecord(Entry
.ID
);
1021 return MaybeCode
.takeError();
1022 if (MaybeCode
.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT
) {
1023 // Anything other than a global decl attachment signals the end of
1024 // these records. Check that we parsed them all.
1025 assert(NumGlobalDeclAttachSkipped
== NumGlobalDeclAttachParsed
);
1029 NumGlobalDeclAttachParsed
++;
1031 // FIXME: we need to do this early because we don't materialize global
1032 // value explicitly.
1033 if (Error Err
= TempCursor
.JumpToBit(CurrentPos
))
1034 return std::move(Err
);
1036 if (Expected
<unsigned> MaybeRecord
=
1037 TempCursor
.readRecord(Entry
.ID
, Record
))
1040 return MaybeRecord
.takeError();
1041 if (Record
.size() % 2 == 0)
1042 return error("Invalid record");
1043 unsigned ValueID
= Record
[0];
1044 if (ValueID
>= ValueList
.size())
1045 return error("Invalid record");
1046 if (auto *GO
= dyn_cast
<GlobalObject
>(ValueList
[ValueID
])) {
1047 // Need to save and restore the current position since
1048 // parseGlobalObjectAttachment will resolve all forward references which
1049 // would require parsing from locations stored in the index.
1050 CurrentPos
= TempCursor
.GetCurrentBitNo();
1051 if (Error Err
= parseGlobalObjectAttachment(
1052 *GO
, ArrayRef
<uint64_t>(Record
).slice(1)))
1053 return std::move(Err
);
1054 if (Error Err
= TempCursor
.JumpToBit(CurrentPos
))
1055 return std::move(Err
);
1060 void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(Metadata
**Val
,
1062 if (Callbacks
.MDType
) {
1063 (*Callbacks
.MDType
)(Val
, TypeID
, Callbacks
.GetTypeByID
,
1064 Callbacks
.GetContainedTypeID
);
1068 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1069 /// module level metadata.
1070 Error
MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel
) {
1071 if (!ModuleLevel
&& MetadataList
.hasFwdRefs())
1072 return error("Invalid metadata: fwd refs into function blocks");
1074 // Record the entry position so that we can jump back here and efficiently
1075 // skip the whole block in case we lazy-load.
1076 auto EntryPos
= Stream
.GetCurrentBitNo();
1078 if (Error Err
= Stream
.EnterSubBlock(bitc::METADATA_BLOCK_ID
))
1081 SmallVector
<uint64_t, 64> Record
;
1082 PlaceholderQueue Placeholders
;
1084 // We lazy-load module-level metadata: we build an index for each record, and
1085 // then load individual record as needed, starting with the named metadata.
1086 if (ModuleLevel
&& IsImporting
&& MetadataList
.empty() &&
1087 !DisableLazyLoading
) {
1088 auto SuccessOrErr
= lazyLoadModuleMetadataBlock();
1090 return SuccessOrErr
.takeError();
1091 if (SuccessOrErr
.get()) {
1092 // An index was successfully created and we will be able to load metadata
1094 MetadataList
.resize(MDStringRef
.size() +
1095 GlobalMetadataBitPosIndex
.size());
1097 // Now that we have built the index, load the global decl attachments
1098 // that were deferred during that process. This avoids creating
1100 SuccessOrErr
= loadGlobalDeclAttachments();
1102 return SuccessOrErr
.takeError();
1103 assert(SuccessOrErr
.get());
1105 // Reading the named metadata created forward references and/or
1106 // placeholders, that we flush here.
1107 resolveForwardRefsAndPlaceholders(Placeholders
);
1109 // Return at the beginning of the block, since it is easy to skip it
1110 // entirely from there.
1111 Stream
.ReadBlockEnd(); // Pop the abbrev block context.
1112 if (Error Err
= IndexCursor
.JumpToBit(EntryPos
))
1114 if (Error Err
= Stream
.SkipBlock()) {
1115 // FIXME this drops the error on the floor, which
1116 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1117 consumeError(std::move(Err
));
1118 return Error::success();
1120 return Error::success();
1122 // Couldn't load an index, fallback to loading all the block "old-style".
1125 unsigned NextMetadataNo
= MetadataList
.size();
1127 // Read all the records.
1129 BitstreamEntry Entry
;
1130 if (Error E
= Stream
.advanceSkippingSubblocks().moveInto(Entry
))
1133 switch (Entry
.Kind
) {
1134 case BitstreamEntry::SubBlock
: // Handled for us already.
1135 case BitstreamEntry::Error
:
1136 return error("Malformed block");
1137 case BitstreamEntry::EndBlock
:
1138 resolveForwardRefsAndPlaceholders(Placeholders
);
1140 return Error::success();
1141 case BitstreamEntry::Record
:
1142 // The interesting case.
1149 ++NumMDRecordLoaded
;
1150 if (Expected
<unsigned> MaybeCode
=
1151 Stream
.readRecord(Entry
.ID
, Record
, &Blob
)) {
1152 if (Error Err
= parseOneMetadata(Record
, MaybeCode
.get(), Placeholders
,
1153 Blob
, NextMetadataNo
))
1156 return MaybeCode
.takeError();
1160 MDString
*MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID
) {
1161 ++NumMDStringLoaded
;
1162 if (Metadata
*MD
= MetadataList
.lookup(ID
))
1163 return cast
<MDString
>(MD
);
1164 auto MDS
= MDString::get(Context
, MDStringRef
[ID
]);
1165 MetadataList
.assignValue(MDS
, ID
);
1169 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1170 unsigned ID
, PlaceholderQueue
&Placeholders
) {
1171 assert(ID
< (MDStringRef
.size()) + GlobalMetadataBitPosIndex
.size());
1172 assert(ID
>= MDStringRef
.size() && "Unexpected lazy-loading of MDString");
1173 // Lookup first if the metadata hasn't already been loaded.
1174 if (auto *MD
= MetadataList
.lookup(ID
)) {
1175 auto *N
= cast
<MDNode
>(MD
);
1176 if (!N
->isTemporary())
1179 SmallVector
<uint64_t, 64> Record
;
1181 if (Error Err
= IndexCursor
.JumpToBit(
1182 GlobalMetadataBitPosIndex
[ID
- MDStringRef
.size()]))
1183 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1184 Twine(toString(std::move(Err
))));
1185 BitstreamEntry Entry
;
1186 if (Error E
= IndexCursor
.advanceSkippingSubblocks().moveInto(Entry
))
1187 // FIXME this drops the error on the floor.
1188 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1189 Twine(toString(std::move(E
))));
1190 ++NumMDRecordLoaded
;
1191 if (Expected
<unsigned> MaybeCode
=
1192 IndexCursor
.readRecord(Entry
.ID
, Record
, &Blob
)) {
1194 parseOneMetadata(Record
, MaybeCode
.get(), Placeholders
, Blob
, ID
))
1195 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1196 Twine(toString(std::move(Err
))));
1198 report_fatal_error("Can't lazyload MD: " +
1199 Twine(toString(MaybeCode
.takeError())));
1202 /// Ensure that all forward-references and placeholders are resolved.
1203 /// Iteratively lazy-loading metadata on-demand if needed.
1204 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1205 PlaceholderQueue
&Placeholders
) {
1206 DenseSet
<unsigned> Temporaries
;
1208 // Populate Temporaries with the placeholders that haven't been loaded yet.
1209 Placeholders
.getTemporaries(MetadataList
, Temporaries
);
1211 // If we don't have any temporary, or FwdReference, we're done!
1212 if (Temporaries
.empty() && !MetadataList
.hasFwdRefs())
1215 // First, load all the temporaries. This can add new placeholders or
1216 // forward references.
1217 for (auto ID
: Temporaries
)
1218 lazyLoadOneMetadata(ID
, Placeholders
);
1219 Temporaries
.clear();
1221 // Second, load the forward-references. This can also add new placeholders
1222 // or forward references.
1223 while (MetadataList
.hasFwdRefs())
1224 lazyLoadOneMetadata(MetadataList
.getNextFwdRef(), Placeholders
);
1226 // At this point we don't have any forward reference remaining, or temporary
1227 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1229 MetadataList
.tryToResolveCycles();
1231 // Finally, everything is in place, we can replace the placeholders operands
1232 // with the final node they refer to.
1233 Placeholders
.flush(MetadataList
);
1236 Error
MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1237 SmallVectorImpl
<uint64_t> &Record
, unsigned Code
,
1238 PlaceholderQueue
&Placeholders
, StringRef Blob
, unsigned &NextMetadataNo
) {
1240 bool IsDistinct
= false;
1241 auto getMD
= [&](unsigned ID
) -> Metadata
* {
1242 if (ID
< MDStringRef
.size())
1243 return lazyLoadOneMDString(ID
);
1245 if (auto *MD
= MetadataList
.lookup(ID
))
1247 // If lazy-loading is enabled, we try recursively to load the operand
1248 // instead of creating a temporary.
1249 if (ID
< (MDStringRef
.size() + GlobalMetadataBitPosIndex
.size())) {
1250 // Create a temporary for the node that is referencing the operand we
1251 // will lazy-load. It is needed before recursing in case there are
1253 MetadataList
.getMetadataFwdRef(NextMetadataNo
);
1254 lazyLoadOneMetadata(ID
, Placeholders
);
1255 return MetadataList
.lookup(ID
);
1257 // Return a temporary.
1258 return MetadataList
.getMetadataFwdRef(ID
);
1260 if (auto *MD
= MetadataList
.getMetadataIfResolved(ID
))
1262 return &Placeholders
.getPlaceholderOp(ID
);
1264 auto getMDOrNull
= [&](unsigned ID
) -> Metadata
* {
1266 return getMD(ID
- 1);
1269 auto getMDOrNullWithoutPlaceholders
= [&](unsigned ID
) -> Metadata
* {
1271 return MetadataList
.getMetadataFwdRef(ID
- 1);
1274 auto getMDString
= [&](unsigned ID
) -> MDString
* {
1275 // This requires that the ID is not really a forward reference. In
1276 // particular, the MDString must already have been resolved.
1277 auto MDS
= getMDOrNull(ID
);
1278 return cast_or_null
<MDString
>(MDS
);
1281 // Support for old type refs.
1282 auto getDITypeRefOrNull
= [&](unsigned ID
) {
1283 return MetadataList
.upgradeTypeRef(getMDOrNull(ID
));
1286 #define GET_OR_DISTINCT(CLASS, ARGS) \
1287 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1290 default: // Default behavior: ignore.
1292 case bitc::METADATA_NAME
: {
1293 // Read name of the named metadata.
1294 SmallString
<8> Name(Record
.begin(), Record
.end());
1296 if (Error E
= Stream
.ReadCode().moveInto(Code
))
1299 ++NumMDRecordLoaded
;
1300 if (Expected
<unsigned> MaybeNextBitCode
= Stream
.readRecord(Code
, Record
)) {
1301 if (MaybeNextBitCode
.get() != bitc::METADATA_NAMED_NODE
)
1302 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1304 return MaybeNextBitCode
.takeError();
1306 // Read named metadata elements.
1307 unsigned Size
= Record
.size();
1308 NamedMDNode
*NMD
= TheModule
.getOrInsertNamedMetadata(Name
);
1309 for (unsigned i
= 0; i
!= Size
; ++i
) {
1310 MDNode
*MD
= MetadataList
.getMDNodeFwdRefOrNull(Record
[i
]);
1312 return error("Invalid named metadata: expect fwd ref to MDNode");
1313 NMD
->addOperand(MD
);
1317 case bitc::METADATA_OLD_FN_NODE
: {
1318 // Deprecated, but still needed to read old bitcode files.
1319 // This is a LocalAsMetadata record, the only type of function-local
1321 if (Record
.size() % 2 == 1)
1322 return error("Invalid record");
1324 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1325 // to be legal, but there's no upgrade path.
1326 auto dropRecord
= [&] {
1327 MetadataList
.assignValue(MDNode::get(Context
, std::nullopt
),
1331 if (Record
.size() != 2) {
1336 unsigned TyID
= Record
[0];
1337 Type
*Ty
= Callbacks
.GetTypeByID(TyID
);
1338 if (!Ty
|| Ty
->isMetadataTy() || Ty
->isVoidTy()) {
1343 Value
*V
= ValueList
.getValueFwdRef(Record
[1], Ty
, TyID
,
1344 /*ConstExprInsertBB*/ nullptr);
1346 return error("Invalid value reference from old fn metadata");
1348 MetadataList
.assignValue(LocalAsMetadata::get(V
), NextMetadataNo
);
1352 case bitc::METADATA_OLD_NODE
: {
1353 // Deprecated, but still needed to read old bitcode files.
1354 if (Record
.size() % 2 == 1)
1355 return error("Invalid record");
1357 unsigned Size
= Record
.size();
1358 SmallVector
<Metadata
*, 8> Elts
;
1359 for (unsigned i
= 0; i
!= Size
; i
+= 2) {
1360 unsigned TyID
= Record
[i
];
1361 Type
*Ty
= Callbacks
.GetTypeByID(TyID
);
1363 return error("Invalid record");
1364 if (Ty
->isMetadataTy())
1365 Elts
.push_back(getMD(Record
[i
+ 1]));
1366 else if (!Ty
->isVoidTy()) {
1367 Value
*V
= ValueList
.getValueFwdRef(Record
[i
+ 1], Ty
, TyID
,
1368 /*ConstExprInsertBB*/ nullptr);
1370 return error("Invalid value reference from old metadata");
1371 Metadata
*MD
= ValueAsMetadata::get(V
);
1372 assert(isa
<ConstantAsMetadata
>(MD
) &&
1373 "Expected non-function-local metadata");
1374 callMDTypeCallback(&MD
, TyID
);
1377 Elts
.push_back(nullptr);
1379 MetadataList
.assignValue(MDNode::get(Context
, Elts
), NextMetadataNo
);
1383 case bitc::METADATA_VALUE
: {
1384 if (Record
.size() != 2)
1385 return error("Invalid record");
1387 unsigned TyID
= Record
[0];
1388 Type
*Ty
= Callbacks
.GetTypeByID(TyID
);
1389 if (!Ty
|| Ty
->isMetadataTy() || Ty
->isVoidTy())
1390 return error("Invalid record");
1392 Value
*V
= ValueList
.getValueFwdRef(Record
[1], Ty
, TyID
,
1393 /*ConstExprInsertBB*/ nullptr);
1395 return error("Invalid value reference from metadata");
1397 Metadata
*MD
= ValueAsMetadata::get(V
);
1398 callMDTypeCallback(&MD
, TyID
);
1399 MetadataList
.assignValue(MD
, NextMetadataNo
);
1403 case bitc::METADATA_DISTINCT_NODE
:
1406 case bitc::METADATA_NODE
: {
1407 SmallVector
<Metadata
*, 8> Elts
;
1408 Elts
.reserve(Record
.size());
1409 for (unsigned ID
: Record
)
1410 Elts
.push_back(getMDOrNull(ID
));
1411 MetadataList
.assignValue(IsDistinct
? MDNode::getDistinct(Context
, Elts
)
1412 : MDNode::get(Context
, Elts
),
1417 case bitc::METADATA_LOCATION
: {
1418 if (Record
.size() != 5 && Record
.size() != 6)
1419 return error("Invalid record");
1421 IsDistinct
= Record
[0];
1422 unsigned Line
= Record
[1];
1423 unsigned Column
= Record
[2];
1424 Metadata
*Scope
= getMD(Record
[3]);
1425 Metadata
*InlinedAt
= getMDOrNull(Record
[4]);
1426 bool ImplicitCode
= Record
.size() == 6 && Record
[5];
1427 MetadataList
.assignValue(
1428 GET_OR_DISTINCT(DILocation
, (Context
, Line
, Column
, Scope
, InlinedAt
,
1434 case bitc::METADATA_GENERIC_DEBUG
: {
1435 if (Record
.size() < 4)
1436 return error("Invalid record");
1438 IsDistinct
= Record
[0];
1439 unsigned Tag
= Record
[1];
1440 unsigned Version
= Record
[2];
1442 if (Tag
>= 1u << 16 || Version
!= 0)
1443 return error("Invalid record");
1445 auto *Header
= getMDString(Record
[3]);
1446 SmallVector
<Metadata
*, 8> DwarfOps
;
1447 for (unsigned I
= 4, E
= Record
.size(); I
!= E
; ++I
)
1448 DwarfOps
.push_back(getMDOrNull(Record
[I
]));
1449 MetadataList
.assignValue(
1450 GET_OR_DISTINCT(GenericDINode
, (Context
, Tag
, Header
, DwarfOps
)),
1455 case bitc::METADATA_SUBRANGE
: {
1456 Metadata
*Val
= nullptr;
1457 // Operand 'count' is interpreted as:
1458 // - Signed integer (version 0)
1459 // - Metadata node (version 1)
1460 // Operand 'lowerBound' is interpreted as:
1461 // - Signed integer (version 0 and 1)
1462 // - Metadata node (version 2)
1463 // Operands 'upperBound' and 'stride' are interpreted as:
1464 // - Metadata node (version 2)
1465 switch (Record
[0] >> 1) {
1467 Val
= GET_OR_DISTINCT(DISubrange
,
1468 (Context
, Record
[1], unrotateSign(Record
[2])));
1471 Val
= GET_OR_DISTINCT(DISubrange
, (Context
, getMDOrNull(Record
[1]),
1472 unrotateSign(Record
[2])));
1475 Val
= GET_OR_DISTINCT(
1476 DISubrange
, (Context
, getMDOrNull(Record
[1]), getMDOrNull(Record
[2]),
1477 getMDOrNull(Record
[3]), getMDOrNull(Record
[4])));
1480 return error("Invalid record: Unsupported version of DISubrange");
1483 MetadataList
.assignValue(Val
, NextMetadataNo
);
1484 IsDistinct
= Record
[0] & 1;
1488 case bitc::METADATA_GENERIC_SUBRANGE
: {
1489 Metadata
*Val
= nullptr;
1490 Val
= GET_OR_DISTINCT(DIGenericSubrange
,
1491 (Context
, getMDOrNull(Record
[1]),
1492 getMDOrNull(Record
[2]), getMDOrNull(Record
[3]),
1493 getMDOrNull(Record
[4])));
1495 MetadataList
.assignValue(Val
, NextMetadataNo
);
1496 IsDistinct
= Record
[0] & 1;
1500 case bitc::METADATA_ENUMERATOR
: {
1501 if (Record
.size() < 3)
1502 return error("Invalid record");
1504 IsDistinct
= Record
[0] & 1;
1505 bool IsUnsigned
= Record
[0] & 2;
1506 bool IsBigInt
= Record
[0] & 4;
1510 const uint64_t BitWidth
= Record
[1];
1511 const size_t NumWords
= Record
.size() - 3;
1512 Value
= readWideAPInt(ArrayRef(&Record
[3], NumWords
), BitWidth
);
1514 Value
= APInt(64, unrotateSign(Record
[1]), !IsUnsigned
);
1516 MetadataList
.assignValue(
1517 GET_OR_DISTINCT(DIEnumerator
,
1518 (Context
, Value
, IsUnsigned
, getMDString(Record
[2]))),
1523 case bitc::METADATA_BASIC_TYPE
: {
1524 if (Record
.size() < 6 || Record
.size() > 7)
1525 return error("Invalid record");
1527 IsDistinct
= Record
[0];
1528 DINode::DIFlags Flags
= (Record
.size() > 6)
1529 ? static_cast<DINode::DIFlags
>(Record
[6])
1532 MetadataList
.assignValue(
1533 GET_OR_DISTINCT(DIBasicType
,
1534 (Context
, Record
[1], getMDString(Record
[2]), Record
[3],
1535 Record
[4], Record
[5], Flags
)),
1540 case bitc::METADATA_STRING_TYPE
: {
1541 if (Record
.size() > 9 || Record
.size() < 8)
1542 return error("Invalid record");
1544 IsDistinct
= Record
[0];
1545 bool SizeIs8
= Record
.size() == 8;
1546 // StringLocationExp (i.e. Record[5]) is added at a later time
1547 // than the other fields. The code here enables backward compatibility.
1548 Metadata
*StringLocationExp
= SizeIs8
? nullptr : getMDOrNull(Record
[5]);
1549 unsigned Offset
= SizeIs8
? 5 : 6;
1550 MetadataList
.assignValue(
1551 GET_OR_DISTINCT(DIStringType
,
1552 (Context
, Record
[1], getMDString(Record
[2]),
1553 getMDOrNull(Record
[3]), getMDOrNull(Record
[4]),
1554 StringLocationExp
, Record
[Offset
], Record
[Offset
+ 1],
1555 Record
[Offset
+ 2])),
1560 case bitc::METADATA_DERIVED_TYPE
: {
1561 if (Record
.size() < 12 || Record
.size() > 14)
1562 return error("Invalid record");
1564 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1565 // that there is no DWARF address space associated with DIDerivedType.
1566 std::optional
<unsigned> DWARFAddressSpace
;
1567 if (Record
.size() > 12 && Record
[12])
1568 DWARFAddressSpace
= Record
[12] - 1;
1570 Metadata
*Annotations
= nullptr;
1571 if (Record
.size() > 13 && Record
[13])
1572 Annotations
= getMDOrNull(Record
[13]);
1574 IsDistinct
= Record
[0];
1575 DINode::DIFlags Flags
= static_cast<DINode::DIFlags
>(Record
[10]);
1576 MetadataList
.assignValue(
1577 GET_OR_DISTINCT(DIDerivedType
,
1578 (Context
, Record
[1], getMDString(Record
[2]),
1579 getMDOrNull(Record
[3]), Record
[4],
1580 getDITypeRefOrNull(Record
[5]),
1581 getDITypeRefOrNull(Record
[6]), Record
[7], Record
[8],
1582 Record
[9], DWARFAddressSpace
, Flags
,
1583 getDITypeRefOrNull(Record
[11]), Annotations
)),
1588 case bitc::METADATA_COMPOSITE_TYPE
: {
1589 if (Record
.size() < 16 || Record
.size() > 22)
1590 return error("Invalid record");
1592 // If we have a UUID and this is not a forward declaration, lookup the
1594 IsDistinct
= Record
[0] & 0x1;
1595 bool IsNotUsedInTypeRef
= Record
[0] >= 2;
1596 unsigned Tag
= Record
[1];
1597 MDString
*Name
= getMDString(Record
[2]);
1598 Metadata
*File
= getMDOrNull(Record
[3]);
1599 unsigned Line
= Record
[4];
1600 Metadata
*Scope
= getDITypeRefOrNull(Record
[5]);
1601 Metadata
*BaseType
= nullptr;
1602 uint64_t SizeInBits
= Record
[7];
1603 if (Record
[8] > (uint64_t)std::numeric_limits
<uint32_t>::max())
1604 return error("Alignment value is too large");
1605 uint32_t AlignInBits
= Record
[8];
1606 uint64_t OffsetInBits
= 0;
1607 DINode::DIFlags Flags
= static_cast<DINode::DIFlags
>(Record
[10]);
1608 Metadata
*Elements
= nullptr;
1609 unsigned RuntimeLang
= Record
[12];
1610 Metadata
*VTableHolder
= nullptr;
1611 Metadata
*TemplateParams
= nullptr;
1612 Metadata
*Discriminator
= nullptr;
1613 Metadata
*DataLocation
= nullptr;
1614 Metadata
*Associated
= nullptr;
1615 Metadata
*Allocated
= nullptr;
1616 Metadata
*Rank
= nullptr;
1617 Metadata
*Annotations
= nullptr;
1618 auto *Identifier
= getMDString(Record
[15]);
1619 // If this module is being parsed so that it can be ThinLTO imported
1620 // into another module, composite types only need to be imported
1621 // as type declarations (unless full type definitions requested).
1622 // Create type declarations up front to save memory. Also, buildODRType
1623 // handles the case where this is type ODRed with a definition needed
1624 // by the importing module, in which case the existing definition is
1626 if (IsImporting
&& !ImportFullTypeDefinitions
&& Identifier
&&
1627 (Tag
== dwarf::DW_TAG_enumeration_type
||
1628 Tag
== dwarf::DW_TAG_class_type
||
1629 Tag
== dwarf::DW_TAG_structure_type
||
1630 Tag
== dwarf::DW_TAG_union_type
)) {
1631 Flags
= Flags
| DINode::FlagFwdDecl
;
1633 // This is a hack around preserving template parameters for simplified
1634 // template names - it should probably be replaced with a
1635 // DICompositeType flag specifying whether template parameters are
1636 // required on declarations of this type.
1637 StringRef NameStr
= Name
->getString();
1638 if (!NameStr
.contains('<') || NameStr
.startswith("_STN|"))
1639 TemplateParams
= getMDOrNull(Record
[14]);
1642 BaseType
= getDITypeRefOrNull(Record
[6]);
1643 OffsetInBits
= Record
[9];
1644 Elements
= getMDOrNull(Record
[11]);
1645 VTableHolder
= getDITypeRefOrNull(Record
[13]);
1646 TemplateParams
= getMDOrNull(Record
[14]);
1647 if (Record
.size() > 16)
1648 Discriminator
= getMDOrNull(Record
[16]);
1649 if (Record
.size() > 17)
1650 DataLocation
= getMDOrNull(Record
[17]);
1651 if (Record
.size() > 19) {
1652 Associated
= getMDOrNull(Record
[18]);
1653 Allocated
= getMDOrNull(Record
[19]);
1655 if (Record
.size() > 20) {
1656 Rank
= getMDOrNull(Record
[20]);
1658 if (Record
.size() > 21) {
1659 Annotations
= getMDOrNull(Record
[21]);
1662 DICompositeType
*CT
= nullptr;
1664 CT
= DICompositeType::buildODRType(
1665 Context
, *Identifier
, Tag
, Name
, File
, Line
, Scope
, BaseType
,
1666 SizeInBits
, AlignInBits
, OffsetInBits
, Flags
, Elements
, RuntimeLang
,
1667 VTableHolder
, TemplateParams
, Discriminator
, DataLocation
, Associated
,
1668 Allocated
, Rank
, Annotations
);
1670 // Create a node if we didn't get a lazy ODR type.
1672 CT
= GET_OR_DISTINCT(DICompositeType
,
1673 (Context
, Tag
, Name
, File
, Line
, Scope
, BaseType
,
1674 SizeInBits
, AlignInBits
, OffsetInBits
, Flags
,
1675 Elements
, RuntimeLang
, VTableHolder
, TemplateParams
,
1676 Identifier
, Discriminator
, DataLocation
, Associated
,
1677 Allocated
, Rank
, Annotations
));
1678 if (!IsNotUsedInTypeRef
&& Identifier
)
1679 MetadataList
.addTypeRef(*Identifier
, *cast
<DICompositeType
>(CT
));
1681 MetadataList
.assignValue(CT
, NextMetadataNo
);
1685 case bitc::METADATA_SUBROUTINE_TYPE
: {
1686 if (Record
.size() < 3 || Record
.size() > 4)
1687 return error("Invalid record");
1688 bool IsOldTypeRefArray
= Record
[0] < 2;
1689 unsigned CC
= (Record
.size() > 3) ? Record
[3] : 0;
1691 IsDistinct
= Record
[0] & 0x1;
1692 DINode::DIFlags Flags
= static_cast<DINode::DIFlags
>(Record
[1]);
1693 Metadata
*Types
= getMDOrNull(Record
[2]);
1694 if (LLVM_UNLIKELY(IsOldTypeRefArray
))
1695 Types
= MetadataList
.upgradeTypeRefArray(Types
);
1697 MetadataList
.assignValue(
1698 GET_OR_DISTINCT(DISubroutineType
, (Context
, Flags
, CC
, Types
)),
1704 case bitc::METADATA_MODULE
: {
1705 if (Record
.size() < 5 || Record
.size() > 9)
1706 return error("Invalid record");
1708 unsigned Offset
= Record
.size() >= 8 ? 2 : 1;
1709 IsDistinct
= Record
[0];
1710 MetadataList
.assignValue(
1713 (Context
, Record
.size() >= 8 ? getMDOrNull(Record
[1]) : nullptr,
1714 getMDOrNull(Record
[0 + Offset
]), getMDString(Record
[1 + Offset
]),
1715 getMDString(Record
[2 + Offset
]), getMDString(Record
[3 + Offset
]),
1716 getMDString(Record
[4 + Offset
]),
1717 Record
.size() <= 7 ? 0 : Record
[7],
1718 Record
.size() <= 8 ? false : Record
[8])),
1724 case bitc::METADATA_FILE
: {
1725 if (Record
.size() != 3 && Record
.size() != 5 && Record
.size() != 6)
1726 return error("Invalid record");
1728 IsDistinct
= Record
[0];
1729 std::optional
<DIFile::ChecksumInfo
<MDString
*>> Checksum
;
1730 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1731 // is not present. This matches up with the old internal representation,
1732 // and the old encoding for CSK_None in the ChecksumKind. The new
1733 // representation reserves the value 0 in the ChecksumKind to continue to
1734 // encode None in a backwards-compatible way.
1735 if (Record
.size() > 4 && Record
[3] && Record
[4])
1736 Checksum
.emplace(static_cast<DIFile::ChecksumKind
>(Record
[3]),
1737 getMDString(Record
[4]));
1738 MetadataList
.assignValue(
1739 GET_OR_DISTINCT(DIFile
,
1740 (Context
, getMDString(Record
[1]),
1741 getMDString(Record
[2]), Checksum
,
1742 Record
.size() > 5 ? getMDString(Record
[5]) : nullptr)),
1747 case bitc::METADATA_COMPILE_UNIT
: {
1748 if (Record
.size() < 14 || Record
.size() > 22)
1749 return error("Invalid record");
1751 // Ignore Record[0], which indicates whether this compile unit is
1752 // distinct. It's always distinct.
1754 auto *CU
= DICompileUnit::getDistinct(
1755 Context
, Record
[1], getMDOrNull(Record
[2]), getMDString(Record
[3]),
1756 Record
[4], getMDString(Record
[5]), Record
[6], getMDString(Record
[7]),
1757 Record
[8], getMDOrNull(Record
[9]), getMDOrNull(Record
[10]),
1758 getMDOrNull(Record
[12]), getMDOrNull(Record
[13]),
1759 Record
.size() <= 15 ? nullptr : getMDOrNull(Record
[15]),
1760 Record
.size() <= 14 ? 0 : Record
[14],
1761 Record
.size() <= 16 ? true : Record
[16],
1762 Record
.size() <= 17 ? false : Record
[17],
1763 Record
.size() <= 18 ? 0 : Record
[18],
1764 Record
.size() <= 19 ? false : Record
[19],
1765 Record
.size() <= 20 ? nullptr : getMDString(Record
[20]),
1766 Record
.size() <= 21 ? nullptr : getMDString(Record
[21]));
1768 MetadataList
.assignValue(CU
, NextMetadataNo
);
1771 // Move the Upgrade the list of subprograms.
1772 if (Metadata
*SPs
= getMDOrNullWithoutPlaceholders(Record
[11]))
1773 CUSubprograms
.push_back({CU
, SPs
});
1776 case bitc::METADATA_SUBPROGRAM
: {
1777 if (Record
.size() < 18 || Record
.size() > 21)
1778 return error("Invalid record");
1780 bool HasSPFlags
= Record
[0] & 4;
1782 DINode::DIFlags Flags
;
1783 DISubprogram::DISPFlags SPFlags
;
1785 Flags
= static_cast<DINode::DIFlags
>(Record
[11 + 2]);
1787 Flags
= static_cast<DINode::DIFlags
>(Record
[11]);
1788 SPFlags
= static_cast<DISubprogram::DISPFlags
>(Record
[9]);
1791 // Support for old metadata when
1792 // subprogram specific flags are placed in DIFlags.
1793 const unsigned DIFlagMainSubprogram
= 1 << 21;
1794 bool HasOldMainSubprogramFlag
= Flags
& DIFlagMainSubprogram
;
1795 if (HasOldMainSubprogramFlag
)
1796 // Remove old DIFlagMainSubprogram from DIFlags.
1797 // Note: This assumes that any future use of bit 21 defaults to it
1799 Flags
&= ~static_cast<DINode::DIFlags
>(DIFlagMainSubprogram
);
1801 if (HasOldMainSubprogramFlag
&& HasSPFlags
)
1802 SPFlags
|= DISubprogram::SPFlagMainSubprogram
;
1803 else if (!HasSPFlags
)
1804 SPFlags
= DISubprogram::toSPFlags(
1805 /*IsLocalToUnit=*/Record
[7], /*IsDefinition=*/Record
[8],
1806 /*IsOptimized=*/Record
[14], /*Virtuality=*/Record
[11],
1807 /*IsMainSubprogram=*/HasOldMainSubprogramFlag
);
1809 // All definitions should be distinct.
1810 IsDistinct
= (Record
[0] & 1) || (SPFlags
& DISubprogram::SPFlagDefinition
);
1811 // Version 1 has a Function as Record[15].
1812 // Version 2 has removed Record[15].
1813 // Version 3 has the Unit as Record[15].
1814 // Version 4 added thisAdjustment.
1815 // Version 5 repacked flags into DISPFlags, changing many element numbers.
1816 bool HasUnit
= Record
[0] & 2;
1817 if (!HasSPFlags
&& HasUnit
&& Record
.size() < 19)
1818 return error("Invalid record");
1819 if (HasSPFlags
&& !HasUnit
)
1820 return error("Invalid record");
1821 // Accommodate older formats.
1823 bool HasThisAdj
= true;
1824 bool HasThrownTypes
= true;
1825 bool HasAnnotations
= false;
1826 bool HasTargetFuncName
= false;
1827 unsigned OffsetA
= 0;
1828 unsigned OffsetB
= 0;
1832 if (Record
.size() >= 19) {
1836 HasThisAdj
= Record
.size() >= 20;
1837 HasThrownTypes
= Record
.size() >= 21;
1839 HasAnnotations
= Record
.size() >= 19;
1840 HasTargetFuncName
= Record
.size() >= 20;
1842 Metadata
*CUorFn
= getMDOrNull(Record
[12 + OffsetB
]);
1843 DISubprogram
*SP
= GET_OR_DISTINCT(
1846 getDITypeRefOrNull(Record
[1]), // scope
1847 getMDString(Record
[2]), // name
1848 getMDString(Record
[3]), // linkageName
1849 getMDOrNull(Record
[4]), // file
1851 getMDOrNull(Record
[6]), // type
1852 Record
[7 + OffsetA
], // scopeLine
1853 getDITypeRefOrNull(Record
[8 + OffsetA
]), // containingType
1854 Record
[10 + OffsetA
], // virtualIndex
1855 HasThisAdj
? Record
[16 + OffsetB
] : 0, // thisAdjustment
1858 HasUnit
? CUorFn
: nullptr, // unit
1859 getMDOrNull(Record
[13 + OffsetB
]), // templateParams
1860 getMDOrNull(Record
[14 + OffsetB
]), // declaration
1861 getMDOrNull(Record
[15 + OffsetB
]), // retainedNodes
1862 HasThrownTypes
? getMDOrNull(Record
[17 + OffsetB
])
1863 : nullptr, // thrownTypes
1864 HasAnnotations
? getMDOrNull(Record
[18 + OffsetB
])
1865 : nullptr, // annotations
1866 HasTargetFuncName
? getMDString(Record
[19 + OffsetB
])
1867 : nullptr // targetFuncName
1869 MetadataList
.assignValue(SP
, NextMetadataNo
);
1872 // Upgrade sp->function mapping to function->sp mapping.
1874 if (auto *CMD
= dyn_cast_or_null
<ConstantAsMetadata
>(CUorFn
))
1875 if (auto *F
= dyn_cast
<Function
>(CMD
->getValue())) {
1876 if (F
->isMaterializable())
1877 // Defer until materialized; unmaterialized functions may not have
1879 FunctionsWithSPs
[F
] = SP
;
1880 else if (!F
->empty())
1881 F
->setSubprogram(SP
);
1886 case bitc::METADATA_LEXICAL_BLOCK
: {
1887 if (Record
.size() != 5)
1888 return error("Invalid record");
1890 IsDistinct
= Record
[0];
1891 MetadataList
.assignValue(
1892 GET_OR_DISTINCT(DILexicalBlock
,
1893 (Context
, getMDOrNull(Record
[1]),
1894 getMDOrNull(Record
[2]), Record
[3], Record
[4])),
1899 case bitc::METADATA_LEXICAL_BLOCK_FILE
: {
1900 if (Record
.size() != 4)
1901 return error("Invalid record");
1903 IsDistinct
= Record
[0];
1904 MetadataList
.assignValue(
1905 GET_OR_DISTINCT(DILexicalBlockFile
,
1906 (Context
, getMDOrNull(Record
[1]),
1907 getMDOrNull(Record
[2]), Record
[3])),
1912 case bitc::METADATA_COMMON_BLOCK
: {
1913 IsDistinct
= Record
[0] & 1;
1914 MetadataList
.assignValue(
1915 GET_OR_DISTINCT(DICommonBlock
,
1916 (Context
, getMDOrNull(Record
[1]),
1917 getMDOrNull(Record
[2]), getMDString(Record
[3]),
1918 getMDOrNull(Record
[4]), Record
[5])),
1923 case bitc::METADATA_NAMESPACE
: {
1924 // Newer versions of DINamespace dropped file and line.
1926 if (Record
.size() == 3)
1927 Name
= getMDString(Record
[2]);
1928 else if (Record
.size() == 5)
1929 Name
= getMDString(Record
[3]);
1931 return error("Invalid record");
1933 IsDistinct
= Record
[0] & 1;
1934 bool ExportSymbols
= Record
[0] & 2;
1935 MetadataList
.assignValue(
1936 GET_OR_DISTINCT(DINamespace
,
1937 (Context
, getMDOrNull(Record
[1]), Name
, ExportSymbols
)),
1942 case bitc::METADATA_MACRO
: {
1943 if (Record
.size() != 5)
1944 return error("Invalid record");
1946 IsDistinct
= Record
[0];
1947 MetadataList
.assignValue(
1948 GET_OR_DISTINCT(DIMacro
,
1949 (Context
, Record
[1], Record
[2], getMDString(Record
[3]),
1950 getMDString(Record
[4]))),
1955 case bitc::METADATA_MACRO_FILE
: {
1956 if (Record
.size() != 5)
1957 return error("Invalid record");
1959 IsDistinct
= Record
[0];
1960 MetadataList
.assignValue(
1961 GET_OR_DISTINCT(DIMacroFile
,
1962 (Context
, Record
[1], Record
[2], getMDOrNull(Record
[3]),
1963 getMDOrNull(Record
[4]))),
1968 case bitc::METADATA_TEMPLATE_TYPE
: {
1969 if (Record
.size() < 3 || Record
.size() > 4)
1970 return error("Invalid record");
1972 IsDistinct
= Record
[0];
1973 MetadataList
.assignValue(
1974 GET_OR_DISTINCT(DITemplateTypeParameter
,
1975 (Context
, getMDString(Record
[1]),
1976 getDITypeRefOrNull(Record
[2]),
1977 (Record
.size() == 4) ? getMDOrNull(Record
[3])
1978 : getMDOrNull(false))),
1983 case bitc::METADATA_TEMPLATE_VALUE
: {
1984 if (Record
.size() < 5 || Record
.size() > 6)
1985 return error("Invalid record");
1987 IsDistinct
= Record
[0];
1989 MetadataList
.assignValue(
1991 DITemplateValueParameter
,
1992 (Context
, Record
[1], getMDString(Record
[2]),
1993 getDITypeRefOrNull(Record
[3]),
1994 (Record
.size() == 6) ? getMDOrNull(Record
[4]) : getMDOrNull(false),
1995 (Record
.size() == 6) ? getMDOrNull(Record
[5])
1996 : getMDOrNull(Record
[4]))),
2001 case bitc::METADATA_GLOBAL_VAR
: {
2002 if (Record
.size() < 11 || Record
.size() > 13)
2003 return error("Invalid record");
2005 IsDistinct
= Record
[0] & 1;
2006 unsigned Version
= Record
[0] >> 1;
2009 Metadata
*Annotations
= nullptr;
2010 if (Record
.size() > 12)
2011 Annotations
= getMDOrNull(Record
[12]);
2013 MetadataList
.assignValue(
2014 GET_OR_DISTINCT(DIGlobalVariable
,
2015 (Context
, getMDOrNull(Record
[1]),
2016 getMDString(Record
[2]), getMDString(Record
[3]),
2017 getMDOrNull(Record
[4]), Record
[5],
2018 getDITypeRefOrNull(Record
[6]), Record
[7], Record
[8],
2019 getMDOrNull(Record
[9]), getMDOrNull(Record
[10]),
2020 Record
[11], Annotations
)),
2024 } else if (Version
== 1) {
2025 // No upgrade necessary. A null field will be introduced to indicate
2026 // that no parameter information is available.
2027 MetadataList
.assignValue(
2030 (Context
, getMDOrNull(Record
[1]), getMDString(Record
[2]),
2031 getMDString(Record
[3]), getMDOrNull(Record
[4]), Record
[5],
2032 getDITypeRefOrNull(Record
[6]), Record
[7], Record
[8],
2033 getMDOrNull(Record
[10]), nullptr, Record
[11], nullptr)),
2037 } else if (Version
== 0) {
2038 // Upgrade old metadata, which stored a global variable reference or a
2039 // ConstantInt here.
2040 NeedUpgradeToDIGlobalVariableExpression
= true;
2041 Metadata
*Expr
= getMDOrNull(Record
[9]);
2042 uint32_t AlignInBits
= 0;
2043 if (Record
.size() > 11) {
2044 if (Record
[11] > (uint64_t)std::numeric_limits
<uint32_t>::max())
2045 return error("Alignment value is too large");
2046 AlignInBits
= Record
[11];
2048 GlobalVariable
*Attach
= nullptr;
2049 if (auto *CMD
= dyn_cast_or_null
<ConstantAsMetadata
>(Expr
)) {
2050 if (auto *GV
= dyn_cast
<GlobalVariable
>(CMD
->getValue())) {
2053 } else if (auto *CI
= dyn_cast
<ConstantInt
>(CMD
->getValue())) {
2054 Expr
= DIExpression::get(Context
,
2055 {dwarf::DW_OP_constu
, CI
->getZExtValue(),
2056 dwarf::DW_OP_stack_value
});
2061 DIGlobalVariable
*DGV
= GET_OR_DISTINCT(
2063 (Context
, getMDOrNull(Record
[1]), getMDString(Record
[2]),
2064 getMDString(Record
[3]), getMDOrNull(Record
[4]), Record
[5],
2065 getDITypeRefOrNull(Record
[6]), Record
[7], Record
[8],
2066 getMDOrNull(Record
[10]), nullptr, AlignInBits
, nullptr));
2068 DIGlobalVariableExpression
*DGVE
= nullptr;
2070 DGVE
= DIGlobalVariableExpression::getDistinct(
2071 Context
, DGV
, Expr
? Expr
: DIExpression::get(Context
, {}));
2073 Attach
->addDebugInfo(DGVE
);
2075 auto *MDNode
= Expr
? cast
<Metadata
>(DGVE
) : cast
<Metadata
>(DGV
);
2076 MetadataList
.assignValue(MDNode
, NextMetadataNo
);
2079 return error("Invalid record");
2083 case bitc::METADATA_ASSIGN_ID
: {
2084 if (Record
.size() != 1)
2085 return error("Invalid DIAssignID record.");
2087 IsDistinct
= Record
[0] & 1;
2089 return error("Invalid DIAssignID record. Must be distinct");
2091 MetadataList
.assignValue(DIAssignID::getDistinct(Context
), NextMetadataNo
);
2095 case bitc::METADATA_LOCAL_VAR
: {
2096 // 10th field is for the obseleted 'inlinedAt:' field.
2097 if (Record
.size() < 8 || Record
.size() > 10)
2098 return error("Invalid record");
2100 IsDistinct
= Record
[0] & 1;
2101 bool HasAlignment
= Record
[0] & 2;
2102 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2103 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
2104 // this is newer version of record which doesn't have artificial tag.
2105 bool HasTag
= !HasAlignment
&& Record
.size() > 8;
2106 DINode::DIFlags Flags
= static_cast<DINode::DIFlags
>(Record
[7 + HasTag
]);
2107 uint32_t AlignInBits
= 0;
2108 Metadata
*Annotations
= nullptr;
2110 if (Record
[8] > (uint64_t)std::numeric_limits
<uint32_t>::max())
2111 return error("Alignment value is too large");
2112 AlignInBits
= Record
[8];
2113 if (Record
.size() > 9)
2114 Annotations
= getMDOrNull(Record
[9]);
2117 MetadataList
.assignValue(
2118 GET_OR_DISTINCT(DILocalVariable
,
2119 (Context
, getMDOrNull(Record
[1 + HasTag
]),
2120 getMDString(Record
[2 + HasTag
]),
2121 getMDOrNull(Record
[3 + HasTag
]), Record
[4 + HasTag
],
2122 getDITypeRefOrNull(Record
[5 + HasTag
]),
2123 Record
[6 + HasTag
], Flags
, AlignInBits
, Annotations
)),
2128 case bitc::METADATA_LABEL
: {
2129 if (Record
.size() != 5)
2130 return error("Invalid record");
2132 IsDistinct
= Record
[0] & 1;
2133 MetadataList
.assignValue(
2134 GET_OR_DISTINCT(DILabel
, (Context
, getMDOrNull(Record
[1]),
2135 getMDString(Record
[2]),
2136 getMDOrNull(Record
[3]), Record
[4])),
2141 case bitc::METADATA_EXPRESSION
: {
2142 if (Record
.size() < 1)
2143 return error("Invalid record");
2145 IsDistinct
= Record
[0] & 1;
2146 uint64_t Version
= Record
[0] >> 1;
2147 auto Elts
= MutableArrayRef
<uint64_t>(Record
).slice(1);
2149 SmallVector
<uint64_t, 6> Buffer
;
2150 if (Error Err
= upgradeDIExpression(Version
, Elts
, Buffer
))
2153 MetadataList
.assignValue(GET_OR_DISTINCT(DIExpression
, (Context
, Elts
)),
2158 case bitc::METADATA_GLOBAL_VAR_EXPR
: {
2159 if (Record
.size() != 3)
2160 return error("Invalid record");
2162 IsDistinct
= Record
[0];
2163 Metadata
*Expr
= getMDOrNull(Record
[2]);
2165 Expr
= DIExpression::get(Context
, {});
2166 MetadataList
.assignValue(
2167 GET_OR_DISTINCT(DIGlobalVariableExpression
,
2168 (Context
, getMDOrNull(Record
[1]), Expr
)),
2173 case bitc::METADATA_OBJC_PROPERTY
: {
2174 if (Record
.size() != 8)
2175 return error("Invalid record");
2177 IsDistinct
= Record
[0];
2178 MetadataList
.assignValue(
2179 GET_OR_DISTINCT(DIObjCProperty
,
2180 (Context
, getMDString(Record
[1]),
2181 getMDOrNull(Record
[2]), Record
[3],
2182 getMDString(Record
[4]), getMDString(Record
[5]),
2183 Record
[6], getDITypeRefOrNull(Record
[7]))),
2188 case bitc::METADATA_IMPORTED_ENTITY
: {
2189 if (Record
.size() < 6 || Record
.size() > 8)
2190 return error("Invalid DIImportedEntity record");
2192 IsDistinct
= Record
[0];
2193 bool HasFile
= (Record
.size() >= 7);
2194 bool HasElements
= (Record
.size() >= 8);
2195 MetadataList
.assignValue(
2196 GET_OR_DISTINCT(DIImportedEntity
,
2197 (Context
, Record
[1], getMDOrNull(Record
[2]),
2198 getDITypeRefOrNull(Record
[3]),
2199 HasFile
? getMDOrNull(Record
[6]) : nullptr,
2200 HasFile
? Record
[4] : 0, getMDString(Record
[5]),
2201 HasElements
? getMDOrNull(Record
[7]) : nullptr)),
2206 case bitc::METADATA_STRING_OLD
: {
2207 std::string
String(Record
.begin(), Record
.end());
2209 // Test for upgrading !llvm.loop.
2210 HasSeenOldLoopTags
|= mayBeOldLoopAttachmentTag(String
);
2211 ++NumMDStringLoaded
;
2212 Metadata
*MD
= MDString::get(Context
, String
);
2213 MetadataList
.assignValue(MD
, NextMetadataNo
);
2217 case bitc::METADATA_STRINGS
: {
2218 auto CreateNextMDString
= [&](StringRef Str
) {
2219 ++NumMDStringLoaded
;
2220 MetadataList
.assignValue(MDString::get(Context
, Str
), NextMetadataNo
);
2223 if (Error Err
= parseMetadataStrings(Record
, Blob
, CreateNextMDString
))
2227 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT
: {
2228 if (Record
.size() % 2 == 0)
2229 return error("Invalid record");
2230 unsigned ValueID
= Record
[0];
2231 if (ValueID
>= ValueList
.size())
2232 return error("Invalid record");
2233 if (auto *GO
= dyn_cast
<GlobalObject
>(ValueList
[ValueID
]))
2234 if (Error Err
= parseGlobalObjectAttachment(
2235 *GO
, ArrayRef
<uint64_t>(Record
).slice(1)))
2239 case bitc::METADATA_KIND
: {
2240 // Support older bitcode files that had METADATA_KIND records in a
2241 // block with METADATA_BLOCK_ID.
2242 if (Error Err
= parseMetadataKindRecord(Record
))
2246 case bitc::METADATA_ARG_LIST
: {
2247 SmallVector
<ValueAsMetadata
*, 4> Elts
;
2248 Elts
.reserve(Record
.size());
2249 for (uint64_t Elt
: Record
) {
2250 Metadata
*MD
= getMD(Elt
);
2251 if (isa
<MDNode
>(MD
) && cast
<MDNode
>(MD
)->isTemporary())
2253 "Invalid record: DIArgList should not contain forward refs");
2254 if (!isa
<ValueAsMetadata
>(MD
))
2255 return error("Invalid record");
2256 Elts
.push_back(cast
<ValueAsMetadata
>(MD
));
2259 MetadataList
.assignValue(DIArgList::get(Context
, Elts
), NextMetadataNo
);
2264 return Error::success();
2265 #undef GET_OR_DISTINCT
2268 Error
MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2269 ArrayRef
<uint64_t> Record
, StringRef Blob
,
2270 function_ref
<void(StringRef
)> CallBack
) {
2271 // All the MDStrings in the block are emitted together in a single
2272 // record. The strings are concatenated and stored in a blob along with
2274 if (Record
.size() != 2)
2275 return error("Invalid record: metadata strings layout");
2277 unsigned NumStrings
= Record
[0];
2278 unsigned StringsOffset
= Record
[1];
2280 return error("Invalid record: metadata strings with no strings");
2281 if (StringsOffset
> Blob
.size())
2282 return error("Invalid record: metadata strings corrupt offset");
2284 StringRef Lengths
= Blob
.slice(0, StringsOffset
);
2285 SimpleBitstreamCursor
R(Lengths
);
2287 StringRef Strings
= Blob
.drop_front(StringsOffset
);
2289 if (R
.AtEndOfStream())
2290 return error("Invalid record: metadata strings bad length");
2293 if (Error E
= R
.ReadVBR(6).moveInto(Size
))
2295 if (Strings
.size() < Size
)
2296 return error("Invalid record: metadata strings truncated chars");
2298 CallBack(Strings
.slice(0, Size
));
2299 Strings
= Strings
.drop_front(Size
);
2300 } while (--NumStrings
);
2302 return Error::success();
2305 Error
MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2306 GlobalObject
&GO
, ArrayRef
<uint64_t> Record
) {
2307 assert(Record
.size() % 2 == 0);
2308 for (unsigned I
= 0, E
= Record
.size(); I
!= E
; I
+= 2) {
2309 auto K
= MDKindMap
.find(Record
[I
]);
2310 if (K
== MDKindMap
.end())
2311 return error("Invalid ID");
2313 dyn_cast_or_null
<MDNode
>(getMetadataFwdRefOrLoad(Record
[I
+ 1]));
2315 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2316 GO
.addMetadata(K
->second
, *MD
);
2318 return Error::success();
2321 /// Parse metadata attachments.
2322 Error
MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
2323 Function
&F
, ArrayRef
<Instruction
*> InstructionList
) {
2324 if (Error Err
= Stream
.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID
))
2327 SmallVector
<uint64_t, 64> Record
;
2328 PlaceholderQueue Placeholders
;
2331 BitstreamEntry Entry
;
2332 if (Error E
= Stream
.advanceSkippingSubblocks().moveInto(Entry
))
2335 switch (Entry
.Kind
) {
2336 case BitstreamEntry::SubBlock
: // Handled for us already.
2337 case BitstreamEntry::Error
:
2338 return error("Malformed block");
2339 case BitstreamEntry::EndBlock
:
2340 resolveForwardRefsAndPlaceholders(Placeholders
);
2341 return Error::success();
2342 case BitstreamEntry::Record
:
2343 // The interesting case.
2347 // Read a metadata attachment record.
2349 ++NumMDRecordLoaded
;
2350 Expected
<unsigned> MaybeRecord
= Stream
.readRecord(Entry
.ID
, Record
);
2352 return MaybeRecord
.takeError();
2353 switch (MaybeRecord
.get()) {
2354 default: // Default behavior: ignore.
2356 case bitc::METADATA_ATTACHMENT
: {
2357 unsigned RecordLength
= Record
.size();
2359 return error("Invalid record");
2360 if (RecordLength
% 2 == 0) {
2361 // A function attachment.
2362 if (Error Err
= parseGlobalObjectAttachment(F
, Record
))
2367 // An instruction attachment.
2368 Instruction
*Inst
= InstructionList
[Record
[0]];
2369 for (unsigned i
= 1; i
!= RecordLength
; i
= i
+ 2) {
2370 unsigned Kind
= Record
[i
];
2371 DenseMap
<unsigned, unsigned>::iterator I
= MDKindMap
.find(Kind
);
2372 if (I
== MDKindMap
.end())
2373 return error("Invalid ID");
2374 if (I
->second
== LLVMContext::MD_tbaa
&& StripTBAA
)
2377 auto Idx
= Record
[i
+ 1];
2378 if (Idx
< (MDStringRef
.size() + GlobalMetadataBitPosIndex
.size()) &&
2379 !MetadataList
.lookup(Idx
)) {
2380 // Load the attachment if it is in the lazy-loadable range and hasn't
2382 lazyLoadOneMetadata(Idx
, Placeholders
);
2383 resolveForwardRefsAndPlaceholders(Placeholders
);
2386 Metadata
*Node
= MetadataList
.getMetadataFwdRef(Idx
);
2387 if (isa
<LocalAsMetadata
>(Node
))
2388 // Drop the attachment. This used to be legal, but there's no
2391 MDNode
*MD
= dyn_cast_or_null
<MDNode
>(Node
);
2393 return error("Invalid metadata attachment");
2395 if (HasSeenOldLoopTags
&& I
->second
== LLVMContext::MD_loop
)
2396 MD
= upgradeInstructionLoopAttachment(*MD
);
2398 if (I
->second
== LLVMContext::MD_tbaa
) {
2399 assert(!MD
->isTemporary() && "should load MDs before attachments");
2400 MD
= UpgradeTBAANode(*MD
);
2402 Inst
->setMetadata(I
->second
, MD
);
2410 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2411 Error
MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2412 SmallVectorImpl
<uint64_t> &Record
) {
2413 if (Record
.size() < 2)
2414 return error("Invalid record");
2416 unsigned Kind
= Record
[0];
2417 SmallString
<8> Name(Record
.begin() + 1, Record
.end());
2419 unsigned NewKind
= TheModule
.getMDKindID(Name
.str());
2420 if (!MDKindMap
.insert(std::make_pair(Kind
, NewKind
)).second
)
2421 return error("Conflicting METADATA_KIND records");
2422 return Error::success();
2425 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2426 Error
MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
2427 if (Error Err
= Stream
.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID
))
2430 SmallVector
<uint64_t, 64> Record
;
2432 // Read all the records.
2434 BitstreamEntry Entry
;
2435 if (Error E
= Stream
.advanceSkippingSubblocks().moveInto(Entry
))
2438 switch (Entry
.Kind
) {
2439 case BitstreamEntry::SubBlock
: // Handled for us already.
2440 case BitstreamEntry::Error
:
2441 return error("Malformed block");
2442 case BitstreamEntry::EndBlock
:
2443 return Error::success();
2444 case BitstreamEntry::Record
:
2445 // The interesting case.
2451 ++NumMDRecordLoaded
;
2452 Expected
<unsigned> MaybeCode
= Stream
.readRecord(Entry
.ID
, Record
);
2454 return MaybeCode
.takeError();
2455 switch (MaybeCode
.get()) {
2456 default: // Default behavior: ignore.
2458 case bitc::METADATA_KIND
: {
2459 if (Error Err
= parseMetadataKindRecord(Record
))
2467 MetadataLoader
&MetadataLoader::operator=(MetadataLoader
&&RHS
) {
2468 Pimpl
= std::move(RHS
.Pimpl
);
2471 MetadataLoader::MetadataLoader(MetadataLoader
&&RHS
)
2472 : Pimpl(std::move(RHS
.Pimpl
)) {}
2474 MetadataLoader::~MetadataLoader() = default;
2475 MetadataLoader::MetadataLoader(BitstreamCursor
&Stream
, Module
&TheModule
,
2476 BitcodeReaderValueList
&ValueList
,
2478 MetadataLoaderCallbacks Callbacks
)
2479 : Pimpl(std::make_unique
<MetadataLoaderImpl
>(
2480 Stream
, TheModule
, ValueList
, std::move(Callbacks
), IsImporting
)) {}
2482 Error
MetadataLoader::parseMetadata(bool ModuleLevel
) {
2483 return Pimpl
->parseMetadata(ModuleLevel
);
2486 bool MetadataLoader::hasFwdRefs() const { return Pimpl
->hasFwdRefs(); }
2488 /// Return the given metadata, creating a replaceable forward reference if
2490 Metadata
*MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx
) {
2491 return Pimpl
->getMetadataFwdRefOrLoad(Idx
);
2494 DISubprogram
*MetadataLoader::lookupSubprogramForFunction(Function
*F
) {
2495 return Pimpl
->lookupSubprogramForFunction(F
);
2498 Error
MetadataLoader::parseMetadataAttachment(
2499 Function
&F
, ArrayRef
<Instruction
*> InstructionList
) {
2500 return Pimpl
->parseMetadataAttachment(F
, InstructionList
);
2503 Error
MetadataLoader::parseMetadataKinds() {
2504 return Pimpl
->parseMetadataKinds();
2507 void MetadataLoader::setStripTBAA(bool StripTBAA
) {
2508 return Pimpl
->setStripTBAA(StripTBAA
);
2511 bool MetadataLoader::isStrippingTBAA() { return Pimpl
->isStrippingTBAA(); }
2513 unsigned MetadataLoader::size() const { return Pimpl
->size(); }
2514 void MetadataLoader::shrinkTo(unsigned N
) { return Pimpl
->shrinkTo(N
); }
2516 void MetadataLoader::upgradeDebugIntrinsics(Function
&F
) {
2517 return Pimpl
->upgradeDebugIntrinsics(F
);