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