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