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