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   bool NeedUpgradeToDIGlobalVariableExpression = false;
455 
456   /// True if metadata is being parsed for a module being ThinLTO imported.
457   bool IsImporting = false;
458 
459   Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
460                          PlaceholderQueue &Placeholders, StringRef Blob,
461                          unsigned &NextMetadataNo);
462   Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
463                              function_ref<void(StringRef)> CallBack);
464   Error parseGlobalObjectAttachment(GlobalObject &GO,
465                                     ArrayRef<uint64_t> Record);
466   Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
467 
468   void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
469 
470   /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
471   void upgradeCUSubprograms() {
472     for (auto CU_SP : CUSubprograms)
473       if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
474         for (auto &Op : SPs->operands())
475           if (auto *SP = dyn_cast_or_null<MDNode>(Op))
476             SP->replaceOperandWith(7, CU_SP.first);
477     CUSubprograms.clear();
478   }
479 
480   /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
481   void upgradeCUVariables() {
482     if (!NeedUpgradeToDIGlobalVariableExpression)
483       return;
484 
485     // Upgrade list of variables attached to the CUs.
486     if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
487       for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
488         auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
489         if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
490           for (unsigned I = 0; I < GVs->getNumOperands(); I++)
491             if (auto *GV =
492                     dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
493               auto *DGVE =
494                   DIGlobalVariableExpression::getDistinct(Context, GV, nullptr);
495               GVs->replaceOperandWith(I, DGVE);
496             }
497       }
498 
499     // Upgrade variables attached to globals.
500     for (auto &GV : TheModule.globals()) {
501       SmallVector<MDNode *, 1> MDs, NewMDs;
502       GV.getMetadata(LLVMContext::MD_dbg, MDs);
503       GV.eraseMetadata(LLVMContext::MD_dbg);
504       for (auto *MD : MDs)
505         if (auto *DGV = dyn_cast_or_null<DIGlobalVariable>(MD)) {
506           auto *DGVE =
507               DIGlobalVariableExpression::getDistinct(Context, DGV, nullptr);
508           GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
509         } else
510           GV.addMetadata(LLVMContext::MD_dbg, *MD);
511     }
512   }
513 
514   void upgradeDebugInfo() {
515     upgradeCUSubprograms();
516     upgradeCUVariables();
517   }
518 
519 public:
520   MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
521                      BitcodeReaderValueList &ValueList,
522                      std::function<Type *(unsigned)> getTypeByID,
523                      bool IsImporting)
524       : MetadataList(TheModule.getContext()), ValueList(ValueList),
525         Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
526         getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
527 
528   Error parseMetadata(bool ModuleLevel);
529 
530   bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
531 
532   Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
533     if (ID < MDStringRef.size())
534       return lazyLoadOneMDString(ID);
535     if (auto *MD = MetadataList.lookup(ID))
536       return MD;
537     // If lazy-loading is enabled, we try recursively to load the operand
538     // instead of creating a temporary.
539     if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
540       PlaceholderQueue Placeholders;
541       lazyLoadOneMetadata(ID, Placeholders);
542       resolveForwardRefsAndPlaceholders(Placeholders);
543       return MetadataList.lookup(ID);
544     }
545     return MetadataList.getMetadataFwdRef(ID);
546   }
547 
548   MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
549     return MetadataList.getMDNodeFwdRefOrNull(Idx);
550   }
551 
552   DISubprogram *lookupSubprogramForFunction(Function *F) {
553     return FunctionsWithSPs.lookup(F);
554   }
555 
556   bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
557 
558   Error parseMetadataAttachment(
559       Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
560 
561   Error parseMetadataKinds();
562 
563   void setStripTBAA(bool Value) { StripTBAA = Value; }
564   bool isStrippingTBAA() { return StripTBAA; }
565 
566   unsigned size() const { return MetadataList.size(); }
567   void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
568 };
569 
570 static Error error(const Twine &Message) {
571   return make_error<StringError>(
572       Message, make_error_code(BitcodeError::CorruptedBitcode));
573 }
574 
575 Expected<bool>
576 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
577   IndexCursor = Stream;
578   SmallVector<uint64_t, 64> Record;
579   // Get the abbrevs, and preload record positions to make them lazy-loadable.
580   while (true) {
581     BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
582         BitstreamCursor::AF_DontPopBlockAtEnd);
583     switch (Entry.Kind) {
584     case BitstreamEntry::SubBlock: // Handled for us already.
585     case BitstreamEntry::Error:
586       return error("Malformed block");
587     case BitstreamEntry::EndBlock: {
588       return true;
589     }
590     case BitstreamEntry::Record: {
591       // The interesting case.
592       ++NumMDRecordLoaded;
593       uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
594       auto Code = IndexCursor.skipRecord(Entry.ID);
595       switch (Code) {
596       case bitc::METADATA_STRINGS: {
597         // Rewind and parse the strings.
598         IndexCursor.JumpToBit(CurrentPos);
599         StringRef Blob;
600         Record.clear();
601         IndexCursor.readRecord(Entry.ID, Record, &Blob);
602         unsigned NumStrings = Record[0];
603         MDStringRef.reserve(NumStrings);
604         auto IndexNextMDString = [&](StringRef Str) {
605           MDStringRef.push_back(Str);
606         };
607         if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
608           return std::move(Err);
609         break;
610       }
611       case bitc::METADATA_INDEX_OFFSET: {
612         // This is the offset to the index, when we see this we skip all the
613         // records and load only an index to these.
614         IndexCursor.JumpToBit(CurrentPos);
615         Record.clear();
616         IndexCursor.readRecord(Entry.ID, Record);
617         if (Record.size() != 2)
618           return error("Invalid record");
619         auto Offset = Record[0] + (Record[1] << 32);
620         auto BeginPos = IndexCursor.GetCurrentBitNo();
621         IndexCursor.JumpToBit(BeginPos + Offset);
622         Entry = IndexCursor.advanceSkippingSubblocks(
623             BitstreamCursor::AF_DontPopBlockAtEnd);
624         assert(Entry.Kind == BitstreamEntry::Record &&
625                "Corrupted bitcode: Expected `Record` when trying to find the "
626                "Metadata index");
627         Record.clear();
628         auto Code = IndexCursor.readRecord(Entry.ID, Record);
629         (void)Code;
630         assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
631                                                "`METADATA_INDEX` when trying "
632                                                "to find the Metadata index");
633 
634         // Delta unpack
635         auto CurrentValue = BeginPos;
636         GlobalMetadataBitPosIndex.reserve(Record.size());
637         for (auto &Elt : Record) {
638           CurrentValue += Elt;
639           GlobalMetadataBitPosIndex.push_back(CurrentValue);
640         }
641         break;
642       }
643       case bitc::METADATA_INDEX:
644         // We don't expect to get there, the Index is loaded when we encounter
645         // the offset.
646         return error("Corrupted Metadata block");
647       case bitc::METADATA_NAME: {
648         // Named metadata need to be materialized now and aren't deferred.
649         IndexCursor.JumpToBit(CurrentPos);
650         Record.clear();
651         unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
652         assert(Code == bitc::METADATA_NAME);
653 
654         // Read name of the named metadata.
655         SmallString<8> Name(Record.begin(), Record.end());
656         Code = IndexCursor.ReadCode();
657 
658         // Named Metadata comes in two parts, we expect the name to be followed
659         // by the node
660         Record.clear();
661         unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
662         assert(NextBitCode == bitc::METADATA_NAMED_NODE);
663         (void)NextBitCode;
664 
665         // Read named metadata elements.
666         unsigned Size = Record.size();
667         NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
668         for (unsigned i = 0; i != Size; ++i) {
669           // FIXME: We could use a placeholder here, however NamedMDNode are
670           // taking MDNode as operand and not using the Metadata infrastructure.
671           // It is acknowledged by 'TODO: Inherit from Metadata' in the
672           // NamedMDNode class definition.
673           MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
674           assert(MD && "Invalid record");
675           NMD->addOperand(MD);
676         }
677         break;
678       }
679       case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
680         // FIXME: we need to do this early because we don't materialize global
681         // value explicitly.
682         IndexCursor.JumpToBit(CurrentPos);
683         Record.clear();
684         IndexCursor.readRecord(Entry.ID, Record);
685         if (Record.size() % 2 == 0)
686           return error("Invalid record");
687         unsigned ValueID = Record[0];
688         if (ValueID >= ValueList.size())
689           return error("Invalid record");
690         if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
691           if (Error Err = parseGlobalObjectAttachment(
692                   *GO, ArrayRef<uint64_t>(Record).slice(1)))
693             return std::move(Err);
694         break;
695       }
696       case bitc::METADATA_KIND:
697       case bitc::METADATA_STRING_OLD:
698       case bitc::METADATA_OLD_FN_NODE:
699       case bitc::METADATA_OLD_NODE:
700       case bitc::METADATA_VALUE:
701       case bitc::METADATA_DISTINCT_NODE:
702       case bitc::METADATA_NODE:
703       case bitc::METADATA_LOCATION:
704       case bitc::METADATA_GENERIC_DEBUG:
705       case bitc::METADATA_SUBRANGE:
706       case bitc::METADATA_ENUMERATOR:
707       case bitc::METADATA_BASIC_TYPE:
708       case bitc::METADATA_DERIVED_TYPE:
709       case bitc::METADATA_COMPOSITE_TYPE:
710       case bitc::METADATA_SUBROUTINE_TYPE:
711       case bitc::METADATA_MODULE:
712       case bitc::METADATA_FILE:
713       case bitc::METADATA_COMPILE_UNIT:
714       case bitc::METADATA_SUBPROGRAM:
715       case bitc::METADATA_LEXICAL_BLOCK:
716       case bitc::METADATA_LEXICAL_BLOCK_FILE:
717       case bitc::METADATA_NAMESPACE:
718       case bitc::METADATA_MACRO:
719       case bitc::METADATA_MACRO_FILE:
720       case bitc::METADATA_TEMPLATE_TYPE:
721       case bitc::METADATA_TEMPLATE_VALUE:
722       case bitc::METADATA_GLOBAL_VAR:
723       case bitc::METADATA_LOCAL_VAR:
724       case bitc::METADATA_EXPRESSION:
725       case bitc::METADATA_OBJC_PROPERTY:
726       case bitc::METADATA_IMPORTED_ENTITY:
727       case bitc::METADATA_GLOBAL_VAR_EXPR:
728         // We don't expect to see any of these, if we see one, give up on
729         // lazy-loading and fallback.
730         MDStringRef.clear();
731         GlobalMetadataBitPosIndex.clear();
732         return false;
733       }
734       break;
735     }
736     }
737   }
738 }
739 
740 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
741 /// module level metadata.
742 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
743   if (!ModuleLevel && MetadataList.hasFwdRefs())
744     return error("Invalid metadata: fwd refs into function blocks");
745 
746   // Record the entry position so that we can jump back here and efficiently
747   // skip the whole block in case we lazy-load.
748   auto EntryPos = Stream.GetCurrentBitNo();
749 
750   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
751     return error("Invalid record");
752 
753   SmallVector<uint64_t, 64> Record;
754   PlaceholderQueue Placeholders;
755 
756   // We lazy-load module-level metadata: we build an index for each record, and
757   // then load individual record as needed, starting with the named metadata.
758   if (ModuleLevel && IsImporting && MetadataList.empty() &&
759       !DisableLazyLoading) {
760     auto SuccessOrErr = lazyLoadModuleMetadataBlock();
761     if (!SuccessOrErr)
762       return SuccessOrErr.takeError();
763     if (SuccessOrErr.get()) {
764       // An index was successfully created and we will be able to load metadata
765       // on-demand.
766       MetadataList.resize(MDStringRef.size() +
767                           GlobalMetadataBitPosIndex.size());
768 
769       // Reading the named metadata created forward references and/or
770       // placeholders, that we flush here.
771       resolveForwardRefsAndPlaceholders(Placeholders);
772       upgradeDebugInfo();
773       // Return at the beginning of the block, since it is easy to skip it
774       // entirely from there.
775       Stream.ReadBlockEnd(); // Pop the abbrev block context.
776       Stream.JumpToBit(EntryPos);
777       if (Stream.SkipBlock())
778         return error("Invalid record");
779       return Error::success();
780     }
781     // Couldn't load an index, fallback to loading all the block "old-style".
782   }
783 
784   unsigned NextMetadataNo = MetadataList.size();
785 
786   // Read all the records.
787   while (true) {
788     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
789 
790     switch (Entry.Kind) {
791     case BitstreamEntry::SubBlock: // Handled for us already.
792     case BitstreamEntry::Error:
793       return error("Malformed block");
794     case BitstreamEntry::EndBlock:
795       resolveForwardRefsAndPlaceholders(Placeholders);
796       upgradeDebugInfo();
797       return Error::success();
798     case BitstreamEntry::Record:
799       // The interesting case.
800       break;
801     }
802 
803     // Read a record.
804     Record.clear();
805     StringRef Blob;
806     ++NumMDRecordLoaded;
807     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
808     if (Error Err =
809             parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
810       return Err;
811   }
812 }
813 
814 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
815   ++NumMDStringLoaded;
816   if (Metadata *MD = MetadataList.lookup(ID))
817     return cast<MDString>(MD);
818   auto MDS = MDString::get(Context, MDStringRef[ID]);
819   MetadataList.assignValue(MDS, ID);
820   return MDS;
821 }
822 
823 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
824     unsigned ID, PlaceholderQueue &Placeholders) {
825   assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
826   assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
827   // Lookup first if the metadata hasn't already been loaded.
828   if (auto *MD = MetadataList.lookup(ID)) {
829     auto *N = dyn_cast_or_null<MDNode>(MD);
830     if (!N->isTemporary())
831       return;
832   }
833   SmallVector<uint64_t, 64> Record;
834   StringRef Blob;
835   IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
836   auto Entry = IndexCursor.advanceSkippingSubblocks();
837   ++NumMDRecordLoaded;
838   unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
839   if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
840     report_fatal_error("Can't lazyload MD");
841 }
842 
843 /// Ensure that all forward-references and placeholders are resolved.
844 /// Iteratively lazy-loading metadata on-demand if needed.
845 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
846     PlaceholderQueue &Placeholders) {
847   DenseSet<unsigned> Temporaries;
848   while (1) {
849     // Populate Temporaries with the placeholders that haven't been loaded yet.
850     Placeholders.getTemporaries(MetadataList, Temporaries);
851 
852     // If we don't have any temporary, or FwdReference, we're done!
853     if (Temporaries.empty() && !MetadataList.hasFwdRefs())
854       break;
855 
856     // First, load all the temporaries. This can add new placeholders or
857     // forward references.
858     for (auto ID : Temporaries)
859       lazyLoadOneMetadata(ID, Placeholders);
860     Temporaries.clear();
861 
862     // Second, load the forward-references. This can also add new placeholders
863     // or forward references.
864     while (MetadataList.hasFwdRefs())
865       lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
866   }
867   // At this point we don't have any forward reference remaining, or temporary
868   // that haven't been loaded. We can safely drop RAUW support and mark cycles
869   // as resolved.
870   MetadataList.tryToResolveCycles();
871 
872   // Finally, everything is in place, we can replace the placeholders operands
873   // with the final node they refer to.
874   Placeholders.flush(MetadataList);
875 }
876 
877 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
878     SmallVectorImpl<uint64_t> &Record, unsigned Code,
879     PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
880 
881   bool IsDistinct = false;
882   auto getMD = [&](unsigned ID) -> Metadata * {
883     if (ID < MDStringRef.size())
884       return lazyLoadOneMDString(ID);
885     if (!IsDistinct) {
886       if (auto *MD = MetadataList.lookup(ID))
887         return MD;
888       // If lazy-loading is enabled, we try recursively to load the operand
889       // instead of creating a temporary.
890       if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
891         // Create a temporary for the node that is referencing the operand we
892         // will lazy-load. It is needed before recursing in case there are
893         // uniquing cycles.
894         MetadataList.getMetadataFwdRef(NextMetadataNo);
895         lazyLoadOneMetadata(ID, Placeholders);
896         return MetadataList.lookup(ID);
897       }
898       // Return a temporary.
899       return MetadataList.getMetadataFwdRef(ID);
900     }
901     if (auto *MD = MetadataList.getMetadataIfResolved(ID))
902       return MD;
903     return &Placeholders.getPlaceholderOp(ID);
904   };
905   auto getMDOrNull = [&](unsigned ID) -> Metadata * {
906     if (ID)
907       return getMD(ID - 1);
908     return nullptr;
909   };
910   auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
911     if (ID)
912       return MetadataList.getMetadataFwdRef(ID - 1);
913     return nullptr;
914   };
915   auto getMDString = [&](unsigned ID) -> MDString * {
916     // This requires that the ID is not really a forward reference.  In
917     // particular, the MDString must already have been resolved.
918     auto MDS = getMDOrNull(ID);
919     return cast_or_null<MDString>(MDS);
920   };
921 
922   // Support for old type refs.
923   auto getDITypeRefOrNull = [&](unsigned ID) {
924     return MetadataList.upgradeTypeRef(getMDOrNull(ID));
925   };
926 
927 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
928   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
929 
930   switch (Code) {
931   default: // Default behavior: ignore.
932     break;
933   case bitc::METADATA_NAME: {
934     // Read name of the named metadata.
935     SmallString<8> Name(Record.begin(), Record.end());
936     Record.clear();
937     Code = Stream.ReadCode();
938 
939     ++NumMDRecordLoaded;
940     unsigned NextBitCode = Stream.readRecord(Code, Record);
941     if (NextBitCode != bitc::METADATA_NAMED_NODE)
942       return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
943 
944     // Read named metadata elements.
945     unsigned Size = Record.size();
946     NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
947     for (unsigned i = 0; i != Size; ++i) {
948       MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
949       if (!MD)
950         return error("Invalid record");
951       NMD->addOperand(MD);
952     }
953     break;
954   }
955   case bitc::METADATA_OLD_FN_NODE: {
956     // FIXME: Remove in 4.0.
957     // This is a LocalAsMetadata record, the only type of function-local
958     // metadata.
959     if (Record.size() % 2 == 1)
960       return error("Invalid record");
961 
962     // If this isn't a LocalAsMetadata record, we're dropping it.  This used
963     // to be legal, but there's no upgrade path.
964     auto dropRecord = [&] {
965       MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
966       NextMetadataNo++;
967     };
968     if (Record.size() != 2) {
969       dropRecord();
970       break;
971     }
972 
973     Type *Ty = getTypeByID(Record[0]);
974     if (Ty->isMetadataTy() || Ty->isVoidTy()) {
975       dropRecord();
976       break;
977     }
978 
979     MetadataList.assignValue(
980         LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
981         NextMetadataNo);
982     NextMetadataNo++;
983     break;
984   }
985   case bitc::METADATA_OLD_NODE: {
986     // FIXME: Remove in 4.0.
987     if (Record.size() % 2 == 1)
988       return error("Invalid record");
989 
990     unsigned Size = Record.size();
991     SmallVector<Metadata *, 8> Elts;
992     for (unsigned i = 0; i != Size; i += 2) {
993       Type *Ty = getTypeByID(Record[i]);
994       if (!Ty)
995         return error("Invalid record");
996       if (Ty->isMetadataTy())
997         Elts.push_back(getMD(Record[i + 1]));
998       else if (!Ty->isVoidTy()) {
999         auto *MD =
1000             ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1001         assert(isa<ConstantAsMetadata>(MD) &&
1002                "Expected non-function-local metadata");
1003         Elts.push_back(MD);
1004       } else
1005         Elts.push_back(nullptr);
1006     }
1007     MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1008     NextMetadataNo++;
1009     break;
1010   }
1011   case bitc::METADATA_VALUE: {
1012     if (Record.size() != 2)
1013       return error("Invalid record");
1014 
1015     Type *Ty = getTypeByID(Record[0]);
1016     if (Ty->isMetadataTy() || Ty->isVoidTy())
1017       return error("Invalid record");
1018 
1019     MetadataList.assignValue(
1020         ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1021         NextMetadataNo);
1022     NextMetadataNo++;
1023     break;
1024   }
1025   case bitc::METADATA_DISTINCT_NODE:
1026     IsDistinct = true;
1027     LLVM_FALLTHROUGH;
1028   case bitc::METADATA_NODE: {
1029     SmallVector<Metadata *, 8> Elts;
1030     Elts.reserve(Record.size());
1031     for (unsigned ID : Record)
1032       Elts.push_back(getMDOrNull(ID));
1033     MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1034                                         : MDNode::get(Context, Elts),
1035                              NextMetadataNo);
1036     NextMetadataNo++;
1037     break;
1038   }
1039   case bitc::METADATA_LOCATION: {
1040     if (Record.size() != 5)
1041       return error("Invalid record");
1042 
1043     IsDistinct = Record[0];
1044     unsigned Line = Record[1];
1045     unsigned Column = Record[2];
1046     Metadata *Scope = getMD(Record[3]);
1047     Metadata *InlinedAt = getMDOrNull(Record[4]);
1048     MetadataList.assignValue(
1049         GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
1050         NextMetadataNo);
1051     NextMetadataNo++;
1052     break;
1053   }
1054   case bitc::METADATA_GENERIC_DEBUG: {
1055     if (Record.size() < 4)
1056       return error("Invalid record");
1057 
1058     IsDistinct = Record[0];
1059     unsigned Tag = Record[1];
1060     unsigned Version = Record[2];
1061 
1062     if (Tag >= 1u << 16 || Version != 0)
1063       return error("Invalid record");
1064 
1065     auto *Header = getMDString(Record[3]);
1066     SmallVector<Metadata *, 8> DwarfOps;
1067     for (unsigned I = 4, E = Record.size(); I != E; ++I)
1068       DwarfOps.push_back(getMDOrNull(Record[I]));
1069     MetadataList.assignValue(
1070         GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1071         NextMetadataNo);
1072     NextMetadataNo++;
1073     break;
1074   }
1075   case bitc::METADATA_SUBRANGE: {
1076     if (Record.size() != 3)
1077       return error("Invalid record");
1078 
1079     IsDistinct = Record[0];
1080     MetadataList.assignValue(
1081         GET_OR_DISTINCT(DISubrange,
1082                         (Context, Record[1], unrotateSign(Record[2]))),
1083         NextMetadataNo);
1084     NextMetadataNo++;
1085     break;
1086   }
1087   case bitc::METADATA_ENUMERATOR: {
1088     if (Record.size() != 3)
1089       return error("Invalid record");
1090 
1091     IsDistinct = Record[0];
1092     MetadataList.assignValue(
1093         GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
1094                                        getMDString(Record[2]))),
1095         NextMetadataNo);
1096     NextMetadataNo++;
1097     break;
1098   }
1099   case bitc::METADATA_BASIC_TYPE: {
1100     if (Record.size() != 6)
1101       return error("Invalid record");
1102 
1103     IsDistinct = Record[0];
1104     MetadataList.assignValue(
1105         GET_OR_DISTINCT(DIBasicType,
1106                         (Context, Record[1], getMDString(Record[2]), Record[3],
1107                          Record[4], Record[5])),
1108         NextMetadataNo);
1109     NextMetadataNo++;
1110     break;
1111   }
1112   case bitc::METADATA_DERIVED_TYPE: {
1113     if (Record.size() < 12 || Record.size() > 13)
1114       return error("Invalid record");
1115 
1116     // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1117     // that there is no DWARF address space associated with DIDerivedType.
1118     Optional<unsigned> DWARFAddressSpace;
1119     if (Record.size() > 12 && Record[12])
1120       DWARFAddressSpace = Record[12] - 1;
1121 
1122     IsDistinct = Record[0];
1123     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1124     MetadataList.assignValue(
1125         GET_OR_DISTINCT(DIDerivedType,
1126                         (Context, Record[1], getMDString(Record[2]),
1127                          getMDOrNull(Record[3]), Record[4],
1128                          getDITypeRefOrNull(Record[5]),
1129                          getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1130                          Record[9], DWARFAddressSpace, Flags,
1131                          getDITypeRefOrNull(Record[11]))),
1132         NextMetadataNo);
1133     NextMetadataNo++;
1134     break;
1135   }
1136   case bitc::METADATA_COMPOSITE_TYPE: {
1137     if (Record.size() != 16)
1138       return error("Invalid record");
1139 
1140     // If we have a UUID and this is not a forward declaration, lookup the
1141     // mapping.
1142     IsDistinct = Record[0] & 0x1;
1143     bool IsNotUsedInTypeRef = Record[0] >= 2;
1144     unsigned Tag = Record[1];
1145     MDString *Name = getMDString(Record[2]);
1146     Metadata *File = getMDOrNull(Record[3]);
1147     unsigned Line = Record[4];
1148     Metadata *Scope = getDITypeRefOrNull(Record[5]);
1149     Metadata *BaseType = nullptr;
1150     uint64_t SizeInBits = Record[7];
1151     if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1152       return error("Alignment value is too large");
1153     uint32_t AlignInBits = Record[8];
1154     uint64_t OffsetInBits = 0;
1155     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1156     Metadata *Elements = nullptr;
1157     unsigned RuntimeLang = Record[12];
1158     Metadata *VTableHolder = nullptr;
1159     Metadata *TemplateParams = nullptr;
1160     auto *Identifier = getMDString(Record[15]);
1161     // If this module is being parsed so that it can be ThinLTO imported
1162     // into another module, composite types only need to be imported
1163     // as type declarations (unless full type definitions requested).
1164     // Create type declarations up front to save memory. Also, buildODRType
1165     // handles the case where this is type ODRed with a definition needed
1166     // by the importing module, in which case the existing definition is
1167     // used.
1168     if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1169         (Tag == dwarf::DW_TAG_enumeration_type ||
1170          Tag == dwarf::DW_TAG_class_type ||
1171          Tag == dwarf::DW_TAG_structure_type ||
1172          Tag == dwarf::DW_TAG_union_type)) {
1173       Flags = Flags | DINode::FlagFwdDecl;
1174     } else {
1175       BaseType = getDITypeRefOrNull(Record[6]);
1176       OffsetInBits = Record[9];
1177       Elements = getMDOrNull(Record[11]);
1178       VTableHolder = getDITypeRefOrNull(Record[13]);
1179       TemplateParams = getMDOrNull(Record[14]);
1180     }
1181     DICompositeType *CT = nullptr;
1182     if (Identifier)
1183       CT = DICompositeType::buildODRType(
1184           Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1185           SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1186           VTableHolder, TemplateParams);
1187 
1188     // Create a node if we didn't get a lazy ODR type.
1189     if (!CT)
1190       CT = GET_OR_DISTINCT(DICompositeType,
1191                            (Context, Tag, Name, File, Line, Scope, BaseType,
1192                             SizeInBits, AlignInBits, OffsetInBits, Flags,
1193                             Elements, RuntimeLang, VTableHolder, TemplateParams,
1194                             Identifier));
1195     if (!IsNotUsedInTypeRef && Identifier)
1196       MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1197 
1198     MetadataList.assignValue(CT, NextMetadataNo);
1199     NextMetadataNo++;
1200     break;
1201   }
1202   case bitc::METADATA_SUBROUTINE_TYPE: {
1203     if (Record.size() < 3 || Record.size() > 4)
1204       return error("Invalid record");
1205     bool IsOldTypeRefArray = Record[0] < 2;
1206     unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1207 
1208     IsDistinct = Record[0] & 0x1;
1209     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1210     Metadata *Types = getMDOrNull(Record[2]);
1211     if (LLVM_UNLIKELY(IsOldTypeRefArray))
1212       Types = MetadataList.upgradeTypeRefArray(Types);
1213 
1214     MetadataList.assignValue(
1215         GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1216         NextMetadataNo);
1217     NextMetadataNo++;
1218     break;
1219   }
1220 
1221   case bitc::METADATA_MODULE: {
1222     if (Record.size() != 6)
1223       return error("Invalid record");
1224 
1225     IsDistinct = Record[0];
1226     MetadataList.assignValue(
1227         GET_OR_DISTINCT(DIModule,
1228                         (Context, getMDOrNull(Record[1]),
1229                          getMDString(Record[2]), getMDString(Record[3]),
1230                          getMDString(Record[4]), getMDString(Record[5]))),
1231         NextMetadataNo);
1232     NextMetadataNo++;
1233     break;
1234   }
1235 
1236   case bitc::METADATA_FILE: {
1237     if (Record.size() != 3 && Record.size() != 5)
1238       return error("Invalid record");
1239 
1240     IsDistinct = Record[0];
1241     MetadataList.assignValue(
1242         GET_OR_DISTINCT(
1243             DIFile,
1244             (Context, getMDString(Record[1]), getMDString(Record[2]),
1245              Record.size() == 3 ? DIFile::CSK_None
1246                                 : static_cast<DIFile::ChecksumKind>(Record[3]),
1247              Record.size() == 3 ? nullptr : getMDString(Record[4]))),
1248         NextMetadataNo);
1249     NextMetadataNo++;
1250     break;
1251   }
1252   case bitc::METADATA_COMPILE_UNIT: {
1253     if (Record.size() < 14 || Record.size() > 18)
1254       return error("Invalid record");
1255 
1256     // Ignore Record[0], which indicates whether this compile unit is
1257     // distinct.  It's always distinct.
1258     IsDistinct = true;
1259     auto *CU = DICompileUnit::getDistinct(
1260         Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1261         Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1262         Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1263         getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1264         Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1265         Record.size() <= 14 ? 0 : Record[14],
1266         Record.size() <= 16 ? true : Record[16],
1267         Record.size() <= 17 ? false : Record[17]);
1268 
1269     MetadataList.assignValue(CU, NextMetadataNo);
1270     NextMetadataNo++;
1271 
1272     // Move the Upgrade the list of subprograms.
1273     if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1274       CUSubprograms.push_back({CU, SPs});
1275     break;
1276   }
1277   case bitc::METADATA_SUBPROGRAM: {
1278     if (Record.size() < 18 || Record.size() > 20)
1279       return error("Invalid record");
1280 
1281     IsDistinct =
1282         (Record[0] & 1) || Record[8]; // All definitions should be distinct.
1283     // Version 1 has a Function as Record[15].
1284     // Version 2 has removed Record[15].
1285     // Version 3 has the Unit as Record[15].
1286     // Version 4 added thisAdjustment.
1287     bool HasUnit = Record[0] >= 2;
1288     if (HasUnit && Record.size() < 19)
1289       return error("Invalid record");
1290     Metadata *CUorFn = getMDOrNull(Record[15]);
1291     unsigned Offset = Record.size() >= 19 ? 1 : 0;
1292     bool HasFn = Offset && !HasUnit;
1293     bool HasThisAdj = Record.size() >= 20;
1294     DISubprogram *SP = GET_OR_DISTINCT(
1295         DISubprogram, (Context,
1296                        getDITypeRefOrNull(Record[1]),          // scope
1297                        getMDString(Record[2]),                 // name
1298                        getMDString(Record[3]),                 // linkageName
1299                        getMDOrNull(Record[4]),                 // file
1300                        Record[5],                              // line
1301                        getMDOrNull(Record[6]),                 // type
1302                        Record[7],                              // isLocal
1303                        Record[8],                              // isDefinition
1304                        Record[9],                              // scopeLine
1305                        getDITypeRefOrNull(Record[10]),         // containingType
1306                        Record[11],                             // virtuality
1307                        Record[12],                             // virtualIndex
1308                        HasThisAdj ? Record[19] : 0,            // thisAdjustment
1309                        static_cast<DINode::DIFlags>(Record[13] // flags
1310                                                     ),
1311                        Record[14],                       // isOptimized
1312                        HasUnit ? CUorFn : nullptr,       // unit
1313                        getMDOrNull(Record[15 + Offset]), // templateParams
1314                        getMDOrNull(Record[16 + Offset]), // declaration
1315                        getMDOrNull(Record[17 + Offset])  // variables
1316                        ));
1317     MetadataList.assignValue(SP, NextMetadataNo);
1318     NextMetadataNo++;
1319 
1320     // Upgrade sp->function mapping to function->sp mapping.
1321     if (HasFn) {
1322       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1323         if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1324           if (F->isMaterializable())
1325             // Defer until materialized; unmaterialized functions may not have
1326             // metadata.
1327             FunctionsWithSPs[F] = SP;
1328           else if (!F->empty())
1329             F->setSubprogram(SP);
1330         }
1331     }
1332     break;
1333   }
1334   case bitc::METADATA_LEXICAL_BLOCK: {
1335     if (Record.size() != 5)
1336       return error("Invalid record");
1337 
1338     IsDistinct = Record[0];
1339     MetadataList.assignValue(
1340         GET_OR_DISTINCT(DILexicalBlock,
1341                         (Context, getMDOrNull(Record[1]),
1342                          getMDOrNull(Record[2]), Record[3], Record[4])),
1343         NextMetadataNo);
1344     NextMetadataNo++;
1345     break;
1346   }
1347   case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1348     if (Record.size() != 4)
1349       return error("Invalid record");
1350 
1351     IsDistinct = Record[0];
1352     MetadataList.assignValue(
1353         GET_OR_DISTINCT(DILexicalBlockFile,
1354                         (Context, getMDOrNull(Record[1]),
1355                          getMDOrNull(Record[2]), Record[3])),
1356         NextMetadataNo);
1357     NextMetadataNo++;
1358     break;
1359   }
1360   case bitc::METADATA_NAMESPACE: {
1361     if (Record.size() != 5)
1362       return error("Invalid record");
1363 
1364     IsDistinct = Record[0] & 1;
1365     bool ExportSymbols = Record[0] & 2;
1366     MetadataList.assignValue(
1367         GET_OR_DISTINCT(DINamespace,
1368                         (Context, getMDOrNull(Record[1]),
1369                          getMDOrNull(Record[2]), getMDString(Record[3]),
1370                          Record[4], ExportSymbols)),
1371         NextMetadataNo);
1372     NextMetadataNo++;
1373     break;
1374   }
1375   case bitc::METADATA_MACRO: {
1376     if (Record.size() != 5)
1377       return error("Invalid record");
1378 
1379     IsDistinct = Record[0];
1380     MetadataList.assignValue(
1381         GET_OR_DISTINCT(DIMacro,
1382                         (Context, Record[1], Record[2], getMDString(Record[3]),
1383                          getMDString(Record[4]))),
1384         NextMetadataNo);
1385     NextMetadataNo++;
1386     break;
1387   }
1388   case bitc::METADATA_MACRO_FILE: {
1389     if (Record.size() != 5)
1390       return error("Invalid record");
1391 
1392     IsDistinct = Record[0];
1393     MetadataList.assignValue(
1394         GET_OR_DISTINCT(DIMacroFile,
1395                         (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1396                          getMDOrNull(Record[4]))),
1397         NextMetadataNo);
1398     NextMetadataNo++;
1399     break;
1400   }
1401   case bitc::METADATA_TEMPLATE_TYPE: {
1402     if (Record.size() != 3)
1403       return error("Invalid record");
1404 
1405     IsDistinct = Record[0];
1406     MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1407                                              (Context, getMDString(Record[1]),
1408                                               getDITypeRefOrNull(Record[2]))),
1409                              NextMetadataNo);
1410     NextMetadataNo++;
1411     break;
1412   }
1413   case bitc::METADATA_TEMPLATE_VALUE: {
1414     if (Record.size() != 5)
1415       return error("Invalid record");
1416 
1417     IsDistinct = Record[0];
1418     MetadataList.assignValue(
1419         GET_OR_DISTINCT(DITemplateValueParameter,
1420                         (Context, Record[1], getMDString(Record[2]),
1421                          getDITypeRefOrNull(Record[3]),
1422                          getMDOrNull(Record[4]))),
1423         NextMetadataNo);
1424     NextMetadataNo++;
1425     break;
1426   }
1427   case bitc::METADATA_GLOBAL_VAR: {
1428     if (Record.size() < 11 || Record.size() > 12)
1429       return error("Invalid record");
1430 
1431     IsDistinct = Record[0] & 1;
1432     unsigned Version = Record[0] >> 1;
1433 
1434     if (Version == 1) {
1435       MetadataList.assignValue(
1436           GET_OR_DISTINCT(DIGlobalVariable,
1437                           (Context, getMDOrNull(Record[1]),
1438                            getMDString(Record[2]), getMDString(Record[3]),
1439                            getMDOrNull(Record[4]), Record[5],
1440                            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1441                            getMDOrNull(Record[10]), Record[11])),
1442           NextMetadataNo);
1443       NextMetadataNo++;
1444     } else if (Version == 0) {
1445       // Upgrade old metadata, which stored a global variable reference or a
1446       // ConstantInt here.
1447       NeedUpgradeToDIGlobalVariableExpression = true;
1448       Metadata *Expr = getMDOrNull(Record[9]);
1449       uint32_t AlignInBits = 0;
1450       if (Record.size() > 11) {
1451         if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1452           return error("Alignment value is too large");
1453         AlignInBits = Record[11];
1454       }
1455       GlobalVariable *Attach = nullptr;
1456       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1457         if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1458           Attach = GV;
1459           Expr = nullptr;
1460         } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1461           Expr = DIExpression::get(Context,
1462                                    {dwarf::DW_OP_constu, CI->getZExtValue(),
1463                                     dwarf::DW_OP_stack_value});
1464         } else {
1465           Expr = nullptr;
1466         }
1467       }
1468       DIGlobalVariable *DGV = GET_OR_DISTINCT(
1469           DIGlobalVariable,
1470           (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1471            getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1472            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1473            getMDOrNull(Record[10]), AlignInBits));
1474 
1475       DIGlobalVariableExpression *DGVE = nullptr;
1476       if (Attach || Expr)
1477         DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
1478       if (Attach)
1479         Attach->addDebugInfo(DGVE);
1480 
1481       auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1482       MetadataList.assignValue(MDNode, NextMetadataNo);
1483       NextMetadataNo++;
1484     } else
1485       return error("Invalid record");
1486 
1487     break;
1488   }
1489   case bitc::METADATA_LOCAL_VAR: {
1490     // 10th field is for the obseleted 'inlinedAt:' field.
1491     if (Record.size() < 8 || Record.size() > 10)
1492       return error("Invalid record");
1493 
1494     IsDistinct = Record[0] & 1;
1495     bool HasAlignment = Record[0] & 2;
1496     // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1497     // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1498     // this is newer version of record which doesn't have artifical tag.
1499     bool HasTag = !HasAlignment && Record.size() > 8;
1500     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1501     uint32_t AlignInBits = 0;
1502     if (HasAlignment) {
1503       if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1504         return error("Alignment value is too large");
1505       AlignInBits = Record[8 + HasTag];
1506     }
1507     MetadataList.assignValue(
1508         GET_OR_DISTINCT(DILocalVariable,
1509                         (Context, getMDOrNull(Record[1 + HasTag]),
1510                          getMDString(Record[2 + HasTag]),
1511                          getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1512                          getDITypeRefOrNull(Record[5 + HasTag]),
1513                          Record[6 + HasTag], Flags, AlignInBits)),
1514         NextMetadataNo);
1515     NextMetadataNo++;
1516     break;
1517   }
1518   case bitc::METADATA_EXPRESSION: {
1519     if (Record.size() < 1)
1520       return error("Invalid record");
1521 
1522     IsDistinct = Record[0] & 1;
1523     bool HasOpFragment = Record[0] & 2;
1524     auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
1525     if (!HasOpFragment)
1526       if (unsigned N = Elts.size())
1527         if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece)
1528           Elts[N - 3] = dwarf::DW_OP_LLVM_fragment;
1529 
1530     MetadataList.assignValue(
1531         GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))),
1532         NextMetadataNo);
1533     NextMetadataNo++;
1534     break;
1535   }
1536   case bitc::METADATA_GLOBAL_VAR_EXPR: {
1537     if (Record.size() != 3)
1538       return error("Invalid record");
1539 
1540     IsDistinct = Record[0];
1541     MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
1542                                              (Context, getMDOrNull(Record[1]),
1543                                               getMDOrNull(Record[2]))),
1544                              NextMetadataNo);
1545     NextMetadataNo++;
1546     break;
1547   }
1548   case bitc::METADATA_OBJC_PROPERTY: {
1549     if (Record.size() != 8)
1550       return error("Invalid record");
1551 
1552     IsDistinct = Record[0];
1553     MetadataList.assignValue(
1554         GET_OR_DISTINCT(DIObjCProperty,
1555                         (Context, getMDString(Record[1]),
1556                          getMDOrNull(Record[2]), Record[3],
1557                          getMDString(Record[4]), getMDString(Record[5]),
1558                          Record[6], getDITypeRefOrNull(Record[7]))),
1559         NextMetadataNo);
1560     NextMetadataNo++;
1561     break;
1562   }
1563   case bitc::METADATA_IMPORTED_ENTITY: {
1564     if (Record.size() != 6)
1565       return error("Invalid record");
1566 
1567     IsDistinct = Record[0];
1568     MetadataList.assignValue(
1569         GET_OR_DISTINCT(DIImportedEntity,
1570                         (Context, Record[1], getMDOrNull(Record[2]),
1571                          getDITypeRefOrNull(Record[3]), Record[4],
1572                          getMDString(Record[5]))),
1573         NextMetadataNo);
1574     NextMetadataNo++;
1575     break;
1576   }
1577   case bitc::METADATA_STRING_OLD: {
1578     std::string String(Record.begin(), Record.end());
1579 
1580     // Test for upgrading !llvm.loop.
1581     HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
1582     ++NumMDStringLoaded;
1583     Metadata *MD = MDString::get(Context, String);
1584     MetadataList.assignValue(MD, NextMetadataNo);
1585     NextMetadataNo++;
1586     break;
1587   }
1588   case bitc::METADATA_STRINGS: {
1589     auto CreateNextMDString = [&](StringRef Str) {
1590       ++NumMDStringLoaded;
1591       MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
1592       NextMetadataNo++;
1593     };
1594     if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
1595       return Err;
1596     break;
1597   }
1598   case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1599     if (Record.size() % 2 == 0)
1600       return error("Invalid record");
1601     unsigned ValueID = Record[0];
1602     if (ValueID >= ValueList.size())
1603       return error("Invalid record");
1604     if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1605       if (Error Err = parseGlobalObjectAttachment(
1606               *GO, ArrayRef<uint64_t>(Record).slice(1)))
1607         return Err;
1608     break;
1609   }
1610   case bitc::METADATA_KIND: {
1611     // Support older bitcode files that had METADATA_KIND records in a
1612     // block with METADATA_BLOCK_ID.
1613     if (Error Err = parseMetadataKindRecord(Record))
1614       return Err;
1615     break;
1616   }
1617   }
1618   return Error::success();
1619 #undef GET_OR_DISTINCT
1620 }
1621 
1622 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
1623     ArrayRef<uint64_t> Record, StringRef Blob,
1624     function_ref<void(StringRef)> CallBack) {
1625   // All the MDStrings in the block are emitted together in a single
1626   // record.  The strings are concatenated and stored in a blob along with
1627   // their sizes.
1628   if (Record.size() != 2)
1629     return error("Invalid record: metadata strings layout");
1630 
1631   unsigned NumStrings = Record[0];
1632   unsigned StringsOffset = Record[1];
1633   if (!NumStrings)
1634     return error("Invalid record: metadata strings with no strings");
1635   if (StringsOffset > Blob.size())
1636     return error("Invalid record: metadata strings corrupt offset");
1637 
1638   StringRef Lengths = Blob.slice(0, StringsOffset);
1639   SimpleBitstreamCursor R(Lengths);
1640 
1641   StringRef Strings = Blob.drop_front(StringsOffset);
1642   do {
1643     if (R.AtEndOfStream())
1644       return error("Invalid record: metadata strings bad length");
1645 
1646     unsigned Size = R.ReadVBR(6);
1647     if (Strings.size() < Size)
1648       return error("Invalid record: metadata strings truncated chars");
1649 
1650     CallBack(Strings.slice(0, Size));
1651     Strings = Strings.drop_front(Size);
1652   } while (--NumStrings);
1653 
1654   return Error::success();
1655 }
1656 
1657 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1658     GlobalObject &GO, ArrayRef<uint64_t> Record) {
1659   assert(Record.size() % 2 == 0);
1660   for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1661     auto K = MDKindMap.find(Record[I]);
1662     if (K == MDKindMap.end())
1663       return error("Invalid ID");
1664     MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1665     if (!MD)
1666       return error("Invalid metadata attachment");
1667     GO.addMetadata(K->second, *MD);
1668   }
1669   return Error::success();
1670 }
1671 
1672 /// Parse metadata attachments.
1673 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1674     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1675   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1676     return error("Invalid record");
1677 
1678   SmallVector<uint64_t, 64> Record;
1679   PlaceholderQueue Placeholders;
1680 
1681   while (true) {
1682     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1683 
1684     switch (Entry.Kind) {
1685     case BitstreamEntry::SubBlock: // Handled for us already.
1686     case BitstreamEntry::Error:
1687       return error("Malformed block");
1688     case BitstreamEntry::EndBlock:
1689       resolveForwardRefsAndPlaceholders(Placeholders);
1690       return Error::success();
1691     case BitstreamEntry::Record:
1692       // The interesting case.
1693       break;
1694     }
1695 
1696     // Read a metadata attachment record.
1697     Record.clear();
1698     ++NumMDRecordLoaded;
1699     switch (Stream.readRecord(Entry.ID, Record)) {
1700     default: // Default behavior: ignore.
1701       break;
1702     case bitc::METADATA_ATTACHMENT: {
1703       unsigned RecordLength = Record.size();
1704       if (Record.empty())
1705         return error("Invalid record");
1706       if (RecordLength % 2 == 0) {
1707         // A function attachment.
1708         if (Error Err = parseGlobalObjectAttachment(F, Record))
1709           return Err;
1710         continue;
1711       }
1712 
1713       // An instruction attachment.
1714       Instruction *Inst = InstructionList[Record[0]];
1715       for (unsigned i = 1; i != RecordLength; i = i + 2) {
1716         unsigned Kind = Record[i];
1717         DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1718         if (I == MDKindMap.end())
1719           return error("Invalid ID");
1720         if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1721           continue;
1722 
1723         auto Idx = Record[i + 1];
1724         if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
1725             !MetadataList.lookup(Idx)) {
1726           // Load the attachment if it is in the lazy-loadable range and hasn't
1727           // been loaded yet.
1728           lazyLoadOneMetadata(Idx, Placeholders);
1729           resolveForwardRefsAndPlaceholders(Placeholders);
1730         }
1731 
1732         Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
1733         if (isa<LocalAsMetadata>(Node))
1734           // Drop the attachment.  This used to be legal, but there's no
1735           // upgrade path.
1736           break;
1737         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1738         if (!MD)
1739           return error("Invalid metadata attachment");
1740 
1741         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1742           MD = upgradeInstructionLoopAttachment(*MD);
1743 
1744         if (I->second == LLVMContext::MD_tbaa) {
1745           assert(!MD->isTemporary() && "should load MDs before attachments");
1746           MD = UpgradeTBAANode(*MD);
1747         }
1748         Inst->setMetadata(I->second, MD);
1749       }
1750       break;
1751     }
1752     }
1753   }
1754 }
1755 
1756 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1757 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1758     SmallVectorImpl<uint64_t> &Record) {
1759   if (Record.size() < 2)
1760     return error("Invalid record");
1761 
1762   unsigned Kind = Record[0];
1763   SmallString<8> Name(Record.begin() + 1, Record.end());
1764 
1765   unsigned NewKind = TheModule.getMDKindID(Name.str());
1766   if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1767     return error("Conflicting METADATA_KIND records");
1768   return Error::success();
1769 }
1770 
1771 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1772 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1773   if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1774     return error("Invalid record");
1775 
1776   SmallVector<uint64_t, 64> Record;
1777 
1778   // Read all the records.
1779   while (true) {
1780     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1781 
1782     switch (Entry.Kind) {
1783     case BitstreamEntry::SubBlock: // Handled for us already.
1784     case BitstreamEntry::Error:
1785       return error("Malformed block");
1786     case BitstreamEntry::EndBlock:
1787       return Error::success();
1788     case BitstreamEntry::Record:
1789       // The interesting case.
1790       break;
1791     }
1792 
1793     // Read a record.
1794     Record.clear();
1795     ++NumMDRecordLoaded;
1796     unsigned Code = Stream.readRecord(Entry.ID, Record);
1797     switch (Code) {
1798     default: // Default behavior: ignore.
1799       break;
1800     case bitc::METADATA_KIND: {
1801       if (Error Err = parseMetadataKindRecord(Record))
1802         return Err;
1803       break;
1804     }
1805     }
1806   }
1807 }
1808 
1809 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1810   Pimpl = std::move(RHS.Pimpl);
1811   return *this;
1812 }
1813 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
1814     : Pimpl(std::move(RHS.Pimpl)) {}
1815 
1816 MetadataLoader::~MetadataLoader() = default;
1817 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1818                                BitcodeReaderValueList &ValueList,
1819                                bool IsImporting,
1820                                std::function<Type *(unsigned)> getTypeByID)
1821     : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
1822           Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
1823 
1824 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
1825   return Pimpl->parseMetadata(ModuleLevel);
1826 }
1827 
1828 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1829 
1830 /// Return the given metadata, creating a replaceable forward reference if
1831 /// necessary.
1832 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
1833   return Pimpl->getMetadataFwdRefOrLoad(Idx);
1834 }
1835 
1836 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1837   return Pimpl->getMDNodeFwdRefOrNull(Idx);
1838 }
1839 
1840 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1841   return Pimpl->lookupSubprogramForFunction(F);
1842 }
1843 
1844 Error MetadataLoader::parseMetadataAttachment(
1845     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1846   return Pimpl->parseMetadataAttachment(F, InstructionList);
1847 }
1848 
1849 Error MetadataLoader::parseMetadataKinds() {
1850   return Pimpl->parseMetadataKinds();
1851 }
1852 
1853 void MetadataLoader::setStripTBAA(bool StripTBAA) {
1854   return Pimpl->setStripTBAA(StripTBAA);
1855 }
1856 
1857 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1858 
1859 unsigned MetadataLoader::size() const { return Pimpl->size(); }
1860 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
1861