65#define DEBUG_TYPE "bitcode-reader"
67STATISTIC(NumMDStringLoaded,
"Number of MDStrings loaded");
68STATISTIC(NumMDNodeTemporary,
"Number of MDNode::Temporary created");
69STATISTIC(NumMDRecordLoaded,
"Number of Metadata records loaded");
75 cl::desc(
"Import full type definitions for ThinLTO."));
79 cl::desc(
"Force disable the lazy-loading on-demand of metadata when "
80 "loading bitcode for importing."));
84class BitcodeReaderMetadataList {
107 LLVMContext &Context;
111 unsigned RefsUpperBound;
114 BitcodeReaderMetadataList(LLVMContext &
C,
size_t RefsUpperBound)
116 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::
max(),
119 using const_iterator = SmallVector<TrackingMDRef, 1>::const_iterator;
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(); }
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(); }
132 Metadata *operator[](
unsigned i)
const {
return MetadataPtrs[i]; }
135 if (
I < MetadataPtrs.size())
136 return MetadataPtrs[
I];
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);
149 Metadata *getMetadataFwdRef(
unsigned Idx);
155 Metadata *getMetadataIfResolved(
unsigned Idx);
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() {
163 return *ForwardReference.begin();
167 void addTypeRef(MDString &
UUID, DICompositeType &CT);
182void BitcodeReaderMetadataList::assignValue(
Metadata *MD,
unsigned Idx) {
184 if (!MDN->isResolved())
185 UnresolvedNodes.
insert(Idx);
195 TrackingMDRef &OldMD = MetadataPtrs[Idx];
203 PrevMD->replaceAllUsesWith(MD);
207Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(
unsigned Idx) {
209 if (Idx >= RefsUpperBound)
215 if (
Metadata *MD = MetadataPtrs[Idx])
222 ++NumMDNodeTemporary;
224 MetadataPtrs[Idx].reset(MD);
228Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(
unsigned Idx) {
231 if (!
N->isResolved())
236MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(
unsigned Idx) {
240void BitcodeReaderMetadataList::tryToResolveCycles() {
246 for (
const auto &
Ref : OldTypeRefs.FwdDecls)
247 OldTypeRefs.Final.insert(
Ref);
248 OldTypeRefs.FwdDecls.clear();
252 for (
const auto &Array : OldTypeRefs.Arrays)
253 Array.second->replaceAllUsesWith(resolveTypeArray(
Array.first.get()));
254 OldTypeRefs.Arrays.clear();
259 for (
const auto &
Ref : OldTypeRefs.Unknown) {
260 if (DICompositeType *CT = OldTypeRefs.Final.lookup(
Ref.first))
261 Ref.second->replaceAllUsesWith(CT);
263 Ref.second->replaceAllUsesWith(
Ref.first);
265 OldTypeRefs.Unknown.clear();
267 if (UnresolvedNodes.
empty())
272 for (
unsigned I : UnresolvedNodes) {
273 auto &MD = MetadataPtrs[
I];
278 assert(!
N->isTemporary() &&
"Unexpected forward reference");
283 UnresolvedNodes.clear();
286void BitcodeReaderMetadataList::addTypeRef(MDString &
UUID,
287 DICompositeType &CT) {
290 OldTypeRefs.FwdDecls.insert(std::make_pair(&
UUID, &CT));
292 OldTypeRefs.Final.insert(std::make_pair(&
UUID, &CT));
300 if (
auto *CT = OldTypeRefs.Final.lookup(
UUID))
303 auto &
Ref = OldTypeRefs.Unknown[
UUID];
309Metadata *BitcodeReaderMetadataList::upgradeTypeArray(
Metadata *MaybeTuple) {
311 if (!Tuple || Tuple->isDistinct())
315 if (!Tuple->isTemporary())
316 return resolveTypeArray(Tuple);
320 OldTypeRefs.Arrays.emplace_back(
321 std::piecewise_construct, std::forward_as_tuple(Tuple),
323 return OldTypeRefs.Arrays.back().second.get();
326Metadata *BitcodeReaderMetadataList::resolveTypeArray(
Metadata *MaybeTuple) {
328 if (!Tuple || Tuple->isDistinct())
333 Ops.reserve(Tuple->getNumOperands());
334 for (
Metadata *MD : Tuple->operands())
335 Ops.push_back(upgradeTypeRef(MD));
342class PlaceholderQueue {
345 std::deque<DistinctMDOperandPlaceholder> PHs;
348 ~PlaceholderQueue() {
350 "PlaceholderQueue hasn't been flushed before being destroyed");
352 bool empty()
const {
return PHs.empty(); }
353 DistinctMDOperandPlaceholder &getPlaceholderOp(
unsigned ID);
354 void flush(BitcodeReaderMetadataList &MetadataList);
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);
368 if (
N &&
N->isTemporary())
376DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(
unsigned ID) {
377 PHs.emplace_back(
ID);
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");
387 assert(MDN->isResolved() &&
388 "Flushing Placeholder while cycles aren't resolved");
390 PHs.front().replaceUseWith(MD);
401 BitcodeReaderMetadataList MetadataList;
414 std::vector<StringRef> MDStringRef;
418 MDString *lazyLoadOneMDString(
unsigned Idx);
421 std::vector<uint64_t> GlobalMetadataBitPosIndex;
426 uint64_t GlobalDeclAttachmentPos = 0;
431 unsigned NumGlobalDeclAttachSkipped = 0;
432 unsigned NumGlobalDeclAttachParsed = 0;
445 void lazyLoadOneMetadata(
unsigned Idx, PlaceholderQueue &Placeholders);
449 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
463 bool StripTBAA =
false;
464 bool HasSeenOldLoopTags =
false;
465 bool NeedUpgradeToDIGlobalVariableExpression =
false;
466 bool NeedDeclareExpressionUpgrade =
false;
472 bool IsImporting =
false;
475 PlaceholderQueue &Placeholders,
StringRef Blob,
476 unsigned &NextMetadataNo);
483 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
486 void upgradeCUSubprograms() {
487 for (
auto CU_SP : CUSubprograms)
489 for (
auto &
Op : SPs->operands())
491 SP->replaceUnit(CU_SP.first);
492 CUSubprograms.clear();
496 void upgradeCUVariables() {
497 if (!NeedUpgradeToDIGlobalVariableExpression)
501 if (
NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu"))
502 for (
unsigned I = 0, E = CUNodes->getNumOperands();
I != E; ++
I) {
505 for (
unsigned I = 0;
I < GVs->getNumOperands();
I++)
510 GVs->replaceOperandWith(
I, DGVE);
515 for (
auto &GV : TheModule.globals()) {
517 GV.getMetadata(LLVMContext::MD_dbg, MDs);
518 GV.eraseMetadata(LLVMContext::MD_dbg);
523 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
525 GV.addMetadata(LLVMContext::MD_dbg, *MD);
532 if (
auto *SP = ParentSubprogram[S]) {
540 if (!Visited.
insert(S).second)
544 return ParentSubprogram[InitialScope] =
552 void upgradeCULocals() {
553 NamedMDNode *CUNodes = TheModule.getNamedMetadata(
"llvm.dbg.cu");
558 auto FilterTuple = [
this](
MDNode *
T,
563 Result.push_back(
Op);
583 if (
CU->getRawImportedEntities())
584 for (
Metadata *
Op :
CU->getImportedEntities()->operands()) {
587 MetadataToRemove.
insert(IE);
590 if (
CU->getRawEnumTypes())
594 MetadataToRemove.
insert(Enum);
597 if (MetadataToRemove.
empty())
601 if (
CU->getRawImportedEntities())
602 CU->replaceImportedEntities(
603 FilterTuple(
CU->getImportedEntities().get(), MetadataToRemove));
606 if (
CU->getRawEnumTypes())
607 CU->replaceEnumTypes(
608 FilterTuple(
CU->getEnumTypes().get(), MetadataToRemove));
612 for (
auto *
I : MetadataToRemove) {
615 if (
auto *SP = findEnclosingSubprogram(Scope))
616 SPToEntities[SP].push_back(
I);
620 for (
auto I = SPToEntities.
begin();
I != SPToEntities.
end(); ++
I) {
622 auto RetainedNodes = SP->getRetainedNodes();
625 SP->replaceRetainedNodes(
MDNode::get(Context, MDs));
629 ParentSubprogram.clear();
634 void upgradeDeclareExpressions(
Function &
F) {
635 if (!NeedDeclareExpressionUpgrade)
638 auto UpdateDeclareIfNeeded = [&](
auto *Declare) {
639 auto *DIExpr = Declare->getExpression();
640 if (!DIExpr || !DIExpr->startsWithDeref() ||
644 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
651 if (DVR.isDbgDeclare())
652 UpdateDeclareIfNeeded(&DVR);
655 UpdateDeclareIfNeeded(DDI);
663 auto N = Expr.
size();
664 switch (FromVersion) {
666 return error(
"Invalid record");
668 if (
N >= 3 && Expr[
N - 3] == dwarf::DW_OP_bit_piece)
673 if (
N && Expr[0] == dwarf::DW_OP_deref) {
674 auto End = Expr.
end();
675 if (Expr.
size() >= 3 &&
677 End = std::prev(End, 3);
678 std::move(std::next(Expr.
begin()), End, Expr.
begin());
679 *std::prev(End) = dwarf::DW_OP_deref;
681 NeedDeclareExpressionUpgrade =
true;
687 while (!SubExpr.empty()) {
692 switch (SubExpr.front()) {
696 case dwarf::DW_OP_constu:
697 case dwarf::DW_OP_minus:
698 case dwarf::DW_OP_plus:
708 HistoricSize = std::min(SubExpr.size(), HistoricSize);
711 switch (SubExpr.front()) {
712 case dwarf::DW_OP_plus:
713 Buffer.
push_back(dwarf::DW_OP_plus_uconst);
714 Buffer.
append(Args.begin(), Args.end());
716 case dwarf::DW_OP_minus:
718 Buffer.
append(Args.begin(), Args.end());
723 Buffer.
append(Args.begin(), Args.end());
728 SubExpr = SubExpr.slice(HistoricSize);
746 enum class DebugInfoUpgradeMode {
755 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
756 if (Mode == DebugInfoUpgradeMode::None)
758 upgradeCUSubprograms();
759 upgradeCUVariables();
760 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
765 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
766 DebugInfoUpgradeMode DIUpgradeMode) {
767 resolveForwardRefsAndPlaceholders(Placeholders);
768 upgradeDebugInfo(DIUpgradeMode);
771 << NewDistinctSPs.size() <<
" subprogram(s).\n");
772 NewDistinctSPs.clear();
775 void callMDTypeCallback(
Metadata **Val,
unsigned TypeID);
781 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
782 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
783 TheModule(TheModule), Callbacks(
std::
move(Callbacks)),
784 IsImporting(IsImporting) {}
788 bool hasFwdRefs()
const {
return MetadataList.hasFwdRefs(); }
791 if (
ID < MDStringRef.size())
792 return lazyLoadOneMDString(
ID);
793 if (
auto *MD = MetadataList.lookup(
ID))
797 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
798 PlaceholderQueue Placeholders;
799 lazyLoadOneMetadata(
ID, Placeholders);
801 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
802 return MetadataList.lookup(
ID);
804 return MetadataList.getMetadataFwdRef(
ID);
808 return FunctionsWithSPs.lookup(
F);
821 unsigned size()
const {
return MetadataList.size(); }
827MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
828 IndexCursor = Stream;
830 GlobalDeclAttachmentPos = 0;
833 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
841 switch (Entry.Kind) {
844 return error(
"Malformed block");
851 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
853 if (
Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
858 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
859 return std::move(Err);
863 IndexCursor.readRecord(Entry.ID,
Record, &Blob))
866 return MaybeRecord.takeError();
867 unsigned NumStrings =
Record[0];
868 MDStringRef.reserve(NumStrings);
869 auto IndexNextMDString = [&](
StringRef Str) {
870 MDStringRef.push_back(Str);
872 if (
auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
873 return std::move(Err);
879 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
880 return std::move(Err);
882 if (Expected<unsigned> MaybeRecord =
883 IndexCursor.readRecord(
Entry.ID, Record))
886 return MaybeRecord.takeError();
888 return error(
"Invalid record");
890 auto BeginPos = IndexCursor.GetCurrentBitNo();
891 if (
Error Err = IndexCursor.JumpToBit(BeginPos +
Offset))
892 return std::move(Err);
893 Expected<BitstreamEntry> MaybeEntry =
894 IndexCursor.advanceSkippingSubblocks(
900 "Corrupted bitcode: Expected `Record` when trying to find the "
903 if (Expected<unsigned> MaybeCode =
904 IndexCursor.readRecord(
Entry.ID, Record))
906 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
907 "find the Metadata index");
909 return MaybeCode.takeError();
911 auto CurrentValue = BeginPos;
912 GlobalMetadataBitPosIndex.reserve(
Record.size());
913 for (
auto &Elt : Record) {
915 GlobalMetadataBitPosIndex.push_back(CurrentValue);
922 return error(
"Corrupted Metadata block");
925 if (
Error Err = IndexCursor.JumpToBit(CurrentPos))
926 return std::move(Err);
930 if (Expected<unsigned> MaybeCode =
931 IndexCursor.readRecord(
Entry.ID, Record)) {
932 Code = MaybeCode.get();
935 return MaybeCode.takeError();
939 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
940 Code = MaybeCode.get();
942 return MaybeCode.takeError();
947 if (Expected<unsigned> MaybeNextBitCode =
948 IndexCursor.readRecord(Code, Record))
951 return MaybeNextBitCode.takeError();
955 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
956 for (
unsigned i = 0; i !=
Size; ++i) {
961 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
962 assert(MD &&
"Invalid metadata: expect fwd ref to MDNode");
968 if (!GlobalDeclAttachmentPos)
969 GlobalDeclAttachmentPos = SavedPos;
971 NumGlobalDeclAttachSkipped++;
1014 MDStringRef.clear();
1015 GlobalMetadataBitPosIndex.clear();
1029Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1031 if (!GlobalDeclAttachmentPos)
1035 BitstreamCursor TempCursor = Stream;
1036 SmallVector<uint64_t, 64>
Record;
1040 return std::move(Err);
1042 BitstreamEntry
Entry;
1047 return std::move(
E);
1049 switch (
Entry.Kind) {
1052 return error(
"Malformed block");
1055 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1067 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1071 NumGlobalDeclAttachParsed++;
1076 return std::move(Err);
1078 if (Expected<unsigned> MaybeRecord =
1082 return MaybeRecord.takeError();
1083 if (
Record.size() % 2 == 0)
1084 return error(
"Invalid record");
1085 unsigned ValueID =
Record[0];
1086 if (ValueID >= ValueList.size())
1087 return error(
"Invalid record");
1093 if (
Error Err = parseGlobalObjectAttachment(
1094 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1095 return std::move(Err);
1097 return std::move(Err);
1102void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(
Metadata **Val,
1104 if (Callbacks.MDType) {
1105 (*Callbacks.MDType)(Val,
TypeID, Callbacks.GetTypeByID,
1106 Callbacks.GetContainedTypeID);
1114 if (!ModuleLevel && MetadataList.hasFwdRefs())
1115 return error(
"Invalid metadata: fwd refs into function blocks");
1119 auto EntryPos = Stream.GetCurrentBitNo();
1125 PlaceholderQueue Placeholders;
1126 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1127 : DebugInfoUpgradeMode::Partial;
1131 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1133 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1135 return SuccessOrErr.takeError();
1136 if (SuccessOrErr.get()) {
1139 MetadataList.resize(MDStringRef.size() +
1140 GlobalMetadataBitPosIndex.size());
1145 SuccessOrErr = loadGlobalDeclAttachments();
1147 return SuccessOrErr.takeError();
1148 assert(SuccessOrErr.get());
1153 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1156 Stream.ReadBlockEnd();
1157 if (
Error Err = IndexCursor.JumpToBit(EntryPos))
1159 if (
Error Err = Stream.SkipBlock()) {
1170 unsigned NextMetadataNo = MetadataList.size();
1175 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1178 switch (Entry.Kind) {
1181 return error(
"Malformed block");
1184 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1194 ++NumMDRecordLoaded;
1196 Stream.readRecord(Entry.ID,
Record, &Blob)) {
1197 if (
Error Err = parseOneMetadata(
Record, MaybeCode.
get(), Placeholders,
1198 Blob, NextMetadataNo))
1205MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(
unsigned ID) {
1206 ++NumMDStringLoaded;
1210 MetadataList.assignValue(MDS,
ID);
1214void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1215 unsigned ID, PlaceholderQueue &Placeholders) {
1216 assert(
ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1217 assert(
ID >= MDStringRef.size() &&
"Unexpected lazy-loading of MDString");
1219 if (
auto *MD = MetadataList.lookup(
ID)) {
1223 if (!
N || !
N->isTemporary())
1228 if (
Error Err = IndexCursor.JumpToBit(
1229 GlobalMetadataBitPosIndex[
ID - MDStringRef.size()]))
1233 if (
Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1237 ++NumMDRecordLoaded;
1239 IndexCursor.readRecord(Entry.ID,
Record, &Blob)) {
1241 parseOneMetadata(
Record, MaybeCode.
get(), Placeholders, Blob,
ID))
1251void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1252 PlaceholderQueue &Placeholders) {
1253 DenseSet<unsigned> Temporaries;
1256 Placeholders.getTemporaries(MetadataList, Temporaries);
1259 if (Temporaries.
empty() && !MetadataList.hasFwdRefs())
1264 for (
auto ID : Temporaries)
1265 lazyLoadOneMetadata(
ID, Placeholders);
1266 Temporaries.clear();
1270 while (MetadataList.hasFwdRefs())
1271 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1276 MetadataList.tryToResolveCycles();
1280 Placeholders.flush(MetadataList);
1284 Type *Ty,
unsigned TyID) {
1296 if (Idx < ValueList.
size() && ValueList[Idx] &&
1297 ValueList[Idx]->getType() == Ty)
1303Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1304 SmallVectorImpl<uint64_t> &Record,
unsigned Code,
1305 PlaceholderQueue &Placeholders, StringRef Blob,
unsigned &NextMetadataNo) {
1307 bool IsDistinct =
false;
1308 auto getMD = [&](
unsigned ID) ->
Metadata * {
1309 if (
ID < MDStringRef.size())
1310 return lazyLoadOneMDString(
ID);
1312 if (
auto *MD = MetadataList.lookup(
ID))
1316 if (
ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1320 MetadataList.getMetadataFwdRef(NextMetadataNo);
1321 lazyLoadOneMetadata(
ID, Placeholders);
1322 return MetadataList.lookup(
ID);
1325 return MetadataList.getMetadataFwdRef(
ID);
1327 if (
auto *MD = MetadataList.getMetadataIfResolved(
ID))
1329 return &Placeholders.getPlaceholderOp(
ID);
1331 auto getMDOrNull = [&](
unsigned ID) ->
Metadata * {
1333 return getMD(
ID - 1);
1336 auto getMDOrNullWithoutPlaceholders = [&](
unsigned ID) ->
Metadata * {
1338 return MetadataList.getMetadataFwdRef(
ID - 1);
1341 auto getMDString = [&](
unsigned ID) -> MDString * {
1344 auto MDS = getMDOrNull(
ID);
1349 auto getDITypeRefOrNull = [&](
unsigned ID) {
1350 return MetadataList.upgradeTypeRef(getMDOrNull(
ID));
1353 auto getMetadataOrConstant = [&](
bool IsMetadata,
1356 return getMDOrNull(Entry);
1358 ConstantInt::get(Type::getInt64Ty(
Context), Entry));
1361#define GET_OR_DISTINCT(CLASS, ARGS) \
1362 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1371 if (
Error E = Stream.ReadCode().moveInto(Code))
1374 ++NumMDRecordLoaded;
1375 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1377 return error(
"METADATA_NAME not followed by METADATA_NAMED_NODE");
1379 return MaybeNextBitCode.takeError();
1383 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1384 for (
unsigned i = 0; i !=
Size; ++i) {
1385 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1387 return error(
"Invalid named metadata: expect fwd ref to MDNode");
1396 if (
Record.size() % 2 == 1)
1397 return error(
"Invalid record");
1401 auto dropRecord = [&] {
1405 if (
Record.size() != 2) {
1410 unsigned TyID =
Record[0];
1411 Type *Ty = Callbacks.GetTypeByID(TyID);
1417 Value *
V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1420 return error(
"Invalid value reference from old fn metadata");
1428 if (
Record.size() % 2 == 1)
1429 return error(
"Invalid record");
1433 for (
unsigned i = 0; i !=
Size; i += 2) {
1434 unsigned TyID =
Record[i];
1435 Type *Ty = Callbacks.GetTypeByID(TyID);
1437 return error(
"Invalid record");
1443 return error(
"Invalid value reference from old metadata");
1446 "Expected non-function-local metadata");
1447 callMDTypeCallback(&MD, TyID);
1458 return error(
"Invalid record");
1460 unsigned TyID =
Record[0];
1461 Type *Ty = Callbacks.GetTypeByID(TyID);
1463 return error(
"Invalid record");
1467 return error(
"Invalid value reference from metadata");
1470 callMDTypeCallback(&MD, TyID);
1471 MetadataList.assignValue(MD, NextMetadataNo);
1481 for (
unsigned ID : Record)
1492 return error(
"Invalid record");
1496 unsigned Column =
Record[2];
1498 Metadata *InlinedAt = getMDOrNull(Record[4]);
1500 uint64_t AtomGroup =
Record.size() == 8 ?
Record[6] : 0;
1502 MetadataList.assignValue(
1504 ImplicitCode, AtomGroup, AtomRank)),
1511 return error(
"Invalid record");
1518 return error(
"Invalid record");
1520 auto *Header = getMDString(Record[3]);
1522 for (
unsigned I = 4,
E =
Record.size();
I !=
E; ++
I)
1524 MetadataList.assignValue(
1540 switch (Record[0] >> 1) {
1551 DISubrange, (
Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1552 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1555 return error(
"Invalid record: Unsupported version of DISubrange");
1558 MetadataList.assignValue(Val, NextMetadataNo);
1559 IsDistinct =
Record[0] & 1;
1566 (
Context, getMDOrNull(Record[1]),
1567 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1568 getMDOrNull(Record[4])));
1570 MetadataList.assignValue(Val, NextMetadataNo);
1571 IsDistinct =
Record[0] & 1;
1577 return error(
"Invalid record");
1579 IsDistinct =
Record[0] & 1;
1580 bool IsUnsigned =
Record[0] & 2;
1581 bool IsBigInt =
Record[0] & 4;
1586 const size_t NumWords =
Record.size() - 3;
1591 MetadataList.assignValue(
1600 return error(
"Invalid record");
1602 IsDistinct =
Record[0] & 1;
1603 bool SizeIsMetadata =
Record[0] & 2;
1607 uint32_t NumExtraInhabitants = (
Record.size() > 7) ?
Record[7] : 0;
1608 uint32_t DataSizeInBits = (
Record.size() > 8) ?
Record[8] : 0;
1609 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1610 MetadataList.assignValue(
1612 (
Context, Record[1], getMDString(Record[2]), SizeInBits,
1613 Record[4], Record[5], NumExtraInhabitants,
1614 DataSizeInBits, Flags)),
1621 return error(
"Invalid record");
1623 IsDistinct =
Record[0] & 1;
1624 bool SizeIsMetadata =
Record[0] & 2;
1627 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1631 auto ReadWideInt = [&]() {
1633 unsigned NumWords =
Encoded >> 32;
1640 APInt Numerator = ReadWideInt();
1641 APInt Denominator = ReadWideInt();
1644 return error(
"Invalid record");
1646 MetadataList.assignValue(
1648 (
Context, Record[1], getMDString(Record[2]), SizeInBits,
1649 Record[4], Record[5], Flags, Record[7], Record[8],
1650 Numerator, Denominator)),
1657 return error(
"Invalid record");
1659 IsDistinct =
Record[0] & 1;
1660 bool SizeIsMetadata =
Record[0] & 2;
1661 bool SizeIs8 =
Record.size() == 8;
1664 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1665 unsigned Offset = SizeIs8 ? 5 : 6;
1667 getMetadataOrConstant(SizeIsMetadata, Record[
Offset]);
1669 MetadataList.assignValue(
1671 (
Context, Record[1], getMDString(Record[2]),
1672 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1673 StringLocationExp, SizeInBits, Record[
Offset + 1],
1681 return error(
"Invalid record");
1685 std::optional<unsigned> DWARFAddressSpace;
1686 if (
Record.size() > 12 && Record[12])
1687 DWARFAddressSpace =
Record[12] - 1;
1690 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1695 if (
Record.size() > 14) {
1697 Annotations = getMDOrNull(Record[13]);
1699 PtrAuthData.emplace(Record[14]);
1702 IsDistinct =
Record[0] & 1;
1703 bool SizeIsMetadata =
Record[0] & 2;
1706 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1707 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1709 MetadataList.assignValue(
1711 (
Context, Record[1], getMDString(Record[2]),
1712 getMDOrNull(Record[3]), Record[4],
1713 getDITypeRefOrNull(Record[5]),
1714 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1715 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1716 getDITypeRefOrNull(Record[11]), Annotations)),
1723 return error(
"Invalid record");
1725 IsDistinct =
Record[0] & 1;
1726 bool SizeIsMetadata =
Record[0] & 2;
1729 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1731 MetadataList.assignValue(
1733 (
Context, getMDString(Record[1]),
1734 getMDOrNull(Record[2]), Record[3],
1735 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1736 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1737 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1738 getMDOrNull(Record[12]))),
1745 return error(
"Invalid record");
1749 IsDistinct =
Record[0] & 0x1;
1750 bool IsNotUsedInTypeRef =
Record[0] & 2;
1751 bool SizeIsMetadata =
Record[0] & 4;
1753 MDString *
Name = getMDString(Record[2]);
1758 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1759 return error(
"Alignment value is too large");
1760 uint32_t AlignInBits =
Record[8];
1762 uint32_t NumExtraInhabitants = (
Record.size() > 22) ?
Record[22] : 0;
1765 unsigned RuntimeLang =
Record[12];
1766 std::optional<uint32_t> EnumKind;
1769 Metadata *TemplateParams =
nullptr;
1794 (
Tag == dwarf::DW_TAG_enumeration_type ||
1795 Tag == dwarf::DW_TAG_class_type ||
1796 Tag == dwarf::DW_TAG_structure_type ||
1797 Tag == dwarf::DW_TAG_union_type)) {
1803 StringRef NameStr =
Name->getString();
1805 TemplateParams = getMDOrNull(Record[14]);
1807 BaseType = getDITypeRefOrNull(Record[6]);
1809 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1811 Elements = getMDOrNull(Record[11]);
1812 VTableHolder = getDITypeRefOrNull(Record[13]);
1813 TemplateParams = getMDOrNull(Record[14]);
1817 DataLocation = getMDOrNull(Record[17]);
1818 if (
Record.size() > 19) {
1819 Associated = getMDOrNull(Record[18]);
1820 Allocated = getMDOrNull(Record[19]);
1822 if (
Record.size() > 20) {
1823 Rank = getMDOrNull(Record[20]);
1825 if (
Record.size() > 21) {
1826 Annotations = getMDOrNull(Record[21]);
1828 if (
Record.size() > 23) {
1829 Specification = getMDOrNull(Record[23]);
1832 BitStride = getMDOrNull(Record[25]);
1838 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1840 DICompositeType *CT =
nullptr;
1844 SizeInBits, AlignInBits, OffsetInBits, Specification,
1845 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1846 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1847 Allocated, Rank, Annotations, BitStride);
1854 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1855 VTableHolder, TemplateParams, Identifier, Discriminator,
1856 DataLocation, Associated, Allocated, Rank, Annotations,
1857 Specification, NumExtraInhabitants, BitStride));
1858 if (!IsNotUsedInTypeRef && Identifier)
1861 MetadataList.assignValue(CT, NextMetadataNo);
1867 return error(
"Invalid record");
1868 bool IsOldTypeArray =
Record[0] < 2;
1871 IsDistinct =
Record[0] & 0x1;
1875 Types = MetadataList.upgradeTypeArray(Types);
1877 MetadataList.assignValue(
1886 return error(
"Invalid record");
1890 MetadataList.assignValue(
1893 (
Context,
Record.size() >= 8 ? getMDOrNull(Record[1]) :
nullptr,
1894 getMDOrNull(Record[0 +
Offset]), getMDString(Record[1 +
Offset]),
1895 getMDString(Record[2 +
Offset]), getMDString(Record[3 +
Offset]),
1896 getMDString(Record[4 +
Offset]),
1897 Record.size() <= 7 ? 0 : Record[7],
1898 Record.size() <= 8 ?
false : Record[8])),
1906 return error(
"Invalid record");
1909 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1915 if (
Record.size() > 4 && Record[3] && Record[4])
1917 getMDString(Record[4]));
1918 MetadataList.assignValue(
1920 (
Context, getMDString(Record[1]),
1921 getMDString(Record[2]), Checksum,
1922 Record.size() > 5 ? getMDString(Record[5]) :
nullptr)),
1929 return error(
"Invalid record");
1935 const auto LangVersionMask = (uint64_t(1) << 63);
1936 const bool HasVersionedLanguage =
Record[1] & LangVersionMask;
1939 auto *CU = DICompileUnit::getDistinct(
1941 HasVersionedLanguage
1942 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
1944 : DISourceLanguageName(Record[1]),
1945 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
1946 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
1947 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1948 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1949 Record.size() <= 15 ?
nullptr : getMDOrNull(Record[15]),
1950 Record.size() <= 14 ? 0 : Record[14],
1951 Record.size() <= 16 ?
true : Record[16],
1952 Record.size() <= 17 ?
false : Record[17],
1953 Record.size() <= 18 ? 0 : Record[18],
1954 Record.size() <= 19 ?
false : Record[19],
1955 Record.size() <= 20 ?
nullptr : getMDString(Record[20]),
1956 Record.size() <= 21 ?
nullptr : getMDString(Record[21]));
1958 MetadataList.assignValue(CU, NextMetadataNo);
1962 if (
Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1963 CUSubprograms.push_back({CU, SPs});
1968 return error(
"Invalid record");
1970 bool HasSPFlags =
Record[0] & 4;
1983 const unsigned DIFlagMainSubprogram = 1 << 21;
1984 bool HasOldMainSubprogramFlag =
Flags & DIFlagMainSubprogram;
1985 if (HasOldMainSubprogramFlag)
1989 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1991 if (HasOldMainSubprogramFlag && HasSPFlags)
1992 SPFlags |= DISubprogram::SPFlagMainSubprogram;
1993 else if (!HasSPFlags)
1995 Record[7], Record[8],
1996 Record[14], Record[11],
1997 HasOldMainSubprogramFlag);
2000 IsDistinct = (
Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2006 bool HasUnit =
Record[0] & 2;
2007 if (!HasSPFlags && HasUnit &&
Record.size() < 19)
2008 return error(
"Invalid record");
2009 if (HasSPFlags && !HasUnit)
2010 return error(
"Invalid record");
2013 bool HasThisAdj =
true;
2014 bool HasThrownTypes =
true;
2015 bool HasAnnotations =
false;
2016 bool HasTargetFuncName =
false;
2017 unsigned OffsetA = 0;
2018 unsigned OffsetB = 0;
2021 bool UsesKeyInstructions =
false;
2025 if (
Record.size() >= 19) {
2029 HasThisAdj =
Record.size() >= 20;
2030 HasThrownTypes =
Record.size() >= 21;
2032 HasAnnotations =
Record.size() >= 19;
2033 HasTargetFuncName =
Record.size() >= 20;
2034 UsesKeyInstructions =
Record.size() >= 21 ?
Record[20] : 0;
2037 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2041 getDITypeRefOrNull(Record[1]),
2042 getMDString(Record[2]),
2043 getMDString(Record[3]),
2044 getMDOrNull(Record[4]),
2046 getMDOrNull(Record[6]),
2047 Record[7 + OffsetA],
2048 getDITypeRefOrNull(Record[8 + OffsetA]),
2049 Record[10 + OffsetA],
2050 HasThisAdj ? Record[16 + OffsetB] : 0,
2053 HasUnit ? CUorFn :
nullptr,
2054 getMDOrNull(Record[13 + OffsetB]),
2055 getMDOrNull(Record[14 + OffsetB]),
2056 getMDOrNull(Record[15 + OffsetB]),
2057 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2059 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2061 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2063 UsesKeyInstructions));
2064 MetadataList.assignValue(SP, NextMetadataNo);
2068 NewDistinctSPs.push_back(SP);
2074 if (
F->isMaterializable())
2077 FunctionsWithSPs[
F] =
SP;
2078 else if (!
F->empty())
2079 F->setSubprogram(SP);
2086 return error(
"Invalid record");
2089 MetadataList.assignValue(
2091 (
Context, getMDOrNull(Record[1]),
2092 getMDOrNull(Record[2]), Record[3], Record[4])),
2099 return error(
"Invalid record");
2102 MetadataList.assignValue(
2104 (
Context, getMDOrNull(Record[1]),
2105 getMDOrNull(Record[2]), Record[3])),
2111 IsDistinct =
Record[0] & 1;
2112 MetadataList.assignValue(
2114 (
Context, getMDOrNull(Record[1]),
2115 getMDOrNull(Record[2]), getMDString(Record[3]),
2116 getMDOrNull(Record[4]), Record[5])),
2125 Name = getMDString(Record[2]);
2126 else if (
Record.size() == 5)
2127 Name = getMDString(Record[3]);
2129 return error(
"Invalid record");
2131 IsDistinct =
Record[0] & 1;
2132 bool ExportSymbols =
Record[0] & 2;
2133 MetadataList.assignValue(
2135 (
Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2142 return error(
"Invalid record");
2145 MetadataList.assignValue(
2147 (
Context, Record[1], Record[2], getMDString(Record[3]),
2148 getMDString(Record[4]))),
2155 return error(
"Invalid record");
2158 MetadataList.assignValue(
2160 (
Context, Record[1], Record[2], getMDOrNull(Record[3]),
2161 getMDOrNull(Record[4]))),
2168 return error(
"Invalid record");
2171 MetadataList.assignValue(
2173 (
Context, getMDString(Record[1]),
2174 getDITypeRefOrNull(Record[2]),
2175 (
Record.size() == 4) ? getMDOrNull(Record[3])
2176 : getMDOrNull(
false))),
2183 return error(
"Invalid record");
2187 MetadataList.assignValue(
2189 DITemplateValueParameter,
2190 (
Context, Record[1], getMDString(Record[2]),
2191 getDITypeRefOrNull(Record[3]),
2192 (
Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(
false),
2193 (
Record.size() == 6) ? getMDOrNull(Record[5])
2194 : getMDOrNull(Record[4]))),
2201 return error(
"Invalid record");
2203 IsDistinct =
Record[0] & 1;
2209 Annotations = getMDOrNull(Record[12]);
2211 MetadataList.assignValue(
2213 (
Context, getMDOrNull(Record[1]),
2214 getMDString(Record[2]), getMDString(Record[3]),
2215 getMDOrNull(Record[4]), Record[5],
2216 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2217 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2218 Record[11], Annotations)),
2225 MetadataList.assignValue(
2228 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2229 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2230 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2231 getMDOrNull(Record[10]),
nullptr, Record[11],
nullptr)),
2238 NeedUpgradeToDIGlobalVariableExpression =
true;
2239 Metadata *Expr = getMDOrNull(Record[9]);
2240 uint32_t AlignInBits = 0;
2241 if (
Record.size() > 11) {
2242 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2243 return error(
"Alignment value is too large");
2244 AlignInBits =
Record[11];
2246 GlobalVariable *Attach =
nullptr;
2252 Expr = DIExpression::get(
Context,
2253 {dwarf::DW_OP_constu, CI->getZExtValue(),
2254 dwarf::DW_OP_stack_value});
2261 (
Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2262 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2263 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2264 getMDOrNull(Record[10]),
nullptr, AlignInBits,
nullptr));
2266 DIGlobalVariableExpression *DGVE =
nullptr;
2268 DGVE = DIGlobalVariableExpression::getDistinct(
2274 MetadataList.assignValue(MDNode, NextMetadataNo);
2277 return error(
"Invalid record");
2283 return error(
"Invalid DIAssignID record.");
2285 IsDistinct =
Record[0] & 1;
2287 return error(
"Invalid DIAssignID record. Must be distinct");
2296 return error(
"Invalid record");
2298 IsDistinct =
Record[0] & 1;
2299 bool HasAlignment =
Record[0] & 2;
2303 bool HasTag = !HasAlignment &&
Record.size() > 8;
2305 uint32_t AlignInBits = 0;
2308 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2309 return error(
"Alignment value is too large");
2312 Annotations = getMDOrNull(Record[9]);
2315 MetadataList.assignValue(
2317 (
Context, getMDOrNull(Record[1 + HasTag]),
2318 getMDString(Record[2 + HasTag]),
2319 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2320 getDITypeRefOrNull(Record[5 + HasTag]),
2321 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2328 return error(
"Invalid record");
2330 IsDistinct =
Record[0] & 1;
2333 bool IsArtificial =
Record[0] & 2;
2334 std::optional<unsigned> CoroSuspendIdx;
2336 uint64_t RawSuspendIdx =
Record[6];
2337 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2338 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2339 return error(
"CoroSuspendIdx value is too large");
2340 CoroSuspendIdx = RawSuspendIdx;
2344 MetadataList.assignValue(
2346 (
Context, getMDOrNull(Record[1]),
2347 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2348 Column, IsArtificial, CoroSuspendIdx)),
2355 return error(
"Invalid record");
2357 IsDistinct =
Record[0] & 1;
2362 if (
Error Err = upgradeDIExpression(
Version, Elts, Buffer))
2372 return error(
"Invalid record");
2375 Metadata *Expr = getMDOrNull(Record[2]);
2377 Expr = DIExpression::get(
Context, {});
2378 MetadataList.assignValue(
2380 (
Context, getMDOrNull(Record[1]), Expr)),
2387 return error(
"Invalid record");
2390 MetadataList.assignValue(
2392 (
Context, getMDString(Record[1]),
2393 getMDOrNull(Record[2]), Record[3],
2394 getMDString(Record[5]),
2395 getMDString(Record[4]), Record[6],
2396 getDITypeRefOrNull(Record[7]))),
2403 return error(
"Invalid DIImportedEntity record");
2406 bool HasFile = (
Record.size() >= 7);
2407 bool HasElements = (
Record.size() >= 8);
2408 MetadataList.assignValue(
2410 (
Context, Record[1], getMDOrNull(Record[2]),
2411 getDITypeRefOrNull(Record[3]),
2412 HasFile ? getMDOrNull(Record[6]) :
nullptr,
2413 HasFile ? Record[4] : 0, getMDString(Record[5]),
2414 HasElements ? getMDOrNull(Record[7]) :
nullptr)),
2424 ++NumMDStringLoaded;
2426 MetadataList.assignValue(MD, NextMetadataNo);
2431 auto CreateNextMDString = [&](StringRef Str) {
2432 ++NumMDStringLoaded;
2436 if (
Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2441 if (
Record.size() % 2 == 0)
2442 return error(
"Invalid record");
2443 unsigned ValueID =
Record[0];
2444 if (ValueID >= ValueList.size())
2445 return error(
"Invalid record");
2447 if (
Error Err = parseGlobalObjectAttachment(
2448 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2455 if (
Error Err = parseMetadataKindRecord(Record))
2462 for (uint64_t Elt : Record) {
2466 "Invalid record: DIArgList should not contain forward refs");
2468 return error(
"Invalid record");
2478#undef GET_OR_DISTINCT
2481Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2482 ArrayRef<uint64_t> Record, StringRef Blob,
2483 function_ref<
void(StringRef)> CallBack) {
2488 return error(
"Invalid record: metadata strings layout");
2490 unsigned NumStrings =
Record[0];
2491 unsigned StringsOffset =
Record[1];
2493 return error(
"Invalid record: metadata strings with no strings");
2494 if (StringsOffset > Blob.
size())
2495 return error(
"Invalid record: metadata strings corrupt offset");
2497 StringRef Lengths = Blob.
slice(0, StringsOffset);
2498 SimpleBitstreamCursor
R(Lengths);
2500 StringRef Strings = Blob.
drop_front(StringsOffset);
2502 if (
R.AtEndOfStream())
2503 return error(
"Invalid record: metadata strings bad length");
2509 return error(
"Invalid record: metadata strings truncated chars");
2513 }
while (--NumStrings);
2518Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2519 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2521 for (
unsigned I = 0,
E =
Record.size();
I !=
E;
I += 2) {
2522 auto K = MDKindMap.find(Record[
I]);
2523 if (K == MDKindMap.end())
2524 return error(
"Invalid ID");
2528 return error(
"Invalid metadata attachment: expect fwd ref to MDNode");
2541 PlaceholderQueue Placeholders;
2545 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2548 switch (Entry.Kind) {
2551 return error(
"Malformed block");
2554 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2563 ++NumMDRecordLoaded;
2567 switch (MaybeRecord.
get()) {
2571 unsigned RecordLength =
Record.size();
2573 return error(
"Invalid record");
2574 if (RecordLength % 2 == 0) {
2576 if (
Error Err = parseGlobalObjectAttachment(
F,
Record))
2583 for (
unsigned i = 1; i != RecordLength; i = i + 2) {
2584 unsigned Kind =
Record[i];
2586 if (
I == MDKindMap.end())
2587 return error(
"Invalid ID");
2588 if (
I->second == LLVMContext::MD_tbaa && StripTBAA)
2591 auto Idx =
Record[i + 1];
2592 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2593 !MetadataList.lookup(Idx)) {
2596 lazyLoadOneMetadata(Idx, Placeholders);
2598 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2608 return error(
"Invalid metadata attachment");
2610 if (HasSeenOldLoopTags &&
I->second == LLVMContext::MD_loop)
2613 if (
I->second == LLVMContext::MD_tbaa) {
2626Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2629 return error(
"Invalid record");
2631 unsigned Kind =
Record[0];
2634 unsigned NewKind = TheModule.getMDKindID(Name.str());
2635 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2636 return error(
"Conflicting METADATA_KIND records");
2650 if (
Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2653 switch (Entry.Kind) {
2656 return error(
"Malformed block");
2666 ++NumMDRecordLoaded;
2670 switch (MaybeCode.
get()) {
2683 Pimpl = std::move(RHS.Pimpl);
2687 : Pimpl(
std::
move(RHS.Pimpl)) {}
2695 Stream, TheModule, ValueList,
std::
move(Callbacks), IsImporting)) {}
2697Error MetadataLoader::parseMetadata(
bool ModuleLevel) {
2698 return Pimpl->parseMetadata(ModuleLevel);
2706 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2710 return Pimpl->lookupSubprogramForFunction(
F);
2715 return Pimpl->parseMetadataAttachment(
F, InstructionList);
2719 return Pimpl->parseMetadataKinds();
2723 return Pimpl->setStripTBAA(StripTBAA);
2732 return Pimpl->upgradeDebugIntrinsics(
F);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
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.
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define GET_OR_DISTINCT(CLASS, ARGS)
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)
std::pair< llvm::MachO::Target, std::string > UUID
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - 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.
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 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.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static DILocalScope * getRetainedNodeScope(MDNode *N)
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
DISPFlags
Debug info subprogram flags.
bool isForwardDecl() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
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.
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 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.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
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.
A vector that has set insertion semantics.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
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 reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
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
size - 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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
@ 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
initializer< Ty > init(const Ty &Val)
@ 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.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
FunctionAddr VTableAddr Value
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.
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.
LLVM_ABI MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
auto cast_or_null(const Y &Val)
bool isa_and_nonnull(const Y &Val)
auto dyn_cast_or_null(const Y &Val)
FunctionAddr VTableAddr uintptr_t uintptr_t Version
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...
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.
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)
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...