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