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