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