xref: /llvm-project/llvm/lib/Bitcode/Reader/MetadataLoader.cpp (revision f8aab289b5549086062588fba627b0e4d3a5ab15)
1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MetadataLoader.h"
10 #include "ValueList.h"
11 
12 #include "llvm/ADT/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"
49 
50 #include <algorithm>
51 #include <cassert>
52 #include <cstddef>
53 #include <cstdint>
54 #include <deque>
55 #include <iterator>
56 #include <limits>
57 #include <map>
58 #include <optional>
59 #include <string>
60 #include <tuple>
61 #include <type_traits>
62 #include <utility>
63 #include <vector>
64 namespace llvm {
65 class Argument;
66 }
67 
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "bitcode-reader"
71 
72 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
73 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
74 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
75 
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."));
81 
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."));
86 
87 namespace {
88 
89 static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
90 
91 class BitcodeReaderMetadataList {
92   /// Array of metadata references.
93   ///
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;
97 
98   /// The set of indices in MetadataPtrs above of forward references that were
99   /// generated.
100   SmallDenseSet<unsigned, 1> ForwardReference;
101 
102   /// The set of indices in MetadataPtrs above of Metadata that need to be
103   /// resolved.
104   SmallDenseSet<unsigned, 1> UnresolvedNodes;
105 
106   /// Structures for resolving old type refs.
107   struct {
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;
112   } OldTypeRefs;
113 
114   LLVMContext &Context;
115 
116   /// Maximum number of valid references. Forward references exceeding the
117   /// maximum must be invalid.
118   unsigned RefsUpperBound;
119 
120 public:
121   BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
122       : Context(C),
123         RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
124                                 RefsUpperBound)) {}
125 
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(); }
134 
135   Metadata *operator[](unsigned i) const {
136     assert(i < MetadataPtrs.size());
137     return MetadataPtrs[i];
138   }
139 
140   Metadata *lookup(unsigned I) const {
141     if (I < MetadataPtrs.size())
142       return MetadataPtrs[I];
143     return nullptr;
144   }
145 
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);
151   }
152 
153   /// Return the given metadata, creating a replaceable forward reference if
154   /// necessary.
155   Metadata *getMetadataFwdRef(unsigned Idx);
156 
157   /// Return the given metadata only if it is fully resolved.
158   ///
159   /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
160   /// would give \c false.
161   Metadata *getMetadataIfResolved(unsigned Idx);
162 
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();
170   }
171 
172   /// Upgrade a type that had an MDString reference.
173   void addTypeRef(MDString &UUID, DICompositeType &CT);
174 
175   /// Upgrade a type that had an MDString reference.
176   Metadata *upgradeTypeRef(Metadata *MaybeUUID);
177 
178   /// Upgrade a type ref array that may have MDString references.
179   Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
180 
181 private:
182   Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
183 };
184 
185 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
186   if (auto *MDN = dyn_cast<MDNode>(MD))
187     if (!MDN->isResolved())
188       UnresolvedNodes.insert(Idx);
189 
190   if (Idx == size()) {
191     push_back(MD);
192     return;
193   }
194 
195   if (Idx >= size())
196     resize(Idx + 1);
197 
198   TrackingMDRef &OldMD = MetadataPtrs[Idx];
199   if (!OldMD) {
200     OldMD.reset(MD);
201     return;
202   }
203 
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);
208 }
209 
210 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
211   // Bail out for a clearly invalid value.
212   if (Idx >= RefsUpperBound)
213     return nullptr;
214 
215   if (Idx >= size())
216     resize(Idx + 1);
217 
218   if (Metadata *MD = MetadataPtrs[Idx])
219     return MD;
220 
221   // Track forward refs to be resolved later.
222   ForwardReference.insert(Idx);
223 
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);
228   return MD;
229 }
230 
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())
235       return nullptr;
236   return MD;
237 }
238 
239 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
240   return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
241 }
242 
243 void BitcodeReaderMetadataList::tryToResolveCycles() {
244   if (!ForwardReference.empty())
245     // Still forward references... can't resolve cycles.
246     return;
247 
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();
252 
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();
258 
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);
265     else
266       Ref.second->replaceAllUsesWith(Ref.first);
267   }
268   OldTypeRefs.Unknown.clear();
269 
270   if (UnresolvedNodes.empty())
271     // Nothing to do.
272     return;
273 
274   // Resolve any cycles.
275   for (unsigned I : UnresolvedNodes) {
276     auto &MD = MetadataPtrs[I];
277     auto *N = dyn_cast_or_null<MDNode>(MD);
278     if (!N)
279       continue;
280 
281     assert(!N->isTemporary() && "Unexpected forward reference");
282     N->resolveCycles();
283   }
284 
285   // Make sure we return early again until there's another unresolved ref.
286   UnresolvedNodes.clear();
287 }
288 
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));
294   else
295     OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
296 }
297 
298 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
299   auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
300   if (LLVM_LIKELY(!UUID))
301     return MaybeUUID;
302 
303   if (auto *CT = OldTypeRefs.Final.lookup(UUID))
304     return CT;
305 
306   auto &Ref = OldTypeRefs.Unknown[UUID];
307   if (!Ref)
308     Ref = MDNode::getTemporary(Context, std::nullopt);
309   return Ref.get();
310 }
311 
312 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
313   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
314   if (!Tuple || Tuple->isDistinct())
315     return MaybeTuple;
316 
317   // Look through the array immediately if possible.
318   if (!Tuple->isTemporary())
319     return resolveTypeRefArray(Tuple);
320 
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();
327 }
328 
329 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
330   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
331   if (!Tuple || Tuple->isDistinct())
332     return MaybeTuple;
333 
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));
339 
340   return MDTuple::get(Context, Ops);
341 }
342 
343 namespace {
344 
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;
349 
350 public:
351   ~PlaceholderQueue() {
352     assert(empty() &&
353            "PlaceholderQueue hasn't been flushed before being destroyed");
354   }
355   bool empty() const { return PHs.empty(); }
356   DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
357   void flush(BitcodeReaderMetadataList &MetadataList);
358 
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);
366       if (!MD) {
367         Temporaries.insert(ID);
368         continue;
369       }
370       auto *N = dyn_cast_or_null<MDNode>(MD);
371       if (N && N->isTemporary())
372         Temporaries.insert(ID);
373     }
374   }
375 };
376 
377 } // end anonymous namespace
378 
379 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
380   PHs.emplace_back(ID);
381   return PHs.back();
382 }
383 
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");
388 #ifndef NDEBUG
389     if (auto *MDN = dyn_cast<MDNode>(MD))
390       assert(MDN->isResolved() &&
391              "Flushing Placeholder while cycles aren't resolved");
392 #endif
393     PHs.front().replaceUseWith(MD);
394     PHs.pop_front();
395   }
396 }
397 
398 } // anonymous namespace
399 
400 static Error error(const Twine &Message) {
401   return make_error<StringError>(
402       Message, make_error_code(BitcodeError::CorruptedBitcode));
403 }
404 
405 class MetadataLoader::MetadataLoaderImpl {
406   BitcodeReaderMetadataList MetadataList;
407   BitcodeReaderValueList &ValueList;
408   BitstreamCursor &Stream;
409   LLVMContext &Context;
410   Module &TheModule;
411   MetadataLoaderCallbacks Callbacks;
412 
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;
417 
418   /// Index that keeps track of MDString values.
419   std::vector<StringRef> MDStringRef;
420 
421   /// On-demand loading of a single MDString. Requires the index above to be
422   /// populated.
423   MDString *lazyLoadOneMDString(unsigned Idx);
424 
425   /// Index that keeps track of where to find a metadata record in the stream.
426   std::vector<uint64_t> GlobalMetadataBitPosIndex;
427 
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
430   /// references.
431   uint64_t GlobalDeclAttachmentPos = 0;
432 
433 #ifndef NDEBUG
434   /// Baisic correctness check that we end up parsing all of the global decl
435   /// attachments.
436   unsigned NumGlobalDeclAttachSkipped = 0;
437   unsigned NumGlobalDeclAttachParsed = 0;
438 #endif
439 
440   /// Load the global decl attachments, using the index built for lazy loading.
441   Expected<bool> loadGlobalDeclAttachments();
442 
443   /// Populate the index above to enable lazily loading of metadata, and load
444   /// the named metadata as well as the transitively referenced global
445   /// Metadata.
446   Expected<bool> lazyLoadModuleMetadataBlock();
447 
448   /// On-demand loading of a single metadata. Requires the index above to be
449   /// populated.
450   void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
451 
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;
455 
456   /// Functions that need to be matched with subprograms when upgrading old
457   /// metadata.
458   SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
459 
460   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
461   DenseMap<unsigned, unsigned> MDKindMap;
462 
463   bool StripTBAA = false;
464   bool HasSeenOldLoopTags = false;
465   bool NeedUpgradeToDIGlobalVariableExpression = false;
466   bool NeedDeclareExpressionUpgrade = false;
467 
468   /// Map DILocalScope to the enclosing DISubprogram, if any.
469   DenseMap<DILocalScope *, DISubprogram *> ParentSubprogram;
470 
471   /// True if metadata is being parsed for a module being ThinLTO imported.
472   bool IsImporting = false;
473 
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);
482 
483   void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
484 
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();
493   }
494 
495   /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
496   void upgradeCUVariables() {
497     if (!NeedUpgradeToDIGlobalVariableExpression)
498       return;
499 
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++)
506             if (auto *GV =
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);
511             }
512       }
513 
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);
519       for (auto *MD : MDs)
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);
524         } else
525           GV.addMetadata(LLVMContext::MD_dbg, *MD);
526     }
527   }
528 
529   DISubprogram *findEnclosingSubprogram(DILocalScope *S) {
530     if (!S)
531       return nullptr;
532     if (auto *SP = ParentSubprogram[S]) {
533       return SP;
534     }
535 
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))
541         break;
542       Visited.insert(S);
543     }
544     ParentSubprogram[InitialScope] = llvm::dyn_cast_or_null<DISubprogram>(S);
545 
546     return ParentSubprogram[InitialScope];
547   }
548 
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));
557         if (!CU)
558           continue;
559 
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);
567           }
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);
574           }
575 
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);
583 
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);
590 
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());
599 
600             if (auto *SP = findEnclosingSubprogram(Scope))
601               SPToEntities[SP].push_back(I);
602           }
603 
604           // Update DISubprograms' retainedNodes.
605           for (auto I = SPToEntities.begin(); I != SPToEntities.end(); ++I) {
606             auto *SP = I->first;
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));
612           }
613 
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));
620         }
621       }
622     }
623 
624     ParentSubprogram.clear();
625   }
626 
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)
631       return;
632 
633     for (auto &BB : F)
634       for (auto &I : BB)
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));
643             }
644   }
645 
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) {
652     default:
653       return error("Invalid record");
654     case 0:
655       if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
656         Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
657       [[fallthrough]];
658     case 1:
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;
667       }
668       NeedDeclareExpressionUpgrade = true;
669       [[fallthrough]];
670     case 2: {
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().
678         size_t HistoricSize;
679         switch (SubExpr.front()) {
680         default:
681           HistoricSize = 1;
682           break;
683         case dwarf::DW_OP_constu:
684         case dwarf::DW_OP_minus:
685         case dwarf::DW_OP_plus:
686           HistoricSize = 2;
687           break;
688         case dwarf::DW_OP_LLVM_fragment:
689           HistoricSize = 3;
690           break;
691         }
692 
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);
697 
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());
702           break;
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);
707           break;
708         default:
709           Buffer.push_back(*SubExpr.begin());
710           Buffer.append(Args.begin(), Args.end());
711           break;
712         }
713 
714         // Continue with remaining elements.
715         SubExpr = SubExpr.slice(HistoricSize);
716       }
717       Expr = MutableArrayRef<uint64_t>(Buffer);
718       [[fallthrough]];
719     }
720     case 3:
721       // Up-to-date!
722       break;
723     }
724 
725     return Error::success();
726   }
727 
728   void upgradeDebugInfo() {
729     upgradeCUSubprograms();
730     upgradeCUVariables();
731     upgradeCULocals();
732   }
733 
734   void callMDTypeCallback(Metadata **Val, unsigned TypeID);
735 
736 public:
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) {}
744 
745   Error parseMetadata(bool ModuleLevel);
746 
747   bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
748 
749   Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
750     if (ID < MDStringRef.size())
751       return lazyLoadOneMDString(ID);
752     if (auto *MD = MetadataList.lookup(ID))
753       return MD;
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);
761     }
762     return MetadataList.getMetadataFwdRef(ID);
763   }
764 
765   DISubprogram *lookupSubprogramForFunction(Function *F) {
766     return FunctionsWithSPs.lookup(F);
767   }
768 
769   bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
770 
771   Error parseMetadataAttachment(Function &F,
772                                 ArrayRef<Instruction *> InstructionList);
773 
774   Error parseMetadataKinds();
775 
776   void setStripTBAA(bool Value) { StripTBAA = Value; }
777   bool isStrippingTBAA() const { return StripTBAA; }
778 
779   unsigned size() const { return MetadataList.size(); }
780   void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
781   void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
782 };
783 
784 Expected<bool>
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.
790   while (true) {
791     uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
792     BitstreamEntry Entry;
793     if (Error E =
794             IndexCursor
795                 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
796                 .moveInto(Entry))
797       return std::move(E);
798 
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: {
804       return true;
805     }
806     case BitstreamEntry::Record: {
807       // The interesting case.
808       ++NumMDRecordLoaded;
809       uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
810       unsigned Code;
811       if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
812         return std::move(E);
813       switch (Code) {
814       case bitc::METADATA_STRINGS: {
815         // Rewind and parse the strings.
816         if (Error Err = IndexCursor.JumpToBit(CurrentPos))
817           return std::move(Err);
818         StringRef Blob;
819         Record.clear();
820         if (Expected<unsigned> MaybeRecord =
821                 IndexCursor.readRecord(Entry.ID, Record, &Blob))
822           ;
823         else
824           return MaybeRecord.takeError();
825         unsigned NumStrings = Record[0];
826         MDStringRef.reserve(NumStrings);
827         auto IndexNextMDString = [&](StringRef Str) {
828           MDStringRef.push_back(Str);
829         };
830         if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
831           return std::move(Err);
832         break;
833       }
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);
839         Record.clear();
840         if (Expected<unsigned> MaybeRecord =
841                 IndexCursor.readRecord(Entry.ID, Record))
842           ;
843         else
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);
854         if (!MaybeEntry)
855           return MaybeEntry.takeError();
856         Entry = MaybeEntry.get();
857         assert(Entry.Kind == BitstreamEntry::Record &&
858                "Corrupted bitcode: Expected `Record` when trying to find the "
859                "Metadata index");
860         Record.clear();
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");
866         else
867           return MaybeCode.takeError();
868         // Delta unpack
869         auto CurrentValue = BeginPos;
870         GlobalMetadataBitPosIndex.reserve(Record.size());
871         for (auto &Elt : Record) {
872           CurrentValue += Elt;
873           GlobalMetadataBitPosIndex.push_back(CurrentValue);
874         }
875         break;
876       }
877       case bitc::METADATA_INDEX:
878         // We don't expect to get there, the Index is loaded when we encounter
879         // the offset.
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);
885         Record.clear();
886 
887         unsigned Code;
888         if (Expected<unsigned> MaybeCode =
889                 IndexCursor.readRecord(Entry.ID, Record)) {
890           Code = MaybeCode.get();
891           assert(Code == bitc::METADATA_NAME);
892         } else
893           return MaybeCode.takeError();
894 
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();
899         else
900           return MaybeCode.takeError();
901 
902         // Named Metadata comes in two parts, we expect the name to be followed
903         // by the node
904         Record.clear();
905         if (Expected<unsigned> MaybeNextBitCode =
906                 IndexCursor.readRecord(Code, Record))
907           assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
908         else
909           return MaybeNextBitCode.takeError();
910 
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");
921           NMD->addOperand(MD);
922         }
923         break;
924       }
925       case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
926         if (!GlobalDeclAttachmentPos)
927           GlobalDeclAttachmentPos = SavedPos;
928 #ifndef NDEBUG
929         NumGlobalDeclAttachSkipped++;
930 #endif
931         break;
932       }
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.
972         MDStringRef.clear();
973         GlobalMetadataBitPosIndex.clear();
974         return false;
975       }
976       break;
977     }
978     }
979   }
980 }
981 
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)
990     return true;
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);
999   while (true) {
1000     BitstreamEntry Entry;
1001     if (Error E =
1002             TempCursor
1003                 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
1004                 .moveInto(Entry))
1005       return std::move(E);
1006 
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);
1014       return true;
1015     case BitstreamEntry::Record:
1016       break;
1017     }
1018     uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
1019     Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
1020     if (!MaybeCode)
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);
1026       return true;
1027     }
1028 #ifndef NDEBUG
1029     NumGlobalDeclAttachParsed++;
1030 #endif
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);
1035     Record.clear();
1036     if (Expected<unsigned> MaybeRecord =
1037             TempCursor.readRecord(Entry.ID, Record))
1038       ;
1039     else
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);
1056     }
1057   }
1058 }
1059 
1060 void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(Metadata **Val,
1061                                                             unsigned TypeID) {
1062   if (Callbacks.MDType) {
1063     (*Callbacks.MDType)(Val, TypeID, Callbacks.GetTypeByID,
1064                         Callbacks.GetContainedTypeID);
1065   }
1066 }
1067 
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");
1073 
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();
1077 
1078   if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1079     return Err;
1080 
1081   SmallVector<uint64_t, 64> Record;
1082   PlaceholderQueue Placeholders;
1083 
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();
1089     if (!SuccessOrErr)
1090       return SuccessOrErr.takeError();
1091     if (SuccessOrErr.get()) {
1092       // An index was successfully created and we will be able to load metadata
1093       // on-demand.
1094       MetadataList.resize(MDStringRef.size() +
1095                           GlobalMetadataBitPosIndex.size());
1096 
1097       // Now that we have built the index, load the global decl attachments
1098       // that were deferred during that process. This avoids creating
1099       // temporaries.
1100       SuccessOrErr = loadGlobalDeclAttachments();
1101       if (!SuccessOrErr)
1102         return SuccessOrErr.takeError();
1103       assert(SuccessOrErr.get());
1104 
1105       // Reading the named metadata created forward references and/or
1106       // placeholders, that we flush here.
1107       resolveForwardRefsAndPlaceholders(Placeholders);
1108       upgradeDebugInfo();
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))
1113         return Err;
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();
1119       }
1120       return Error::success();
1121     }
1122     // Couldn't load an index, fallback to loading all the block "old-style".
1123   }
1124 
1125   unsigned NextMetadataNo = MetadataList.size();
1126 
1127   // Read all the records.
1128   while (true) {
1129     BitstreamEntry Entry;
1130     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1131       return E;
1132 
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);
1139       upgradeDebugInfo();
1140       return Error::success();
1141     case BitstreamEntry::Record:
1142       // The interesting case.
1143       break;
1144     }
1145 
1146     // Read a record.
1147     Record.clear();
1148     StringRef Blob;
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))
1154         return Err;
1155     } else
1156       return MaybeCode.takeError();
1157   }
1158 }
1159 
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);
1166   return MDS;
1167 }
1168 
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())
1177       return;
1178   }
1179   SmallVector<uint64_t, 64> Record;
1180   StringRef Blob;
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)) {
1193     if (Error Err =
1194             parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1195       report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1196                          Twine(toString(std::move(Err))));
1197   } else
1198     report_fatal_error("Can't lazyload MD: " +
1199                        Twine(toString(MaybeCode.takeError())));
1200 }
1201 
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;
1207   while (true) {
1208     // Populate Temporaries with the placeholders that haven't been loaded yet.
1209     Placeholders.getTemporaries(MetadataList, Temporaries);
1210 
1211     // If we don't have any temporary, or FwdReference, we're done!
1212     if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1213       break;
1214 
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();
1220 
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);
1225   }
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
1228   // as resolved.
1229   MetadataList.tryToResolveCycles();
1230 
1231   // Finally, everything is in place, we can replace the placeholders operands
1232   // with the final node they refer to.
1233   Placeholders.flush(MetadataList);
1234 }
1235 
1236 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1237     SmallVectorImpl<uint64_t> &Record, unsigned Code,
1238     PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1239 
1240   bool IsDistinct = false;
1241   auto getMD = [&](unsigned ID) -> Metadata * {
1242     if (ID < MDStringRef.size())
1243       return lazyLoadOneMDString(ID);
1244     if (!IsDistinct) {
1245       if (auto *MD = MetadataList.lookup(ID))
1246         return MD;
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
1252         // uniquing cycles.
1253         MetadataList.getMetadataFwdRef(NextMetadataNo);
1254         lazyLoadOneMetadata(ID, Placeholders);
1255         return MetadataList.lookup(ID);
1256       }
1257       // Return a temporary.
1258       return MetadataList.getMetadataFwdRef(ID);
1259     }
1260     if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1261       return MD;
1262     return &Placeholders.getPlaceholderOp(ID);
1263   };
1264   auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1265     if (ID)
1266       return getMD(ID - 1);
1267     return nullptr;
1268   };
1269   auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
1270     if (ID)
1271       return MetadataList.getMetadataFwdRef(ID - 1);
1272     return nullptr;
1273   };
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);
1279   };
1280 
1281   // Support for old type refs.
1282   auto getDITypeRefOrNull = [&](unsigned ID) {
1283     return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1284   };
1285 
1286 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
1287   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1288 
1289   switch (Code) {
1290   default: // Default behavior: ignore.
1291     break;
1292   case bitc::METADATA_NAME: {
1293     // Read name of the named metadata.
1294     SmallString<8> Name(Record.begin(), Record.end());
1295     Record.clear();
1296     if (Error E = Stream.ReadCode().moveInto(Code))
1297       return E;
1298 
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");
1303     } else
1304       return MaybeNextBitCode.takeError();
1305 
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]);
1311       if (!MD)
1312         return error("Invalid named metadata: expect fwd ref to MDNode");
1313       NMD->addOperand(MD);
1314     }
1315     break;
1316   }
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
1320     // metadata.
1321     if (Record.size() % 2 == 1)
1322       return error("Invalid record");
1323 
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),
1328                                NextMetadataNo);
1329       NextMetadataNo++;
1330     };
1331     if (Record.size() != 2) {
1332       dropRecord();
1333       break;
1334     }
1335 
1336     unsigned TyID = Record[0];
1337     Type *Ty = Callbacks.GetTypeByID(TyID);
1338     if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy()) {
1339       dropRecord();
1340       break;
1341     }
1342 
1343     Value *V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1344                                         /*ConstExprInsertBB*/ nullptr);
1345     if (!V)
1346       return error("Invalid value reference from old fn metadata");
1347 
1348     MetadataList.assignValue(LocalAsMetadata::get(V), NextMetadataNo);
1349     NextMetadataNo++;
1350     break;
1351   }
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");
1356 
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);
1362       if (!Ty)
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);
1369         if (!V)
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);
1375         Elts.push_back(MD);
1376       } else
1377         Elts.push_back(nullptr);
1378     }
1379     MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1380     NextMetadataNo++;
1381     break;
1382   }
1383   case bitc::METADATA_VALUE: {
1384     if (Record.size() != 2)
1385       return error("Invalid record");
1386 
1387     unsigned TyID = Record[0];
1388     Type *Ty = Callbacks.GetTypeByID(TyID);
1389     if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy())
1390       return error("Invalid record");
1391 
1392     Value *V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1393                                         /*ConstExprInsertBB*/ nullptr);
1394     if (!V)
1395       return error("Invalid value reference from metadata");
1396 
1397     Metadata *MD = ValueAsMetadata::get(V);
1398     callMDTypeCallback(&MD, TyID);
1399     MetadataList.assignValue(MD, NextMetadataNo);
1400     NextMetadataNo++;
1401     break;
1402   }
1403   case bitc::METADATA_DISTINCT_NODE:
1404     IsDistinct = true;
1405     [[fallthrough]];
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),
1413                              NextMetadataNo);
1414     NextMetadataNo++;
1415     break;
1416   }
1417   case bitc::METADATA_LOCATION: {
1418     if (Record.size() != 5 && Record.size() != 6)
1419       return error("Invalid record");
1420 
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,
1429                                      ImplicitCode)),
1430         NextMetadataNo);
1431     NextMetadataNo++;
1432     break;
1433   }
1434   case bitc::METADATA_GENERIC_DEBUG: {
1435     if (Record.size() < 4)
1436       return error("Invalid record");
1437 
1438     IsDistinct = Record[0];
1439     unsigned Tag = Record[1];
1440     unsigned Version = Record[2];
1441 
1442     if (Tag >= 1u << 16 || Version != 0)
1443       return error("Invalid record");
1444 
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)),
1451         NextMetadataNo);
1452     NextMetadataNo++;
1453     break;
1454   }
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) {
1466     case 0:
1467       Val = GET_OR_DISTINCT(DISubrange,
1468                             (Context, Record[1], unrotateSign(Record[2])));
1469       break;
1470     case 1:
1471       Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1472                                          unrotateSign(Record[2])));
1473       break;
1474     case 2:
1475       Val = GET_OR_DISTINCT(
1476           DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1477                        getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1478       break;
1479     default:
1480       return error("Invalid record: Unsupported version of DISubrange");
1481     }
1482 
1483     MetadataList.assignValue(Val, NextMetadataNo);
1484     IsDistinct = Record[0] & 1;
1485     NextMetadataNo++;
1486     break;
1487   }
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])));
1494 
1495     MetadataList.assignValue(Val, NextMetadataNo);
1496     IsDistinct = Record[0] & 1;
1497     NextMetadataNo++;
1498     break;
1499   }
1500   case bitc::METADATA_ENUMERATOR: {
1501     if (Record.size() < 3)
1502       return error("Invalid record");
1503 
1504     IsDistinct = Record[0] & 1;
1505     bool IsUnsigned = Record[0] & 2;
1506     bool IsBigInt = Record[0] & 4;
1507     APInt Value;
1508 
1509     if (IsBigInt) {
1510       const uint64_t BitWidth = Record[1];
1511       const size_t NumWords = Record.size() - 3;
1512       Value = readWideAPInt(ArrayRef(&Record[3], NumWords), BitWidth);
1513     } else
1514       Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1515 
1516     MetadataList.assignValue(
1517         GET_OR_DISTINCT(DIEnumerator,
1518                         (Context, Value, IsUnsigned, getMDString(Record[2]))),
1519         NextMetadataNo);
1520     NextMetadataNo++;
1521     break;
1522   }
1523   case bitc::METADATA_BASIC_TYPE: {
1524     if (Record.size() < 6 || Record.size() > 7)
1525       return error("Invalid record");
1526 
1527     IsDistinct = Record[0];
1528     DINode::DIFlags Flags = (Record.size() > 6)
1529                                 ? static_cast<DINode::DIFlags>(Record[6])
1530                                 : DINode::FlagZero;
1531 
1532     MetadataList.assignValue(
1533         GET_OR_DISTINCT(DIBasicType,
1534                         (Context, Record[1], getMDString(Record[2]), Record[3],
1535                          Record[4], Record[5], Flags)),
1536         NextMetadataNo);
1537     NextMetadataNo++;
1538     break;
1539   }
1540   case bitc::METADATA_STRING_TYPE: {
1541     if (Record.size() > 9 || Record.size() < 8)
1542       return error("Invalid record");
1543 
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])),
1556         NextMetadataNo);
1557     NextMetadataNo++;
1558     break;
1559   }
1560   case bitc::METADATA_DERIVED_TYPE: {
1561     if (Record.size() < 12 || Record.size() > 14)
1562       return error("Invalid record");
1563 
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;
1569 
1570     Metadata *Annotations = nullptr;
1571     if (Record.size() > 13 && Record[13])
1572       Annotations = getMDOrNull(Record[13]);
1573 
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)),
1584         NextMetadataNo);
1585     NextMetadataNo++;
1586     break;
1587   }
1588   case bitc::METADATA_COMPOSITE_TYPE: {
1589     if (Record.size() < 16 || Record.size() > 22)
1590       return error("Invalid record");
1591 
1592     // If we have a UUID and this is not a forward declaration, lookup the
1593     // mapping.
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
1625     // used.
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;
1632       if (Name) {
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]);
1640       }
1641     } else {
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]);
1654       }
1655       if (Record.size() > 20) {
1656         Rank = getMDOrNull(Record[20]);
1657       }
1658       if (Record.size() > 21) {
1659         Annotations = getMDOrNull(Record[21]);
1660       }
1661     }
1662     DICompositeType *CT = nullptr;
1663     if (Identifier)
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);
1669 
1670     // Create a node if we didn't get a lazy ODR type.
1671     if (!CT)
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));
1680 
1681     MetadataList.assignValue(CT, NextMetadataNo);
1682     NextMetadataNo++;
1683     break;
1684   }
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;
1690 
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);
1696 
1697     MetadataList.assignValue(
1698         GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1699         NextMetadataNo);
1700     NextMetadataNo++;
1701     break;
1702   }
1703 
1704   case bitc::METADATA_MODULE: {
1705     if (Record.size() < 5 || Record.size() > 9)
1706       return error("Invalid record");
1707 
1708     unsigned Offset = Record.size() >= 8 ? 2 : 1;
1709     IsDistinct = Record[0];
1710     MetadataList.assignValue(
1711         GET_OR_DISTINCT(
1712             DIModule,
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])),
1719         NextMetadataNo);
1720     NextMetadataNo++;
1721     break;
1722   }
1723 
1724   case bitc::METADATA_FILE: {
1725     if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1726       return error("Invalid record");
1727 
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)),
1743         NextMetadataNo);
1744     NextMetadataNo++;
1745     break;
1746   }
1747   case bitc::METADATA_COMPILE_UNIT: {
1748     if (Record.size() < 14 || Record.size() > 22)
1749       return error("Invalid record");
1750 
1751     // Ignore Record[0], which indicates whether this compile unit is
1752     // distinct.  It's always distinct.
1753     IsDistinct = true;
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]));
1767 
1768     MetadataList.assignValue(CU, NextMetadataNo);
1769     NextMetadataNo++;
1770 
1771     // Move the Upgrade the list of subprograms.
1772     if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1773       CUSubprograms.push_back({CU, SPs});
1774     break;
1775   }
1776   case bitc::METADATA_SUBPROGRAM: {
1777     if (Record.size() < 18 || Record.size() > 21)
1778       return error("Invalid record");
1779 
1780     bool HasSPFlags = Record[0] & 4;
1781 
1782     DINode::DIFlags Flags;
1783     DISubprogram::DISPFlags SPFlags;
1784     if (!HasSPFlags)
1785       Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
1786     else {
1787       Flags = static_cast<DINode::DIFlags>(Record[11]);
1788       SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
1789     }
1790 
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
1798       // being 0.
1799       Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1800 
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);
1808 
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.
1822     bool HasFn = false;
1823     bool HasThisAdj = true;
1824     bool HasThrownTypes = true;
1825     bool HasAnnotations = false;
1826     bool HasTargetFuncName = false;
1827     unsigned OffsetA = 0;
1828     unsigned OffsetB = 0;
1829     if (!HasSPFlags) {
1830       OffsetA = 2;
1831       OffsetB = 2;
1832       if (Record.size() >= 19) {
1833         HasFn = !HasUnit;
1834         OffsetB++;
1835       }
1836       HasThisAdj = Record.size() >= 20;
1837       HasThrownTypes = Record.size() >= 21;
1838     } else {
1839       HasAnnotations = Record.size() >= 19;
1840       HasTargetFuncName = Record.size() >= 20;
1841     }
1842     Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1843     DISubprogram *SP = GET_OR_DISTINCT(
1844         DISubprogram,
1845         (Context,
1846          getDITypeRefOrNull(Record[1]),           // scope
1847          getMDString(Record[2]),                  // name
1848          getMDString(Record[3]),                  // linkageName
1849          getMDOrNull(Record[4]),                  // file
1850          Record[5],                               // line
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
1856          Flags,                                   // flags
1857          SPFlags,                                 // SPFlags
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
1868          ));
1869     MetadataList.assignValue(SP, NextMetadataNo);
1870     NextMetadataNo++;
1871 
1872     // Upgrade sp->function mapping to function->sp mapping.
1873     if (HasFn) {
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
1878             // metadata.
1879             FunctionsWithSPs[F] = SP;
1880           else if (!F->empty())
1881             F->setSubprogram(SP);
1882         }
1883     }
1884     break;
1885   }
1886   case bitc::METADATA_LEXICAL_BLOCK: {
1887     if (Record.size() != 5)
1888       return error("Invalid record");
1889 
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])),
1895         NextMetadataNo);
1896     NextMetadataNo++;
1897     break;
1898   }
1899   case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1900     if (Record.size() != 4)
1901       return error("Invalid record");
1902 
1903     IsDistinct = Record[0];
1904     MetadataList.assignValue(
1905         GET_OR_DISTINCT(DILexicalBlockFile,
1906                         (Context, getMDOrNull(Record[1]),
1907                          getMDOrNull(Record[2]), Record[3])),
1908         NextMetadataNo);
1909     NextMetadataNo++;
1910     break;
1911   }
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])),
1919         NextMetadataNo);
1920     NextMetadataNo++;
1921     break;
1922   }
1923   case bitc::METADATA_NAMESPACE: {
1924     // Newer versions of DINamespace dropped file and line.
1925     MDString *Name;
1926     if (Record.size() == 3)
1927       Name = getMDString(Record[2]);
1928     else if (Record.size() == 5)
1929       Name = getMDString(Record[3]);
1930     else
1931       return error("Invalid record");
1932 
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)),
1938         NextMetadataNo);
1939     NextMetadataNo++;
1940     break;
1941   }
1942   case bitc::METADATA_MACRO: {
1943     if (Record.size() != 5)
1944       return error("Invalid record");
1945 
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]))),
1951         NextMetadataNo);
1952     NextMetadataNo++;
1953     break;
1954   }
1955   case bitc::METADATA_MACRO_FILE: {
1956     if (Record.size() != 5)
1957       return error("Invalid record");
1958 
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]))),
1964         NextMetadataNo);
1965     NextMetadataNo++;
1966     break;
1967   }
1968   case bitc::METADATA_TEMPLATE_TYPE: {
1969     if (Record.size() < 3 || Record.size() > 4)
1970       return error("Invalid record");
1971 
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))),
1979         NextMetadataNo);
1980     NextMetadataNo++;
1981     break;
1982   }
1983   case bitc::METADATA_TEMPLATE_VALUE: {
1984     if (Record.size() < 5 || Record.size() > 6)
1985       return error("Invalid record");
1986 
1987     IsDistinct = Record[0];
1988 
1989     MetadataList.assignValue(
1990         GET_OR_DISTINCT(
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]))),
1997         NextMetadataNo);
1998     NextMetadataNo++;
1999     break;
2000   }
2001   case bitc::METADATA_GLOBAL_VAR: {
2002     if (Record.size() < 11 || Record.size() > 13)
2003       return error("Invalid record");
2004 
2005     IsDistinct = Record[0] & 1;
2006     unsigned Version = Record[0] >> 1;
2007 
2008     if (Version == 2) {
2009       Metadata *Annotations = nullptr;
2010       if (Record.size() > 12)
2011         Annotations = getMDOrNull(Record[12]);
2012 
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)),
2021           NextMetadataNo);
2022 
2023       NextMetadataNo++;
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(
2028           GET_OR_DISTINCT(
2029               DIGlobalVariable,
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)),
2034           NextMetadataNo);
2035 
2036       NextMetadataNo++;
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];
2047       }
2048       GlobalVariable *Attach = nullptr;
2049       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
2050         if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
2051           Attach = GV;
2052           Expr = nullptr;
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});
2057         } else {
2058           Expr = nullptr;
2059         }
2060       }
2061       DIGlobalVariable *DGV = GET_OR_DISTINCT(
2062           DIGlobalVariable,
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));
2067 
2068       DIGlobalVariableExpression *DGVE = nullptr;
2069       if (Attach || Expr)
2070         DGVE = DIGlobalVariableExpression::getDistinct(
2071             Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
2072       if (Attach)
2073         Attach->addDebugInfo(DGVE);
2074 
2075       auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
2076       MetadataList.assignValue(MDNode, NextMetadataNo);
2077       NextMetadataNo++;
2078     } else
2079       return error("Invalid record");
2080 
2081     break;
2082   }
2083   case bitc::METADATA_ASSIGN_ID: {
2084     if (Record.size() != 1)
2085       return error("Invalid DIAssignID record.");
2086 
2087     IsDistinct = Record[0] & 1;
2088     if (!IsDistinct)
2089       return error("Invalid DIAssignID record. Must be distinct");
2090 
2091     MetadataList.assignValue(DIAssignID::getDistinct(Context), NextMetadataNo);
2092     NextMetadataNo++;
2093     break;
2094   }
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");
2099 
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;
2109     if (HasAlignment) {
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]);
2115     }
2116 
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)),
2124         NextMetadataNo);
2125     NextMetadataNo++;
2126     break;
2127   }
2128   case bitc::METADATA_LABEL: {
2129     if (Record.size() != 5)
2130       return error("Invalid record");
2131 
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])),
2137         NextMetadataNo);
2138     NextMetadataNo++;
2139     break;
2140   }
2141   case bitc::METADATA_EXPRESSION: {
2142     if (Record.size() < 1)
2143       return error("Invalid record");
2144 
2145     IsDistinct = Record[0] & 1;
2146     uint64_t Version = Record[0] >> 1;
2147     auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2148 
2149     SmallVector<uint64_t, 6> Buffer;
2150     if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2151       return Err;
2152 
2153     MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2154                              NextMetadataNo);
2155     NextMetadataNo++;
2156     break;
2157   }
2158   case bitc::METADATA_GLOBAL_VAR_EXPR: {
2159     if (Record.size() != 3)
2160       return error("Invalid record");
2161 
2162     IsDistinct = Record[0];
2163     Metadata *Expr = getMDOrNull(Record[2]);
2164     if (!Expr)
2165       Expr = DIExpression::get(Context, {});
2166     MetadataList.assignValue(
2167         GET_OR_DISTINCT(DIGlobalVariableExpression,
2168                         (Context, getMDOrNull(Record[1]), Expr)),
2169         NextMetadataNo);
2170     NextMetadataNo++;
2171     break;
2172   }
2173   case bitc::METADATA_OBJC_PROPERTY: {
2174     if (Record.size() != 8)
2175       return error("Invalid record");
2176 
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]))),
2184         NextMetadataNo);
2185     NextMetadataNo++;
2186     break;
2187   }
2188   case bitc::METADATA_IMPORTED_ENTITY: {
2189     if (Record.size() < 6 || Record.size() > 8)
2190       return error("Invalid DIImportedEntity record");
2191 
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)),
2202         NextMetadataNo);
2203     NextMetadataNo++;
2204     break;
2205   }
2206   case bitc::METADATA_STRING_OLD: {
2207     std::string String(Record.begin(), Record.end());
2208 
2209     // Test for upgrading !llvm.loop.
2210     HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2211     ++NumMDStringLoaded;
2212     Metadata *MD = MDString::get(Context, String);
2213     MetadataList.assignValue(MD, NextMetadataNo);
2214     NextMetadataNo++;
2215     break;
2216   }
2217   case bitc::METADATA_STRINGS: {
2218     auto CreateNextMDString = [&](StringRef Str) {
2219       ++NumMDStringLoaded;
2220       MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2221       NextMetadataNo++;
2222     };
2223     if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2224       return Err;
2225     break;
2226   }
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)))
2236         return Err;
2237     break;
2238   }
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))
2243       return Err;
2244     break;
2245   }
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())
2252         return error(
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));
2257     }
2258 
2259     MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2260     NextMetadataNo++;
2261     break;
2262   }
2263   }
2264   return Error::success();
2265 #undef GET_OR_DISTINCT
2266 }
2267 
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
2273   // their sizes.
2274   if (Record.size() != 2)
2275     return error("Invalid record: metadata strings layout");
2276 
2277   unsigned NumStrings = Record[0];
2278   unsigned StringsOffset = Record[1];
2279   if (!NumStrings)
2280     return error("Invalid record: metadata strings with no strings");
2281   if (StringsOffset > Blob.size())
2282     return error("Invalid record: metadata strings corrupt offset");
2283 
2284   StringRef Lengths = Blob.slice(0, StringsOffset);
2285   SimpleBitstreamCursor R(Lengths);
2286 
2287   StringRef Strings = Blob.drop_front(StringsOffset);
2288   do {
2289     if (R.AtEndOfStream())
2290       return error("Invalid record: metadata strings bad length");
2291 
2292     uint32_t Size;
2293     if (Error E = R.ReadVBR(6).moveInto(Size))
2294       return E;
2295     if (Strings.size() < Size)
2296       return error("Invalid record: metadata strings truncated chars");
2297 
2298     CallBack(Strings.slice(0, Size));
2299     Strings = Strings.drop_front(Size);
2300   } while (--NumStrings);
2301 
2302   return Error::success();
2303 }
2304 
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");
2312     MDNode *MD =
2313         dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
2314     if (!MD)
2315       return error("Invalid metadata attachment: expect fwd ref to MDNode");
2316     GO.addMetadata(K->second, *MD);
2317   }
2318   return Error::success();
2319 }
2320 
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))
2325     return Err;
2326 
2327   SmallVector<uint64_t, 64> Record;
2328   PlaceholderQueue Placeholders;
2329 
2330   while (true) {
2331     BitstreamEntry Entry;
2332     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2333       return E;
2334 
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.
2344       break;
2345     }
2346 
2347     // Read a metadata attachment record.
2348     Record.clear();
2349     ++NumMDRecordLoaded;
2350     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2351     if (!MaybeRecord)
2352       return MaybeRecord.takeError();
2353     switch (MaybeRecord.get()) {
2354     default: // Default behavior: ignore.
2355       break;
2356     case bitc::METADATA_ATTACHMENT: {
2357       unsigned RecordLength = Record.size();
2358       if (Record.empty())
2359         return error("Invalid record");
2360       if (RecordLength % 2 == 0) {
2361         // A function attachment.
2362         if (Error Err = parseGlobalObjectAttachment(F, Record))
2363           return Err;
2364         continue;
2365       }
2366 
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)
2375           continue;
2376 
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
2381           // been loaded yet.
2382           lazyLoadOneMetadata(Idx, Placeholders);
2383           resolveForwardRefsAndPlaceholders(Placeholders);
2384         }
2385 
2386         Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2387         if (isa<LocalAsMetadata>(Node))
2388           // Drop the attachment.  This used to be legal, but there's no
2389           // upgrade path.
2390           break;
2391         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
2392         if (!MD)
2393           return error("Invalid metadata attachment");
2394 
2395         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2396           MD = upgradeInstructionLoopAttachment(*MD);
2397 
2398         if (I->second == LLVMContext::MD_tbaa) {
2399           assert(!MD->isTemporary() && "should load MDs before attachments");
2400           MD = UpgradeTBAANode(*MD);
2401         }
2402         Inst->setMetadata(I->second, MD);
2403       }
2404       break;
2405     }
2406     }
2407   }
2408 }
2409 
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");
2415 
2416   unsigned Kind = Record[0];
2417   SmallString<8> Name(Record.begin() + 1, Record.end());
2418 
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();
2423 }
2424 
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))
2428     return Err;
2429 
2430   SmallVector<uint64_t, 64> Record;
2431 
2432   // Read all the records.
2433   while (true) {
2434     BitstreamEntry Entry;
2435     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2436       return E;
2437 
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.
2446       break;
2447     }
2448 
2449     // Read a record.
2450     Record.clear();
2451     ++NumMDRecordLoaded;
2452     Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2453     if (!MaybeCode)
2454       return MaybeCode.takeError();
2455     switch (MaybeCode.get()) {
2456     default: // Default behavior: ignore.
2457       break;
2458     case bitc::METADATA_KIND: {
2459       if (Error Err = parseMetadataKindRecord(Record))
2460         return Err;
2461       break;
2462     }
2463     }
2464   }
2465 }
2466 
2467 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
2468   Pimpl = std::move(RHS.Pimpl);
2469   return *this;
2470 }
2471 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
2472     : Pimpl(std::move(RHS.Pimpl)) {}
2473 
2474 MetadataLoader::~MetadataLoader() = default;
2475 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
2476                                BitcodeReaderValueList &ValueList,
2477                                bool IsImporting,
2478                                MetadataLoaderCallbacks Callbacks)
2479     : Pimpl(std::make_unique<MetadataLoaderImpl>(
2480           Stream, TheModule, ValueList, std::move(Callbacks), IsImporting)) {}
2481 
2482 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2483   return Pimpl->parseMetadata(ModuleLevel);
2484 }
2485 
2486 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2487 
2488 /// Return the given metadata, creating a replaceable forward reference if
2489 /// necessary.
2490 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
2491   return Pimpl->getMetadataFwdRefOrLoad(Idx);
2492 }
2493 
2494 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
2495   return Pimpl->lookupSubprogramForFunction(F);
2496 }
2497 
2498 Error MetadataLoader::parseMetadataAttachment(
2499     Function &F, ArrayRef<Instruction *> InstructionList) {
2500   return Pimpl->parseMetadataAttachment(F, InstructionList);
2501 }
2502 
2503 Error MetadataLoader::parseMetadataKinds() {
2504   return Pimpl->parseMetadataKinds();
2505 }
2506 
2507 void MetadataLoader::setStripTBAA(bool StripTBAA) {
2508   return Pimpl->setStripTBAA(StripTBAA);
2509 }
2510 
2511 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2512 
2513 unsigned MetadataLoader::size() const { return Pimpl->size(); }
2514 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2515 
2516 void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
2517   return Pimpl->upgradeDebugIntrinsics(F);
2518 }
2519