1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
12 
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Bitcode/BitcodeReader.h"
27 #include "llvm/Bitcode/BitstreamReader.h"
28 #include "llvm/Bitcode/LLVMBitCodes.h"
29 #include "llvm/IR/Argument.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/AutoUpgrade.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Comdat.h"
36 #include "llvm/IR/Constant.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/DebugInfoMetadata.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/DiagnosticPrinter.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GVMaterializer.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalIFunc.h"
48 #include "llvm/IR/GlobalIndirectSymbol.h"
49 #include "llvm/IR/GlobalObject.h"
50 #include "llvm/IR/GlobalValue.h"
51 #include "llvm/IR/GlobalVariable.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/InstrTypes.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/Intrinsics.h"
57 #include "llvm/IR/LLVMContext.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/ModuleSummaryIndex.h"
60 #include "llvm/IR/OperandTraits.h"
61 #include "llvm/IR/Operator.h"
62 #include "llvm/IR/TrackingMDRef.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/ValueHandle.h"
65 #include "llvm/Support/AtomicOrdering.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/Error.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/ManagedStatic.h"
73 #include "llvm/Support/MemoryBuffer.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <deque>
80 #include <limits>
81 #include <map>
82 #include <memory>
83 #include <string>
84 #include <system_error>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "bitcode-reader"
92 
93 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
94 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
95 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
96 
97 /// Flag whether we need to import full type definitions for ThinLTO.
98 /// Currently needed for Darwin and LLDB.
99 static cl::opt<bool> ImportFullTypeDefinitions(
100     "import-full-type-definitions", cl::init(false), cl::Hidden,
101     cl::desc("Import full type definitions for ThinLTO."));
102 
103 static cl::opt<bool> DisableLazyLoading(
104     "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
105     cl::desc("Force disable the lazy-loading on-demand of metadata when "
106              "loading bitcode for importing."));
107 
108 namespace {
109 
110 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
111 
112 class BitcodeReaderMetadataList {
113   /// Array of metadata references.
114   ///
115   /// Don't use std::vector here.  Some versions of libc++ copy (instead of
116   /// move) on resize, and TrackingMDRef is very expensive to copy.
117   SmallVector<TrackingMDRef, 1> MetadataPtrs;
118 
119   /// The set of indices in MetadataPtrs above of forward references that were
120   /// generated.
121   SmallDenseSet<unsigned, 1> ForwardReference;
122 
123   /// The set of indices in MetadataPtrs above of Metadata that need to be
124   /// resolved.
125   SmallDenseSet<unsigned, 1> UnresolvedNodes;
126 
127   /// Structures for resolving old type refs.
128   struct {
129     SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
130     SmallDenseMap<MDString *, DICompositeType *, 1> Final;
131     SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
132     SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
133   } OldTypeRefs;
134 
135   LLVMContext &Context;
136 
137 public:
138   BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
139 
140   // vector compatibility methods
141   unsigned size() const { return MetadataPtrs.size(); }
142   void resize(unsigned N) { MetadataPtrs.resize(N); }
143   void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
144   void clear() { MetadataPtrs.clear(); }
145   Metadata *back() const { return MetadataPtrs.back(); }
146   void pop_back() { MetadataPtrs.pop_back(); }
147   bool empty() const { return MetadataPtrs.empty(); }
148 
149   Metadata *operator[](unsigned i) const {
150     assert(i < MetadataPtrs.size());
151     return MetadataPtrs[i];
152   }
153 
154   Metadata *lookup(unsigned I) const {
155     if (I < MetadataPtrs.size())
156       return MetadataPtrs[I];
157     return nullptr;
158   }
159 
160   void shrinkTo(unsigned N) {
161     assert(N <= size() && "Invalid shrinkTo request!");
162     assert(ForwardReference.empty() && "Unexpected forward refs");
163     assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
164     MetadataPtrs.resize(N);
165   }
166 
167   /// Return the given metadata, creating a replaceable forward reference if
168   /// necessary.
169   Metadata *getMetadataFwdRef(unsigned Idx);
170 
171   /// Return the the given metadata only if it is fully resolved.
172   ///
173   /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
174   /// would give \c false.
175   Metadata *getMetadataIfResolved(unsigned Idx);
176 
177   MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
178   void assignValue(Metadata *MD, unsigned Idx);
179   void tryToResolveCycles();
180   bool hasFwdRefs() const { return !ForwardReference.empty(); }
181   int getNextFwdRef() {
182     assert(hasFwdRefs());
183     return *ForwardReference.begin();
184   }
185 
186   /// Upgrade a type that had an MDString reference.
187   void addTypeRef(MDString &UUID, DICompositeType &CT);
188 
189   /// Upgrade a type that had an MDString reference.
190   Metadata *upgradeTypeRef(Metadata *MaybeUUID);
191 
192   /// Upgrade a type ref array that may have MDString references.
193   Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
194 
195 private:
196   Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
197 };
198 
199 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
200   if (auto *MDN = dyn_cast<MDNode>(MD))
201     if (!MDN->isResolved())
202       UnresolvedNodes.insert(Idx);
203 
204   if (Idx == size()) {
205     push_back(MD);
206     return;
207   }
208 
209   if (Idx >= size())
210     resize(Idx + 1);
211 
212   TrackingMDRef &OldMD = MetadataPtrs[Idx];
213   if (!OldMD) {
214     OldMD.reset(MD);
215     return;
216   }
217 
218   // If there was a forward reference to this value, replace it.
219   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
220   PrevMD->replaceAllUsesWith(MD);
221   ForwardReference.erase(Idx);
222 }
223 
224 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
225   if (Idx >= size())
226     resize(Idx + 1);
227 
228   if (Metadata *MD = MetadataPtrs[Idx])
229     return MD;
230 
231   // Track forward refs to be resolved later.
232   ForwardReference.insert(Idx);
233 
234   // Create and return a placeholder, which will later be RAUW'd.
235   ++NumMDNodeTemporary;
236   Metadata *MD = MDNode::getTemporary(Context, None).release();
237   MetadataPtrs[Idx].reset(MD);
238   return MD;
239 }
240 
241 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
242   Metadata *MD = lookup(Idx);
243   if (auto *N = dyn_cast_or_null<MDNode>(MD))
244     if (!N->isResolved())
245       return nullptr;
246   return MD;
247 }
248 
249 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
250   return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
251 }
252 
253 void BitcodeReaderMetadataList::tryToResolveCycles() {
254   if (!ForwardReference.empty())
255     // Still forward references... can't resolve cycles.
256     return;
257 
258   // Give up on finding a full definition for any forward decls that remain.
259   for (const auto &Ref : OldTypeRefs.FwdDecls)
260     OldTypeRefs.Final.insert(Ref);
261   OldTypeRefs.FwdDecls.clear();
262 
263   // Upgrade from old type ref arrays.  In strange cases, this could add to
264   // OldTypeRefs.Unknown.
265   for (const auto &Array : OldTypeRefs.Arrays)
266     Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
267   OldTypeRefs.Arrays.clear();
268 
269   // Replace old string-based type refs with the resolved node, if possible.
270   // If we haven't seen the node, leave it to the verifier to complain about
271   // the invalid string reference.
272   for (const auto &Ref : OldTypeRefs.Unknown) {
273     if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
274       Ref.second->replaceAllUsesWith(CT);
275     else
276       Ref.second->replaceAllUsesWith(Ref.first);
277   }
278   OldTypeRefs.Unknown.clear();
279 
280   if (UnresolvedNodes.empty())
281     // Nothing to do.
282     return;
283 
284   // Resolve any cycles.
285   for (unsigned I : UnresolvedNodes) {
286     auto &MD = MetadataPtrs[I];
287     auto *N = dyn_cast_or_null<MDNode>(MD);
288     if (!N)
289       continue;
290 
291     assert(!N->isTemporary() && "Unexpected forward reference");
292     N->resolveCycles();
293   }
294 
295   // Make sure we return early again until there's another unresolved ref.
296   UnresolvedNodes.clear();
297 }
298 
299 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
300                                            DICompositeType &CT) {
301   assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
302   if (CT.isForwardDecl())
303     OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
304   else
305     OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
306 }
307 
308 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
309   auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
310   if (LLVM_LIKELY(!UUID))
311     return MaybeUUID;
312 
313   if (auto *CT = OldTypeRefs.Final.lookup(UUID))
314     return CT;
315 
316   auto &Ref = OldTypeRefs.Unknown[UUID];
317   if (!Ref)
318     Ref = MDNode::getTemporary(Context, None);
319   return Ref.get();
320 }
321 
322 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
323   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
324   if (!Tuple || Tuple->isDistinct())
325     return MaybeTuple;
326 
327   // Look through the array immediately if possible.
328   if (!Tuple->isTemporary())
329     return resolveTypeRefArray(Tuple);
330 
331   // Create and return a placeholder to use for now.  Eventually
332   // resolveTypeRefArrays() will be resolve this forward reference.
333   OldTypeRefs.Arrays.emplace_back(
334       std::piecewise_construct, std::forward_as_tuple(Tuple),
335       std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
336   return OldTypeRefs.Arrays.back().second.get();
337 }
338 
339 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
340   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
341   if (!Tuple || Tuple->isDistinct())
342     return MaybeTuple;
343 
344   // Look through the DITypeRefArray, upgrading each DITypeRef.
345   SmallVector<Metadata *, 32> Ops;
346   Ops.reserve(Tuple->getNumOperands());
347   for (Metadata *MD : Tuple->operands())
348     Ops.push_back(upgradeTypeRef(MD));
349 
350   return MDTuple::get(Context, Ops);
351 }
352 
353 namespace {
354 
355 class PlaceholderQueue {
356   // Placeholders would thrash around when moved, so store in a std::deque
357   // instead of some sort of vector.
358   std::deque<DistinctMDOperandPlaceholder> PHs;
359 
360 public:
361   ~PlaceholderQueue() {
362     assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed");
363   }
364   bool empty() { return PHs.empty(); }
365   DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
366   void flush(BitcodeReaderMetadataList &MetadataList);
367 
368   /// Return the list of temporaries nodes in the queue, these need to be
369   /// loaded before we can flush the queue.
370   void getTemporaries(BitcodeReaderMetadataList &MetadataList,
371                       DenseSet<unsigned> &Temporaries) {
372     for (auto &PH : PHs) {
373       auto ID = PH.getID();
374       auto *MD = MetadataList.lookup(ID);
375       if (!MD) {
376         Temporaries.insert(ID);
377         continue;
378       }
379       auto *N = dyn_cast_or_null<MDNode>(MD);
380       if (N && N->isTemporary())
381         Temporaries.insert(ID);
382     }
383   }
384 };
385 
386 } // end anonymous namespace
387 
388 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
389   PHs.emplace_back(ID);
390   return PHs.back();
391 }
392 
393 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
394   while (!PHs.empty()) {
395     auto *MD = MetadataList.lookup(PHs.front().getID());
396     assert(MD && "Flushing placeholder on unassigned MD");
397 #ifndef NDEBUG
398     if (auto *MDN = dyn_cast<MDNode>(MD))
399       assert(MDN->isResolved() &&
400              "Flushing Placeholder while cycles aren't resolved");
401 #endif
402     PHs.front().replaceUseWith(MD);
403     PHs.pop_front();
404   }
405 }
406 
407 } // anonynous namespace
408 
409 class MetadataLoader::MetadataLoaderImpl {
410   BitcodeReaderMetadataList MetadataList;
411   BitcodeReaderValueList &ValueList;
412   BitstreamCursor &Stream;
413   LLVMContext &Context;
414   Module &TheModule;
415   std::function<Type *(unsigned)> getTypeByID;
416 
417   /// Cursor associated with the lazy-loading of Metadata. This is the easy way
418   /// to keep around the right "context" (Abbrev list) to be able to jump in
419   /// the middle of the metadata block and load any record.
420   BitstreamCursor IndexCursor;
421 
422   /// Index that keeps track of MDString values.
423   std::vector<StringRef> MDStringRef;
424 
425   /// On-demand loading of a single MDString. Requires the index above to be
426   /// populated.
427   MDString *lazyLoadOneMDString(unsigned Idx);
428 
429   /// Index that keeps track of where to find a metadata record in the stream.
430   std::vector<uint64_t> GlobalMetadataBitPosIndex;
431 
432   /// Populate the index above to enable lazily loading of metadata, and load
433   /// the named metadata as well as the transitively referenced global
434   /// Metadata.
435   Expected<bool> lazyLoadModuleMetadataBlock();
436 
437   /// On-demand loading of a single metadata. Requires the index above to be
438   /// populated.
439   void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
440 
441   // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
442   // point from SP to CU after a block is completly parsed.
443   std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
444 
445   /// Functions that need to be matched with subprograms when upgrading old
446   /// metadata.
447   SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
448 
449   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
450   DenseMap<unsigned, unsigned> MDKindMap;
451 
452   bool StripTBAA = false;
453   bool HasSeenOldLoopTags = false;
454 
455   /// True if metadata is being parsed for a module being ThinLTO imported.
456   bool IsImporting = false;
457 
458   Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
459                          PlaceholderQueue &Placeholders, StringRef Blob,
460                          unsigned &NextMetadataNo);
461   Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
462                              function_ref<void(StringRef)> CallBack);
463   Error parseGlobalObjectAttachment(GlobalObject &GO,
464                                     ArrayRef<uint64_t> Record);
465   Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
466 
467   void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
468 
469   /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
470   void upgradeCUSubprograms() {
471     for (auto CU_SP : CUSubprograms)
472       if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
473         for (auto &Op : SPs->operands())
474           if (auto *SP = dyn_cast_or_null<MDNode>(Op))
475             SP->replaceOperandWith(7, CU_SP.first);
476     CUSubprograms.clear();
477   }
478 
479 public:
480   MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
481                      BitcodeReaderValueList &ValueList,
482                      std::function<Type *(unsigned)> getTypeByID,
483                      bool IsImporting)
484       : MetadataList(TheModule.getContext()), ValueList(ValueList),
485         Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
486         getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
487 
488   Error parseMetadata(bool ModuleLevel);
489 
490   bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
491 
492   Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
493     if (ID < MDStringRef.size())
494       return lazyLoadOneMDString(ID);
495     if (auto *MD = MetadataList.lookup(ID))
496       return MD;
497     // If lazy-loading is enabled, we try recursively to load the operand
498     // instead of creating a temporary.
499     if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
500       PlaceholderQueue Placeholders;
501       lazyLoadOneMetadata(ID, Placeholders);
502       resolveForwardRefsAndPlaceholders(Placeholders);
503       return MetadataList.lookup(ID);
504     }
505     return MetadataList.getMetadataFwdRef(ID);
506   }
507 
508   MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
509     return MetadataList.getMDNodeFwdRefOrNull(Idx);
510   }
511 
512   DISubprogram *lookupSubprogramForFunction(Function *F) {
513     return FunctionsWithSPs.lookup(F);
514   }
515 
516   bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
517 
518   Error parseMetadataAttachment(
519       Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
520 
521   Error parseMetadataKinds();
522 
523   void setStripTBAA(bool Value) { StripTBAA = Value; }
524   bool isStrippingTBAA() { return StripTBAA; }
525 
526   unsigned size() const { return MetadataList.size(); }
527   void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
528 };
529 
530 Error error(const Twine &Message) {
531   return make_error<StringError>(
532       Message, make_error_code(BitcodeError::CorruptedBitcode));
533 }
534 
535 Expected<bool>
536 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
537   IndexCursor = Stream;
538   SmallVector<uint64_t, 64> Record;
539   // Get the abbrevs, and preload record positions to make them lazy-loadable.
540   while (true) {
541     BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
542         BitstreamCursor::AF_DontPopBlockAtEnd);
543     switch (Entry.Kind) {
544     case BitstreamEntry::SubBlock: // Handled for us already.
545     case BitstreamEntry::Error:
546       return error("Malformed block");
547     case BitstreamEntry::EndBlock: {
548       return true;
549     }
550     case BitstreamEntry::Record: {
551       // The interesting case.
552       ++NumMDRecordLoaded;
553       uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
554       auto Code = IndexCursor.skipRecord(Entry.ID);
555       switch (Code) {
556       case bitc::METADATA_STRINGS: {
557         // Rewind and parse the strings.
558         IndexCursor.JumpToBit(CurrentPos);
559         StringRef Blob;
560         Record.clear();
561         IndexCursor.readRecord(Entry.ID, Record, &Blob);
562         unsigned NumStrings = Record[0];
563         MDStringRef.reserve(NumStrings);
564         auto IndexNextMDString = [&](StringRef Str) {
565           MDStringRef.push_back(Str);
566         };
567         if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
568           return std::move(Err);
569         break;
570       }
571       case bitc::METADATA_INDEX_OFFSET: {
572         // This is the offset to the index, when we see this we skip all the
573         // records and load only an index to these.
574         IndexCursor.JumpToBit(CurrentPos);
575         Record.clear();
576         IndexCursor.readRecord(Entry.ID, Record);
577         if (Record.size() != 2)
578           return error("Invalid record");
579         auto Offset = Record[0] + (Record[1] << 32);
580         auto BeginPos = IndexCursor.GetCurrentBitNo();
581         IndexCursor.JumpToBit(BeginPos + Offset);
582         Entry = IndexCursor.advanceSkippingSubblocks(
583             BitstreamCursor::AF_DontPopBlockAtEnd);
584         assert(Entry.Kind == BitstreamEntry::Record &&
585                "Corrupted bitcode: Expected `Record` when trying to find the "
586                "Metadata index");
587         Record.clear();
588         auto Code = IndexCursor.readRecord(Entry.ID, Record);
589         (void)Code;
590         assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
591                                                "`METADATA_INDEX` when trying "
592                                                "to find the Metadata index");
593 
594         // Delta unpack
595         auto CurrentValue = BeginPos;
596         GlobalMetadataBitPosIndex.reserve(Record.size());
597         for (auto &Elt : Record) {
598           CurrentValue += Elt;
599           GlobalMetadataBitPosIndex.push_back(CurrentValue);
600         }
601         break;
602       }
603       case bitc::METADATA_INDEX:
604         // We don't expect to get there, the Index is loaded when we encounter
605         // the offset.
606         return error("Corrupted Metadata block");
607       case bitc::METADATA_NAME: {
608         // Named metadata need to be materialized now and aren't deferred.
609         IndexCursor.JumpToBit(CurrentPos);
610         Record.clear();
611         unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
612         assert(Code == bitc::METADATA_NAME);
613 
614         // Read name of the named metadata.
615         SmallString<8> Name(Record.begin(), Record.end());
616         Code = IndexCursor.ReadCode();
617 
618         // Named Metadata comes in two parts, we expect the name to be followed
619         // by the node
620         Record.clear();
621         unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
622         assert(NextBitCode == bitc::METADATA_NAMED_NODE);
623         (void)NextBitCode;
624 
625         // Read named metadata elements.
626         unsigned Size = Record.size();
627         NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
628         for (unsigned i = 0; i != Size; ++i) {
629           // FIXME: We could use a placeholder here, however NamedMDNode are
630           // taking MDNode as operand and not using the Metadata infrastructure.
631           // It is acknowledged by 'TODO: Inherit from Metadata' in the
632           // NamedMDNode class definition.
633           MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
634           assert(MD && "Invalid record");
635           NMD->addOperand(MD);
636         }
637         break;
638       }
639       case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
640         // FIXME: we need to do this early because we don't materialize global
641         // value explicitly.
642         IndexCursor.JumpToBit(CurrentPos);
643         Record.clear();
644         IndexCursor.readRecord(Entry.ID, Record);
645         if (Record.size() % 2 == 0)
646           return error("Invalid record");
647         unsigned ValueID = Record[0];
648         if (ValueID >= ValueList.size())
649           return error("Invalid record");
650         if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
651           if (Error Err = parseGlobalObjectAttachment(
652                   *GO, ArrayRef<uint64_t>(Record).slice(1)))
653             return std::move(Err);
654         break;
655       }
656       case bitc::METADATA_KIND:
657       case bitc::METADATA_STRING_OLD:
658       case bitc::METADATA_OLD_FN_NODE:
659       case bitc::METADATA_OLD_NODE:
660       case bitc::METADATA_VALUE:
661       case bitc::METADATA_DISTINCT_NODE:
662       case bitc::METADATA_NODE:
663       case bitc::METADATA_LOCATION:
664       case bitc::METADATA_GENERIC_DEBUG:
665       case bitc::METADATA_SUBRANGE:
666       case bitc::METADATA_ENUMERATOR:
667       case bitc::METADATA_BASIC_TYPE:
668       case bitc::METADATA_DERIVED_TYPE:
669       case bitc::METADATA_COMPOSITE_TYPE:
670       case bitc::METADATA_SUBROUTINE_TYPE:
671       case bitc::METADATA_MODULE:
672       case bitc::METADATA_FILE:
673       case bitc::METADATA_COMPILE_UNIT:
674       case bitc::METADATA_SUBPROGRAM:
675       case bitc::METADATA_LEXICAL_BLOCK:
676       case bitc::METADATA_LEXICAL_BLOCK_FILE:
677       case bitc::METADATA_NAMESPACE:
678       case bitc::METADATA_MACRO:
679       case bitc::METADATA_MACRO_FILE:
680       case bitc::METADATA_TEMPLATE_TYPE:
681       case bitc::METADATA_TEMPLATE_VALUE:
682       case bitc::METADATA_GLOBAL_VAR:
683       case bitc::METADATA_LOCAL_VAR:
684       case bitc::METADATA_EXPRESSION:
685       case bitc::METADATA_OBJC_PROPERTY:
686       case bitc::METADATA_IMPORTED_ENTITY:
687       case bitc::METADATA_GLOBAL_VAR_EXPR:
688         // We don't expect to see any of these, if we see one, give up on
689         // lazy-loading and fallback.
690         MDStringRef.clear();
691         GlobalMetadataBitPosIndex.clear();
692         return false;
693       }
694       break;
695     }
696     }
697   }
698 }
699 
700 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
701 /// module level metadata.
702 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
703   if (!ModuleLevel && MetadataList.hasFwdRefs())
704     return error("Invalid metadata: fwd refs into function blocks");
705 
706   // Record the entry position so that we can jump back here and efficiently
707   // skip the whole block in case we lazy-load.
708   auto EntryPos = Stream.GetCurrentBitNo();
709 
710   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
711     return error("Invalid record");
712 
713   SmallVector<uint64_t, 64> Record;
714   PlaceholderQueue Placeholders;
715 
716   // We lazy-load module-level metadata: we build an index for each record, and
717   // then load individual record as needed, starting with the named metadata.
718   if (ModuleLevel && IsImporting && MetadataList.empty() &&
719       !DisableLazyLoading) {
720     auto SuccessOrErr = lazyLoadModuleMetadataBlock();
721     if (!SuccessOrErr)
722       return SuccessOrErr.takeError();
723     if (SuccessOrErr.get()) {
724       // An index was successfully created and we will be able to load metadata
725       // on-demand.
726       MetadataList.resize(MDStringRef.size() +
727                           GlobalMetadataBitPosIndex.size());
728 
729       // Reading the named metadata created forward references and/or
730       // placeholders, that we flush here.
731       resolveForwardRefsAndPlaceholders(Placeholders);
732       upgradeCUSubprograms();
733       // Return at the beginning of the block, since it is easy to skip it
734       // entirely from there.
735       Stream.ReadBlockEnd(); // Pop the abbrev block context.
736       Stream.JumpToBit(EntryPos);
737       if (Stream.SkipBlock())
738         return error("Invalid record");
739       return Error::success();
740     }
741     // Couldn't load an index, fallback to loading all the block "old-style".
742   }
743 
744   unsigned NextMetadataNo = MetadataList.size();
745 
746   // Read all the records.
747   while (true) {
748     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
749 
750     switch (Entry.Kind) {
751     case BitstreamEntry::SubBlock: // Handled for us already.
752     case BitstreamEntry::Error:
753       return error("Malformed block");
754     case BitstreamEntry::EndBlock:
755       resolveForwardRefsAndPlaceholders(Placeholders);
756       upgradeCUSubprograms();
757       return Error::success();
758     case BitstreamEntry::Record:
759       // The interesting case.
760       break;
761     }
762 
763     // Read a record.
764     Record.clear();
765     StringRef Blob;
766     ++NumMDRecordLoaded;
767     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
768     if (Error Err =
769             parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
770       return Err;
771   }
772 }
773 
774 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
775   ++NumMDStringLoaded;
776   if (Metadata *MD = MetadataList.lookup(ID))
777     return cast<MDString>(MD);
778   auto MDS = MDString::get(Context, MDStringRef[ID]);
779   MetadataList.assignValue(MDS, ID);
780   return MDS;
781 }
782 
783 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
784     unsigned ID, PlaceholderQueue &Placeholders) {
785   assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
786   assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
787   // Lookup first if the metadata hasn't already been loaded.
788   if (auto *MD = MetadataList.lookup(ID)) {
789     auto *N = dyn_cast_or_null<MDNode>(MD);
790     if (!N->isTemporary())
791       return;
792   }
793   SmallVector<uint64_t, 64> Record;
794   StringRef Blob;
795   IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
796   auto Entry = IndexCursor.advanceSkippingSubblocks();
797   ++NumMDRecordLoaded;
798   unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
799   if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
800     report_fatal_error("Can't lazyload MD");
801 }
802 
803 /// Ensure that all forward-references and placeholders are resolved.
804 /// Iteratively lazy-loading metadata on-demand if needed.
805 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
806     PlaceholderQueue &Placeholders) {
807   DenseSet<unsigned> Temporaries;
808   while (1) {
809     // Populate Temporaries with the placeholders that haven't been loaded yet.
810     Placeholders.getTemporaries(MetadataList, Temporaries);
811 
812     // If we don't have any temporary, or FwdReference, we're done!
813     if (Temporaries.empty() && !MetadataList.hasFwdRefs())
814       break;
815 
816     // First, load all the temporaries. This can add new placeholders or
817     // forward references.
818     for (auto ID : Temporaries)
819       lazyLoadOneMetadata(ID, Placeholders);
820     Temporaries.clear();
821 
822     // Second, load the forward-references. This can also add new placeholders
823     // or forward references.
824     while (MetadataList.hasFwdRefs())
825       lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
826   }
827   // At this point we don't have any forward reference remaining, or temporary
828   // that haven't been loaded. We can safely drop RAUW support and mark cycles
829   // as resolved.
830   MetadataList.tryToResolveCycles();
831 
832   // Finally, everything is in place, we can replace the placeholders operands
833   // with the final node they refer to.
834   Placeholders.flush(MetadataList);
835 }
836 
837 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
838     SmallVectorImpl<uint64_t> &Record, unsigned Code,
839     PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
840 
841   bool IsDistinct = false;
842   auto getMD = [&](unsigned ID) -> Metadata * {
843     if (ID < MDStringRef.size())
844       return lazyLoadOneMDString(ID);
845     if (!IsDistinct) {
846       if (auto *MD = MetadataList.lookup(ID))
847         return MD;
848       // If lazy-loading is enabled, we try recursively to load the operand
849       // instead of creating a temporary.
850       if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
851         // Create a temporary for the node that is referencing the operand we
852         // will lazy-load. It is needed before recursing in case there are
853         // uniquing cycles.
854         MetadataList.getMetadataFwdRef(NextMetadataNo);
855         lazyLoadOneMetadata(ID, Placeholders);
856         return MetadataList.lookup(ID);
857       }
858       // Return a temporary.
859       return MetadataList.getMetadataFwdRef(ID);
860     }
861     if (auto *MD = MetadataList.getMetadataIfResolved(ID))
862       return MD;
863     return &Placeholders.getPlaceholderOp(ID);
864   };
865   auto getMDOrNull = [&](unsigned ID) -> Metadata * {
866     if (ID)
867       return getMD(ID - 1);
868     return nullptr;
869   };
870   auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
871     if (ID)
872       return MetadataList.getMetadataFwdRef(ID - 1);
873     return nullptr;
874   };
875   auto getMDString = [&](unsigned ID) -> MDString * {
876     // This requires that the ID is not really a forward reference.  In
877     // particular, the MDString must already have been resolved.
878     auto MDS = getMDOrNull(ID);
879     return cast_or_null<MDString>(MDS);
880   };
881 
882   // Support for old type refs.
883   auto getDITypeRefOrNull = [&](unsigned ID) {
884     return MetadataList.upgradeTypeRef(getMDOrNull(ID));
885   };
886 
887 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
888   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
889 
890   switch (Code) {
891   default: // Default behavior: ignore.
892     break;
893   case bitc::METADATA_NAME: {
894     // Read name of the named metadata.
895     SmallString<8> Name(Record.begin(), Record.end());
896     Record.clear();
897     Code = Stream.ReadCode();
898 
899     ++NumMDRecordLoaded;
900     unsigned NextBitCode = Stream.readRecord(Code, Record);
901     if (NextBitCode != bitc::METADATA_NAMED_NODE)
902       return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
903 
904     // Read named metadata elements.
905     unsigned Size = Record.size();
906     NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
907     for (unsigned i = 0; i != Size; ++i) {
908       MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
909       if (!MD)
910         return error("Invalid record");
911       NMD->addOperand(MD);
912     }
913     break;
914   }
915   case bitc::METADATA_OLD_FN_NODE: {
916     // FIXME: Remove in 4.0.
917     // This is a LocalAsMetadata record, the only type of function-local
918     // metadata.
919     if (Record.size() % 2 == 1)
920       return error("Invalid record");
921 
922     // If this isn't a LocalAsMetadata record, we're dropping it.  This used
923     // to be legal, but there's no upgrade path.
924     auto dropRecord = [&] {
925       MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
926     };
927     if (Record.size() != 2) {
928       dropRecord();
929       break;
930     }
931 
932     Type *Ty = getTypeByID(Record[0]);
933     if (Ty->isMetadataTy() || Ty->isVoidTy()) {
934       dropRecord();
935       break;
936     }
937 
938     MetadataList.assignValue(
939         LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
940         NextMetadataNo++);
941     break;
942   }
943   case bitc::METADATA_OLD_NODE: {
944     // FIXME: Remove in 4.0.
945     if (Record.size() % 2 == 1)
946       return error("Invalid record");
947 
948     unsigned Size = Record.size();
949     SmallVector<Metadata *, 8> Elts;
950     for (unsigned i = 0; i != Size; i += 2) {
951       Type *Ty = getTypeByID(Record[i]);
952       if (!Ty)
953         return error("Invalid record");
954       if (Ty->isMetadataTy())
955         Elts.push_back(getMD(Record[i + 1]));
956       else if (!Ty->isVoidTy()) {
957         auto *MD =
958             ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
959         assert(isa<ConstantAsMetadata>(MD) &&
960                "Expected non-function-local metadata");
961         Elts.push_back(MD);
962       } else
963         Elts.push_back(nullptr);
964     }
965     MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
966     break;
967   }
968   case bitc::METADATA_VALUE: {
969     if (Record.size() != 2)
970       return error("Invalid record");
971 
972     Type *Ty = getTypeByID(Record[0]);
973     if (Ty->isMetadataTy() || Ty->isVoidTy())
974       return error("Invalid record");
975 
976     MetadataList.assignValue(
977         ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
978         NextMetadataNo++);
979     break;
980   }
981   case bitc::METADATA_DISTINCT_NODE:
982     IsDistinct = true;
983     LLVM_FALLTHROUGH;
984   case bitc::METADATA_NODE: {
985     SmallVector<Metadata *, 8> Elts;
986     Elts.reserve(Record.size());
987     for (unsigned ID : Record)
988       Elts.push_back(getMDOrNull(ID));
989     MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
990                                         : MDNode::get(Context, Elts),
991                              NextMetadataNo++);
992     break;
993   }
994   case bitc::METADATA_LOCATION: {
995     if (Record.size() != 5)
996       return error("Invalid record");
997 
998     IsDistinct = Record[0];
999     unsigned Line = Record[1];
1000     unsigned Column = Record[2];
1001     Metadata *Scope = getMD(Record[3]);
1002     Metadata *InlinedAt = getMDOrNull(Record[4]);
1003     MetadataList.assignValue(
1004         GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
1005         NextMetadataNo++);
1006     break;
1007   }
1008   case bitc::METADATA_GENERIC_DEBUG: {
1009     if (Record.size() < 4)
1010       return error("Invalid record");
1011 
1012     IsDistinct = Record[0];
1013     unsigned Tag = Record[1];
1014     unsigned Version = Record[2];
1015 
1016     if (Tag >= 1u << 16 || Version != 0)
1017       return error("Invalid record");
1018 
1019     auto *Header = getMDString(Record[3]);
1020     SmallVector<Metadata *, 8> DwarfOps;
1021     for (unsigned I = 4, E = Record.size(); I != E; ++I)
1022       DwarfOps.push_back(getMDOrNull(Record[I]));
1023     MetadataList.assignValue(
1024         GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1025         NextMetadataNo++);
1026     break;
1027   }
1028   case bitc::METADATA_SUBRANGE: {
1029     if (Record.size() != 3)
1030       return error("Invalid record");
1031 
1032     IsDistinct = Record[0];
1033     MetadataList.assignValue(
1034         GET_OR_DISTINCT(DISubrange,
1035                         (Context, Record[1], unrotateSign(Record[2]))),
1036         NextMetadataNo++);
1037     break;
1038   }
1039   case bitc::METADATA_ENUMERATOR: {
1040     if (Record.size() != 3)
1041       return error("Invalid record");
1042 
1043     IsDistinct = Record[0];
1044     MetadataList.assignValue(
1045         GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
1046                                        getMDString(Record[2]))),
1047         NextMetadataNo++);
1048     break;
1049   }
1050   case bitc::METADATA_BASIC_TYPE: {
1051     if (Record.size() != 6)
1052       return error("Invalid record");
1053 
1054     IsDistinct = Record[0];
1055     MetadataList.assignValue(
1056         GET_OR_DISTINCT(DIBasicType,
1057                         (Context, Record[1], getMDString(Record[2]), Record[3],
1058                          Record[4], Record[5])),
1059         NextMetadataNo++);
1060     break;
1061   }
1062   case bitc::METADATA_DERIVED_TYPE: {
1063     if (Record.size() != 12)
1064       return error("Invalid record");
1065 
1066     IsDistinct = Record[0];
1067     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1068     MetadataList.assignValue(
1069         GET_OR_DISTINCT(DIDerivedType,
1070                         (Context, Record[1], getMDString(Record[2]),
1071                          getMDOrNull(Record[3]), Record[4],
1072                          getDITypeRefOrNull(Record[5]),
1073                          getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1074                          Record[9], Flags, getDITypeRefOrNull(Record[11]))),
1075         NextMetadataNo++);
1076     break;
1077   }
1078   case bitc::METADATA_COMPOSITE_TYPE: {
1079     if (Record.size() != 16)
1080       return error("Invalid record");
1081 
1082     // If we have a UUID and this is not a forward declaration, lookup the
1083     // mapping.
1084     IsDistinct = Record[0] & 0x1;
1085     bool IsNotUsedInTypeRef = Record[0] >= 2;
1086     unsigned Tag = Record[1];
1087     MDString *Name = getMDString(Record[2]);
1088     Metadata *File = getMDOrNull(Record[3]);
1089     unsigned Line = Record[4];
1090     Metadata *Scope = getDITypeRefOrNull(Record[5]);
1091     Metadata *BaseType = nullptr;
1092     uint64_t SizeInBits = Record[7];
1093     if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1094       return error("Alignment value is too large");
1095     uint32_t AlignInBits = Record[8];
1096     uint64_t OffsetInBits = 0;
1097     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1098     Metadata *Elements = nullptr;
1099     unsigned RuntimeLang = Record[12];
1100     Metadata *VTableHolder = nullptr;
1101     Metadata *TemplateParams = nullptr;
1102     auto *Identifier = getMDString(Record[15]);
1103     // If this module is being parsed so that it can be ThinLTO imported
1104     // into another module, composite types only need to be imported
1105     // as type declarations (unless full type definitions requested).
1106     // Create type declarations up front to save memory. Also, buildODRType
1107     // handles the case where this is type ODRed with a definition needed
1108     // by the importing module, in which case the existing definition is
1109     // used.
1110     if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1111         (Tag == dwarf::DW_TAG_enumeration_type ||
1112          Tag == dwarf::DW_TAG_class_type ||
1113          Tag == dwarf::DW_TAG_structure_type ||
1114          Tag == dwarf::DW_TAG_union_type)) {
1115       Flags = Flags | DINode::FlagFwdDecl;
1116     } else {
1117       BaseType = getDITypeRefOrNull(Record[6]);
1118       OffsetInBits = Record[9];
1119       Elements = getMDOrNull(Record[11]);
1120       VTableHolder = getDITypeRefOrNull(Record[13]);
1121       TemplateParams = getMDOrNull(Record[14]);
1122     }
1123     DICompositeType *CT = nullptr;
1124     if (Identifier)
1125       CT = DICompositeType::buildODRType(
1126           Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1127           SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1128           VTableHolder, TemplateParams);
1129 
1130     // Create a node if we didn't get a lazy ODR type.
1131     if (!CT)
1132       CT = GET_OR_DISTINCT(DICompositeType,
1133                            (Context, Tag, Name, File, Line, Scope, BaseType,
1134                             SizeInBits, AlignInBits, OffsetInBits, Flags,
1135                             Elements, RuntimeLang, VTableHolder, TemplateParams,
1136                             Identifier));
1137     if (!IsNotUsedInTypeRef && Identifier)
1138       MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1139 
1140     MetadataList.assignValue(CT, NextMetadataNo++);
1141     break;
1142   }
1143   case bitc::METADATA_SUBROUTINE_TYPE: {
1144     if (Record.size() < 3 || Record.size() > 4)
1145       return error("Invalid record");
1146     bool IsOldTypeRefArray = Record[0] < 2;
1147     unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1148 
1149     IsDistinct = Record[0] & 0x1;
1150     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1151     Metadata *Types = getMDOrNull(Record[2]);
1152     if (LLVM_UNLIKELY(IsOldTypeRefArray))
1153       Types = MetadataList.upgradeTypeRefArray(Types);
1154 
1155     MetadataList.assignValue(
1156         GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1157         NextMetadataNo++);
1158     break;
1159   }
1160 
1161   case bitc::METADATA_MODULE: {
1162     if (Record.size() != 6)
1163       return error("Invalid record");
1164 
1165     IsDistinct = Record[0];
1166     MetadataList.assignValue(
1167         GET_OR_DISTINCT(DIModule,
1168                         (Context, getMDOrNull(Record[1]),
1169                          getMDString(Record[2]), getMDString(Record[3]),
1170                          getMDString(Record[4]), getMDString(Record[5]))),
1171         NextMetadataNo++);
1172     break;
1173   }
1174 
1175   case bitc::METADATA_FILE: {
1176     if (Record.size() != 3 && Record.size() != 5)
1177       return error("Invalid record");
1178 
1179     IsDistinct = Record[0];
1180     MetadataList.assignValue(
1181         GET_OR_DISTINCT(
1182             DIFile,
1183             (Context, getMDString(Record[1]), getMDString(Record[2]),
1184              Record.size() == 3 ? DIFile::CSK_None
1185                                 : static_cast<DIFile::ChecksumKind>(Record[3]),
1186              Record.size() == 3 ? nullptr : getMDString(Record[4]))),
1187         NextMetadataNo++);
1188     break;
1189   }
1190   case bitc::METADATA_COMPILE_UNIT: {
1191     if (Record.size() < 14 || Record.size() > 17)
1192       return error("Invalid record");
1193 
1194     // Ignore Record[0], which indicates whether this compile unit is
1195     // distinct.  It's always distinct.
1196     IsDistinct = true;
1197     auto *CU = DICompileUnit::getDistinct(
1198         Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1199         Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1200         Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1201         getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1202         Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1203         Record.size() <= 14 ? 0 : Record[14],
1204         Record.size() <= 16 ? true : Record[16]);
1205 
1206     MetadataList.assignValue(CU, NextMetadataNo++);
1207 
1208     // Move the Upgrade the list of subprograms.
1209     if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1210       CUSubprograms.push_back({CU, SPs});
1211     break;
1212   }
1213   case bitc::METADATA_SUBPROGRAM: {
1214     if (Record.size() < 18 || Record.size() > 20)
1215       return error("Invalid record");
1216 
1217     IsDistinct =
1218         (Record[0] & 1) || Record[8]; // All definitions should be distinct.
1219     // Version 1 has a Function as Record[15].
1220     // Version 2 has removed Record[15].
1221     // Version 3 has the Unit as Record[15].
1222     // Version 4 added thisAdjustment.
1223     bool HasUnit = Record[0] >= 2;
1224     if (HasUnit && Record.size() < 19)
1225       return error("Invalid record");
1226     Metadata *CUorFn = getMDOrNull(Record[15]);
1227     unsigned Offset = Record.size() >= 19 ? 1 : 0;
1228     bool HasFn = Offset && !HasUnit;
1229     bool HasThisAdj = Record.size() >= 20;
1230     DISubprogram *SP = GET_OR_DISTINCT(
1231         DISubprogram, (Context,
1232                        getDITypeRefOrNull(Record[1]),          // scope
1233                        getMDString(Record[2]),                 // name
1234                        getMDString(Record[3]),                 // linkageName
1235                        getMDOrNull(Record[4]),                 // file
1236                        Record[5],                              // line
1237                        getMDOrNull(Record[6]),                 // type
1238                        Record[7],                              // isLocal
1239                        Record[8],                              // isDefinition
1240                        Record[9],                              // scopeLine
1241                        getDITypeRefOrNull(Record[10]),         // containingType
1242                        Record[11],                             // virtuality
1243                        Record[12],                             // virtualIndex
1244                        HasThisAdj ? Record[19] : 0,            // thisAdjustment
1245                        static_cast<DINode::DIFlags>(Record[13] // flags
1246                                                     ),
1247                        Record[14],                       // isOptimized
1248                        HasUnit ? CUorFn : nullptr,       // unit
1249                        getMDOrNull(Record[15 + Offset]), // templateParams
1250                        getMDOrNull(Record[16 + Offset]), // declaration
1251                        getMDOrNull(Record[17 + Offset])  // variables
1252                        ));
1253     MetadataList.assignValue(SP, NextMetadataNo++);
1254 
1255     // Upgrade sp->function mapping to function->sp mapping.
1256     if (HasFn) {
1257       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1258         if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1259           if (F->isMaterializable())
1260             // Defer until materialized; unmaterialized functions may not have
1261             // metadata.
1262             FunctionsWithSPs[F] = SP;
1263           else if (!F->empty())
1264             F->setSubprogram(SP);
1265         }
1266     }
1267     break;
1268   }
1269   case bitc::METADATA_LEXICAL_BLOCK: {
1270     if (Record.size() != 5)
1271       return error("Invalid record");
1272 
1273     IsDistinct = Record[0];
1274     MetadataList.assignValue(
1275         GET_OR_DISTINCT(DILexicalBlock,
1276                         (Context, getMDOrNull(Record[1]),
1277                          getMDOrNull(Record[2]), Record[3], Record[4])),
1278         NextMetadataNo++);
1279     break;
1280   }
1281   case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1282     if (Record.size() != 4)
1283       return error("Invalid record");
1284 
1285     IsDistinct = Record[0];
1286     MetadataList.assignValue(
1287         GET_OR_DISTINCT(DILexicalBlockFile,
1288                         (Context, getMDOrNull(Record[1]),
1289                          getMDOrNull(Record[2]), Record[3])),
1290         NextMetadataNo++);
1291     break;
1292   }
1293   case bitc::METADATA_NAMESPACE: {
1294     if (Record.size() != 5)
1295       return error("Invalid record");
1296 
1297     IsDistinct = Record[0] & 1;
1298     bool ExportSymbols = Record[0] & 2;
1299     MetadataList.assignValue(
1300         GET_OR_DISTINCT(DINamespace,
1301                         (Context, getMDOrNull(Record[1]),
1302                          getMDOrNull(Record[2]), getMDString(Record[3]),
1303                          Record[4], ExportSymbols)),
1304         NextMetadataNo++);
1305     break;
1306   }
1307   case bitc::METADATA_MACRO: {
1308     if (Record.size() != 5)
1309       return error("Invalid record");
1310 
1311     IsDistinct = Record[0];
1312     MetadataList.assignValue(
1313         GET_OR_DISTINCT(DIMacro,
1314                         (Context, Record[1], Record[2], getMDString(Record[3]),
1315                          getMDString(Record[4]))),
1316         NextMetadataNo++);
1317     break;
1318   }
1319   case bitc::METADATA_MACRO_FILE: {
1320     if (Record.size() != 5)
1321       return error("Invalid record");
1322 
1323     IsDistinct = Record[0];
1324     MetadataList.assignValue(
1325         GET_OR_DISTINCT(DIMacroFile,
1326                         (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1327                          getMDOrNull(Record[4]))),
1328         NextMetadataNo++);
1329     break;
1330   }
1331   case bitc::METADATA_TEMPLATE_TYPE: {
1332     if (Record.size() != 3)
1333       return error("Invalid record");
1334 
1335     IsDistinct = Record[0];
1336     MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1337                                              (Context, getMDString(Record[1]),
1338                                               getDITypeRefOrNull(Record[2]))),
1339                              NextMetadataNo++);
1340     break;
1341   }
1342   case bitc::METADATA_TEMPLATE_VALUE: {
1343     if (Record.size() != 5)
1344       return error("Invalid record");
1345 
1346     IsDistinct = Record[0];
1347     MetadataList.assignValue(
1348         GET_OR_DISTINCT(DITemplateValueParameter,
1349                         (Context, Record[1], getMDString(Record[2]),
1350                          getDITypeRefOrNull(Record[3]),
1351                          getMDOrNull(Record[4]))),
1352         NextMetadataNo++);
1353     break;
1354   }
1355   case bitc::METADATA_GLOBAL_VAR: {
1356     if (Record.size() < 11 || Record.size() > 12)
1357       return error("Invalid record");
1358 
1359     IsDistinct = Record[0] & 1;
1360     unsigned Version = Record[0] >> 1;
1361 
1362     if (Version == 1) {
1363       MetadataList.assignValue(
1364           GET_OR_DISTINCT(DIGlobalVariable,
1365                           (Context, getMDOrNull(Record[1]),
1366                            getMDString(Record[2]), getMDString(Record[3]),
1367                            getMDOrNull(Record[4]), Record[5],
1368                            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1369                            getMDOrNull(Record[10]), Record[11])),
1370           NextMetadataNo++);
1371     } else if (Version == 0) {
1372       // Upgrade old metadata, which stored a global variable reference or a
1373       // ConstantInt here.
1374       Metadata *Expr = getMDOrNull(Record[9]);
1375       uint32_t AlignInBits = 0;
1376       if (Record.size() > 11) {
1377         if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1378           return error("Alignment value is too large");
1379         AlignInBits = Record[11];
1380       }
1381       GlobalVariable *Attach = nullptr;
1382       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1383         if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1384           Attach = GV;
1385           Expr = nullptr;
1386         } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1387           Expr = DIExpression::get(Context,
1388                                    {dwarf::DW_OP_constu, CI->getZExtValue(),
1389                                     dwarf::DW_OP_stack_value});
1390         } else {
1391           Expr = nullptr;
1392         }
1393       }
1394       DIGlobalVariable *DGV = GET_OR_DISTINCT(
1395           DIGlobalVariable,
1396           (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1397            getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1398            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1399            getMDOrNull(Record[10]), AlignInBits));
1400 
1401       auto *DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
1402       MetadataList.assignValue(DGVE, NextMetadataNo++);
1403       if (Attach)
1404         Attach->addDebugInfo(DGVE);
1405     } else
1406       return error("Invalid record");
1407 
1408     break;
1409   }
1410   case bitc::METADATA_LOCAL_VAR: {
1411     // 10th field is for the obseleted 'inlinedAt:' field.
1412     if (Record.size() < 8 || Record.size() > 10)
1413       return error("Invalid record");
1414 
1415     IsDistinct = Record[0] & 1;
1416     bool HasAlignment = Record[0] & 2;
1417     // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1418     // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1419     // this is newer version of record which doesn't have artifical tag.
1420     bool HasTag = !HasAlignment && Record.size() > 8;
1421     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1422     uint32_t AlignInBits = 0;
1423     if (HasAlignment) {
1424       if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1425         return error("Alignment value is too large");
1426       AlignInBits = Record[8 + HasTag];
1427     }
1428     MetadataList.assignValue(
1429         GET_OR_DISTINCT(DILocalVariable,
1430                         (Context, getMDOrNull(Record[1 + HasTag]),
1431                          getMDString(Record[2 + HasTag]),
1432                          getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1433                          getDITypeRefOrNull(Record[5 + HasTag]),
1434                          Record[6 + HasTag], Flags, AlignInBits)),
1435         NextMetadataNo++);
1436     break;
1437   }
1438   case bitc::METADATA_EXPRESSION: {
1439     if (Record.size() < 1)
1440       return error("Invalid record");
1441 
1442     IsDistinct = Record[0] & 1;
1443     bool HasOpFragment = Record[0] & 2;
1444     auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
1445     if (!HasOpFragment)
1446       if (unsigned N = Elts.size())
1447         if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece)
1448           Elts[N - 3] = dwarf::DW_OP_LLVM_fragment;
1449 
1450     MetadataList.assignValue(
1451         GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))),
1452         NextMetadataNo++);
1453     break;
1454   }
1455   case bitc::METADATA_GLOBAL_VAR_EXPR: {
1456     if (Record.size() != 3)
1457       return error("Invalid record");
1458 
1459     IsDistinct = Record[0];
1460     MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
1461                                              (Context, getMDOrNull(Record[1]),
1462                                               getMDOrNull(Record[2]))),
1463                              NextMetadataNo++);
1464     break;
1465   }
1466   case bitc::METADATA_OBJC_PROPERTY: {
1467     if (Record.size() != 8)
1468       return error("Invalid record");
1469 
1470     IsDistinct = Record[0];
1471     MetadataList.assignValue(
1472         GET_OR_DISTINCT(DIObjCProperty,
1473                         (Context, getMDString(Record[1]),
1474                          getMDOrNull(Record[2]), Record[3],
1475                          getMDString(Record[4]), getMDString(Record[5]),
1476                          Record[6], getDITypeRefOrNull(Record[7]))),
1477         NextMetadataNo++);
1478     break;
1479   }
1480   case bitc::METADATA_IMPORTED_ENTITY: {
1481     if (Record.size() != 6)
1482       return error("Invalid record");
1483 
1484     IsDistinct = Record[0];
1485     MetadataList.assignValue(
1486         GET_OR_DISTINCT(DIImportedEntity,
1487                         (Context, Record[1], getMDOrNull(Record[2]),
1488                          getDITypeRefOrNull(Record[3]), Record[4],
1489                          getMDString(Record[5]))),
1490         NextMetadataNo++);
1491     break;
1492   }
1493   case bitc::METADATA_STRING_OLD: {
1494     std::string String(Record.begin(), Record.end());
1495 
1496     // Test for upgrading !llvm.loop.
1497     HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
1498     ++NumMDStringLoaded;
1499     Metadata *MD = MDString::get(Context, String);
1500     MetadataList.assignValue(MD, NextMetadataNo++);
1501     break;
1502   }
1503   case bitc::METADATA_STRINGS: {
1504     auto CreateNextMDString = [&](StringRef Str) {
1505       ++NumMDStringLoaded;
1506       MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo++);
1507     };
1508     if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
1509       return Err;
1510     break;
1511   }
1512   case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1513     if (Record.size() % 2 == 0)
1514       return error("Invalid record");
1515     unsigned ValueID = Record[0];
1516     if (ValueID >= ValueList.size())
1517       return error("Invalid record");
1518     if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1519       if (Error Err = parseGlobalObjectAttachment(
1520               *GO, ArrayRef<uint64_t>(Record).slice(1)))
1521         return Err;
1522     break;
1523   }
1524   case bitc::METADATA_KIND: {
1525     // Support older bitcode files that had METADATA_KIND records in a
1526     // block with METADATA_BLOCK_ID.
1527     if (Error Err = parseMetadataKindRecord(Record))
1528       return Err;
1529     break;
1530   }
1531   }
1532   return Error::success();
1533 #undef GET_OR_DISTINCT
1534 }
1535 
1536 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
1537     ArrayRef<uint64_t> Record, StringRef Blob,
1538     function_ref<void(StringRef)> CallBack) {
1539   // All the MDStrings in the block are emitted together in a single
1540   // record.  The strings are concatenated and stored in a blob along with
1541   // their sizes.
1542   if (Record.size() != 2)
1543     return error("Invalid record: metadata strings layout");
1544 
1545   unsigned NumStrings = Record[0];
1546   unsigned StringsOffset = Record[1];
1547   if (!NumStrings)
1548     return error("Invalid record: metadata strings with no strings");
1549   if (StringsOffset > Blob.size())
1550     return error("Invalid record: metadata strings corrupt offset");
1551 
1552   StringRef Lengths = Blob.slice(0, StringsOffset);
1553   SimpleBitstreamCursor R(Lengths);
1554 
1555   StringRef Strings = Blob.drop_front(StringsOffset);
1556   do {
1557     if (R.AtEndOfStream())
1558       return error("Invalid record: metadata strings bad length");
1559 
1560     unsigned Size = R.ReadVBR(6);
1561     if (Strings.size() < Size)
1562       return error("Invalid record: metadata strings truncated chars");
1563 
1564     CallBack(Strings.slice(0, Size));
1565     Strings = Strings.drop_front(Size);
1566   } while (--NumStrings);
1567 
1568   return Error::success();
1569 }
1570 
1571 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1572     GlobalObject &GO, ArrayRef<uint64_t> Record) {
1573   assert(Record.size() % 2 == 0);
1574   for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1575     auto K = MDKindMap.find(Record[I]);
1576     if (K == MDKindMap.end())
1577       return error("Invalid ID");
1578     MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1579     if (!MD)
1580       return error("Invalid metadata attachment");
1581     GO.addMetadata(K->second, *MD);
1582   }
1583   return Error::success();
1584 }
1585 
1586 /// Parse metadata attachments.
1587 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1588     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1589   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1590     return error("Invalid record");
1591 
1592   SmallVector<uint64_t, 64> Record;
1593   PlaceholderQueue Placeholders;
1594 
1595   while (true) {
1596     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1597 
1598     switch (Entry.Kind) {
1599     case BitstreamEntry::SubBlock: // Handled for us already.
1600     case BitstreamEntry::Error:
1601       return error("Malformed block");
1602     case BitstreamEntry::EndBlock:
1603       resolveForwardRefsAndPlaceholders(Placeholders);
1604       return Error::success();
1605     case BitstreamEntry::Record:
1606       // The interesting case.
1607       break;
1608     }
1609 
1610     // Read a metadata attachment record.
1611     Record.clear();
1612     ++NumMDRecordLoaded;
1613     switch (Stream.readRecord(Entry.ID, Record)) {
1614     default: // Default behavior: ignore.
1615       break;
1616     case bitc::METADATA_ATTACHMENT: {
1617       unsigned RecordLength = Record.size();
1618       if (Record.empty())
1619         return error("Invalid record");
1620       if (RecordLength % 2 == 0) {
1621         // A function attachment.
1622         if (Error Err = parseGlobalObjectAttachment(F, Record))
1623           return Err;
1624         continue;
1625       }
1626 
1627       // An instruction attachment.
1628       Instruction *Inst = InstructionList[Record[0]];
1629       for (unsigned i = 1; i != RecordLength; i = i + 2) {
1630         unsigned Kind = Record[i];
1631         DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1632         if (I == MDKindMap.end())
1633           return error("Invalid ID");
1634         if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1635           continue;
1636 
1637         auto Idx = Record[i + 1];
1638         if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
1639             !MetadataList.lookup(Idx)) {
1640           // Load the attachment if it is in the lazy-loadable range and hasn't
1641           // been loaded yet.
1642           lazyLoadOneMetadata(Idx, Placeholders);
1643           resolveForwardRefsAndPlaceholders(Placeholders);
1644         }
1645 
1646         Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
1647         if (isa<LocalAsMetadata>(Node))
1648           // Drop the attachment.  This used to be legal, but there's no
1649           // upgrade path.
1650           break;
1651         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1652         if (!MD)
1653           return error("Invalid metadata attachment");
1654 
1655         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1656           MD = upgradeInstructionLoopAttachment(*MD);
1657 
1658         if (I->second == LLVMContext::MD_tbaa) {
1659           assert(!MD->isTemporary() && "should load MDs before attachments");
1660           MD = UpgradeTBAANode(*MD);
1661         }
1662         Inst->setMetadata(I->second, MD);
1663       }
1664       break;
1665     }
1666     }
1667   }
1668 }
1669 
1670 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1671 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1672     SmallVectorImpl<uint64_t> &Record) {
1673   if (Record.size() < 2)
1674     return error("Invalid record");
1675 
1676   unsigned Kind = Record[0];
1677   SmallString<8> Name(Record.begin() + 1, Record.end());
1678 
1679   unsigned NewKind = TheModule.getMDKindID(Name.str());
1680   if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1681     return error("Conflicting METADATA_KIND records");
1682   return Error::success();
1683 }
1684 
1685 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1686 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1687   if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1688     return error("Invalid record");
1689 
1690   SmallVector<uint64_t, 64> Record;
1691 
1692   // Read all the records.
1693   while (true) {
1694     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1695 
1696     switch (Entry.Kind) {
1697     case BitstreamEntry::SubBlock: // Handled for us already.
1698     case BitstreamEntry::Error:
1699       return error("Malformed block");
1700     case BitstreamEntry::EndBlock:
1701       return Error::success();
1702     case BitstreamEntry::Record:
1703       // The interesting case.
1704       break;
1705     }
1706 
1707     // Read a record.
1708     Record.clear();
1709     ++NumMDRecordLoaded;
1710     unsigned Code = Stream.readRecord(Entry.ID, Record);
1711     switch (Code) {
1712     default: // Default behavior: ignore.
1713       break;
1714     case bitc::METADATA_KIND: {
1715       if (Error Err = parseMetadataKindRecord(Record))
1716         return Err;
1717       break;
1718     }
1719     }
1720   }
1721 }
1722 
1723 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1724   Pimpl = std::move(RHS.Pimpl);
1725   return *this;
1726 }
1727 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
1728     : Pimpl(std::move(RHS.Pimpl)) {}
1729 
1730 MetadataLoader::~MetadataLoader() = default;
1731 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1732                                BitcodeReaderValueList &ValueList,
1733                                bool IsImporting,
1734                                std::function<Type *(unsigned)> getTypeByID)
1735     : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
1736           Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
1737 
1738 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
1739   return Pimpl->parseMetadata(ModuleLevel);
1740 }
1741 
1742 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1743 
1744 /// Return the given metadata, creating a replaceable forward reference if
1745 /// necessary.
1746 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
1747   return Pimpl->getMetadataFwdRefOrLoad(Idx);
1748 }
1749 
1750 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1751   return Pimpl->getMDNodeFwdRefOrNull(Idx);
1752 }
1753 
1754 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1755   return Pimpl->lookupSubprogramForFunction(F);
1756 }
1757 
1758 Error MetadataLoader::parseMetadataAttachment(
1759     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1760   return Pimpl->parseMetadataAttachment(F, InstructionList);
1761 }
1762 
1763 Error MetadataLoader::parseMetadataKinds() {
1764   return Pimpl->parseMetadataKinds();
1765 }
1766 
1767 void MetadataLoader::setStripTBAA(bool StripTBAA) {
1768   return Pimpl->setStripTBAA(StripTBAA);
1769 }
1770 
1771 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1772 
1773 unsigned MetadataLoader::size() const { return Pimpl->size(); }
1774 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
1775