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