63#define DEBUG_TYPE "bitcode-reader"
65STATISTIC(NumMDStringLoaded,
"Number of MDStrings loaded");
66STATISTIC(NumMDNodeTemporary,
"Number of MDNode::Temporary created");
67STATISTIC(NumMDRecordLoaded,
"Number of Metadata records loaded");
71class BitcodeReaderMetadataList {
98 unsigned RefsUpperBound;
101 BitcodeReaderMetadataList(LLVMContext &
C,
size_t RefsUpperBound)
103 RefsUpperBound(std::
min((size_t)std::numeric_limits<unsigned>::
max(),
106 using const_iterator = SmallVector<TrackingMDRef, 1>::const_iterator;
109 unsigned size()
const {
return MetadataPtrs.size(); }
110 void resize(
unsigned N) { MetadataPtrs.resize(
N); }
111 void push_back(
Metadata *MD) { MetadataPtrs.emplace_back(MD); }
112 void clear() { MetadataPtrs.clear(); }
114 void pop_back() { MetadataPtrs.pop_back(); }
115 bool empty()
const {
return MetadataPtrs.empty(); }
116 const_iterator
begin()
const {
return MetadataPtrs.begin(); }
117 const_iterator
end()
const {
return MetadataPtrs.end(); }
119 Metadata *operator[](
unsigned i)
const {
return MetadataPtrs[i]; }
122 if (
I < MetadataPtrs.size())
123 return MetadataPtrs[
I];
127 void shrinkTo(
unsigned N) {
128 assert(
N <=
size() &&
"Invalid shrinkTo request!");
129 assert(ForwardReference.empty() &&
"Unexpected forward refs");
130 assert(UnresolvedNodes.empty() &&
"Unexpected unresolved node");
131 MetadataPtrs.resize(
N);
136 Metadata *getMetadataFwdRef(
unsigned Idx);
142 Metadata *getMetadataIfResolved(
unsigned Idx);
144 MDNode *getMDNodeFwdRefOrNull(
unsigned Idx);
145 void assignValue(
Metadata *MD,
unsigned Idx);
146 void tryToResolveCycles();
147 bool hasFwdRefs()
const {
return !ForwardReference.empty(); }
148 int getNextFwdRef() {
150 return *ForwardReference.begin();
154 void addTypeRef(MDString &
UUID, DICompositeType &CT);
169void BitcodeReaderMetadataList::assignValue(
Metadata *MD,
unsigned Idx) {
171 if (!MDN->isResolved())
172 UnresolvedNodes.
insert(Idx);
182 TrackingMDRef &OldMD = MetadataPtrs[
Idx];
190 PrevMD->replaceAllUsesWith(MD);
194Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(
unsigned Idx) {
196 if (Idx >= RefsUpperBound)
202 if (
Metadata *MD = MetadataPtrs[Idx])
209 ++NumMDNodeTemporary;
211 MetadataPtrs[
Idx].reset(MD);
215Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(
unsigned Idx) {
218 if (!
N->isResolved())
223MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(
unsigned Idx) {
227void BitcodeReaderMetadataList::tryToResolveCycles() {
233 for (
const auto &[
UUID, CT] : OldTypeRefs.FwdDecls)
234 OldTypeRefs.Final.try_emplace(
UUID, CT);
235 OldTypeRefs.FwdDecls.clear();
239 for (
const auto &Array : OldTypeRefs.Arrays)
240 Array.second->replaceAllUsesWith(resolveTypeArray(
Array.first.get()));
241 OldTypeRefs.Arrays.clear();
246 for (
const auto &
Ref : OldTypeRefs.Unknown) {
247 if (DICompositeType *CT = OldTypeRefs.Final.lookup(
Ref.first))
248 Ref.second->replaceAllUsesWith(CT);
250 Ref.second->replaceAllUsesWith(
Ref.first);
252 OldTypeRefs.Unknown.clear();
254 if (UnresolvedNodes.
empty())
259 for (
unsigned I : UnresolvedNodes) {
260 auto &MD = MetadataPtrs[
I];
265 assert(!
N->isTemporary() &&
"Unexpected forward reference");
270 UnresolvedNodes.clear();
273void BitcodeReaderMetadataList::addTypeRef(MDString &
UUID,
274 DICompositeType &CT) {
277 OldTypeRefs.FwdDecls.insert(std::make_pair(&
UUID, &CT));
279 OldTypeRefs.Final.insert(std::make_pair(&
UUID, &CT));
287 if (
auto *CT = OldTypeRefs.Final.lookup(
UUID))
290 auto &
Ref = OldTypeRefs.Unknown[
UUID];
296Metadata *BitcodeReaderMetadataList::upgradeTypeArray(
Metadata *MaybeTuple) {
298 if (!Tuple ||
Tuple->isDistinct())
302 if (!
Tuple->isTemporary())
303 return resolveTypeArray(Tuple);
307 OldTypeRefs.Arrays.emplace_back(
308 std::piecewise_construct, std::forward_as_tuple(Tuple),
310 return OldTypeRefs.Arrays.back().second.get();
313Metadata *BitcodeReaderMetadataList::resolveTypeArray(
Metadata *MaybeTuple) {
315 if (!Tuple ||
Tuple->isDistinct())
320 Ops.reserve(
Tuple->getNumOperands());
322 Ops.push_back(upgradeTypeRef(MD));
329class PlaceholderQueue {
332 std::deque<DistinctMDOperandPlaceholder> PHs;
335 ~PlaceholderQueue() {
337 "PlaceholderQueue hasn't been flushed before being destroyed");
339 bool empty()
const {
return PHs.empty(); }
340 DistinctMDOperandPlaceholder &getPlaceholderOp(
unsigned ID);
341 void flush(BitcodeReaderMetadataList &MetadataList);
345 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
346 DenseSet<unsigned> &Temporaries) {
347 for (
auto &PH : PHs) {
348 auto ID = PH.getID();
349 auto *MD = MetadataList.lookup(ID);
355 if (
N &&
N->isTemporary())
363DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(
unsigned ID) {
364 PHs.emplace_back(ID);
368void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
369 while (!PHs.empty()) {
370 auto *MD = MetadataList.lookup(PHs.front().getID());
371 assert(MD &&
"Flushing placeholder on unassigned MD");
374 assert(MDN->isResolved() &&
375 "Flushing Placeholder while cycles aren't resolved");
377 PHs.front().replaceUseWith(MD);
388 const BitReaderOptions &Opts;
389 BitcodeReaderMetadataList MetadataList;
401 FLMDScopeMetadataIDs;
403 FLMDInlineeMetadataIDs;
411 std::vector<StringRef> MDStringRef;
415 MDString *lazyLoadOneMDString(
unsigned Idx);
418 std::vector<uint64_t> GlobalMetadataBitPosIndex;
423 uint64_t GlobalDeclAttachmentPos = 0;
428 unsigned NumGlobalDeclAttachSkipped = 0;
429 unsigned NumGlobalDeclAttachParsed = 0;
442 void lazyLoadOneMetadata(
unsigned Idx, PlaceholderQueue &Placeholders);
446 std::vector<std::pair<DICompileUnit *, unsigned>> CUSubprograms;
460 bool StripTBAA =
false;
461 bool HasSeenOldLoopTags =
false;
466 bool NeedUpgradeToDIGlobalVariableExpression =
false;
467 bool NeedDeclareExpressionUpgrade =
false;
471 GlobalVariableExpression;
477 bool IsImporting =
false;
480 PlaceholderQueue &Placeholders,
StringRef Blob,
481 unsigned &NextMetadataNo);
488 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
491 void upgradeCUSubprograms() {
492 for (
auto CU_SP : CUSubprograms)
495 for (
auto &
Op : SPs->operands())
497 SP->replaceUnit(CU_SP.first);
498 CUSubprograms.clear();
502 void upgradeCUVariables() {
503 if (!NeedUpgradeToDIGlobalVariableExpression)
507 if (
NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu"))
508 for (
unsigned I = 0, E = CUNodes->getNumOperands();
I != E; ++
I) {
511 for (
unsigned I = 0;
I < GVs->getNumOperands();
I++)
524 for (
auto &GV : TheModule.globals()) {
526 GV.getMetadata(LLVMContext::MD_dbg, MDs);
527 GV.eraseMetadata(LLVMContext::MD_dbg);
535 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
537 GV.addMetadata(LLVMContext::MD_dbg, *MD);
544 if (
auto *SP = ParentSubprogram[S]) {
552 if (!Visited.
insert(S).second)
556 return ParentSubprogram[InitialScope] =
562 using SPToEntitiesMap =
568 template <
typename NodeT>
569 void upgradeOneCULocalsList(SPToEntitiesMap &SPToEntities,
DICompileUnit *
CU,
570 unsigned ListIndex) {
576 return !isa_and_nonnull<DILocalScope>(getScope(cast<NodeT>(MD)));
586 else if (
auto *SP = findEnclosingSubprogram(LS))
587 SPToEntities[SP].push_back(MD);
595 void upgradeCULocals() {
596 NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu");
600 SPToEntitiesMap SPToEntities;
607 upgradeOneCULocalsList<DIGlobalVariableExpression>(SPToEntities,
CU, 6);
609 upgradeOneCULocalsList<DIImportedEntity>(SPToEntities,
CU, 7);
611 upgradeOneCULocalsList<DICompositeType>(SPToEntities,
CU, 4);
615 for (
auto &[SP, Nodes] : SPToEntities)
616 SP->retainNodes(Nodes.begin(), Nodes.end());
617 SPToEntities.clear();
620 ParentSubprogram.clear();
625 void upgradeDeclareExpressions(
Function &
F) {
626 if (!NeedDeclareExpressionUpgrade)
629 auto UpdateDeclareIfNeeded = [&](
auto *Declare) {
630 auto *DIExpr = Declare->getExpression();
631 if (!DIExpr || !DIExpr->startsWithDeref() ||
635 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
642 if (DVR.isDbgDeclare())
643 UpdateDeclareIfNeeded(&DVR);
646 UpdateDeclareIfNeeded(DDI);
651 Error upgradeDIExpression(uint64_t FromVersion,
654 auto N = Expr.
size();
655 switch (FromVersion) {
657 return error(
"Invalid record");
659 if (
N >= 3 && Expr[
N - 3] == dwarf::DW_OP_bit_piece)
664 if (
N && Expr[0] == dwarf::DW_OP_deref) {
666 if (Expr.
size() >= 3 &&
670 *std::prev(
End) = dwarf::DW_OP_deref;
672 NeedDeclareExpressionUpgrade =
true;
678 while (!SubExpr.empty()) {
683 switch (SubExpr.front()) {
687 case dwarf::DW_OP_constu:
688 case dwarf::DW_OP_minus:
689 case dwarf::DW_OP_plus:
699 HistoricSize = std::min(SubExpr.size(), HistoricSize);
702 switch (SubExpr.front()) {
703 case dwarf::DW_OP_plus:
704 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
705 Buffer.
append(Args.begin(), Args.end());
707 case dwarf::DW_OP_minus:
709 Buffer.
append(Args.begin(), Args.end());
714 Buffer.
append(Args.begin(), Args.end());
719 SubExpr = SubExpr.slice(HistoricSize);
737 enum class DebugInfoUpgradeMode {
746 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
747 if (Mode == DebugInfoUpgradeMode::None)
749 upgradeCUSubprograms();
750 upgradeCUVariables();
751 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
756 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
757 DebugInfoUpgradeMode DIUpgradeMode) {
758 resolveForwardRefsAndPlaceholders(Placeholders);
759 upgradeDebugInfo(DIUpgradeMode);
762 << NewDistinctSPs.size() <<
" subprogram(s).\n");
763 NewDistinctSPs.clear();
766 void callMDTypeCallback(
Metadata **Val,
unsigned TypeID);
773 MetadataList(TheModule.
getContext(), Stream.SizeInBytes()),
774 ValueList(ValueList), Stream(Stream), Context(TheModule.
getContext()),
775 TheModule(TheModule), Callbacks(
std::
move(Callbacks)),
776 IsImporting(IsImporting) {}
780 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
783 if (ID < MDStringRef.size())
784 return lazyLoadOneMDString(ID);
785 if (
auto *MD = MetadataList.lookup(ID))
789 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
790 PlaceholderQueue Placeholders;
791 lazyLoadOneMetadata(ID, Placeholders);
793 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
794 return MetadataList.lookup(ID);
796 return MetadataList.getMetadataFwdRef(ID);
800 return FunctionsWithSPs.lookup(
F);
817 unsigned size()
const {
return MetadataList.size(); }
823MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
824 IndexCursor = Stream;
826 GlobalDeclAttachmentPos = 0;
829 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
837 switch (Entry.Kind) {
840 return error(
"Malformed block");
847 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
849 if (
Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
854 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
855 return std::move(Err);
859 IndexCursor.readRecord(Entry.ID,
Record, &Blob))
862 return MaybeRecord.takeError();
863 unsigned NumStrings =
Record[0];
864 MDStringRef.reserve(NumStrings);
865 auto IndexNextMDString = [&](
StringRef Str) {
866 MDStringRef.push_back(Str);
868 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
869 return std::move(Err);
875 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
876 return std::move(Err);
878 if (Expected<unsigned> MaybeRecord =
879 IndexCursor.readRecord(
Entry.ID, Record))
882 return MaybeRecord.takeError();
884 return error(
"Invalid record");
886 auto BeginPos = IndexCursor.GetCurrentBitNo();
887 if (
Error Err = IndexCursor.JumpToBit(BeginPos +
Offset))
888 return std::move(Err);
889 Expected<BitstreamEntry> MaybeEntry =
890 IndexCursor.advanceSkippingSubblocks(
896 "Corrupted bitcode: Expected `Record` when trying to find the "
899 if (Expected<unsigned> MaybeCode =
900 IndexCursor.readRecord(
Entry.ID, Record))
902 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
903 "find the Metadata index");
905 return MaybeCode.takeError();
907 auto CurrentValue = BeginPos;
908 GlobalMetadataBitPosIndex.reserve(
Record.size());
909 for (
auto &Elt : Record) {
911 GlobalMetadataBitPosIndex.push_back(CurrentValue);
918 return error(
"Corrupted Metadata block");
921 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
922 return std::move(Err);
926 if (Expected<unsigned> MaybeCode =
927 IndexCursor.readRecord(
Entry.ID, Record)) {
928 Code = MaybeCode.get();
931 return MaybeCode.takeError();
935 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
936 Code = MaybeCode.get();
938 return MaybeCode.takeError();
943 if (Expected<unsigned> MaybeNextBitCode =
944 IndexCursor.readRecord(Code, Record))
947 return MaybeNextBitCode.takeError();
951 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
952 for (
unsigned i = 0; i !=
Size; ++i) {
957 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
958 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
964 if (!GlobalDeclAttachmentPos)
965 GlobalDeclAttachmentPos = SavedPos;
967 NumGlobalDeclAttachSkipped++;
1011 MDStringRef.clear();
1012 GlobalMetadataBitPosIndex.clear();
1026Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1028 if (!GlobalDeclAttachmentPos)
1032 BitstreamCursor TempCursor = Stream;
1033 SmallVector<uint64_t, 64>
Record;
1037 return std::move(Err);
1039 BitstreamEntry
Entry;
1044 return std::move(
E);
1046 switch (
Entry.Kind) {
1049 return error(
"Malformed block");
1052 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1064 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1068 NumGlobalDeclAttachParsed++;
1073 return std::move(Err);
1075 if (Expected<unsigned> MaybeRecord =
1079 return MaybeRecord.takeError();
1080 if (
Record.size() % 2 == 0)
1081 return error(
"Invalid record");
1082 unsigned ValueID =
Record[0];
1083 if (ValueID >= ValueList.size())
1084 return error(
"Invalid record");
1090 if (
Error Err = parseGlobalObjectAttachment(
1091 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1092 return std::move(Err);
1094 return std::move(Err);
1099void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1101 if (Callbacks.MDType) {
1102 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1103 Callbacks.GetContainedTypeID);
1111 if (!ModuleLevel && MetadataList.hasFwdRefs())
1112 return error(
"Invalid metadata: fwd refs into function blocks");
1116 auto EntryPos = Stream.GetCurrentBitNo();
1122 PlaceholderQueue Placeholders;
1123 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1124 : DebugInfoUpgradeMode::Partial;
1128 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1129 Opts.ondemand_mds_loading) {
1130 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1132 return SuccessOrErr.takeError();
1133 if (SuccessOrErr.get()) {
1136 MetadataList.resize(MDStringRef.size() +
1137 GlobalMetadataBitPosIndex.size());
1142 SuccessOrErr = loadGlobalDeclAttachments();
1144 return SuccessOrErr.takeError();
1145 assert(SuccessOrErr.get());
1150 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1153 Stream.ReadBlockEnd();
1154 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1156 if (
Error Err = Stream.SkipBlock()) {
1167 unsigned NextMetadataNo = MetadataList.size();
1172 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1175 switch (Entry.Kind) {
1178 return error(
"Malformed block");
1181 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1191 ++NumMDRecordLoaded;
1193 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1194 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1195 Blob, NextMetadataNo))
1202MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1203 ++NumMDStringLoaded;
1204 if (
Metadata *MD = MetadataList.lookup(ID))
1207 MetadataList.assignValue(MDS, ID);
1211void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1212 unsigned ID, PlaceholderQueue &Placeholders) {
1213 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1214 assert(ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1216 if (
auto *MD = MetadataList.lookup(ID)) {
1220 if (!
N || !
N->isTemporary())
1225 if (
Error Err = IndexCursor.JumpToBit(
1226 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1230 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1234 ++NumMDRecordLoaded;
1236 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1238 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob, ID))
1248void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1249 PlaceholderQueue &Placeholders) {
1250 DenseSet<unsigned> Temporaries;
1253 Placeholders.getTemporaries(MetadataList, Temporaries);
1256 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1261 for (
auto ID : Temporaries)
1262 lazyLoadOneMetadata(ID, Placeholders);
1263 Temporaries.clear();
1267 while (MetadataList.hasFwdRefs())
1268 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1273 MetadataList.tryToResolveCycles();
1277 Placeholders.flush(MetadataList);
1280 for (
auto &[FLMD, ScopeMDs] : FLMDScopeMetadataIDs) {
1281 for (
size_t ScopeIdx = 0; ScopeIdx < FLMD->Scopes.size(); ++ScopeIdx) {
1284 if (FLMD->Scopes[ScopeIdx].Scope)
1286 Metadata *ScopeMD = MetadataList.lookup(ScopeMDs[ScopeIdx]);
1292 for (
auto &[FLMD, InlineeMDs] : FLMDInlineeMetadataIDs) {
1293 for (
size_t InlinedCallIdx = 0; InlinedCallIdx < FLMD->InlinedCalls.size();
1297 if (FLMD->InlinedCalls[InlinedCallIdx].InlineeContext)
1300 MetadataList.lookup(InlineeMDs[InlinedCallIdx]);
1303 FLMD->InlinedCalls[InlinedCallIdx].InlineeContext =
1307 FLMDScopeMetadataIDs.clear();
1308 FLMDInlineeMetadataIDs.clear();
1312 Type *Ty,
unsigned TyID) {
1324 if (Idx < ValueList.
size() && ValueList[Idx] &&
1325 ValueList[Idx]->getType() == Ty)
1331Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1332 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1333 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1335 bool IsDistinct =
false;
1336 auto getMD = [&](
unsigned ID,
bool ForceLazyLoad =
false) ->
Metadata * {
1337 if (ID < MDStringRef.size())
1338 return lazyLoadOneMDString(ID);
1339 if (!IsDistinct || ForceLazyLoad) {
1340 if (
auto *MD = MetadataList.lookup(ID))
1344 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1348 MetadataList.getMetadataFwdRef(NextMetadataNo);
1349 lazyLoadOneMetadata(ID, Placeholders);
1350 return MetadataList.lookup(ID);
1354 return MetadataList.getMetadataFwdRef(ID);
1356 if (
auto *MD = MetadataList.getMetadataIfResolved(ID))
1358 return &Placeholders.getPlaceholderOp(ID);
1360 auto getMDOrNull = [&](
unsigned ID,
1361 bool ForceLazyLoad =
false) ->
Metadata * {
1363 return getMD(ID - 1, ForceLazyLoad);
1366 auto getMDString = [&](
unsigned ID) -> MDString * {
1369 auto MDS = getMDOrNull(ID);
1374 auto getDITypeRefOrNull = [&](
unsigned ID) {
1375 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1378 auto getMetadataOrConstant = [&](
bool IsMetadata,
uint64_t Entry,
1379 bool ForceLazyLoad =
false) ->
Metadata * {
1381 return getMDOrNull(Entry, ForceLazyLoad);
1383 ConstantInt::get(Type::getInt64Ty(
Context), Entry));
1386#define GET_OR_DISTINCT(CLASS, ARGS) \
1387 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1396 if (
Error E = Stream.ReadCode().moveInto(Code))
1399 ++NumMDRecordLoaded;
1400 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1402 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1404 return MaybeNextBitCode.takeError();
1408 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1409 for (
unsigned i = 0; i !=
Size; ++i) {
1410 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1412 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1421 if (
Record.size() % 2 == 1)
1422 return error(
"Invalid record");
1426 auto dropRecord = [&] {
1430 if (
Record.size() != 2) {
1435 unsigned TyID =
Record[0];
1436 Type *Ty = Callbacks.GetTypeByID(TyID);
1442 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1445 return error(
"Invalid value reference from old fn metadata");
1453 if (
Record.size() % 2 == 1)
1454 return error(
"Invalid record");
1458 for (
unsigned i = 0; i !=
Size; i += 2) {
1459 unsigned TyID =
Record[i];
1460 Type *Ty = Callbacks.GetTypeByID(TyID);
1462 return error(
"Invalid record");
1468 return error(
"Invalid value reference from old metadata");
1471 "Expected non-function-local metadata");
1472 callMDTypeCallback(&MD, TyID);
1483 return error(
"Invalid record");
1485 unsigned TyID =
Record[0];
1486 Type *Ty = Callbacks.GetTypeByID(TyID);
1488 return error(
"Invalid record");
1492 return error(
"Invalid value reference from metadata");
1495 callMDTypeCallback(&MD, TyID);
1496 MetadataList.assignValue(MD, NextMetadataNo);
1506 for (
unsigned ID : Record)
1517 return error(
"Invalid record");
1521 unsigned Column =
Record[2];
1523 Metadata *InlinedAt = getMDOrNull(Record[4]);
1527 Metadata *IRLayers =
Record.size() >= 9 ? getMDOrNull(Record[8]) : nullptr;
1528 MetadataList.assignValue(
1530 (
Context, Line, Column, Scope, InlinedAt, ImplicitCode,
1531 AtomGroup, AtomRank, IRLayers)),
1538 return error(
"Invalid record");
1542 unsigned Column =
Record[2];
1547 MetadataList.assignValue(
1555 return error(
"Invalid record");
1559 for (
unsigned I = 1,
E =
Record.size();
I !=
E; ++
I)
1568 return error(
"Invalid record");
1575 return error(
"Invalid record");
1577 auto *Header = getMDString(Record[3]);
1579 for (
unsigned I = 4,
E =
Record.size();
I !=
E; ++
I)
1581 MetadataList.assignValue(
1597 switch (Record[0] >> 1) {
1608 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1609 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1612 return error(
"Invalid record: Unsupported version of DISubrange");
1615 MetadataList.assignValue(Val, NextMetadataNo);
1616 IsDistinct =
Record[0] & 1;
1623 (
Context, getMDOrNull(Record[1]),
1624 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1625 getMDOrNull(Record[4])));
1627 MetadataList.assignValue(Val, NextMetadataNo);
1628 IsDistinct =
Record[0] & 1;
1634 return error(
"Invalid record");
1636 IsDistinct =
Record[0] & 1;
1637 bool IsUnsigned =
Record[0] & 2;
1638 bool IsBigInt =
Record[0] & 4;
1643 const size_t NumWords =
Record.size() - 3;
1648 MetadataList.assignValue(
1657 return error(
"Invalid record");
1659 IsDistinct =
Record[0] & 1;
1660 bool SizeIsMetadata =
Record[0] & 2;
1664 uint32_t NumExtraInhabitants = (
Record.size() > 7) ?
Record[7] : 0;
1665 uint32_t DataSizeInBits = (
Record.size() > 8) ?
Record[8] : 0;
1666 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1668 unsigned LineNo = 0;
1671 File = getMDOrNull(Record[9]);
1673 Scope = getMDOrNull(Record[11]);
1675 MetadataList.assignValue(
1677 (
Context, Record[1], getMDString(Record[2]), File,
1678 LineNo, Scope, SizeInBits, Record[4], Record[5],
1679 NumExtraInhabitants, DataSizeInBits, Flags)),
1686 return error(
"Invalid record");
1688 IsDistinct =
Record[0] & 1;
1689 bool SizeIsMetadata =
Record[0] & 2;
1692 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1696 auto ReadWideInt = [&]() {
1698 unsigned NumWords =
Encoded >> 32;
1705 APInt Numerator = ReadWideInt();
1706 APInt Denominator = ReadWideInt();
1709 unsigned LineNo = 0;
1717 return error(
"Invalid record");
1719 MetadataList.assignValue(
1721 (
Context, Record[1], getMDString(Record[2]), File,
1722 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1723 Record[7], Record[8], Numerator, Denominator)),
1730 return error(
"Invalid record");
1732 IsDistinct =
Record[0] & 1;
1733 bool SizeIsMetadata =
Record[0] & 2;
1738 Metadata *StringLocationExp =
nullptr;
1741 bool StringLocPresent =
Record.size() > 8;
1742 size_t SizeOffset = StringLocPresent ? 6 : 5;
1745 getMetadataOrConstant(SizeIsMetadata, Record[SizeOffset]);
1746 if (StringLocPresent) {
1747 StringLocationExp = getMDOrNull(Record[5]);
1749 if (
Record.size() == 10) {
1750 CharType = getMDOrNull(Record[9]);
1753 MetadataList.assignValue(
1755 (
Context, Record[1], getMDString(Record[2]),
1756 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1757 StringLocationExp, SizeInBits, Record[SizeOffset + 1],
1758 Record[SizeOffset + 2], CharType)),
1765 return error(
"Invalid record");
1769 std::optional<unsigned> DWARFAddressSpace;
1770 if (
Record.size() > 12 && Record[12])
1771 DWARFAddressSpace =
Record[12] - 1;
1774 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1779 if (
Record.size() > 14) {
1781 Annotations = getMDOrNull(Record[13]);
1783 PtrAuthData.emplace(Record[14]);
1786 IsDistinct =
Record[0] & 1;
1787 bool SizeIsMetadata =
Record[0] & 2;
1790 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1791 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1793 MetadataList.assignValue(
1795 (
Context, Record[1], getMDString(Record[2]),
1796 getMDOrNull(Record[3]), Record[4],
1797 getDITypeRefOrNull(Record[5]),
1798 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1799 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1800 getDITypeRefOrNull(Record[11]), Annotations)),
1807 return error(
"Invalid record");
1809 IsDistinct =
Record[0] & 1;
1810 bool SizeIsMetadata =
Record[0] & 2;
1813 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1815 MetadataList.assignValue(
1817 (
Context, getMDString(Record[1]),
1818 getMDOrNull(Record[2]), Record[3],
1819 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1820 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1821 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1822 getMDOrNull(Record[12]))),
1829 return error(
"Invalid record");
1833 IsDistinct =
Record[0] & 0x1;
1834 bool IsNotUsedInTypeRef =
Record[0] & 2;
1835 bool SizeIsMetadata =
Record[0] & 4;
1837 MDString *
Name = getMDString(Record[2]);
1842 if (Record[8] > (
uint64_t)std::numeric_limits<uint32_t>::max())
1843 return error(
"Alignment value is too large");
1844 uint32_t AlignInBits =
Record[8];
1846 uint32_t NumExtraInhabitants = (
Record.size() > 22) ?
Record[22] : 0;
1849 unsigned RuntimeLang =
Record[12];
1850 std::optional<uint32_t> EnumKind;
1853 Metadata *TemplateParams =
nullptr;
1877 if (IsImporting && !Opts.import_full_type_definitions && Identifier &&
1879 (
Tag == dwarf::DW_TAG_enumeration_type ||
1880 Tag == dwarf::DW_TAG_class_type ||
1881 Tag == dwarf::DW_TAG_structure_type ||
1882 Tag == dwarf::DW_TAG_union_type)) {
1888 StringRef NameStr =
Name->getString();
1890 TemplateParams = getMDOrNull(Record[14]);
1892 BaseType = getDITypeRefOrNull(Record[6]);
1894 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1896 Elements = getMDOrNull(Record[11]);
1897 VTableHolder = getDITypeRefOrNull(Record[13]);
1898 TemplateParams = getMDOrNull(Record[14]);
1902 DataLocation = getMDOrNull(Record[17]);
1903 if (
Record.size() > 19) {
1904 Associated = getMDOrNull(Record[18]);
1905 Allocated = getMDOrNull(Record[19]);
1907 if (
Record.size() > 20) {
1908 Rank = getMDOrNull(Record[20]);
1910 if (
Record.size() > 21) {
1911 Annotations = getMDOrNull(Record[21]);
1913 if (
Record.size() > 23) {
1914 Specification = getMDOrNull(Record[23]);
1917 BitStride = getMDOrNull(Record[25]);
1925 Metadata *SizeInBits = getMetadataOrConstant(
1926 SizeIsMetadata, Record[7],
1927 Identifier &&
Context.isODRUniquingDebugTypes());
1929 DICompositeType *CT =
nullptr;
1933 SizeInBits, AlignInBits, OffsetInBits, Specification,
1934 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1935 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1936 Allocated, Rank, Annotations, BitStride);
1943 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1944 VTableHolder, TemplateParams, Identifier, Discriminator,
1945 DataLocation, Associated, Allocated, Rank, Annotations,
1946 Specification, NumExtraInhabitants, BitStride));
1947 if (!IsNotUsedInTypeRef && Identifier)
1950 MetadataList.assignValue(CT, NextMetadataNo);
1956 return error(
"Invalid record");
1957 bool IsOldTypeArray =
Record[0] < 2;
1960 IsDistinct =
Record[0] & 0x1;
1964 Types = MetadataList.upgradeTypeArray(Types);
1966 MetadataList.assignValue(
1975 return error(
"Invalid record");
1979 MetadataList.assignValue(
1982 (
Context,
Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
1983 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
1984 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
1985 getMDString(Record[4 +
Offset]),
1986 Record.size() <= 7 ? 0 : Record[7],
1987 Record.size() <= 8 ?
false : Record[8])),
1995 return error(
"Invalid record");
1998 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
2004 if (
Record.size() > 4 && Record[3] && Record[4])
2006 getMDString(Record[4]));
2007 MetadataList.assignValue(
2009 (
Context, getMDString(Record[1]),
2010 getMDString(Record[2]), Checksum,
2011 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
2018 return error(
"Invalid record");
2024 const auto LangVersionMask = (
uint64_t(1) << 63);
2025 const bool HasVersionedLanguage =
Record[1] & LangVersionMask;
2032 if (
Record.size() > 23 &&
2034 return error(
"Invalid DICompileUnit dialect value");
2035 const uint16_t Dialect =
2036 Record.size() > 23 ?
static_cast<uint16_t
>(
Record[23]) : uint16_t(0);
2038 auto *CU = DICompileUnit::getDistinct(
2040 HasVersionedLanguage
2041 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
2042 LanguageVersion, Dialect)
2043 : DISourceLanguageName(Record[1], Dialect),
2044 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
2045 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
2046 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2047 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2048 Record.size() <= 15 ?
nullptr : getMDOrNull(Record[15]),
2049 Record.size() <= 14 ? 0 : Record[14],
2050 Record.size() <= 16 ?
true : Record[16],
2051 Record.size() <= 17 ?
false : Record[17],
2052 Record.size() <= 18 ? 0 : Record[18],
2053 Record.size() <= 19 ?
false : Record[19],
2058 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
2059 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
2061 MetadataList.assignValue(CU, NextMetadataNo);
2066 CUSubprograms.push_back({CU,
Record[11]});
2071 return error(
"Invalid record");
2073 bool HasSPFlags =
Record[0] & 4;
2086 const unsigned DIFlagMainSubprogram = 1 << 21;
2087 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
2088 if (HasOldMainSubprogramFlag)
2092 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2094 if (HasOldMainSubprogramFlag && HasSPFlags)
2095 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2096 else if (!HasSPFlags)
2098 Record[7], Record[8],
2099 Record[14], Record[11],
2100 HasOldMainSubprogramFlag);
2103 IsDistinct = (
Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2109 bool HasUnit =
Record[0] & 2;
2110 if (!HasSPFlags && HasUnit &&
Record.size() < 19)
2111 return error(
"Invalid record");
2112 if (HasSPFlags && !HasUnit)
2113 return error(
"Invalid record");
2116 bool HasThisAdj =
true;
2117 bool HasThrownTypes =
true;
2118 bool HasAnnotations =
false;
2119 bool HasTargetFuncName =
false;
2120 unsigned OffsetA = 0;
2121 unsigned OffsetB = 0;
2124 bool UsesKeyInstructions =
false;
2128 if (
Record.size() >= 19) {
2132 HasThisAdj =
Record.size() >= 20;
2133 HasThrownTypes =
Record.size() >= 21;
2135 HasAnnotations =
Record.size() >= 19;
2136 HasTargetFuncName =
Record.size() >= 20;
2137 UsesKeyInstructions =
Record.size() >= 21 ?
Record[20] : 0;
2140 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2144 getDITypeRefOrNull(Record[1]),
2145 getMDString(Record[2]),
2146 getMDString(Record[3]),
2147 getMDOrNull(Record[4]),
2149 getMDOrNull(Record[6]),
2150 Record[7 + OffsetA],
2151 getDITypeRefOrNull(Record[8 + OffsetA]),
2152 Record[10 + OffsetA],
2153 HasThisAdj ? Record[16 + OffsetB] : 0,
2156 HasUnit ? CUorFn :
nullptr,
2157 getMDOrNull(Record[13 + OffsetB]),
2158 getMDOrNull(Record[14 + OffsetB]),
2159 getMDOrNull(Record[15 + OffsetB]),
2160 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2162 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2164 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2166 UsesKeyInstructions));
2167 MetadataList.assignValue(SP, NextMetadataNo);
2171 NewDistinctSPs.push_back(SP);
2177 if (
F->isMaterializable())
2180 FunctionsWithSPs[
F] =
SP;
2181 else if (!
F->empty())
2182 F->setSubprogram(SP);
2189 return error(
"Invalid record");
2192 MetadataList.assignValue(
2194 (
Context, getMDOrNull(Record[1]),
2195 getMDOrNull(Record[2]), Record[3], Record[4])),
2202 return error(
"Invalid record");
2205 MetadataList.assignValue(
2207 (
Context, getMDOrNull(Record[1]),
2208 getMDOrNull(Record[2]), Record[3])),
2214 IsDistinct =
Record[0] & 1;
2215 MetadataList.assignValue(
2217 (
Context, getMDOrNull(Record[1]),
2218 getMDOrNull(Record[2]), getMDString(Record[3]),
2219 getMDOrNull(Record[4]), Record[5])),
2228 Name = getMDString(Record[2]);
2229 else if (
Record.size() == 5)
2230 Name = getMDString(Record[3]);
2232 return error(
"Invalid record");
2234 IsDistinct =
Record[0] & 1;
2235 bool ExportSymbols =
Record[0] & 2;
2236 MetadataList.assignValue(
2238 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2245 return error(
"Invalid record");
2248 MetadataList.assignValue(
2250 (
Context, Record[1], Record[2], getMDString(Record[3]),
2251 getMDString(Record[4]))),
2258 return error(
"Invalid record");
2261 MetadataList.assignValue(
2263 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2264 getMDOrNull(Record[4]))),
2271 return error(
"Invalid record");
2274 MetadataList.assignValue(
2276 (
Context, getMDString(Record[1]),
2277 getDITypeRefOrNull(Record[2]),
2278 (
Record.size() == 4) ? getMDOrNull(Record[3])
2279 : getMDOrNull(
false))),
2286 return error(
"Invalid record");
2290 MetadataList.assignValue(
2292 DITemplateValueParameter,
2293 (
Context, Record[1], getMDString(Record[2]),
2294 getDITypeRefOrNull(Record[3]),
2295 (
Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2296 (
Record.size() == 6) ? getMDOrNull(Record[5])
2297 : getMDOrNull(Record[4]))),
2304 return error(
"Invalid record");
2306 IsDistinct =
Record[0] & 1;
2312 Annotations = getMDOrNull(Record[12]);
2314 MetadataList.assignValue(
2316 (
Context, getMDOrNull(Record[1]),
2317 getMDString(Record[2]), getMDString(Record[3]),
2318 getMDOrNull(Record[4]), Record[5],
2319 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2320 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2321 Record[11], Annotations)),
2328 MetadataList.assignValue(
2331 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2332 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2333 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2334 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2341 NeedUpgradeToDIGlobalVariableExpression =
true;
2342 Metadata *Expr = getMDOrNull(Record[9]);
2343 uint32_t AlignInBits = 0;
2344 if (
Record.size() > 11) {
2345 if (Record[11] > (
uint64_t)std::numeric_limits<uint32_t>::max())
2346 return error(
"Alignment value is too large");
2347 AlignInBits =
Record[11];
2349 GlobalVariable *Attach =
nullptr;
2355 Expr = DIExpression::get(
Context,
2356 {dwarf::DW_OP_constu, CI->getZExtValue(),
2357 dwarf::DW_OP_stack_value});
2364 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2365 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2366 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2367 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2369 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
2370 if (Attach || Expr) {
2372 DGVE = DIGlobalVariableExpression::getDistinct(
2380 MetadataList.assignValue(MDNode, NextMetadataNo);
2383 return error(
"Invalid record");
2389 return error(
"Invalid DIAssignID record.");
2391 IsDistinct =
Record[0] & 1;
2393 return error(
"Invalid DIAssignID record. Must be distinct");
2402 return error(
"Invalid record");
2404 IsDistinct =
Record[0] & 1;
2405 bool HasAlignment =
Record[0] & 2;
2409 bool HasTag = !HasAlignment &&
Record.size() > 8;
2411 uint32_t AlignInBits = 0;
2414 if (Record[8] > (
uint64_t)std::numeric_limits<uint32_t>::max())
2415 return error(
"Alignment value is too large");
2418 Annotations = getMDOrNull(Record[9]);
2421 MetadataList.assignValue(
2423 (
Context, getMDOrNull(Record[1 + HasTag]),
2424 getMDString(Record[2 + HasTag]),
2425 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2426 getDITypeRefOrNull(Record[5 + HasTag]),
2427 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2434 return error(
"Invalid record");
2436 IsDistinct =
Record[0] & 1;
2439 bool IsArtificial =
Record[0] & 2;
2440 std::optional<unsigned> CoroSuspendIdx;
2443 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2444 if (RawSuspendIdx > (
uint64_t)std::numeric_limits<unsigned>::max())
2445 return error(
"CoroSuspendIdx value is too large");
2446 CoroSuspendIdx = RawSuspendIdx;
2450 MetadataList.assignValue(
2452 (
Context, getMDOrNull(Record[1]),
2453 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2454 Column, IsArtificial, CoroSuspendIdx)),
2461 return error(
"Invalid record");
2463 IsDistinct =
Record[0] & 1;
2468 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2478 return error(
"Invalid record");
2481 Metadata *Expr = getMDOrNull(Record[2]);
2483 Expr = DIExpression::get(
Context, {});
2484 MetadataList.assignValue(
2486 (
Context, getMDOrNull(Record[1]), Expr)),
2493 return error(
"Invalid record");
2496 MetadataList.assignValue(
2498 (
Context, getMDString(Record[1]),
2499 getMDOrNull(Record[2]), Record[3],
2500 getMDString(Record[5]),
2501 getMDString(Record[4]), Record[6],
2502 getDITypeRefOrNull(Record[7]))),
2509 return error(
"Invalid record");
2512 MetadataList.assignValue(
2514 getMDOrNull(Record[2]), Record[3],
2515 getDITypeRefOrNull(Record[4]),
2516 getMDOrNull(Record[5]))),
2523 return error(
"Invalid DIImportedEntity record");
2526 bool HasFile = (
Record.size() >= 7);
2527 bool HasElements = (
Record.size() >= 8);
2528 MetadataList.assignValue(
2530 (
Context, Record[1], getMDOrNull(Record[2]),
2531 getDITypeRefOrNull(Record[3]),
2532 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2533 HasFile ? Record[4] : 0, getMDString(Record[5]),
2534 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2544 ++NumMDStringLoaded;
2546 MetadataList.assignValue(MD, NextMetadataNo);
2551 auto CreateNextMDString = [&](StringRef Str) {
2555 ++NumMDStringLoaded;
2559 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2564 if (
Record.size() % 2 == 0)
2565 return error(
"Invalid record");
2566 unsigned ValueID =
Record[0];
2567 if (ValueID >= ValueList.size())
2568 return error(
"Invalid record");
2570 if (
Error Err = parseGlobalObjectAttachment(
2571 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2578 if (
Error Err = parseMetadataKindRecord(Record))
2589 "Invalid record: DIArgList should not contain forward refs");
2591 return error(
"Invalid record");
2604 size_t NumRecords =
Record.size();
2607 return error(
"Invalid record");
2608 bool IsNonDebug =
Record[0] & 1;
2613 MDFunctionLocalContext *NewFLMD =
2617 MetadataList.assignValue(NewFLMD, NextMetadataNo);
2624 if (NumRecords - CurrentRecord < NumScopes + 2)
2625 return error(
"Invalid record");
2629 SmallVectorImpl<uint64_t> *ScopeFwdRefs =
nullptr;
2630 for (
uint64_t ScopeIdx = 0; ScopeIdx < NumScopes; ++ScopeIdx) {
2632 auto *ScopeMD = getMD(Scope);
2636 NewFLMD->Scopes.push_back(FLScope(ScopeNode));
2638 if (!ScopeFwdRefs) {
2639 FLMDScopeMetadataIDs.push_back({NewFLMD, {}});
2640 ScopeFwdRefs = &FLMDScopeMetadataIDs.
back().second;
2643 (*ScopeFwdRefs)[ScopeIdx] =
Scope;
2644 NewFLMD->Scopes.push_back(FLScope(
nullptr));
2650 if (NumRecords - CurrentRecord < (NumSrcLocs * 3) + 1)
2651 return error(
"Invalid record");
2652 for (
uint64_t SrcLocIdx = 0; SrcLocIdx < NumSrcLocs; ++SrcLocIdx) {
2654 uint16_t Column =
Record[CurrentRecord++];
2655 uint16_t RawScopeIdx =
Record[CurrentRecord++];
2656 NewFLMD->SrcLocs.push_back(
2663 if (NumRecords - CurrentRecord != (NumInlinedCalls * 3))
2664 return error(
"Invalid record");
2668 SmallVectorImpl<uint64_t> *InlinedCallFwdRefs =
nullptr;
2669 for (
uint64_t InlinedCallIdx = 0; InlinedCallIdx < NumInlinedCalls;
2671 uint32_t RawSrcLocIdx =
Record[CurrentRecord++];
2673 uint32_t RawInlinedAtUniquable =
Record[CurrentRecord++];
2674 uint16_t RawInlinedAtIdx = RawInlinedAtUniquable >> 1;
2675 bool Uniquable = RawInlinedAtUniquable & 1;
2677 auto *InlineeMD = getMD(InlineeContext);
2678 if (MDFunctionLocalContext *InlineeFLContext =
2680 NewFLMD->InlinedCalls.push_back(
2683 InlineeFLContext, Uniquable));
2685 if (!InlinedCallFwdRefs) {
2686 FLMDInlineeMetadataIDs.push_back({NewFLMD, {}});
2687 InlinedCallFwdRefs = &FLMDInlineeMetadataIDs.
back().second;
2690 (*InlinedCallFwdRefs)[InlinedCallIdx] = InlineeContext;
2691 NewFLMD->InlinedCalls.push_back(
2694 nullptr, Uniquable));
2702#undef GET_OR_DISTINCT
2705Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2706 ArrayRef<uint64_t> Record, StringRef Blob,
2707 function_ref<
void(StringRef)> CallBack) {
2712 return error(
"Invalid record: metadata strings layout");
2714 unsigned NumStrings =
Record[0];
2715 unsigned StringsOffset =
Record[1];
2717 return error(
"Invalid record: metadata strings with no strings");
2718 if (StringsOffset > Blob.
size())
2719 return error(
"Invalid record: metadata strings corrupt offset");
2721 StringRef Lengths = Blob.
slice(0, StringsOffset);
2722 SimpleBitstreamCursor
R(Lengths);
2724 StringRef Strings = Blob.
drop_front(StringsOffset);
2726 if (
R.AtEndOfStream())
2727 return error(
"Invalid record: metadata strings bad length");
2733 return error(
"Invalid record: metadata strings truncated chars");
2737 }
while (--NumStrings);
2742Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2743 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2745 for (
unsigned I = 0,
E =
Record.size();
I !=
E;
I += 2) {
2746 auto K = MDKindMap.find(Record[
I]);
2747 if (K == MDKindMap.end())
2748 return error(
"Invalid ID");
2752 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2765 PlaceholderQueue Placeholders;
2769 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2772 switch (Entry.Kind) {
2775 return error(
"Malformed block");
2778 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2787 ++NumMDRecordLoaded;
2791 switch (MaybeRecord.
get()) {
2795 unsigned RecordLength =
Record.size();
2797 return error(
"Invalid record");
2798 if (RecordLength % 2 == 0) {
2800 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2807 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2808 unsigned Kind =
Record[i];
2809 auto I = MDKindMap.find(Kind);
2810 if (
I == MDKindMap.end())
2811 return error(
"Invalid ID");
2812 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2815 auto Idx =
Record[i + 1];
2816 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2817 !MetadataList.lookup(Idx)) {
2820 lazyLoadOneMetadata(Idx, Placeholders);
2822 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2832 return error(
"Invalid metadata attachment");
2834 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2837 if (
I->second == LLVMContext::MD_tbaa) {
2840 }
else if (
I->second == LLVMContext::MD_tbaa_struct) {
2845 if (
I->second == LLVMContext::MD_alias_scope ||
2846 I->second == LLVMContext::MD_noalias)
2858Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2861 return error(
"Invalid record");
2863 unsigned Kind =
Record[0];
2866 unsigned NewKind = TheModule.getMDKindID(Name.str());
2867 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2868 return error(
"Conflicting METADATA_KIND records");
2882 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2885 switch (Entry.Kind) {
2888 return error(
"Malformed block");
2898 ++NumMDRecordLoaded;
2902 switch (MaybeCode.
get()) {
2915 Pimpl = std::move(RHS.Pimpl);
2919 : Pimpl(
std::
move(RHS.Pimpl)) {}
2927 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2929Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2930 return Pimpl->parseMetadata(ModuleLevel);
2938 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2942 return Pimpl->lookupSubprogramForFunction(
F);
2947 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2951 return Pimpl->parseMetadataKinds();
2955 return Pimpl->setStripTBAA(StripTBAA);
2964 return Pimpl->upgradeDebugIntrinsics(
F);
2968 return Pimpl->upgradeAliasScopeList(ScopeList);
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_LIKELY(EXPR)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
static APFloat flush(APFloat Value, DenormalMode::DenormalModeKind Mode)
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)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
std::pair< llvm::MachO::Target, std::string > UUID
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
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...
Error JumpToBit(uint64_t NewBitNo)
Reset the stream to the specified bit number.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
MDString * getRawIdentifier() const
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
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.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
static FLIndex fromRaw(IndexType RawIndex)
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.
static LLVM_ABI MDFunctionLocalContext * getDistinct(LLVMContext &Context, bool NonDebug=false)
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
A Module instance is used to store all the information related to an LLVM module.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
iterator_range< op_iterator > operands()
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.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
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.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
LLVM Value Representation.
std::pair< iterator, bool > insert(const ValueT &V)
An efficient, type-erasing, non-owning reference to a callable.
constexpr char LanguageVersion[]
Key for Kernel::Metadata::mLanguageVersion.
@ METADATA_TEMPLATE_VALUE
@ METADATA_LEXICAL_BLOCK_FILE
@ METADATA_SUBROUTINE_TYPE
@ METADATA_GLOBAL_DECL_ATTACHMENT
@ METADATA_IMPORTED_ENTITY
@ METADATA_GENERIC_SUBRANGE
@ METADATA_COMPOSITE_TYPE
@ METADATA_FIXED_POINT_TYPE
@ METADATA_GLOBAL_VAR_EXPR
@ DW_LLVM_LANG_DIALECT_max
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< CodeNode * > Code
LLVM_ABI Instruction & back() const
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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.
@ Unknown
Not known to have no common set bits.
std::error_code make_error_code(BitcodeError E)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
LLVM_ABI MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
auto cast_or_null(const Y &Val)
bool isa_and_nonnull(const Y &Val)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
static const DIScope * getScope(const NodeT *N)
auto dyn_cast_or_null(const Y &Val)
const BitReaderOptions & getBitReaderOptions(const LLVMContext &C)
bool mayBeOldLoopAttachmentTag(StringRef Name)
Check whether a string looks like an old loop attachment tag.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI MDNode * UpgradeTBAAStructNode(MDNode &TBAAStructNode)
If the given !tbaa.struct node has old-style scalar field tags, return an equivalent node with each f...
LLVM_ABI MDNode * UpgradeAliasScopeList(MDNode &ScopeList, DenseMap< MDNode *, MDNode * > &UpgradedAliasScopes)
Mark any domains from scopes in ScopeList that don't have a disjointness flag as non-disjoint.
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...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
@ Ref
The access may reference the value stored in memory.
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.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
@ End
Run the machine verifier once, at the end of the pipeline.
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.
Implement std::hash so that hash_code can be used in STL containers.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...