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