LLVM 24.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"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
27#include "llvm/IR/Argument.h"
28#include "llvm/IR/AutoUpgrade.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
35#include "llvm/IR/Instruction.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
41#include "llvm/IR/Type.h"
47
48#include <algorithm>
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <deque>
53#include <iterator>
54#include <limits>
55#include <optional>
56#include <string>
57#include <tuple>
58#include <utility>
59#include <vector>
60
61using namespace llvm;
62
63#define DEBUG_TYPE "bitcode-reader"
64
65STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
66STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
67STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
68
69/// Flag whether we need to import full type definitions for ThinLTO.
70/// Currently needed for Darwin and LLDB.
72 "import-full-type-definitions", cl::init(false), cl::Hidden,
73 cl::desc("Import full type definitions for ThinLTO."));
74
76 "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
77 cl::desc("Force disable the lazy-loading on-demand of metadata when "
78 "loading bitcode for importing."));
79
80namespace {
81
82class BitcodeReaderMetadataList {
83 /// Array of metadata references.
84 ///
85 /// Don't use std::vector here. Some versions of libc++ copy (instead of
86 /// move) on resize, and TrackingMDRef is very expensive to copy.
88
89 /// The set of indices in MetadataPtrs above of forward references that were
90 /// generated.
91 SmallDenseSet<unsigned, 1> ForwardReference;
92
93 /// The set of indices in MetadataPtrs above of Metadata that need to be
94 /// resolved.
95 SmallDenseSet<unsigned, 1> UnresolvedNodes;
96
97 /// Structures for resolving old type refs.
98 struct {
103 } OldTypeRefs;
104
105 LLVMContext &Context;
106
107 /// Maximum number of valid references. Forward references exceeding the
108 /// maximum must be invalid.
109 unsigned RefsUpperBound;
110
111public:
112 BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
113 : Context(C),
114 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
115 RefsUpperBound)) {}
116
117 using const_iterator = SmallVector<TrackingMDRef, 1>::const_iterator;
118
119 // vector compatibility methods
120 unsigned size() const { return MetadataPtrs.size(); }
121 void resize(unsigned N) { MetadataPtrs.resize(N); }
122 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
123 void clear() { MetadataPtrs.clear(); }
124 Metadata *back() const { return MetadataPtrs.back(); }
125 void pop_back() { MetadataPtrs.pop_back(); }
126 bool empty() const { return MetadataPtrs.empty(); }
127 const_iterator begin() const { return MetadataPtrs.begin(); }
128 const_iterator end() const { return MetadataPtrs.end(); }
129
130 Metadata *operator[](unsigned i) const { return MetadataPtrs[i]; }
131
132 Metadata *lookup(unsigned I) const {
133 if (I < MetadataPtrs.size())
134 return MetadataPtrs[I];
135 return nullptr;
136 }
137
138 void shrinkTo(unsigned N) {
139 assert(N <= size() && "Invalid shrinkTo request!");
140 assert(ForwardReference.empty() && "Unexpected forward refs");
141 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
142 MetadataPtrs.resize(N);
143 }
144
145 /// Return the given metadata, creating a replaceable forward reference if
146 /// necessary.
147 Metadata *getMetadataFwdRef(unsigned Idx);
148
149 /// Return the given metadata only if it is fully resolved.
150 ///
151 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
152 /// would give \c false.
153 Metadata *getMetadataIfResolved(unsigned Idx);
154
155 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
156 void assignValue(Metadata *MD, unsigned Idx);
157 void tryToResolveCycles();
158 bool hasFwdRefs() const { return !ForwardReference.empty(); }
159 int getNextFwdRef() {
160 assert(hasFwdRefs());
161 return *ForwardReference.begin();
162 }
163
164 /// Upgrade a type that had an MDString reference.
165 void addTypeRef(MDString &UUID, DICompositeType &CT);
166
167 /// Upgrade a type that had an MDString reference.
168 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
169
170 /// Upgrade a type array that may have MDString references.
171 Metadata *upgradeTypeArray(Metadata *MaybeTuple);
172
173private:
174 Metadata *resolveTypeArray(Metadata *MaybeTuple);
175};
176} // namespace
177
178static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
179
180void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
181 if (auto *MDN = dyn_cast<MDNode>(MD))
182 if (!MDN->isResolved())
183 UnresolvedNodes.insert(Idx);
184
185 if (Idx == size()) {
186 push_back(MD);
187 return;
188 }
189
190 if (Idx >= size())
191 resize(Idx + 1);
192
193 TrackingMDRef &OldMD = MetadataPtrs[Idx];
194 if (!OldMD) {
195 OldMD.reset(MD);
196 return;
197 }
198
199 // If there was a forward reference to this value, replace it.
200 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
201 PrevMD->replaceAllUsesWith(MD);
202 ForwardReference.erase(Idx);
203}
204
205Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
206 // Bail out for a clearly invalid value.
207 if (Idx >= RefsUpperBound)
208 return nullptr;
209
210 if (Idx >= size())
211 resize(Idx + 1);
212
213 if (Metadata *MD = MetadataPtrs[Idx])
214 return MD;
215
216 // Track forward refs to be resolved later.
217 ForwardReference.insert(Idx);
218
219 // Create and return a placeholder, which will later be RAUW'd.
220 ++NumMDNodeTemporary;
222 MetadataPtrs[Idx].reset(MD);
223 return MD;
224}
225
226Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
227 Metadata *MD = lookup(Idx);
228 if (auto *N = dyn_cast_or_null<MDNode>(MD))
229 if (!N->isResolved())
230 return nullptr;
231 return MD;
232}
233
234MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
235 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
236}
237
238void BitcodeReaderMetadataList::tryToResolveCycles() {
239 if (!ForwardReference.empty())
240 // Still forward references... can't resolve cycles.
241 return;
242
243 // Give up on finding a full definition for any forward decls that remain.
244 for (const auto &[UUID, CT] : OldTypeRefs.FwdDecls)
245 OldTypeRefs.Final.try_emplace(UUID, CT);
246 OldTypeRefs.FwdDecls.clear();
247
248 // Upgrade from old type ref arrays. In strange cases, this could add to
249 // OldTypeRefs.Unknown.
250 for (const auto &Array : OldTypeRefs.Arrays)
251 Array.second->replaceAllUsesWith(resolveTypeArray(Array.first.get()));
252 OldTypeRefs.Arrays.clear();
253
254 // Replace old string-based type refs with the resolved node, if possible.
255 // If we haven't seen the node, leave it to the verifier to complain about
256 // the invalid string reference.
257 for (const auto &Ref : OldTypeRefs.Unknown) {
258 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
259 Ref.second->replaceAllUsesWith(CT);
260 else
261 Ref.second->replaceAllUsesWith(Ref.first);
262 }
263 OldTypeRefs.Unknown.clear();
264
265 if (UnresolvedNodes.empty())
266 // Nothing to do.
267 return;
268
269 // Resolve any cycles.
270 for (unsigned I : UnresolvedNodes) {
271 auto &MD = MetadataPtrs[I];
272 auto *N = dyn_cast_or_null<MDNode>(MD);
273 if (!N)
274 continue;
275
276 assert(!N->isTemporary() && "Unexpected forward reference");
277 N->resolveCycles();
278 }
279
280 // Make sure we return early again until there's another unresolved ref.
281 UnresolvedNodes.clear();
282}
283
284void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
285 DICompositeType &CT) {
286 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
287 if (CT.isForwardDecl())
288 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
289 else
290 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
291}
292
293Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
294 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
295 if (LLVM_LIKELY(!UUID))
296 return MaybeUUID;
297
298 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
299 return CT;
300
301 auto &Ref = OldTypeRefs.Unknown[UUID];
302 if (!Ref)
304 return Ref.get();
305}
306
307Metadata *BitcodeReaderMetadataList::upgradeTypeArray(Metadata *MaybeTuple) {
308 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
309 if (!Tuple || Tuple->isDistinct())
310 return MaybeTuple;
311
312 // Look through the array immediately if possible.
313 if (!Tuple->isTemporary())
314 return resolveTypeArray(Tuple);
315
316 // Create and return a placeholder to use for now. Eventually
317 // resolveTypeArrays() will be resolve this forward reference.
318 OldTypeRefs.Arrays.emplace_back(
319 std::piecewise_construct, std::forward_as_tuple(Tuple),
320 std::forward_as_tuple(MDTuple::getTemporary(Context, {})));
321 return OldTypeRefs.Arrays.back().second.get();
322}
323
324Metadata *BitcodeReaderMetadataList::resolveTypeArray(Metadata *MaybeTuple) {
325 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
326 if (!Tuple || Tuple->isDistinct())
327 return MaybeTuple;
328
329 // Look through the DITypeArray, upgrading each DIType *.
331 Ops.reserve(Tuple->getNumOperands());
332 for (Metadata *MD : Tuple->operands())
333 Ops.push_back(upgradeTypeRef(MD));
334
335 return MDTuple::get(Context, Ops);
336}
337
338/// Rebuild the alias scope or domain \p Old with \p Ops, keeping its identity:
339/// a self reference has to point at the replacement, and a distinct node must
340/// not be uniqued. The first operand of both a scope and a domain is its name,
341/// which is either a string or a self reference.
344 LLVMContext &Context = Old->getContext();
345 if (Ops[0] != Old)
346 return Old->isDistinct() ? MDNode::getDistinct(Context, Ops)
347 : MDNode::get(Context, Ops);
348
349 Ops[0] = nullptr;
350 MDNode *New = MDNode::getDistinct(Context, Ops);
351 New->replaceOperandWith(0, New);
352 return New;
353}
354
357 unsigned NumOperands = Domain->getNumOperands();
358 bool HadDescription = NumOperands == 2;
359 // Already upgraded, or invalid and left to the verifier.
360 if (NumOperands == 0 || NumOperands > 2 ||
361 (HadDescription && mdconst::hasa<ConstantInt>(Domain->getOperand(1))))
362 return Domain;
363
364 MDNode *&Upgrade = Upgraded[Domain];
365 if (Upgrade)
366 return Upgrade;
367
368 LLVMContext &Context = Domain->getContext();
370 Domain->getOperand(0),
372 if (HadDescription)
373 Ops.push_back(Domain->getOperand(1));
374
376 return Upgrade;
377}
378
381 if (MDNode *Upgrade = Upgraded.lookup(Scope))
382 return Upgrade;
383
384 auto *Domain = cast<MDNode>(Scope->getOperand(1));
385
386 MDNode *UpgradedDomain = upgradeAliasScopeDomain(Domain, Upgraded);
387 if (UpgradedDomain == Domain)
388 return Scope;
389
390 SmallVector<Metadata *, 3> Ops(Scope->op_begin(), Scope->op_end());
391 Ops[1] = UpgradedDomain;
392 MDNode *Upgrade = rebuildScopeOrDomainNode(Scope, Ops);
393 Upgraded[Scope] = Upgrade;
394 return Upgrade;
395}
396
397namespace {
398
399class PlaceholderQueue {
400 // Placeholders would thrash around when moved, so store in a std::deque
401 // instead of some sort of vector.
402 std::deque<DistinctMDOperandPlaceholder> PHs;
403
404public:
405 ~PlaceholderQueue() {
406 assert(empty() &&
407 "PlaceholderQueue hasn't been flushed before being destroyed");
408 }
409 bool empty() const { return PHs.empty(); }
410 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
411 void flush(BitcodeReaderMetadataList &MetadataList);
412
413 /// Return the list of temporaries nodes in the queue, these need to be
414 /// loaded before we can flush the queue.
415 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
416 DenseSet<unsigned> &Temporaries) {
417 for (auto &PH : PHs) {
418 auto ID = PH.getID();
419 auto *MD = MetadataList.lookup(ID);
420 if (!MD) {
421 Temporaries.insert(ID);
422 continue;
423 }
424 auto *N = dyn_cast_or_null<MDNode>(MD);
425 if (N && N->isTemporary())
426 Temporaries.insert(ID);
427 }
428 }
429};
430
431} // end anonymous namespace
432
433DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
434 PHs.emplace_back(ID);
435 return PHs.back();
436}
437
438void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
439 while (!PHs.empty()) {
440 auto *MD = MetadataList.lookup(PHs.front().getID());
441 assert(MD && "Flushing placeholder on unassigned MD");
442#ifndef NDEBUG
443 if (auto *MDN = dyn_cast<MDNode>(MD))
444 assert(MDN->isResolved() &&
445 "Flushing Placeholder while cycles aren't resolved");
446#endif
447 PHs.front().replaceUseWith(MD);
448 PHs.pop_front();
449 }
450}
451
452static Error error(const Twine &Message) {
455}
456
458 BitcodeReaderMetadataList MetadataList;
459 BitcodeReaderValueList &ValueList;
460 BitstreamCursor &Stream;
461 LLVMContext &Context;
462 Module &TheModule;
463 MetadataLoaderCallbacks Callbacks;
464
465 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
466 /// to keep around the right "context" (Abbrev list) to be able to jump in
467 /// the middle of the metadata block and load any record.
468 BitstreamCursor IndexCursor;
469
470 /// Index that keeps track of MDString values.
471 std::vector<StringRef> MDStringRef;
472
473 /// On-demand loading of a single MDString. Requires the index above to be
474 /// populated.
475 MDString *lazyLoadOneMDString(unsigned Idx);
476
477 /// Index that keeps track of where to find a metadata record in the stream.
478 std::vector<uint64_t> GlobalMetadataBitPosIndex;
479
480 /// Cursor position of the start of the global decl attachments, to enable
481 /// loading using the index built for lazy loading, instead of forward
482 /// references.
483 uint64_t GlobalDeclAttachmentPos = 0;
484
485#ifndef NDEBUG
486 /// Baisic correctness check that we end up parsing all of the global decl
487 /// attachments.
488 unsigned NumGlobalDeclAttachSkipped = 0;
489 unsigned NumGlobalDeclAttachParsed = 0;
490#endif
491
492 /// Load the global decl attachments, using the index built for lazy loading.
493 Expected<bool> loadGlobalDeclAttachments();
494
495 /// Populate the index above to enable lazily loading of metadata, and load
496 /// the named metadata as well as the transitively referenced global
497 /// Metadata.
498 Expected<bool> lazyLoadModuleMetadataBlock();
499
500 /// On-demand loading of a single metadata. Requires the index above to be
501 /// populated.
502 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
503
504 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
505 // point from SP to CU after a block is completly parsed.
506 std::vector<std::pair<DICompileUnit *, unsigned>> CUSubprograms;
507
508 /// Functions that need to be matched with subprograms when upgrading old
509 /// metadata.
511
512 /// retainedNodes of these subprograms should be cleaned up from incorrectly
513 /// scoped local types.
514 /// See \ref DISubprogram::cleanupRetainedNodes.
515 SmallVector<DISubprogram *> NewDistinctSPs;
516
517 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
519
520 bool StripTBAA = false;
521 bool HasSeenOldLoopTags = false;
522
523 /// Rebuilt alias scopes and domains, so that upgraded domains get reused
524 /// correctly and to memoize.
525 DenseMap<MDNode *, MDNode *> UpgradedAliasScopes;
526 bool NeedUpgradeToDIGlobalVariableExpression = false;
527 bool NeedDeclareExpressionUpgrade = false;
528
529 /// Map DIGlobalVariable to generated DIGlobalVariable, if any.
531 GlobalVariableExpression;
532
533 /// Map DILocalScope to the enclosing DISubprogram, if any.
535
536 /// True if metadata is being parsed for a module being ThinLTO imported.
537 bool IsImporting = false;
538
539 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
540 PlaceholderQueue &Placeholders, StringRef Blob,
541 unsigned &NextMetadataNo);
542 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
543 function_ref<void(StringRef)> CallBack);
544 Error parseGlobalObjectAttachment(GlobalObject &GO,
546 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
547
548 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
549
550 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
551 void upgradeCUSubprograms() {
552 for (auto CU_SP : CUSubprograms)
553 if (auto *SPs =
554 dyn_cast_or_null<MDTuple>(MetadataList.lookup(CU_SP.second - 1)))
555 for (auto &Op : SPs->operands())
556 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
557 SP->replaceUnit(CU_SP.first);
558 CUSubprograms.clear();
559 }
560
561 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
562 void upgradeCUVariables() {
563 if (!NeedUpgradeToDIGlobalVariableExpression)
564 return;
565
566 // Upgrade list of variables attached to the CUs.
567 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
568 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
569 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
570 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
571 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
572 if (auto *GV =
573 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
574 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[GV];
575 if (!DGVE) {
577 Context, GV, DIExpression::get(Context, {}));
578 }
579 GVs->replaceOperandWith(I, DGVE);
580 }
581 }
582
583 // Upgrade variables attached to globals.
584 for (auto &GV : TheModule.globals()) {
586 GV.getMetadata(LLVMContext::MD_dbg, MDs);
587 GV.eraseMetadata(LLVMContext::MD_dbg);
588 for (auto *MD : MDs)
589 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
590 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
591 if (!DGVE) {
593 Context, DGV, DIExpression::get(Context, {}));
594 }
595 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
596 } else
597 GV.addMetadata(LLVMContext::MD_dbg, *MD);
598 }
599 }
600
601 DISubprogram *findEnclosingSubprogram(DILocalScope *S) {
602 if (!S)
603 return nullptr;
604 if (auto *SP = ParentSubprogram[S]) {
605 return SP;
606 }
607
608 DILocalScope *InitialScope = S;
610 while (S && !isa<DISubprogram>(S)) {
612 if (!Visited.insert(S).second)
613 break;
614 }
615
616 return ParentSubprogram[InitialScope] =
618 }
619
620 /// Map SP -> {Metadata} to store CU locals that should be attached to
621 /// subprogram retainedNodes list during CU upgrade.
622 using SPToEntitiesMap =
624
625 /// Retrieve the CU operand at position ListIndex, treat it as an MDTuple, and
626 /// remove all local debug info nodes from it. Fill SPToEntities map with
627 /// removed local nodes.
628 template <typename NodeT>
629 void upgradeOneCULocalsList(SPToEntitiesMap &SPToEntities, DICompileUnit *CU,
630 unsigned ListIndex) {
631 MDTuple *List = cast_if_present<MDTuple>(CU->getOperand(ListIndex));
632 if (!List)
633 return;
634
635 if (llvm::all_of(List->operands(), [](Metadata *MD) {
636 return !isa_and_nonnull<DILocalScope>(getScope(cast<NodeT>(MD)));
637 }))
638 return;
639
641 for (Metadata *MD : List->operands()) {
642 DILocalScope *LS =
644 if (!LS)
645 MDs.push_back(MD);
646 else if (auto *SP = findEnclosingSubprogram(LS))
647 SPToEntities[SP].push_back(MD);
648 }
649
650 CU->replaceOperandWith(ListIndex, MDNode::get(CU->getContext(), MDs));
651 }
652
653 /// Move function-local entities from DICompileUnit's 'imports',
654 /// 'enums', and 'globals' fields to DISubprogram's retainedNodes.
655 void upgradeCULocals() {
656 NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu");
657 if (!CUNodes)
658 return;
659
660 SPToEntitiesMap SPToEntities;
661 for (MDNode *N : CUNodes->operands()) {
663 if (!CU)
664 continue;
665
666 // Remove all static local variables from CU's globals list.
667 upgradeOneCULocalsList<DIGlobalVariableExpression>(SPToEntities, CU, 6);
668 // Remove all local imports from CU's imports list.
669 upgradeOneCULocalsList<DIImportedEntity>(SPToEntities, CU, 7);
670 // Remove all local types from CU's enums list.
671 upgradeOneCULocalsList<DICompositeType>(SPToEntities, CU, 4);
672
673 // Retain local entities removed from the CU in their corresponding
674 // subprograms.
675 for (auto &[SP, Nodes] : SPToEntities)
676 SP->retainNodes(Nodes.begin(), Nodes.end());
677 SPToEntities.clear();
678 }
679
680 ParentSubprogram.clear();
681 }
682
683 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
684 /// describes a function argument.
685 void upgradeDeclareExpressions(Function &F) {
686 if (!NeedDeclareExpressionUpgrade)
687 return;
688
689 auto UpdateDeclareIfNeeded = [&](auto *Declare) {
690 auto *DIExpr = Declare->getExpression();
691 if (!DIExpr || !DIExpr->startsWithDeref() ||
692 !isa_and_nonnull<Argument>(Declare->getAddress()))
693 return;
695 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
696 Declare->setExpression(DIExpression::get(Context, Ops));
697 };
698
699 for (auto &BB : F)
700 for (auto &I : BB) {
701 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
702 if (DVR.isDbgDeclare())
703 UpdateDeclareIfNeeded(&DVR);
704 }
705 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
706 UpdateDeclareIfNeeded(DDI);
707 }
708 }
709
710 /// Upgrade the expression from previous versions.
711 Error upgradeDIExpression(uint64_t FromVersion,
714 auto N = Expr.size();
715 switch (FromVersion) {
716 default:
717 return error("Invalid record");
718 case 0:
719 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
720 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
721 [[fallthrough]];
722 case 1:
723 // Move DW_OP_deref to the end.
724 if (N && Expr[0] == dwarf::DW_OP_deref) {
725 auto End = Expr.end();
726 if (Expr.size() >= 3 &&
727 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
728 End = std::prev(End, 3);
729 std::move(std::next(Expr.begin()), End, Expr.begin());
730 *std::prev(End) = dwarf::DW_OP_deref;
731 }
732 NeedDeclareExpressionUpgrade = true;
733 [[fallthrough]];
734 case 2: {
735 // Change DW_OP_plus to DW_OP_plus_uconst.
736 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
737 auto SubExpr = ArrayRef<uint64_t>(Expr);
738 while (!SubExpr.empty()) {
739 // Skip past other operators with their operands
740 // for this version of the IR, obtained from
741 // from historic DIExpression::ExprOperand::getSize().
742 size_t HistoricSize;
743 switch (SubExpr.front()) {
744 default:
745 HistoricSize = 1;
746 break;
747 case dwarf::DW_OP_constu:
748 case dwarf::DW_OP_minus:
749 case dwarf::DW_OP_plus:
750 HistoricSize = 2;
751 break;
753 HistoricSize = 3;
754 break;
755 }
756
757 // If the expression is malformed, make sure we don't
758 // copy more elements than we should.
759 HistoricSize = std::min(SubExpr.size(), HistoricSize);
760 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
761
762 switch (SubExpr.front()) {
763 case dwarf::DW_OP_plus:
764 Buffer.push_back(dwarf::DW_OP_plus_uconst);
765 Buffer.append(Args.begin(), Args.end());
766 break;
767 case dwarf::DW_OP_minus:
768 Buffer.push_back(dwarf::DW_OP_constu);
769 Buffer.append(Args.begin(), Args.end());
770 Buffer.push_back(dwarf::DW_OP_minus);
771 break;
772 default:
773 Buffer.push_back(*SubExpr.begin());
774 Buffer.append(Args.begin(), Args.end());
775 break;
776 }
777
778 // Continue with remaining elements.
779 SubExpr = SubExpr.slice(HistoricSize);
780 }
781 Expr = MutableArrayRef<uint64_t>(Buffer);
782 [[fallthrough]];
783 }
784 case 3:
785 // Up-to-date!
786 break;
787 }
788
789 return Error::success();
790 }
791
792 /// Specifies which kind of debug info upgrade should be performed.
793 ///
794 /// The upgrade of compile units' enums: and imports: fields is performed
795 /// only when module level metadata block is loaded (i.e. all elements of
796 /// "llvm.dbg.cu" named metadata node are loaded).
797 enum class DebugInfoUpgradeMode {
798 /// No debug info upgrade.
799 None,
800 /// Debug info upgrade after loading function-level metadata block.
801 Partial,
802 /// Debug info upgrade after loading module-level metadata block.
803 ModuleLevel,
804 };
805
806 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
807 if (Mode == DebugInfoUpgradeMode::None)
808 return;
809 upgradeCUSubprograms();
810 upgradeCUVariables();
811 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
812 upgradeCULocals();
813 }
814
815 /// Prepare loaded metadata nodes to be used by loader clients.
816 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
817 DebugInfoUpgradeMode DIUpgradeMode) {
818 resolveForwardRefsAndPlaceholders(Placeholders);
819 upgradeDebugInfo(DIUpgradeMode);
821 LLVM_DEBUG(llvm::dbgs() << "Resolved loaded metadata. Cleaned up "
822 << NewDistinctSPs.size() << " subprogram(s).\n");
823 NewDistinctSPs.clear();
824 }
825
826 void callMDTypeCallback(Metadata **Val, unsigned TypeID);
827
828public:
830 BitcodeReaderValueList &ValueList,
831 MetadataLoaderCallbacks Callbacks, bool IsImporting)
832 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
833 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
834 TheModule(TheModule), Callbacks(std::move(Callbacks)),
835 IsImporting(IsImporting) {}
836
837 Error parseMetadata(bool ModuleLevel);
838
839 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
840
842 if (ID < MDStringRef.size())
843 return lazyLoadOneMDString(ID);
844 if (auto *MD = MetadataList.lookup(ID))
845 return MD;
846 // If lazy-loading is enabled, we try recursively to load the operand
847 // instead of creating a temporary.
848 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
849 PlaceholderQueue Placeholders;
850 lazyLoadOneMetadata(ID, Placeholders);
851 LLVM_DEBUG(llvm::dbgs() << "\nLazy metadata loading: ");
852 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
853 return MetadataList.lookup(ID);
854 }
855 return MetadataList.getMetadataFwdRef(ID);
856 }
857
859 return FunctionsWithSPs.lookup(F);
860 }
861
862 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
863
864 /// Mark any domains in \p ScopeList that don't have a disjointness
865 /// flag as non-disjoint. Returns the original list if there are no changes.
867 if (MDNode *Upgrade = UpgradedAliasScopes.lookup(ScopeList))
868 return Upgrade;
869
871 bool Changed = false;
872 for (const MDOperand &Op : ScopeList->operands()) {
873 Metadata *Scope = Op;
874 if (auto *ScopeNode = dyn_cast<MDNode>(Op))
875 Scope = upgradeAliasScope(ScopeNode, UpgradedAliasScopes);
876 Changed |= Scope != Op.get();
877 Ops.push_back(Scope);
878 }
879 if (!Changed)
880 return ScopeList;
881
882 MDNode *Upgrade = MDNode::get(ScopeList->getContext(), Ops);
883 UpgradedAliasScopes[ScopeList] = Upgrade;
884 return Upgrade;
885 }
886
888 ArrayRef<Instruction *> InstructionList);
889
891
892 void setStripTBAA(bool Value) { StripTBAA = Value; }
893 bool isStrippingTBAA() const { return StripTBAA; }
894
895 unsigned size() const { return MetadataList.size(); }
896 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
897 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
898};
899
901MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
902 IndexCursor = Stream;
904 GlobalDeclAttachmentPos = 0;
905 // Get the abbrevs, and preload record positions to make them lazy-loadable.
906 while (true) {
907 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
908 BitstreamEntry Entry;
909 if (Error E =
910 IndexCursor
911 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
912 .moveInto(Entry))
913 return std::move(E);
914
915 switch (Entry.Kind) {
916 case BitstreamEntry::SubBlock: // Handled for us already.
918 return error("Malformed block");
920 return true;
921 }
923 // The interesting case.
924 ++NumMDRecordLoaded;
925 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
926 unsigned Code;
927 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
928 return std::move(E);
929 switch (Code) {
931 // Rewind and parse the strings.
932 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
933 return std::move(Err);
934 StringRef Blob;
935 Record.clear();
936 if (Expected<unsigned> MaybeRecord =
937 IndexCursor.readRecord(Entry.ID, Record, &Blob))
938 ;
939 else
940 return MaybeRecord.takeError();
941 unsigned NumStrings = Record[0];
942 MDStringRef.reserve(NumStrings);
943 auto IndexNextMDString = [&](StringRef Str) {
944 MDStringRef.push_back(Str);
945 };
946 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
947 return std::move(Err);
948 break;
949 }
951 // This is the offset to the index, when we see this we skip all the
952 // records and load only an index to these.
953 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
954 return std::move(Err);
955 Record.clear();
956 if (Expected<unsigned> MaybeRecord =
957 IndexCursor.readRecord(Entry.ID, Record))
958 ;
959 else
960 return MaybeRecord.takeError();
961 if (Record.size() != 2)
962 return error("Invalid record");
963 auto Offset = Record[0] + (Record[1] << 32);
964 auto BeginPos = IndexCursor.GetCurrentBitNo();
965 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
966 return std::move(Err);
967 Expected<BitstreamEntry> MaybeEntry =
968 IndexCursor.advanceSkippingSubblocks(
970 if (!MaybeEntry)
971 return MaybeEntry.takeError();
972 Entry = MaybeEntry.get();
974 "Corrupted bitcode: Expected `Record` when trying to find the "
975 "Metadata index");
976 Record.clear();
977 if (Expected<unsigned> MaybeCode =
978 IndexCursor.readRecord(Entry.ID, Record))
979 assert(MaybeCode.get() == bitc::METADATA_INDEX &&
980 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
981 "find the Metadata index");
982 else
983 return MaybeCode.takeError();
984 // Delta unpack
985 auto CurrentValue = BeginPos;
986 GlobalMetadataBitPosIndex.reserve(Record.size());
987 for (auto &Elt : Record) {
988 CurrentValue += Elt;
989 GlobalMetadataBitPosIndex.push_back(CurrentValue);
990 }
991 break;
992 }
994 // We don't expect to get there, the Index is loaded when we encounter
995 // the offset.
996 return error("Corrupted Metadata block");
997 case bitc::METADATA_NAME: {
998 // Named metadata need to be materialized now and aren't deferred.
999 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
1000 return std::move(Err);
1001 Record.clear();
1002
1003 unsigned Code;
1004 if (Expected<unsigned> MaybeCode =
1005 IndexCursor.readRecord(Entry.ID, Record)) {
1006 Code = MaybeCode.get();
1007 assert(Code == bitc::METADATA_NAME);
1008 } else
1009 return MaybeCode.takeError();
1010
1011 // Read name of the named metadata.
1012 SmallString<8> Name(Record.begin(), Record.end());
1013 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
1014 Code = MaybeCode.get();
1015 else
1016 return MaybeCode.takeError();
1017
1018 // Named Metadata comes in two parts, we expect the name to be followed
1019 // by the node
1020 Record.clear();
1021 if (Expected<unsigned> MaybeNextBitCode =
1022 IndexCursor.readRecord(Code, Record))
1023 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
1024 else
1025 return MaybeNextBitCode.takeError();
1026
1027 // Read named metadata elements.
1028 unsigned Size = Record.size();
1029 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1030 for (unsigned i = 0; i != Size; ++i) {
1031 // FIXME: We could use a placeholder here, however NamedMDNode are
1032 // taking MDNode as operand and not using the Metadata infrastructure.
1033 // It is acknowledged by 'TODO: Inherit from Metadata' in the
1034 // NamedMDNode class definition.
1035 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1036 assert(MD && "Invalid metadata: expect fwd ref to MDNode");
1037 NMD->addOperand(MD);
1038 }
1039 break;
1040 }
1042 if (!GlobalDeclAttachmentPos)
1043 GlobalDeclAttachmentPos = SavedPos;
1044#ifndef NDEBUG
1045 NumGlobalDeclAttachSkipped++;
1046#endif
1047 break;
1048 }
1087 // We don't expect to see any of these, if we see one, give up on
1088 // lazy-loading and fallback.
1089 MDStringRef.clear();
1090 GlobalMetadataBitPosIndex.clear();
1091 return false;
1092 }
1093 break;
1094 }
1095 }
1096 }
1097}
1098
1099// Load the global decl attachments after building the lazy loading index.
1100// We don't load them "lazily" - all global decl attachments must be
1101// parsed since they aren't materialized on demand. However, by delaying
1102// their parsing until after the index is created, we can use the index
1103// instead of creating temporaries.
1104Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1105 // Nothing to do if we didn't find any of these metadata records.
1106 if (!GlobalDeclAttachmentPos)
1107 return true;
1108 // Use a temporary cursor so that we don't mess up the main Stream cursor or
1109 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
1110 BitstreamCursor TempCursor = Stream;
1111 SmallVector<uint64_t, 64> Record;
1112 // Jump to the position before the first global decl attachment, so we can
1113 // scan for the first BitstreamEntry record.
1114 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
1115 return std::move(Err);
1116 while (true) {
1117 BitstreamEntry Entry;
1118 if (Error E =
1119 TempCursor
1120 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
1121 .moveInto(Entry))
1122 return std::move(E);
1123
1124 switch (Entry.Kind) {
1125 case BitstreamEntry::SubBlock: // Handled for us already.
1127 return error("Malformed block");
1129 // Check that we parsed them all.
1130 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1131 return true;
1133 break;
1134 }
1135 uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
1136 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
1137 if (!MaybeCode)
1138 return MaybeCode.takeError();
1139 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
1140 // Anything other than a global decl attachment signals the end of
1141 // these records. Check that we parsed them all.
1142 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1143 return true;
1144 }
1145#ifndef NDEBUG
1146 NumGlobalDeclAttachParsed++;
1147#endif
1148 // FIXME: we need to do this early because we don't materialize global
1149 // value explicitly.
1150 if (Error Err = TempCursor.JumpToBit(CurrentPos))
1151 return std::move(Err);
1152 Record.clear();
1153 if (Expected<unsigned> MaybeRecord =
1154 TempCursor.readRecord(Entry.ID, Record))
1155 ;
1156 else
1157 return MaybeRecord.takeError();
1158 if (Record.size() % 2 == 0)
1159 return error("Invalid record");
1160 unsigned ValueID = Record[0];
1161 if (ValueID >= ValueList.size())
1162 return error("Invalid record");
1163 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
1164 // Need to save and restore the current position since
1165 // parseGlobalObjectAttachment will resolve all forward references which
1166 // would require parsing from locations stored in the index.
1167 CurrentPos = TempCursor.GetCurrentBitNo();
1168 if (Error Err = parseGlobalObjectAttachment(
1169 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1170 return std::move(Err);
1171 if (Error Err = TempCursor.JumpToBit(CurrentPos))
1172 return std::move(Err);
1173 }
1174 }
1175}
1176
1177void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(Metadata **Val,
1178 unsigned TypeID) {
1179 if (Callbacks.MDType) {
1180 (*Callbacks.MDType)(Val, TypeID, Callbacks.GetTypeByID,
1181 Callbacks.GetContainedTypeID);
1182 }
1183}
1184
1185/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1186/// module level metadata.
1188 llvm::TimeTraceScope timeScope("Parse metadata");
1189 if (!ModuleLevel && MetadataList.hasFwdRefs())
1190 return error("Invalid metadata: fwd refs into function blocks");
1191
1192 // Record the entry position so that we can jump back here and efficiently
1193 // skip the whole block in case we lazy-load.
1194 auto EntryPos = Stream.GetCurrentBitNo();
1195
1196 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1197 return Err;
1198
1200 PlaceholderQueue Placeholders;
1201 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1202 : DebugInfoUpgradeMode::Partial;
1203
1204 // We lazy-load module-level metadata: we build an index for each record, and
1205 // then load individual record as needed, starting with the named metadata.
1206 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1208 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1209 if (!SuccessOrErr)
1210 return SuccessOrErr.takeError();
1211 if (SuccessOrErr.get()) {
1212 // An index was successfully created and we will be able to load metadata
1213 // on-demand.
1214 MetadataList.resize(MDStringRef.size() +
1215 GlobalMetadataBitPosIndex.size());
1216
1217 // Now that we have built the index, load the global decl attachments
1218 // that were deferred during that process. This avoids creating
1219 // temporaries.
1220 SuccessOrErr = loadGlobalDeclAttachments();
1221 if (!SuccessOrErr)
1222 return SuccessOrErr.takeError();
1223 assert(SuccessOrErr.get());
1224
1225 // Reading the named metadata created forward references and/or
1226 // placeholders, that we flush here.
1227 LLVM_DEBUG(llvm::dbgs() << "\nNamed metadata loading: ");
1228 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1229 // Return at the beginning of the block, since it is easy to skip it
1230 // entirely from there.
1231 Stream.ReadBlockEnd(); // Pop the abbrev block context.
1232 if (Error Err = IndexCursor.JumpToBit(EntryPos))
1233 return Err;
1234 if (Error Err = Stream.SkipBlock()) {
1235 // FIXME this drops the error on the floor, which
1236 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1237 consumeError(std::move(Err));
1238 return Error::success();
1239 }
1240 return Error::success();
1241 }
1242 // Couldn't load an index, fallback to loading all the block "old-style".
1243 }
1244
1245 unsigned NextMetadataNo = MetadataList.size();
1246
1247 // Read all the records.
1248 while (true) {
1249 BitstreamEntry Entry;
1250 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1251 return E;
1252
1253 switch (Entry.Kind) {
1254 case BitstreamEntry::SubBlock: // Handled for us already.
1256 return error("Malformed block");
1258 LLVM_DEBUG(llvm::dbgs() << "\nEager metadata loading: ");
1259 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1260 return Error::success();
1262 // The interesting case.
1263 break;
1264 }
1265
1266 // Read a record.
1267 Record.clear();
1268 StringRef Blob;
1269 ++NumMDRecordLoaded;
1270 if (Expected<unsigned> MaybeCode =
1271 Stream.readRecord(Entry.ID, Record, &Blob)) {
1272 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1273 Blob, NextMetadataNo))
1274 return Err;
1275 } else
1276 return MaybeCode.takeError();
1277 }
1278}
1279
1280MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
1281 ++NumMDStringLoaded;
1282 if (Metadata *MD = MetadataList.lookup(ID))
1283 return cast<MDString>(MD);
1284 auto MDS = MDString::get(Context, MDStringRef[ID]);
1285 MetadataList.assignValue(MDS, ID);
1286 return MDS;
1287}
1288
1289void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1290 unsigned ID, PlaceholderQueue &Placeholders) {
1291 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1292 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
1293 // Lookup first if the metadata hasn't already been loaded.
1294 if (auto *MD = MetadataList.lookup(ID)) {
1295 auto *N = dyn_cast<MDNode>(MD);
1296 // If the node is not an MDNode, or if it is not temporary, then
1297 // we're done.
1298 if (!N || !N->isTemporary())
1299 return;
1300 }
1302 StringRef Blob;
1303 if (Error Err = IndexCursor.JumpToBit(
1304 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1305 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1306 Twine(toString(std::move(Err))));
1307 BitstreamEntry Entry;
1308 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1309 // FIXME this drops the error on the floor.
1310 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1311 Twine(toString(std::move(E))));
1312 ++NumMDRecordLoaded;
1313 if (Expected<unsigned> MaybeCode =
1314 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
1315 if (Error Err =
1316 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1317 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1318 Twine(toString(std::move(Err))));
1319 } else
1320 report_fatal_error("Can't lazyload MD: " +
1321 Twine(toString(MaybeCode.takeError())));
1322}
1323
1324/// Ensure that all forward-references and placeholders are resolved.
1325/// Iteratively lazy-loading metadata on-demand if needed.
1326void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1327 PlaceholderQueue &Placeholders) {
1328 DenseSet<unsigned> Temporaries;
1329 while (true) {
1330 // Populate Temporaries with the placeholders that haven't been loaded yet.
1331 Placeholders.getTemporaries(MetadataList, Temporaries);
1332
1333 // If we don't have any temporary, or FwdReference, we're done!
1334 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1335 break;
1336
1337 // First, load all the temporaries. This can add new placeholders or
1338 // forward references.
1339 for (auto ID : Temporaries)
1340 lazyLoadOneMetadata(ID, Placeholders);
1341 Temporaries.clear();
1342
1343 // Second, load the forward-references. This can also add new placeholders
1344 // or forward references.
1345 while (MetadataList.hasFwdRefs())
1346 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1347 }
1348 // At this point we don't have any forward reference remaining, or temporary
1349 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1350 // as resolved.
1351 MetadataList.tryToResolveCycles();
1352
1353 // Finally, everything is in place, we can replace the placeholders operands
1354 // with the final node they refer to.
1355 Placeholders.flush(MetadataList);
1356}
1357
1358static Value *getValueFwdRef(BitcodeReaderValueList &ValueList, unsigned Idx,
1359 Type *Ty, unsigned TyID) {
1360 Value *V = ValueList.getValueFwdRef(Idx, Ty, TyID,
1361 /*ConstExprInsertBB*/ nullptr);
1362 if (V)
1363 return V;
1364
1365 // This is a reference to a no longer supported constant expression.
1366 // Pretend that the constant was deleted, which will replace metadata
1367 // references with poison.
1368 // TODO: This is a rather indirect check. It would be more elegant to use
1369 // a separate ErrorInfo for constant materialization failure and thread
1370 // the error reporting through getValueFwdRef().
1371 if (Idx < ValueList.size() && ValueList[Idx] &&
1372 ValueList[Idx]->getType() == Ty)
1373 return PoisonValue::get(Ty);
1374
1375 return nullptr;
1376}
1377
1378Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1379 SmallVectorImpl<uint64_t> &Record, unsigned Code,
1380 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1381
1382 bool IsDistinct = false;
1383 auto getMD = [&](unsigned ID) -> Metadata * {
1384 if (ID < MDStringRef.size())
1385 return lazyLoadOneMDString(ID);
1386 if (!IsDistinct) {
1387 if (auto *MD = MetadataList.lookup(ID))
1388 return MD;
1389 // If lazy-loading is enabled, we try recursively to load the operand
1390 // instead of creating a temporary.
1391 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1392 // Create a temporary for the node that is referencing the operand we
1393 // will lazy-load. It is needed before recursing in case there are
1394 // uniquing cycles.
1395 MetadataList.getMetadataFwdRef(NextMetadataNo);
1396 lazyLoadOneMetadata(ID, Placeholders);
1397 return MetadataList.lookup(ID);
1398 }
1399 // Return a temporary.
1400 return MetadataList.getMetadataFwdRef(ID);
1401 }
1402 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1403 return MD;
1404 return &Placeholders.getPlaceholderOp(ID);
1405 };
1406 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1407 if (ID)
1408 return getMD(ID - 1);
1409 return nullptr;
1410 };
1411 auto getMDString = [&](unsigned ID) -> MDString * {
1412 // This requires that the ID is not really a forward reference. In
1413 // particular, the MDString must already have been resolved.
1414 auto MDS = getMDOrNull(ID);
1415 return cast_or_null<MDString>(MDS);
1416 };
1417
1418 // Support for old type refs.
1419 auto getDITypeRefOrNull = [&](unsigned ID) {
1420 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1421 };
1422
1423 auto getMetadataOrConstant = [&](bool IsMetadata,
1424 uint64_t Entry) -> Metadata * {
1425 if (IsMetadata)
1426 return getMDOrNull(Entry);
1428 ConstantInt::get(Type::getInt64Ty(Context), Entry));
1429 };
1430
1431#define GET_OR_DISTINCT(CLASS, ARGS) \
1432 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1433
1434 switch (Code) {
1435 default: // Default behavior: ignore.
1436 break;
1437 case bitc::METADATA_NAME: {
1438 // Read name of the named metadata.
1439 SmallString<8> Name(Record.begin(), Record.end());
1440 Record.clear();
1441 if (Error E = Stream.ReadCode().moveInto(Code))
1442 return E;
1443
1444 ++NumMDRecordLoaded;
1445 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1446 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1447 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1448 } else
1449 return MaybeNextBitCode.takeError();
1450
1451 // Read named metadata elements.
1452 unsigned Size = Record.size();
1453 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1454 for (unsigned i = 0; i != Size; ++i) {
1455 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1456 if (!MD)
1457 return error("Invalid named metadata: expect fwd ref to MDNode");
1458 NMD->addOperand(MD);
1459 }
1460 break;
1461 }
1463 // Deprecated, but still needed to read old bitcode files.
1464 // This is a LocalAsMetadata record, the only type of function-local
1465 // metadata.
1466 if (Record.size() % 2 == 1)
1467 return error("Invalid record");
1468
1469 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1470 // to be legal, but there's no upgrade path.
1471 auto dropRecord = [&] {
1472 MetadataList.assignValue(MDNode::get(Context, {}), NextMetadataNo);
1473 NextMetadataNo++;
1474 };
1475 if (Record.size() != 2) {
1476 dropRecord();
1477 break;
1478 }
1479
1480 unsigned TyID = Record[0];
1481 Type *Ty = Callbacks.GetTypeByID(TyID);
1482 if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy()) {
1483 dropRecord();
1484 break;
1485 }
1486
1487 Value *V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1488 /*ConstExprInsertBB*/ nullptr);
1489 if (!V)
1490 return error("Invalid value reference from old fn metadata");
1491
1492 MetadataList.assignValue(LocalAsMetadata::get(V), NextMetadataNo);
1493 NextMetadataNo++;
1494 break;
1495 }
1497 // Deprecated, but still needed to read old bitcode files.
1498 if (Record.size() % 2 == 1)
1499 return error("Invalid record");
1500
1501 unsigned Size = Record.size();
1503 for (unsigned i = 0; i != Size; i += 2) {
1504 unsigned TyID = Record[i];
1505 Type *Ty = Callbacks.GetTypeByID(TyID);
1506 if (!Ty)
1507 return error("Invalid record");
1508 if (Ty->isMetadataTy())
1509 Elts.push_back(getMD(Record[i + 1]));
1510 else if (!Ty->isVoidTy()) {
1511 Value *V = getValueFwdRef(ValueList, Record[i + 1], Ty, TyID);
1512 if (!V)
1513 return error("Invalid value reference from old metadata");
1516 "Expected non-function-local metadata");
1517 callMDTypeCallback(&MD, TyID);
1518 Elts.push_back(MD);
1519 } else
1520 Elts.push_back(nullptr);
1521 }
1522 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1523 NextMetadataNo++;
1524 break;
1525 }
1526 case bitc::METADATA_VALUE: {
1527 if (Record.size() != 2)
1528 return error("Invalid record");
1529
1530 unsigned TyID = Record[0];
1531 Type *Ty = Callbacks.GetTypeByID(TyID);
1532 if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy())
1533 return error("Invalid record");
1534
1535 Value *V = getValueFwdRef(ValueList, Record[1], Ty, TyID);
1536 if (!V)
1537 return error("Invalid value reference from metadata");
1538
1540 callMDTypeCallback(&MD, TyID);
1541 MetadataList.assignValue(MD, NextMetadataNo);
1542 NextMetadataNo++;
1543 break;
1544 }
1546 IsDistinct = true;
1547 [[fallthrough]];
1548 case bitc::METADATA_NODE: {
1550 Elts.reserve(Record.size());
1551 for (unsigned ID : Record)
1552 Elts.push_back(getMDOrNull(ID));
1553 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1554 : MDNode::get(Context, Elts),
1555 NextMetadataNo);
1556 NextMetadataNo++;
1557 break;
1558 }
1560 // 5: inlinedAt, 6: isImplicit, 8: Key Instructions fields.
1561 if (Record.size() != 5 && Record.size() != 6 && Record.size() != 8)
1562 return error("Invalid record");
1563
1564 IsDistinct = Record[0];
1565 unsigned Line = Record[1];
1566 unsigned Column = Record[2];
1567 Metadata *Scope = getMD(Record[3]);
1568 Metadata *InlinedAt = getMDOrNull(Record[4]);
1569 bool ImplicitCode = Record.size() >= 6 && Record[5];
1570 uint64_t AtomGroup = Record.size() == 8 ? Record[6] : 0;
1571 uint8_t AtomRank = Record.size() == 8 ? Record[7] : 0;
1572 MetadataList.assignValue(
1573 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
1574 ImplicitCode, AtomGroup, AtomRank)),
1575 NextMetadataNo);
1576 NextMetadataNo++;
1577 break;
1578 }
1580 if (Record.size() < 4)
1581 return error("Invalid record");
1582
1583 IsDistinct = Record[0];
1584 unsigned Tag = Record[1];
1585 unsigned Version = Record[2];
1586
1587 if (Tag >= 1u << 16 || Version != 0)
1588 return error("Invalid record");
1589
1590 auto *Header = getMDString(Record[3]);
1592 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1593 DwarfOps.push_back(getMDOrNull(Record[I]));
1594 MetadataList.assignValue(
1595 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1596 NextMetadataNo);
1597 NextMetadataNo++;
1598 break;
1599 }
1601 Metadata *Val = nullptr;
1602 // Operand 'count' is interpreted as:
1603 // - Signed integer (version 0)
1604 // - Metadata node (version 1)
1605 // Operand 'lowerBound' is interpreted as:
1606 // - Signed integer (version 0 and 1)
1607 // - Metadata node (version 2)
1608 // Operands 'upperBound' and 'stride' are interpreted as:
1609 // - Metadata node (version 2)
1610 switch (Record[0] >> 1) {
1611 case 0:
1612 Val = GET_OR_DISTINCT(DISubrange,
1613 (Context, Record[1], unrotateSign(Record[2])));
1614 break;
1615 case 1:
1616 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1617 unrotateSign(Record[2])));
1618 break;
1619 case 2:
1620 Val = GET_OR_DISTINCT(
1621 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1622 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1623 break;
1624 default:
1625 return error("Invalid record: Unsupported version of DISubrange");
1626 }
1627
1628 MetadataList.assignValue(Val, NextMetadataNo);
1629 IsDistinct = Record[0] & 1;
1630 NextMetadataNo++;
1631 break;
1632 }
1634 Metadata *Val = nullptr;
1635 Val = GET_OR_DISTINCT(DIGenericSubrange,
1636 (Context, getMDOrNull(Record[1]),
1637 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1638 getMDOrNull(Record[4])));
1639
1640 MetadataList.assignValue(Val, NextMetadataNo);
1641 IsDistinct = Record[0] & 1;
1642 NextMetadataNo++;
1643 break;
1644 }
1646 if (Record.size() < 3)
1647 return error("Invalid record");
1648
1649 IsDistinct = Record[0] & 1;
1650 bool IsUnsigned = Record[0] & 2;
1651 bool IsBigInt = Record[0] & 4;
1652 APInt Value;
1653
1654 if (IsBigInt) {
1655 const uint64_t BitWidth = Record[1];
1656 const size_t NumWords = Record.size() - 3;
1657 Value = readWideAPInt(ArrayRef(&Record[3], NumWords), BitWidth);
1658 } else
1659 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1660
1661 MetadataList.assignValue(
1662 GET_OR_DISTINCT(DIEnumerator,
1663 (Context, Value, IsUnsigned, getMDString(Record[2]))),
1664 NextMetadataNo);
1665 NextMetadataNo++;
1666 break;
1667 }
1669 if (Record.size() < 6 || Record.size() > 12)
1670 return error("Invalid record");
1671
1672 IsDistinct = Record[0] & 1;
1673 bool SizeIsMetadata = Record[0] & 2;
1674 DINode::DIFlags Flags = (Record.size() > 6)
1675 ? static_cast<DINode::DIFlags>(Record[6])
1676 : DINode::FlagZero;
1677 uint32_t NumExtraInhabitants = (Record.size() > 7) ? Record[7] : 0;
1678 uint32_t DataSizeInBits = (Record.size() > 8) ? Record[8] : 0;
1679 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1680 Metadata *File = nullptr;
1681 unsigned LineNo = 0;
1682 Metadata *Scope = nullptr;
1683 if (Record.size() > 9) {
1684 File = getMDOrNull(Record[9]);
1685 LineNo = Record[10];
1686 Scope = getMDOrNull(Record[11]);
1687 }
1688 MetadataList.assignValue(
1689 GET_OR_DISTINCT(DIBasicType,
1690 (Context, Record[1], getMDString(Record[2]), File,
1691 LineNo, Scope, SizeInBits, Record[4], Record[5],
1692 NumExtraInhabitants, DataSizeInBits, Flags)),
1693 NextMetadataNo);
1694 NextMetadataNo++;
1695 break;
1696 }
1698 if (Record.size() < 11)
1699 return error("Invalid record");
1700
1701 IsDistinct = Record[0] & 1;
1702 bool SizeIsMetadata = Record[0] & 2;
1703 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[6]);
1704
1705 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1706
1707 size_t Offset = 9;
1708
1709 auto ReadWideInt = [&]() {
1711 unsigned NumWords = Encoded >> 32;
1712 unsigned BitWidth = Encoded & 0xffffffff;
1713 auto Value = readWideAPInt(ArrayRef(&Record[Offset], NumWords), BitWidth);
1714 Offset += NumWords;
1715 return Value;
1716 };
1717
1718 APInt Numerator = ReadWideInt();
1719 APInt Denominator = ReadWideInt();
1720
1721 Metadata *File = nullptr;
1722 unsigned LineNo = 0;
1723 Metadata *Scope = nullptr;
1724
1725 if (Offset + 3 == Record.size()) {
1726 File = getMDOrNull(Record[Offset]);
1727 LineNo = Record[Offset + 1];
1728 Scope = getMDOrNull(Record[Offset + 2]);
1729 } else if (Offset != Record.size())
1730 return error("Invalid record");
1731
1732 MetadataList.assignValue(
1733 GET_OR_DISTINCT(DIFixedPointType,
1734 (Context, Record[1], getMDString(Record[2]), File,
1735 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1736 Record[7], Record[8], Numerator, Denominator)),
1737 NextMetadataNo);
1738 NextMetadataNo++;
1739 break;
1740 }
1742 if (Record.size() > 9 || Record.size() < 8)
1743 return error("Invalid record");
1744
1745 IsDistinct = Record[0] & 1;
1746 bool SizeIsMetadata = Record[0] & 2;
1747 bool SizeIs8 = Record.size() == 8;
1748 // StringLocationExp (i.e. Record[5]) is added at a later time
1749 // than the other fields. The code here enables backward compatibility.
1750 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1751 unsigned Offset = SizeIs8 ? 5 : 6;
1752 Metadata *SizeInBits =
1753 getMetadataOrConstant(SizeIsMetadata, Record[Offset]);
1754
1755 MetadataList.assignValue(
1756 GET_OR_DISTINCT(DIStringType,
1757 (Context, Record[1], getMDString(Record[2]),
1758 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1759 StringLocationExp, SizeInBits, Record[Offset + 1],
1760 Record[Offset + 2])),
1761 NextMetadataNo);
1762 NextMetadataNo++;
1763 break;
1764 }
1766 if (Record.size() < 12 || Record.size() > 15)
1767 return error("Invalid record");
1768
1769 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1770 // that there is no DWARF address space associated with DIDerivedType.
1771 std::optional<unsigned> DWARFAddressSpace;
1772 if (Record.size() > 12 && Record[12])
1773 DWARFAddressSpace = Record[12] - 1;
1774
1775 Metadata *Annotations = nullptr;
1776 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1777
1778 // Only look for annotations/ptrauth if both are allocated.
1779 // If not, we can't tell which was intended to be embedded, as both ptrauth
1780 // and annotations have been expected at Record[13] at various times.
1781 if (Record.size() > 14) {
1782 if (Record[13])
1783 Annotations = getMDOrNull(Record[13]);
1784 if (Record[14])
1785 PtrAuthData.emplace(Record[14]);
1786 }
1787
1788 IsDistinct = Record[0] & 1;
1789 bool SizeIsMetadata = Record[0] & 2;
1790 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1791
1792 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1793 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1794
1795 MetadataList.assignValue(
1796 GET_OR_DISTINCT(DIDerivedType,
1797 (Context, Record[1], getMDString(Record[2]),
1798 getMDOrNull(Record[3]), Record[4],
1799 getDITypeRefOrNull(Record[5]),
1800 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1801 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1802 getDITypeRefOrNull(Record[11]), Annotations)),
1803 NextMetadataNo);
1804 NextMetadataNo++;
1805 break;
1806 }
1808 if (Record.size() != 13)
1809 return error("Invalid record");
1810
1811 IsDistinct = Record[0] & 1;
1812 bool SizeIsMetadata = Record[0] & 2;
1813 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7]);
1814
1815 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1816
1817 MetadataList.assignValue(
1818 GET_OR_DISTINCT(DISubrangeType,
1819 (Context, getMDString(Record[1]),
1820 getMDOrNull(Record[2]), Record[3],
1821 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1822 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1823 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1824 getMDOrNull(Record[12]))),
1825 NextMetadataNo);
1826 NextMetadataNo++;
1827 break;
1828 }
1830 if (Record.size() < 16 || Record.size() > 26)
1831 return error("Invalid record");
1832
1833 // If we have a UUID and this is not a forward declaration, lookup the
1834 // mapping.
1835 IsDistinct = Record[0] & 0x1;
1836 bool IsNotUsedInTypeRef = Record[0] & 2;
1837 bool SizeIsMetadata = Record[0] & 4;
1838 unsigned Tag = Record[1];
1839 MDString *Name = getMDString(Record[2]);
1840 Metadata *File = getMDOrNull(Record[3]);
1841 unsigned Line = Record[4];
1842 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1843 Metadata *BaseType = nullptr;
1844 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1845 return error("Alignment value is too large");
1846 uint32_t AlignInBits = Record[8];
1847 Metadata *OffsetInBits = nullptr;
1848 uint32_t NumExtraInhabitants = (Record.size() > 22) ? Record[22] : 0;
1849 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1850 Metadata *Elements = nullptr;
1851 unsigned RuntimeLang = Record[12];
1852 std::optional<uint32_t> EnumKind;
1853
1854 Metadata *VTableHolder = nullptr;
1855 Metadata *TemplateParams = nullptr;
1856 Metadata *Discriminator = nullptr;
1857 Metadata *DataLocation = nullptr;
1858 Metadata *Associated = nullptr;
1859 Metadata *Allocated = nullptr;
1860 Metadata *Rank = nullptr;
1861 Metadata *Annotations = nullptr;
1862 Metadata *Specification = nullptr;
1863 Metadata *BitStride = nullptr;
1864 auto *Identifier = getMDString(Record[15]);
1865 // If this module is being parsed so that it can be ThinLTO imported
1866 // into another module, composite types only need to be imported as
1867 // type declarations (unless full type definitions are requested).
1868 // Create type declarations up front to save memory. This is only
1869 // done for types which have an Identifier, and are therefore
1870 // subject to the ODR.
1871 //
1872 // buildODRType handles the case where this is type ODRed with a
1873 // definition needed by the importing module, in which case the
1874 // existing definition is used.
1875 //
1876 // We always import full definitions for anonymous composite types,
1877 // as without a name, debuggers cannot easily resolve a declaration
1878 // to its definition.
1879 if (IsImporting && !ImportFullTypeDefinitions && Identifier && Name &&
1880 (Tag == dwarf::DW_TAG_enumeration_type ||
1881 Tag == dwarf::DW_TAG_class_type ||
1882 Tag == dwarf::DW_TAG_structure_type ||
1883 Tag == dwarf::DW_TAG_union_type)) {
1884 Flags = Flags | DINode::FlagFwdDecl;
1885 // This is a hack around preserving template parameters for simplified
1886 // template names - it should probably be replaced with a
1887 // DICompositeType flag specifying whether template parameters are
1888 // required on declarations of this type.
1889 StringRef NameStr = Name->getString();
1890 if (!NameStr.contains('<') || NameStr.starts_with("_STN|"))
1891 TemplateParams = getMDOrNull(Record[14]);
1892 } else {
1893 BaseType = getDITypeRefOrNull(Record[6]);
1894
1895 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1896
1897 Elements = getMDOrNull(Record[11]);
1898 VTableHolder = getDITypeRefOrNull(Record[13]);
1899 TemplateParams = getMDOrNull(Record[14]);
1900 if (Record.size() > 16)
1901 Discriminator = getMDOrNull(Record[16]);
1902 if (Record.size() > 17)
1903 DataLocation = getMDOrNull(Record[17]);
1904 if (Record.size() > 19) {
1905 Associated = getMDOrNull(Record[18]);
1906 Allocated = getMDOrNull(Record[19]);
1907 }
1908 if (Record.size() > 20) {
1909 Rank = getMDOrNull(Record[20]);
1910 }
1911 if (Record.size() > 21) {
1912 Annotations = getMDOrNull(Record[21]);
1913 }
1914 if (Record.size() > 23) {
1915 Specification = getMDOrNull(Record[23]);
1916 }
1917 if (Record.size() > 25)
1918 BitStride = getMDOrNull(Record[25]);
1919 }
1920
1921 if (Record.size() > 24 && Record[24] != dwarf::DW_APPLE_ENUM_KIND_invalid)
1922 EnumKind = Record[24];
1923
1924 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1925
1926 DICompositeType *CT = nullptr;
1927 if (Identifier)
1929 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1930 SizeInBits, AlignInBits, OffsetInBits, Specification,
1931 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1932 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1933 Allocated, Rank, Annotations, BitStride);
1934
1935 // Create a node if we didn't get a lazy ODR type.
1936 if (!CT)
1937 CT = GET_OR_DISTINCT(
1938 DICompositeType,
1939 (Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1940 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1941 VTableHolder, TemplateParams, Identifier, Discriminator,
1942 DataLocation, Associated, Allocated, Rank, Annotations,
1943 Specification, NumExtraInhabitants, BitStride));
1944 if (!IsNotUsedInTypeRef && Identifier)
1945 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1946
1947 MetadataList.assignValue(CT, NextMetadataNo);
1948 NextMetadataNo++;
1949 break;
1950 }
1952 if (Record.size() < 3 || Record.size() > 4)
1953 return error("Invalid record");
1954 bool IsOldTypeArray = Record[0] < 2;
1955 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1956
1957 IsDistinct = Record[0] & 0x1;
1958 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1959 Metadata *Types = getMDOrNull(Record[2]);
1960 if (LLVM_UNLIKELY(IsOldTypeArray))
1961 Types = MetadataList.upgradeTypeArray(Types);
1962
1963 MetadataList.assignValue(
1964 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1965 NextMetadataNo);
1966 NextMetadataNo++;
1967 break;
1968 }
1969
1970 case bitc::METADATA_MODULE: {
1971 if (Record.size() < 5 || Record.size() > 9)
1972 return error("Invalid record");
1973
1974 unsigned Offset = Record.size() >= 8 ? 2 : 1;
1975 IsDistinct = Record[0];
1976 MetadataList.assignValue(
1978 DIModule,
1979 (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1980 getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1981 getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1982 getMDString(Record[4 + Offset]),
1983 Record.size() <= 7 ? 0 : Record[7],
1984 Record.size() <= 8 ? false : Record[8])),
1985 NextMetadataNo);
1986 NextMetadataNo++;
1987 break;
1988 }
1989
1990 case bitc::METADATA_FILE: {
1991 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1992 return error("Invalid record");
1993
1994 IsDistinct = Record[0];
1995 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1996 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1997 // is not present. This matches up with the old internal representation,
1998 // and the old encoding for CSK_None in the ChecksumKind. The new
1999 // representation reserves the value 0 in the ChecksumKind to continue to
2000 // encode None in a backwards-compatible way.
2001 if (Record.size() > 4 && Record[3] && Record[4])
2002 Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
2003 getMDString(Record[4]));
2004 MetadataList.assignValue(
2005 GET_OR_DISTINCT(DIFile,
2006 (Context, getMDString(Record[1]),
2007 getMDString(Record[2]), Checksum,
2008 Record.size() > 5 ? getMDString(Record[5]) : nullptr)),
2009 NextMetadataNo);
2010 NextMetadataNo++;
2011 break;
2012 }
2014 if (Record.size() < 14 || Record.size() > 24)
2015 return error("Invalid record");
2016
2017 // Ignore Record[0], which indicates whether this compile unit is
2018 // distinct. It's always distinct.
2019 IsDistinct = true;
2020
2021 const auto LangVersionMask = (uint64_t(1) << 63);
2022 const bool HasVersionedLanguage = Record[1] & LangVersionMask;
2023 const uint32_t LanguageVersion = Record.size() > 22 ? Record[22] : 0;
2024 // The dialect field is written by writeDICompileUnit as a small enum
2025 // value (see dwarf::LanguageDialectAttribute). Reject out-of-range
2026 // values rather than silently truncating to uint16_t; this keeps the
2027 // writer/reader invariant symmetric and surfaces malformed inputs.
2028 // Value 0 means "no dialect specified".
2029 if (Record.size() > 23 &&
2030 Record[23] > static_cast<uint64_t>(dwarf::DW_LLVM_LANG_DIALECT_max))
2031 return error("Invalid DICompileUnit dialect value");
2032 const uint16_t Dialect =
2033 Record.size() > 23 ? static_cast<uint16_t>(Record[23]) : uint16_t(0);
2034
2035 auto *CU = DICompileUnit::getDistinct(
2036 Context,
2037 HasVersionedLanguage
2038 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
2039 LanguageVersion, Dialect)
2040 : DISourceLanguageName(Record[1], Dialect),
2041 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
2042 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
2043 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2044 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2045 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2046 Record.size() <= 14 ? 0 : Record[14],
2047 Record.size() <= 16 ? true : Record[16],
2048 Record.size() <= 17 ? false : Record[17],
2049 Record.size() <= 18 ? 0 : Record[18],
2050 Record.size() <= 19 ? false : Record[19],
2051 // Keep these guarded for backwards-compatibility with older bitcode
2052 // records. Keep this index layout in sync with writeDICompileUnit:
2053 // index 20 is sysroot, 21 is SDK, 22 is source-language version, and
2054 // 23 is dialect (read above as raw enum value, where 0 means unset).
2055 Record.size() <= 20 ? nullptr : getMDString(Record[20]),
2056 Record.size() <= 21 ? nullptr : getMDString(Record[21]));
2057
2058 MetadataList.assignValue(CU, NextMetadataNo);
2059 NextMetadataNo++;
2060
2061 // Move the Upgrade the list of subprograms.
2062 if (Record[11])
2063 CUSubprograms.push_back({CU, Record[11]});
2064 break;
2065 }
2067 if (Record.size() < 18 || Record.size() > 22)
2068 return error("Invalid record");
2069
2070 bool HasSPFlags = Record[0] & 4;
2071
2074 if (!HasSPFlags)
2075 Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
2076 else {
2077 Flags = static_cast<DINode::DIFlags>(Record[11]);
2078 SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
2079 }
2080
2081 // Support for old metadata when
2082 // subprogram specific flags are placed in DIFlags.
2083 const unsigned DIFlagMainSubprogram = 1 << 21;
2084 bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
2085 if (HasOldMainSubprogramFlag)
2086 // Remove old DIFlagMainSubprogram from DIFlags.
2087 // Note: This assumes that any future use of bit 21 defaults to it
2088 // being 0.
2089 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2090
2091 if (HasOldMainSubprogramFlag && HasSPFlags)
2092 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2093 else if (!HasSPFlags)
2094 SPFlags = DISubprogram::toSPFlags(
2095 /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
2096 /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
2097 /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
2098
2099 // All definitions should be distinct.
2100 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2101 // Version 1 has a Function as Record[15].
2102 // Version 2 has removed Record[15].
2103 // Version 3 has the Unit as Record[15].
2104 // Version 4 added thisAdjustment.
2105 // Version 5 repacked flags into DISPFlags, changing many element numbers.
2106 bool HasUnit = Record[0] & 2;
2107 if (!HasSPFlags && HasUnit && Record.size() < 19)
2108 return error("Invalid record");
2109 if (HasSPFlags && !HasUnit)
2110 return error("Invalid record");
2111 // Accommodate older formats.
2112 bool HasFn = false;
2113 bool HasThisAdj = true;
2114 bool HasThrownTypes = true;
2115 bool HasAnnotations = false;
2116 bool HasTargetFuncName = false;
2117 unsigned OffsetA = 0;
2118 unsigned OffsetB = 0;
2119 // Key instructions won't be enabled in old-format bitcode, so only
2120 // check it if HasSPFlags is true.
2121 bool UsesKeyInstructions = false;
2122 if (!HasSPFlags) {
2123 OffsetA = 2;
2124 OffsetB = 2;
2125 if (Record.size() >= 19) {
2126 HasFn = !HasUnit;
2127 OffsetB++;
2128 }
2129 HasThisAdj = Record.size() >= 20;
2130 HasThrownTypes = Record.size() >= 21;
2131 } else {
2132 HasAnnotations = Record.size() >= 19;
2133 HasTargetFuncName = Record.size() >= 20;
2134 UsesKeyInstructions = Record.size() >= 21 ? Record[20] : 0;
2135 }
2136
2137 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2138 DISubprogram *SP = GET_OR_DISTINCT(
2139 DISubprogram,
2140 (Context,
2141 getDITypeRefOrNull(Record[1]), // scope
2142 getMDString(Record[2]), // name
2143 getMDString(Record[3]), // linkageName
2144 getMDOrNull(Record[4]), // file
2145 Record[5], // line
2146 getMDOrNull(Record[6]), // type
2147 Record[7 + OffsetA], // scopeLine
2148 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
2149 Record[10 + OffsetA], // virtualIndex
2150 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
2151 Flags, // flags
2152 SPFlags, // SPFlags
2153 HasUnit ? CUorFn : nullptr, // unit
2154 getMDOrNull(Record[13 + OffsetB]), // templateParams
2155 getMDOrNull(Record[14 + OffsetB]), // declaration
2156 getMDOrNull(Record[15 + OffsetB]), // retainedNodes
2157 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2158 : nullptr, // thrownTypes
2159 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2160 : nullptr, // annotations
2161 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2162 : nullptr, // targetFuncName
2163 UsesKeyInstructions));
2164 MetadataList.assignValue(SP, NextMetadataNo);
2165 NextMetadataNo++;
2166
2167 if (IsDistinct)
2168 NewDistinctSPs.push_back(SP);
2169
2170 // Upgrade sp->function mapping to function->sp mapping.
2171 if (HasFn) {
2172 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
2173 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2174 if (F->isMaterializable())
2175 // Defer until materialized; unmaterialized functions may not have
2176 // metadata.
2177 FunctionsWithSPs[F] = SP;
2178 else if (!F->empty())
2179 F->setSubprogram(SP);
2180 }
2181 }
2182 break;
2183 }
2185 if (Record.size() != 5)
2186 return error("Invalid record");
2187
2188 IsDistinct = Record[0];
2189 MetadataList.assignValue(
2190 GET_OR_DISTINCT(DILexicalBlock,
2191 (Context, getMDOrNull(Record[1]),
2192 getMDOrNull(Record[2]), Record[3], Record[4])),
2193 NextMetadataNo);
2194 NextMetadataNo++;
2195 break;
2196 }
2198 if (Record.size() != 4)
2199 return error("Invalid record");
2200
2201 IsDistinct = Record[0];
2202 MetadataList.assignValue(
2203 GET_OR_DISTINCT(DILexicalBlockFile,
2204 (Context, getMDOrNull(Record[1]),
2205 getMDOrNull(Record[2]), Record[3])),
2206 NextMetadataNo);
2207 NextMetadataNo++;
2208 break;
2209 }
2211 IsDistinct = Record[0] & 1;
2212 MetadataList.assignValue(
2213 GET_OR_DISTINCT(DICommonBlock,
2214 (Context, getMDOrNull(Record[1]),
2215 getMDOrNull(Record[2]), getMDString(Record[3]),
2216 getMDOrNull(Record[4]), Record[5])),
2217 NextMetadataNo);
2218 NextMetadataNo++;
2219 break;
2220 }
2222 // Newer versions of DINamespace dropped file and line.
2223 MDString *Name;
2224 if (Record.size() == 3)
2225 Name = getMDString(Record[2]);
2226 else if (Record.size() == 5)
2227 Name = getMDString(Record[3]);
2228 else
2229 return error("Invalid record");
2230
2231 IsDistinct = Record[0] & 1;
2232 bool ExportSymbols = Record[0] & 2;
2233 MetadataList.assignValue(
2234 GET_OR_DISTINCT(DINamespace,
2235 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2236 NextMetadataNo);
2237 NextMetadataNo++;
2238 break;
2239 }
2240 case bitc::METADATA_MACRO: {
2241 if (Record.size() != 5)
2242 return error("Invalid record");
2243
2244 IsDistinct = Record[0];
2245 MetadataList.assignValue(
2246 GET_OR_DISTINCT(DIMacro,
2247 (Context, Record[1], Record[2], getMDString(Record[3]),
2248 getMDString(Record[4]))),
2249 NextMetadataNo);
2250 NextMetadataNo++;
2251 break;
2252 }
2254 if (Record.size() != 5)
2255 return error("Invalid record");
2256
2257 IsDistinct = Record[0];
2258 MetadataList.assignValue(
2259 GET_OR_DISTINCT(DIMacroFile,
2260 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
2261 getMDOrNull(Record[4]))),
2262 NextMetadataNo);
2263 NextMetadataNo++;
2264 break;
2265 }
2267 if (Record.size() < 3 || Record.size() > 4)
2268 return error("Invalid record");
2269
2270 IsDistinct = Record[0];
2271 MetadataList.assignValue(
2272 GET_OR_DISTINCT(DITemplateTypeParameter,
2273 (Context, getMDString(Record[1]),
2274 getDITypeRefOrNull(Record[2]),
2275 (Record.size() == 4) ? getMDOrNull(Record[3])
2276 : getMDOrNull(false))),
2277 NextMetadataNo);
2278 NextMetadataNo++;
2279 break;
2280 }
2282 if (Record.size() < 5 || Record.size() > 6)
2283 return error("Invalid record");
2284
2285 IsDistinct = Record[0];
2286
2287 MetadataList.assignValue(
2289 DITemplateValueParameter,
2290 (Context, Record[1], getMDString(Record[2]),
2291 getDITypeRefOrNull(Record[3]),
2292 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
2293 (Record.size() == 6) ? getMDOrNull(Record[5])
2294 : getMDOrNull(Record[4]))),
2295 NextMetadataNo);
2296 NextMetadataNo++;
2297 break;
2298 }
2300 if (Record.size() < 11 || Record.size() > 13)
2301 return error("Invalid record");
2302
2303 IsDistinct = Record[0] & 1;
2304 unsigned Version = Record[0] >> 1;
2305
2306 if (Version == 2) {
2307 Metadata *Annotations = nullptr;
2308 if (Record.size() > 12)
2309 Annotations = getMDOrNull(Record[12]);
2310
2311 MetadataList.assignValue(
2312 GET_OR_DISTINCT(DIGlobalVariable,
2313 (Context, getMDOrNull(Record[1]),
2314 getMDString(Record[2]), getMDString(Record[3]),
2315 getMDOrNull(Record[4]), Record[5],
2316 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2317 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2318 Record[11], Annotations)),
2319 NextMetadataNo);
2320
2321 NextMetadataNo++;
2322 } else if (Version == 1) {
2323 // No upgrade necessary. A null field will be introduced to indicate
2324 // that no parameter information is available.
2325 MetadataList.assignValue(
2327 DIGlobalVariable,
2328 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2329 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2330 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2331 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
2332 NextMetadataNo);
2333
2334 NextMetadataNo++;
2335 } else if (Version == 0) {
2336 // Upgrade old metadata, which stored a global variable reference or a
2337 // ConstantInt here.
2338 NeedUpgradeToDIGlobalVariableExpression = true;
2339 Metadata *Expr = getMDOrNull(Record[9]);
2340 uint32_t AlignInBits = 0;
2341 if (Record.size() > 11) {
2342 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2343 return error("Alignment value is too large");
2344 AlignInBits = Record[11];
2345 }
2346 GlobalVariable *Attach = nullptr;
2347 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
2348 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
2349 Attach = GV;
2350 Expr = nullptr;
2351 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
2352 Expr = DIExpression::get(Context,
2353 {dwarf::DW_OP_constu, CI->getZExtValue(),
2354 dwarf::DW_OP_stack_value});
2355 } else {
2356 Expr = nullptr;
2357 }
2358 }
2359 DIGlobalVariable *DGV = GET_OR_DISTINCT(
2360 DIGlobalVariable,
2361 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2362 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2363 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2364 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
2365
2366 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
2367 if (Attach || Expr) {
2368 if (!DGVE) {
2369 DGVE = DIGlobalVariableExpression::getDistinct(
2370 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
2371 }
2372 }
2373 if (Attach)
2374 Attach->addDebugInfo(DGVE);
2375
2376 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
2377 MetadataList.assignValue(MDNode, NextMetadataNo);
2378 NextMetadataNo++;
2379 } else
2380 return error("Invalid record");
2381
2382 break;
2383 }
2385 if (Record.size() != 1)
2386 return error("Invalid DIAssignID record.");
2387
2388 IsDistinct = Record[0] & 1;
2389 if (!IsDistinct)
2390 return error("Invalid DIAssignID record. Must be distinct");
2391
2392 MetadataList.assignValue(DIAssignID::getDistinct(Context), NextMetadataNo);
2393 NextMetadataNo++;
2394 break;
2395 }
2397 // 10th field is for the obseleted 'inlinedAt:' field.
2398 if (Record.size() < 8 || Record.size() > 10)
2399 return error("Invalid record");
2400
2401 IsDistinct = Record[0] & 1;
2402 bool HasAlignment = Record[0] & 2;
2403 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2404 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
2405 // this is newer version of record which doesn't have artificial tag.
2406 bool HasTag = !HasAlignment && Record.size() > 8;
2407 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
2408 uint32_t AlignInBits = 0;
2409 Metadata *Annotations = nullptr;
2410 if (HasAlignment) {
2411 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2412 return error("Alignment value is too large");
2413 AlignInBits = Record[8];
2414 if (Record.size() > 9)
2415 Annotations = getMDOrNull(Record[9]);
2416 }
2417
2418 MetadataList.assignValue(
2419 GET_OR_DISTINCT(DILocalVariable,
2420 (Context, getMDOrNull(Record[1 + HasTag]),
2421 getMDString(Record[2 + HasTag]),
2422 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2423 getDITypeRefOrNull(Record[5 + HasTag]),
2424 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2425 NextMetadataNo);
2426 NextMetadataNo++;
2427 break;
2428 }
2429 case bitc::METADATA_LABEL: {
2430 if (Record.size() < 5 || Record.size() > 7)
2431 return error("Invalid record");
2432
2433 IsDistinct = Record[0] & 1;
2434 uint64_t Line = Record[4];
2435 uint64_t Column = Record.size() > 5 ? Record[5] : 0;
2436 bool IsArtificial = Record[0] & 2;
2437 std::optional<unsigned> CoroSuspendIdx;
2438 if (Record.size() > 6) {
2439 uint64_t RawSuspendIdx = Record[6];
2440 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2441 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2442 return error("CoroSuspendIdx value is too large");
2443 CoroSuspendIdx = RawSuspendIdx;
2444 }
2445 }
2446
2447 MetadataList.assignValue(
2448 GET_OR_DISTINCT(DILabel,
2449 (Context, getMDOrNull(Record[1]),
2450 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2451 Column, IsArtificial, CoroSuspendIdx)),
2452 NextMetadataNo);
2453 NextMetadataNo++;
2454 break;
2455 }
2457 if (Record.size() < 1)
2458 return error("Invalid record");
2459
2460 IsDistinct = Record[0] & 1;
2461 uint64_t Version = Record[0] >> 1;
2462 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2463
2465 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2466 return Err;
2467
2468 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2469 NextMetadataNo);
2470 NextMetadataNo++;
2471 break;
2472 }
2474 if (Record.size() != 3)
2475 return error("Invalid record");
2476
2477 IsDistinct = Record[0];
2478 Metadata *Expr = getMDOrNull(Record[2]);
2479 if (!Expr)
2480 Expr = DIExpression::get(Context, {});
2481 MetadataList.assignValue(
2482 GET_OR_DISTINCT(DIGlobalVariableExpression,
2483 (Context, getMDOrNull(Record[1]), Expr)),
2484 NextMetadataNo);
2485 NextMetadataNo++;
2486 break;
2487 }
2489 if (Record.size() != 8)
2490 return error("Invalid record");
2491
2492 IsDistinct = Record[0];
2493 MetadataList.assignValue(
2494 GET_OR_DISTINCT(DIObjCProperty,
2495 (Context, getMDString(Record[1]),
2496 getMDOrNull(Record[2]), Record[3],
2497 /*GetterName=*/getMDString(Record[5]),
2498 /*SetterName=*/getMDString(Record[4]), Record[6],
2499 getDITypeRefOrNull(Record[7]))),
2500 NextMetadataNo);
2501 NextMetadataNo++;
2502 break;
2503 }
2505 if (Record.size() != 6)
2506 return error("Invalid record");
2507
2508 IsDistinct = Record[0];
2509 MetadataList.assignValue(
2510 GET_OR_DISTINCT(DIProperty, (Context, getMDString(Record[1]),
2511 getMDOrNull(Record[2]), Record[3],
2512 getDITypeRefOrNull(Record[4]),
2513 getMDOrNull(Record[5]))),
2514 NextMetadataNo);
2515 NextMetadataNo++;
2516 break;
2517 }
2519 if (Record.size() < 6 || Record.size() > 8)
2520 return error("Invalid DIImportedEntity record");
2521
2522 IsDistinct = Record[0];
2523 bool HasFile = (Record.size() >= 7);
2524 bool HasElements = (Record.size() >= 8);
2525 MetadataList.assignValue(
2526 GET_OR_DISTINCT(DIImportedEntity,
2527 (Context, Record[1], getMDOrNull(Record[2]),
2528 getDITypeRefOrNull(Record[3]),
2529 HasFile ? getMDOrNull(Record[6]) : nullptr,
2530 HasFile ? Record[4] : 0, getMDString(Record[5]),
2531 HasElements ? getMDOrNull(Record[7]) : nullptr)),
2532 NextMetadataNo);
2533 NextMetadataNo++;
2534 break;
2535 }
2537 std::string String(Record.begin(), Record.end());
2538
2539 // Test for upgrading !llvm.loop.
2540 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2541 ++NumMDStringLoaded;
2543 MetadataList.assignValue(MD, NextMetadataNo);
2544 NextMetadataNo++;
2545 break;
2546 }
2548 auto CreateNextMDString = [&](StringRef Str) {
2549 // Modern bitcode encodes MDStrings via this bulk record, so mirror the
2550 // METADATA_STRING check above to arm the loop-attachment upgrader.
2551 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(Str);
2552 ++NumMDStringLoaded;
2553 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2554 NextMetadataNo++;
2555 };
2556 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2557 return Err;
2558 break;
2559 }
2561 if (Record.size() % 2 == 0)
2562 return error("Invalid record");
2563 unsigned ValueID = Record[0];
2564 if (ValueID >= ValueList.size())
2565 return error("Invalid record");
2566 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2567 if (Error Err = parseGlobalObjectAttachment(
2568 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2569 return Err;
2570 break;
2571 }
2572 case bitc::METADATA_KIND: {
2573 // Support older bitcode files that had METADATA_KIND records in a
2574 // block with METADATA_BLOCK_ID.
2575 if (Error Err = parseMetadataKindRecord(Record))
2576 return Err;
2577 break;
2578 }
2581 Elts.reserve(Record.size());
2582 for (uint64_t Elt : Record) {
2583 Metadata *MD = getMD(Elt);
2584 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2585 return error(
2586 "Invalid record: DIArgList should not contain forward refs");
2587 if (!isa<ValueAsMetadata>(MD))
2588 return error("Invalid record");
2590 }
2591
2592 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2593 NextMetadataNo++;
2594 break;
2595 }
2596 }
2597 return Error::success();
2598#undef GET_OR_DISTINCT
2599}
2600
2601Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2602 ArrayRef<uint64_t> Record, StringRef Blob,
2603 function_ref<void(StringRef)> CallBack) {
2604 // All the MDStrings in the block are emitted together in a single
2605 // record. The strings are concatenated and stored in a blob along with
2606 // their sizes.
2607 if (Record.size() != 2)
2608 return error("Invalid record: metadata strings layout");
2609
2610 unsigned NumStrings = Record[0];
2611 unsigned StringsOffset = Record[1];
2612 if (!NumStrings)
2613 return error("Invalid record: metadata strings with no strings");
2614 if (StringsOffset > Blob.size())
2615 return error("Invalid record: metadata strings corrupt offset");
2616
2617 StringRef Lengths = Blob.slice(0, StringsOffset);
2618 SimpleBitstreamCursor R(Lengths);
2619
2620 StringRef Strings = Blob.drop_front(StringsOffset);
2621 do {
2622 if (R.AtEndOfStream())
2623 return error("Invalid record: metadata strings bad length");
2624
2625 uint32_t Size;
2626 if (Error E = R.ReadVBR(6).moveInto(Size))
2627 return E;
2628 if (Strings.size() < Size)
2629 return error("Invalid record: metadata strings truncated chars");
2630
2631 CallBack(Strings.slice(0, Size));
2632 Strings = Strings.drop_front(Size);
2633 } while (--NumStrings);
2634
2635 return Error::success();
2636}
2637
2638Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2639 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2640 assert(Record.size() % 2 == 0);
2641 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
2642 auto K = MDKindMap.find(Record[I]);
2643 if (K == MDKindMap.end())
2644 return error("Invalid ID");
2645 MDNode *MD =
2646 dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
2647 if (!MD)
2648 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2649 GO.addMetadata(K->second, *MD);
2650 }
2651 return Error::success();
2652}
2653
2654/// Parse metadata attachments.
2656 Function &F, ArrayRef<Instruction *> InstructionList) {
2657 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2658 return Err;
2659
2661 PlaceholderQueue Placeholders;
2662
2663 while (true) {
2664 BitstreamEntry Entry;
2665 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2666 return E;
2667
2668 switch (Entry.Kind) {
2669 case BitstreamEntry::SubBlock: // Handled for us already.
2671 return error("Malformed block");
2673 LLVM_DEBUG(llvm::dbgs() << "\nAttachment metadata loading: ");
2674 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2675 return Error::success();
2677 // The interesting case.
2678 break;
2679 }
2680
2681 // Read a metadata attachment record.
2682 Record.clear();
2683 ++NumMDRecordLoaded;
2684 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2685 if (!MaybeRecord)
2686 return MaybeRecord.takeError();
2687 switch (MaybeRecord.get()) {
2688 default: // Default behavior: ignore.
2689 break;
2691 unsigned RecordLength = Record.size();
2692 if (Record.empty())
2693 return error("Invalid record");
2694 if (RecordLength % 2 == 0) {
2695 // A function attachment.
2696 if (Error Err = parseGlobalObjectAttachment(F, Record))
2697 return Err;
2698 continue;
2699 }
2700
2701 // An instruction attachment.
2702 Instruction *Inst = InstructionList[Record[0]];
2703 for (unsigned i = 1; i != RecordLength; i = i + 2) {
2704 unsigned Kind = Record[i];
2705 auto I = MDKindMap.find(Kind);
2706 if (I == MDKindMap.end())
2707 return error("Invalid ID");
2708 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2709 continue;
2710
2711 auto Idx = Record[i + 1];
2712 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2713 !MetadataList.lookup(Idx)) {
2714 // Load the attachment if it is in the lazy-loadable range and hasn't
2715 // been loaded yet.
2716 lazyLoadOneMetadata(Idx, Placeholders);
2717 LLVM_DEBUG(llvm::dbgs() << "\nLazy attachment metadata loading: ");
2718 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2719 }
2720
2721 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2723 // Drop the attachment. This used to be legal, but there's no
2724 // upgrade path.
2725 break;
2727 if (!MD)
2728 return error("Invalid metadata attachment");
2729
2730 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2732
2733 if (I->second == LLVMContext::MD_tbaa) {
2734 assert(!MD->isTemporary() && "should load MDs before attachments");
2735 MD = UpgradeTBAANode(*MD);
2736 } else if (I->second == LLVMContext::MD_tbaa_struct) {
2737 assert(!MD->isTemporary() && "should load MDs before attachments");
2738 MD = UpgradeTBAAStructNode(*MD);
2739 }
2740
2741 if (I->second == LLVMContext::MD_alias_scope ||
2742 I->second == LLVMContext::MD_noalias)
2743 MD = upgradeAliasScopeList(MD);
2744
2745 Inst->setMetadata(I->second, MD);
2746 }
2747 break;
2748 }
2749 }
2750 }
2751}
2752
2753/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2754Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2756 if (Record.size() < 2)
2757 return error("Invalid record");
2758
2759 unsigned Kind = Record[0];
2760 SmallString<8> Name(Record.begin() + 1, Record.end());
2761
2762 unsigned NewKind = TheModule.getMDKindID(Name.str());
2763 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2764 return error("Conflicting METADATA_KIND records");
2765 return Error::success();
2766}
2767
2768/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2770 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2771 return Err;
2772
2774
2775 // Read all the records.
2776 while (true) {
2777 BitstreamEntry Entry;
2778 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2779 return E;
2780
2781 switch (Entry.Kind) {
2782 case BitstreamEntry::SubBlock: // Handled for us already.
2784 return error("Malformed block");
2786 return Error::success();
2788 // The interesting case.
2789 break;
2790 }
2791
2792 // Read a record.
2793 Record.clear();
2794 ++NumMDRecordLoaded;
2795 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2796 if (!MaybeCode)
2797 return MaybeCode.takeError();
2798 switch (MaybeCode.get()) {
2799 default: // Default behavior: ignore.
2800 break;
2801 case bitc::METADATA_KIND: {
2802 if (Error Err = parseMetadataKindRecord(Record))
2803 return Err;
2804 break;
2805 }
2806 }
2807 }
2808}
2809
2811 Pimpl = std::move(RHS.Pimpl);
2812 return *this;
2813}
2815 : Pimpl(std::move(RHS.Pimpl)) {}
2816
2819 BitcodeReaderValueList &ValueList,
2820 bool IsImporting,
2821 MetadataLoaderCallbacks Callbacks)
2822 : Pimpl(std::make_unique<MetadataLoaderImpl>(
2823 Stream, TheModule, ValueList, std::move(Callbacks), IsImporting)) {}
2824
2825Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2826 return Pimpl->parseMetadata(ModuleLevel);
2827}
2828
2829bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2830
2831/// Return the given metadata, creating a replaceable forward reference if
2832/// necessary.
2834 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2835}
2836
2838 return Pimpl->lookupSubprogramForFunction(F);
2839}
2840
2842 Function &F, ArrayRef<Instruction *> InstructionList) {
2843 return Pimpl->parseMetadataAttachment(F, InstructionList);
2844}
2845
2847 return Pimpl->parseMetadataKinds();
2848}
2849
2850void MetadataLoader::setStripTBAA(bool StripTBAA) {
2851 return Pimpl->setStripTBAA(StripTBAA);
2852}
2853
2854bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2855
2856unsigned MetadataLoader::size() const { return Pimpl->size(); }
2857void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2858
2860 return Pimpl->upgradeDebugIntrinsics(F);
2861}
2862
2864 return Pimpl->upgradeAliasScopeList(ScopeList);
2865}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:352
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:351
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define GET_OR_DISTINCT(CLASS, ARGS)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
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 int64_t unrotateSign(uint64_t U)
static MDNode * rebuildScopeOrDomainNode(MDNode *Old, SmallVectorImpl< Metadata * > &Ops)
Rebuild the alias scope or domain Old with Ops, keeping its identity: a self reference has to point a...
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.
static MDNode * upgradeAliasScope(MDNode *Scope, DenseMap< MDNode *, MDNode * > &Upgraded)
static MDNode * upgradeAliasScopeDomain(MDNode *Domain, DenseMap< MDNode *, MDNode * > &Upgraded)
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define error(X)
std::pair< llvm::MachO::Target, std::string > UUID
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.
MDNode * upgradeAliasScopeList(MDNode *ScopeList)
Mark any domains in ScopeList that don't have a disjointness flag as non-disjoint.
Error parseMetadata(bool ModuleLevel)
Parse a METADATA_BLOCK.
DISubprogram * lookupSubprogramForFunction(Function *F)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
Definition ValueList.cpp:50
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.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
@ AF_DontPopBlockAtEnd
If this flag is used, the advance() method does not automatically pop the block scope when the end of...
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
MDString * getRawIdentifier() const
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
A scope for locals.
DIFlags
Debug info flags.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
DISPFlags
Debug info subprogram flags.
bool isForwardDecl() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:809
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static LocalAsMetadata * get(Value *Local)
Definition Metadata.h:574
Metadata node.
Definition Metadata.h:1081
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1587
bool isTemporary() const
Definition Metadata.h:1265
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1591
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
bool isDistinct() const
Definition Metadata.h:1264
LLVMContext & getContext() const
Definition Metadata.h:1245
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
A single uniqued string.
Definition Metadata.h:733
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:597
Tuple of metadata.
Definition Metadata.h:1496
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1525
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1545
MDNode * upgradeAliasScopeList(MDNode *ScopeList)
Mark any domains in ScopeList that don't have a disjointness flag as non-disjoint.
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.
MetadataLoader & operator=(MetadataLoader &&)
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
iterator end() const
Definition ArrayRef.h:339
iterator begin() const
Definition ArrayRef.h:338
A tuple of MDNodes.
Definition Metadata.h:1797
iterator_range< op_iterator > operands()
Definition Metadata.h:1893
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Metadata * get() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:228
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:514
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
An efficient, type-erasing, non-owning reference to a callable.
Changed
constexpr char LanguageVersion[]
Key for Kernel::Metadata::mLanguageVersion.
@ Entry
Definition COFF.h:862
@ METADATA_COMMON_BLOCK
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_INDEX_OFFSET
@ METADATA_LEXICAL_BLOCK
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_OBJC_PROPERTY
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPILE_UNIT
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_DERIVED_TYPE
@ METADATA_SUBRANGE_TYPE
@ METADATA_TEMPLATE_TYPE
@ METADATA_GLOBAL_VAR_EXPR
@ METADATA_DISTINCT_NODE
@ METADATA_GENERIC_DEBUG
@ METADATA_KIND_BLOCK_ID
@ METADATA_ATTACHMENT_ID
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
Definition Dwarf.h:212
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:144
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
std::enable_if_t< detail::IsValidPointer< X, Y >::value, bool > hasa(Y &&MD)
Check whether Metadata has a Value.
Definition Metadata.h:662
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI Instruction & back() const
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
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:1685
std::error_code make_error_code(BitcodeError E)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
LLVM_ABI MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
auto cast_or_null(const Y &Val)
Definition Casting.h:714
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
static const DIScope * getScope(const NodeT *N)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool mayBeOldLoopAttachmentTag(StringRef Name)
Check whether a string looks like an old loop attachment tag.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI MDNode * UpgradeTBAAStructNode(MDNode &TBAAStructNode)
If the given !tbaa.struct node has old-style scalar field tags, return an equivalent node with each f...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
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:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI 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:1106
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...