33 AcceleratorRecords(&
GlobalData.getAllocator()) {
44 OrigUnit(&OrigUnit), getUnitFromOffset(UnitFromOffset),
46 AcceleratorRecords(&
GlobalData.getAllocator()) {
50 DWARFDie CUDie = OrigUnit.getUnitDIE();
56 if (!
GlobalData.getOptions().NoODR && Language.has_value() &&
68 LineTablePtr = File.Dwarf->getLineTableForUnit(&
getOrigUnit());
81 for (
DIEInfo &Info : DieInfoArray)
82 Info.unsetFlagsWhichSetDuringLiveAnalysis();
88 Dependencies.reset(
nullptr);
95 AcceleratorRecords.erase();
99 DebugAddrIndexMap.clear();
102 StmtSeqListAttributes.clear();
118 OutDieOffsetArray.resize(
getOrigUnit().getNumDIEs(), 0);
125 bool IsODRUnavailableFunctionScope) {
132 bool ChildIsODRUnavailableFunctionScope = IsODRUnavailableFunctionScope;
134 if (DieInfo.getIsInMouduleScope())
135 ChildInfo.setIsInMouduleScope();
137 if (DieInfo.getIsInFunctionScope())
138 ChildInfo.setIsInFunctionScope();
140 if (DieInfo.getIsInAnonNamespaceScope())
141 ChildInfo.setIsInAnonNamespaceScope();
143 switch (CurChild->getTag()) {
144 case dwarf::DW_TAG_module:
145 ChildInfo.setIsInMouduleScope();
146 if (DieEntry->
getTag() == dwarf::DW_TAG_compile_unit &&
151 case dwarf::DW_TAG_subprogram:
152 ChildInfo.setIsInFunctionScope();
153 if (!ChildIsODRUnavailableFunctionScope &&
154 !ChildInfo.getIsInMouduleScope()) {
156 {dwarf::DW_AT_abstract_origin, dwarf::DW_AT_specification}))
157 ChildIsODRUnavailableFunctionScope =
true;
160 case dwarf::DW_TAG_namespace: {
163 if (
find(CurChild, dwarf::DW_AT_extension))
166 if (!NamespaceEntry.
CU->
find(NamespaceEntry.
DieEntry, dwarf::DW_AT_name))
167 ChildInfo.setIsInAnonNamespaceScope();
174 ChildInfo.setTrackLiveness();
176 if ((!ChildInfo.getIsInAnonNamespaceScope() &&
177 !ChildIsODRUnavailableFunctionScope && !NoODR))
178 ChildInfo.setODRAvailable();
180 if (CurChild->hasChildren())
181 analyzeDWARFStructureRec(CurChild, ChildIsODRUnavailableFunctionScope);
188 if (LineTablePtr->hasFileAtIndex(FileIdx)) {
192 if (It == ResolvedFullPaths.end()) {
193 std::string OrigFileName;
194 bool FoundFileName = LineTablePtr->getFileNameByIndex(
199 assert(FoundFileName &&
"Must get file name from line table");
209 ResolvedParentPaths.find(ParentPath);
210 if (ParentIt == ResolvedParentPaths.end()) {
215 .insert({ParentPath, GlobalStrings.
insert(RealPath).first})
223 It = ResolvedFullPaths
224 .insert(std::make_pair(
225 FileIdx, GlobalStrings.
insert(ResolvedPath).first))
237 if (ObjFileIdx > std::numeric_limits<uint32_t>::max())
239 "object files exceeds UINT32_MAX");
240 if (LocalIdx > std::numeric_limits<uint32_t>::max())
242 "local index exceeds UINT32_MAX");
244 Priority = (ObjFileIdx << 32) | LocalIdx;
250 ResolvedFullPaths.shrink_and_clear();
251 ResolvedParentPaths.clear();
256 Dependencies.reset(
nullptr);
257 StmtSeqListAttributes.clear();
267 CurEntry && CurEntry->
getTag() == dwarf::DW_TAG_module;
276 Path.append(
Name.begin(),
Name.end());
277 Path.push_back(
'\0');
285 assert(UnitEntry &&
"unit reached cloning without loaded DIEs");
292 if (CurChild->getTag() == dwarf::DW_TAG_module &&
308 while (!WorkList.
empty()) {
314 if (CurChild->getTag() == dwarf::DW_TAG_module)
323 if (
getDIEInfo(DieEntry).needToPlaceInTypeTable())
342 if (!Language || Language != dwarf::DW_LANG_Swift)
345 if (!
GlobalData.getOptions().ParseableSwiftInterfaces)
350 if (!Path.ends_with(
".swiftinterface"))
353 std::string RemappedPath = File.remapPath(Path);
360 std::string RemappedSysRoot = File.remapPath(
SysRoot);
367 if (!DeveloperDir.
empty() && Path.starts_with(DeveloperDir))
371 if (std::optional<DWARFFormValue> Val =
find(DieEntry, dwarf::DW_AT_name)) {
381 ResolvedPath = File.remapPath(
388 PendingSwiftInterfaces.emplace_back(*
Name, ResolvedPath);
394 for (
auto &Pending : PendingSwiftInterfaces) {
395 auto &Entry = Map[Pending.ModuleName];
396 if (!Entry.empty() && Entry != Pending.ResolvedPath)
397 warn(
Twine(
"conflicting parseable interfaces for Swift Module ") +
398 Pending.ModuleName +
": " + Entry +
" and " + Pending.ResolvedPath +
400 Entry = Pending.ResolvedPath;
402 PendingSwiftInterfaces.clear();
423 assert(ChildInfo.getODRAvailable());
426 ChildrenIndexAssigner.getChildIndex(*
this, CurChild)))
429 if (
Error Err = assignTypeNamesRec(CurChild, NameBuilder))
437 if (std::optional<SectionDescriptor *> DebugInfoSection =
444 Patch.
RefCU.getPointer()->getDieOutOffset(
449 ->ListDebugULEB128DieRefPatch.forEach(
453 Patch.
RefCU.getPointer()->getDieOutOffset(
458 ->ListDebugDieModuleRefPatch.forEach(
462 Patch.
RefCU.getPointer()->getDieOutOffset(
467 if (std::optional<SectionDescriptor *> DebugLocSection =
470 ->ListDebugULEB128DieRefPatch.forEach(
474 Patch.
RefCU.getPointer()->getDieOutOffset(
479 if (std::optional<SectionDescriptor *> DebugLocListsSection =
481 (*DebugLocListsSection)
482 ->ListDebugULEB128DieRefPatch.forEach(
486 Patch.
RefCU.getPointer()->getDieOutOffset(
496 uint64_t RefDIEOffset;
501 RefCU = getUnitFromOffset(*
Offset);
509 if (std::optional<uint32_t> RefDieIdx =
517 }
else if (RefCU && CanResolveInterCUReferences) {
522 if (ReferredCUStage < Stage::Loaded || ReferredCUStage >
Stage::Cloned)
525 if (std::optional<uint32_t> RefDieIdx =
541 if (std::optional<DWARFFormValue> AttrVal =
find(DieEntry, Attr))
549 std::lock_guard<std::mutex> Guard(RangesMutex);
551 Ranges.
insert({FuncLowPc, FuncHighPc}, PcOffset);
553 LowPc = std::min(*LowPc, FuncLowPc + PcOffset);
555 LowPc = FuncLowPc + PcOffset;
556 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
560 std::lock_guard<std::mutex> Guard(LabelsMutex);
561 Labels.
insert({LabelLowPc, PcOffset});
581 if (!DebugInfoSection.ListDebugLocPatch.empty()) {
586 uint64_t OffsetAfterUnitLength = emitLocListHeader(OutLocationSection);
588 DebugInfoSection.ListDebugLocPatch.forEach([&](
DebugLocPatch &Patch) {
591 uint64_t InputDebugLocSectionOffset = DebugInfoSection.
getIntVal(
597 if (!OriginalLocations) {
602 LinkedLocationExpressionsVector LinkedLocationExpressions;
604 LinkedLocationExpressionsWithOffsetPatches LinkedExpression;
606 if (CurExpression.Range) {
608 LinkedExpression.Expression.Range = {
618 InputExpression, LinkedExpression.Expression.Expr,
620 LinkedExpression.Patches,
nullptr,
623 LinkedLocationExpressions.push_back({LinkedExpression});
628 OutLocationSection.
OS.
tell());
629 emitLocListFragment(LinkedLocationExpressions, OutLocationSection);
632 if (OffsetAfterUnitLength > 0) {
633 assert(OffsetAfterUnitLength -
635 OffsetAfterUnitLength);
636 OutLocationSection.
apply(
637 OffsetAfterUnitLength -
639 dwarf::DW_FORM_sec_offset,
640 OutLocationSection.
OS.
tell() - OffsetAfterUnitLength);
666 return OffsetAfterUnitLength;
670uint64_t CompileUnit::emitLocListFragment(
671 const LinkedLocationExpressionsVector &LinkedLocationExpression,
673 uint64_t OffsetBeforeLocationExpression = 0;
677 if (std::optional<uint64_t> LowPC =
getLowPc())
678 BaseAddress = *LowPC;
680 for (
const LinkedLocationExpressionsWithOffsetPatches &LocExpression :
681 LinkedLocationExpression) {
682 if (LocExpression.Expression.Range) {
684 LocExpression.Expression.Range->LowPC - BaseAddress,
687 LocExpression.Expression.Range->HighPC - BaseAddress,
691 OutLocationSection.
emitIntVal(LocExpression.Expression.Expr.size(), 2);
692 OffsetBeforeLocationExpression = OutLocationSection.
OS.
tell();
693 for (
uint64_t *OffsetPtr : LocExpression.Patches)
694 *OffsetPtr += OffsetBeforeLocationExpression;
696 OutLocationSection.
OS
697 << StringRef((
const char *)LocExpression.Expression.Expr.data(),
698 LocExpression.Expression.Expr.size());
706 return OffsetBeforeLocationExpression;
709 std::optional<uint64_t> BaseAddress;
710 for (
const LinkedLocationExpressionsWithOffsetPatches &LocExpression :
711 LinkedLocationExpression) {
712 if (LocExpression.Expression.Range) {
716 BaseAddress = LocExpression.Expression.Range->LowPC;
719 OutLocationSection.
emitIntVal(dwarf::DW_LLE_base_addressx, 1);
721 OutLocationSection.
OS);
725 OutLocationSection.
emitIntVal(dwarf::DW_LLE_offset_pair, 1);
728 encodeULEB128(LocExpression.Expression.Range->LowPC - *BaseAddress,
729 OutLocationSection.
OS);
732 encodeULEB128(LocExpression.Expression.Range->HighPC - *BaseAddress,
733 OutLocationSection.
OS);
736 OutLocationSection.
emitIntVal(dwarf::DW_LLE_default_location, 1);
738 encodeULEB128(LocExpression.Expression.Expr.size(), OutLocationSection.
OS);
739 OffsetBeforeLocationExpression = OutLocationSection.
OS.
tell();
740 for (
uint64_t *OffsetPtr : LocExpression.Patches)
741 *OffsetPtr += OffsetBeforeLocationExpression;
743 OutLocationSection.
OS << StringRef(
744 (
const char *)LocExpression.Expression.Expr.data(),
745 LocExpression.Expression.Expr.size());
749 OutLocationSection.
emitIntVal(dwarf::DW_LLE_end_of_list, 1);
750 return OffsetBeforeLocationExpression;
753Error CompileUnit::emitDebugAddrSection() {
754 if (
GlobalData.getOptions().UpdateIndexTablesOnly)
762 SectionDescriptor &OutAddrSection =
781 RelocFixups.setDebugAddrTableOffset(OutAddrSection.
OS.
tell());
782 for (
uint64_t AddrValue : DebugAddrIndexMap.getValues())
786 OutAddrSection.
apply(
787 OffsetAfterSectionLength -
789 dwarf::DW_FORM_sec_offset,
790 OutAddrSection.
OS.
tell() - OffsetAfterSectionLength);
796 if (RelocFixups.empty())
807 if (!SavedRelocsUnitOffset || !Report)
810 uint64_t DebugAddrOffset = 0;
811 std::optional<SectionDescriptor *>
DebugAddr =
814 DebugAddrOffset = (*DebugAddr)->StartOffset;
815 Report(*SavedRelocsUnitOffset,
827 LinkedFunctionRanges.
insert(
830 emitAranges(LinkedFunctionRanges);
848 if (!DebugInfoSection.ListDebugRangePatch.empty()) {
849 std::optional<AddressRangeValuePair> CachedRange;
850 uint64_t OffsetAfterUnitLength = emitRangeListHeader(OutRangeSection);
853 DebugInfoSection.ListDebugRangePatch.forEach([&](
DebugRangePatch &Patch) {
855 CompileUnitRangePtr = &Patch;
860 uint64_t InputDebugRangesSectionOffset = DebugInfoSection.
getIntVal(
865 InputDebugRangesSectionOffset)) {
867 for (
const auto &
Range : *InputRanges) {
868 if (!CachedRange || !CachedRange->Range.contains(
Range.LowPC))
874 warn(
"inconsistent range data.");
879 LinkedRanges.
insert({
Range.LowPC + CachedRange->Value,
880 Range.HighPC + CachedRange->Value});
884 warn(
"invalid range list ignored.");
889 OutRangeSection.
OS.
tell());
890 emitRangeListFragment(LinkedRanges, OutRangeSection);
894 if (CompileUnitRangePtr !=
nullptr) {
898 dwarf::DW_FORM_sec_offset,
899 OutRangeSection.
OS.
tell());
900 emitRangeListFragment(LinkedFunctionRanges, OutRangeSection);
903 if (OffsetAfterUnitLength > 0) {
904 assert(OffsetAfterUnitLength -
906 OffsetAfterUnitLength);
907 OutRangeSection.
apply(
908 OffsetAfterUnitLength -
910 dwarf::DW_FORM_sec_offset,
911 OutRangeSection.
OS.
tell() - OffsetAfterUnitLength);
936 return OffsetAfterUnitLength;
939void CompileUnit::emitRangeListFragment(
const AddressRanges &LinkedRanges,
944 if (std::optional<uint64_t> LowPC =
getLowPc())
945 BaseAddress = *LowPC;
947 for (
const AddressRange &
Range : LinkedRanges) {
960 std::optional<uint64_t> BaseAddress;
961 for (
const AddressRange &
Range : LinkedRanges) {
963 BaseAddress =
Range.start();
966 OutRangeSection.
emitIntVal(dwarf::DW_RLE_base_addressx, 1);
971 OutRangeSection.
emitIntVal(dwarf::DW_RLE_offset_pair, 1);
981 OutRangeSection.
emitIntVal(dwarf::DW_RLE_end_of_list, 1);
984void CompileUnit::emitAranges(AddressRanges &LinkedFunctionRanges) {
985 if (LinkedFunctionRanges.
empty())
988 SectionDescriptor &DebugInfoSection =
990 SectionDescriptor &OutArangesSection =
1005 uint64_t OffsetAfterArangesLengthField = OutArangesSection.
OS.
tell();
1008 OutArangesSection.notePatch(
1009 DebugOffsetPatch{OutArangesSection.
OS.
tell(), &DebugInfoSection});
1019 for (
const AddressRange &
Range : LinkedFunctionRanges) {
1033 OutArangesSection.
apply(
1034 OffsetAfterArangesLengthField -
1036 dwarf::DW_FORM_sec_offset,
1037 OffsetAfterArangesEnd - OffsetAfterArangesLengthField);
1045 DWARFDie OrigUnitDie = OrigUnit.getUnitDIE();
1048 if (std::optional<uint64_t> MacroAttr =
1052 emitMacroTableImpl(
Table, *MacroAttr,
true);
1057 if (std::optional<uint64_t> MacroAttr =
1061 emitMacroTableImpl(
Table, *MacroAttr,
false);
1068void CompileUnit::emitMacroTableImpl(
const DWARFDebugMacro *MacroTable,
1069 uint64_t OffsetToMacroTable,
1070 bool hasDWARFv5Header) {
1076 bool DefAttributeIsReported =
false;
1077 bool UndefAttributeIsReported =
false;
1078 bool ImportAttributeIsReported =
false;
1080 for (
const DWARFDebugMacro::MacroList &
List : MacroTable->MacroLists) {
1081 if (OffsetToMacroTable == List.Offset) {
1083 if (hasDWARFv5Header) {
1085 OutSection.emitIntVal(List.Header.Version, sizeof(List.Header.Version));
1087 uint8_t Flags = List.Header.Flags;
1091 DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE) {
1093 ~DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE;
1094 warn(
"opcode_operands_table is not supported yet.");
1098 std::optional<uint64_t> StmtListOffset;
1099 if (Flags & DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET) {
1101 for (auto &V : getOutUnitDIE()->values()) {
1102 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1103 StmtListOffset = V.getDIEInteger().getValue();
1108 if (!StmtListOffset) {
1109 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET;
1110 warn(
"couldn`t find line table for macro table.");
1115 OutSection.emitIntVal(Flags, sizeof(Flags));
1118 if (StmtListOffset) {
1119 OutSection.notePatch(DebugOffsetPatch{
1120 OutSection.OS.tell(),
1121 &getOrCreateSectionDescriptor(DebugSectionKind::DebugLine)});
1124 OutSection.emitIntVal(0xBADDEF, List.Header.getOffsetByteSize());
1129 for (const DWARFDebugMacro::Entry &MacroEntry : List.Macros) {
1130 if (MacroEntry.Type == 0) {
1131 encodeULEB128(MacroEntry.Type, OutSection.OS);
1135 uint8_t MacroType = MacroEntry.Type;
1136 switch (MacroType) {
1138 bool HasVendorSpecificExtension =
1139 (!hasDWARFv5Header &&
1140 MacroType == dwarf::DW_MACINFO_vendor_ext) ||
1141 (hasDWARFv5Header && (MacroType >= dwarf::DW_MACRO_lo_user &&
1142 MacroType <= dwarf::DW_MACRO_hi_user));
1144 if (HasVendorSpecificExtension) {
1146 OutSection.emitIntVal(MacroType, 1);
1149 encodeULEB128(MacroEntry.ExtConstant, OutSection.OS);
1152 OutSection.emitString(dwarf::DW_FORM_string, MacroEntry.ExtStr);
1154 warn(
"unknown macro type. skip.");
1162 case dwarf::DW_MACRO_define:
1163 case dwarf::DW_MACRO_undef: {
1165 OutSection.emitIntVal(MacroType, 1);
1168 encodeULEB128(MacroEntry.Line, OutSection.OS);
1171 OutSection.emitString(dwarf::DW_FORM_string, MacroEntry.MacroStr);
1173 case dwarf::DW_MACRO_define_strp:
1174 case dwarf::DW_MACRO_undef_strp:
1175 case dwarf::DW_MACRO_define_strx:
1176 case dwarf::DW_MACRO_undef_strx: {
1179 switch (MacroType) {
1180 case dwarf::DW_MACRO_define_strx: {
1181 MacroType = dwarf::DW_MACRO_define_strp;
1182 if (!DefAttributeIsReported) {
1183 warn(
"DW_MACRO_define_strx unsupported yet. Convert to "
1184 "DW_MACRO_define_strp.");
1185 DefAttributeIsReported = true;
1188 case dwarf::DW_MACRO_undef_strx: {
1189 MacroType = dwarf::DW_MACRO_undef_strp;
1190 if (!UndefAttributeIsReported) {
1191 warn(
"DW_MACRO_undef_strx unsupported yet. Convert to "
1192 "DW_MACRO_undef_strp.");
1193 UndefAttributeIsReported = true;
1202 OutSection.emitIntVal(MacroType, 1);
1205 encodeULEB128(MacroEntry.Line, OutSection.OS);
1208 OutSection.emitString(dwarf::DW_FORM_strp, MacroEntry.MacroStr);
1211 case dwarf::DW_MACRO_start_file: {
1213 OutSection.emitIntVal(MacroType, 1);
1215 encodeULEB128(MacroEntry.Line, OutSection.OS);
1217 encodeULEB128(MacroEntry.File, OutSection.OS);
1219 case dwarf::DW_MACRO_end_file: {
1221 OutSection.emitIntVal(MacroType, 1);
1223 case dwarf::DW_MACRO_import:
1224 case dwarf::DW_MACRO_import_sup: {
1225 if (!ImportAttributeIsReported) {
1226 warn(
"DW_MACRO_import and DW_MACRO_import_sup are unsupported "
1228 ImportAttributeIsReported = true;
1242 std::optional<int64_t> VarAddressAdjustment,
1248 uint8_t OrigAddressByteSize = OrigUnit.getAddressByteSize();
1253 std::optional<uint64_t> AddrOffset =
1254 OrigUnit.getIndexedAddressOffset(
Op.getRawOperand(0));
1256 Cloned->noteDebugAddrOperand(*AddrOffset, OrigAddressByteSize,
1257 OutputExpression.
size());
1263 std::optional<int64_t> Adjustment =
1265 return Address + Adjustment.value_or(VarAddressAdjustment.value_or(0));
1268 uint64_t OpOffset = 0;
1269 for (
auto &
Op : InputExpression) {
1275 warn(
"cannot decode a DW_OP, copying the rest of the expression "
1279 Cloned->noteCopiedBytes(OpOffset, Bytes.
size(),
1280 OutputExpression.
size());
1284 auto Desc =
Op.getDescription();
1287 if ((
Desc.Op.size() == 2 &&
Desc.Op[0] == Encoding::BaseTypeRef) ||
1288 (
Desc.Op.size() == 2 &&
Desc.Op[1] == Encoding::BaseTypeRef &&
1289 Desc.Op[0] != Encoding::Size1))
1290 warn(
"unsupported DW_OP encoding.");
1292 if ((
Desc.Op.size() == 1 &&
Desc.Op[0] == Encoding::BaseTypeRef) ||
1293 (
Desc.Op.size() == 2 &&
Desc.Op[1] == Encoding::BaseTypeRef &&
1294 Desc.Op[0] == Encoding::Size1)) {
1296 assert(OpOffset <
Op.getEndOffset());
1297 uint32_t ULEBsize =
Op.getEndOffset() - OpOffset - 1;
1301 assert(!
Op.getSubCode() &&
"SubOps not yet supported");
1304 if (
Desc.Op.size() == 1) {
1305 RefOffset =
Op.getRawOperand(0);
1308 RefOffset =
Op.getRawOperand(1);
1312 unsigned RealSize = 0;
1316 if (RefOffset > 0 ||
Op.getCode() != dwarf::DW_OP_convert) {
1317 RefOffset += OrigUnit.getOffset();
1319 if (std::optional<uint32_t> Idx =
1320 OrigUnit.getDIEIndexForOffset(RefOffset))
1329 Section.notePatchWithOffsetUpdate(
1336 if (RealSize > ULEBsize) {
1339 warn(
"base type ref doesn't fit.");
1341 assert(RealSize == ULEBsize &&
"padding failed");
1344 }
else if (KeepAddrIndices && (
Op.getCode() == dwarf::DW_OP_addrx ||
1345 Op.getCode() == dwarf::DW_OP_constx)) {
1346 std::optional<object::SectionedAddress> SA =
1347 OrigUnit.getAddrOffsetSectionItem(
Op.getRawOperand(0));
1353 OutputExpression.
append(ULEB, ULEB + ULEBSize);
1354 std::optional<uint64_t> AddrOffset =
1355 OrigUnit.getIndexedAddressOffset(
Op.getRawOperand(0));
1357 RelocFixups.noteDebugAddrEntry({*AddrOffset, Index});
1362 Op.getCode() == dwarf::DW_OP_addrx) {
1363 if (std::optional<object::SectionedAddress> SA =
1364 OrigUnit.getAddrOffsetSectionItem(
Op.getRawOperand(0))) {
1369 OutputExpression.
push_back(dwarf::DW_OP_addr);
1370 uint64_t LinkedAddress = RelocateAddress(
Op, SA->Address);
1374 reinterpret_cast<const uint8_t *
>(&LinkedAddress),
1375 OrigAddressByteSize);
1376 NoteDebugAddrOperand(
Op);
1377 OutputExpression.
append(AddressBytes.
begin(), AddressBytes.
end());
1379 warn(
"cann't read DW_OP_addrx operand.");
1381 Op.getCode() == dwarf::DW_OP_constx) {
1382 if (std::optional<object::SectionedAddress> SA =
1383 OrigUnit.getAddrOffsetSectionItem(
Op.getRawOperand(0))) {
1388 std::optional<uint8_t> OutOperandKind;
1389 switch (OrigAddressByteSize) {
1391 OutOperandKind = dwarf::DW_OP_const2u;
1394 OutOperandKind = dwarf::DW_OP_const4u;
1397 OutOperandKind = dwarf::DW_OP_const8u;
1401 formatv((
"unsupported address size: {0}."), OrigAddressByteSize));
1405 if (OutOperandKind) {
1406 OutputExpression.
push_back(*OutOperandKind);
1407 uint64_t LinkedAddress = RelocateAddress(
Op, SA->Address);
1411 reinterpret_cast<const uint8_t *
>(&LinkedAddress),
1412 OrigAddressByteSize);
1413 NoteDebugAddrOperand(
Op);
1414 OutputExpression.
append(AddressBytes.
begin(), AddressBytes.
end());
1417 warn(
"cann't read DW_OP_constx operand.");
1423 Cloned->noteCopiedBytes(OpOffset, Bytes.
size(),
1424 OutputExpression.
size());
1427 OpOffset =
Op.getEndOffset();
1432 std::optional<std::reference_wrapper<const Triple>> TargetTriple,
1441 if (ArtificialTypeUnit)
1445 std::pair<DIE *, TypeEntry *> OutCUDie =
cloneDIE(
1447 std::nullopt, std::nullopt, Allocator, ArtificialTypeUnit);
1450 if (!TargetTriple.has_value() || (OutCUDie.first ==
nullptr))
1473 if (
Error Err = emitDebugAddrSection())
1489 uint64_t OutOffset, std::optional<int64_t> FuncAddressAdjustment,
1495 bool NeedToClonePlainDIE = Info.needToKeepInPlainDwarf();
1496 bool NeedToCloneTypeDIE =
1497 (InputDieEntry->
getTag() != dwarf::DW_TAG_compile_unit) &&
1498 Info.needToPlaceInTypeTable();
1499 std::pair<DIE *, TypeEntry *> ClonedDIE;
1503 if (NeedToClonePlainDIE)
1506 ClonedDIE.first = createPlainDIEandCloneAttributes(
1507 InputDieEntry, PlainDIEGenerator, OutOffset, FuncAddressAdjustment,
1508 VarAddressAdjustment);
1509 if (NeedToCloneTypeDIE) {
1512 assert(ArtificialTypeUnit !=
nullptr);
1516 ClonedDIE.second = createTypeDIEandCloneAttributes(
1517 InputDieEntry, TypeDIEGenerator, ClonedParentTypeDIE,
1518 ArtificialTypeUnit, SiblingOrdinal);
1521 ClonedDIE.second ? ClonedDIE.second : ClonedParentTypeDIE;
1523 bool HasPlainChildrenToClone =
1524 (ClonedDIE.first && Info.getKeepPlainChildren());
1526 bool HasTypeChildrenToClone =
1527 ((ClonedDIE.second ||
1528 InputDieEntry->
getTag() == dwarf::DW_TAG_compile_unit) &&
1529 Info.getKeepTypeChildren());
1532 if (HasPlainChildrenToClone || HasTypeChildrenToClone) {
1538 std::pair<DIE *, TypeEntry *> ClonedChild =
cloneDIE(
1539 CurChild, TypeParentForChild, OutOffset, FuncAddressAdjustment,
1540 VarAddressAdjustment, Allocator, ArtificialTypeUnit, ChildOrdinal);
1542 if (ClonedChild.first) {
1544 ClonedChild.first->getOffset() + ClonedChild.first->getSize();
1545 PlainDIEGenerator.
addChild(ClonedChild.first);
1548 assert(ClonedDIE.first ==
nullptr ||
1549 HasPlainChildrenToClone == ClonedDIE.first->hasChildren());
1552 if (HasPlainChildrenToClone)
1553 OutOffset +=
sizeof(int8_t);
1557 if (ClonedDIE.first !=
nullptr)
1558 ClonedDIE.first->setSize(OutOffset - ClonedDIE.first->getOffset());
1563DIE *CompileUnit::createPlainDIEandCloneAttributes(
1565 uint64_t &OutOffset, std::optional<int64_t> &FuncAddressAdjustment,
1566 std::optional<int64_t> &VarAddressAdjustment) {
1569 DIE *ClonedDIE =
nullptr;
1570 bool HasLocationExpressionAddress =
false;
1571 if (InputDieEntry->
getTag() == dwarf::DW_TAG_subprogram) {
1573 FuncAddressAdjustment =
1575 getDIE(InputDieEntry),
false);
1576 }
else if (InputDieEntry->
getTag() == dwarf::DW_TAG_label) {
1578 std::optional<uint64_t> lowPC =
1582 if (It != Labels.
end())
1583 FuncAddressAdjustment = It->second;
1585 }
else if (InputDieEntry->
getTag() == dwarf::DW_TAG_variable) {
1587 std::pair<bool, std::optional<int64_t>> LocExprAddrAndRelocAdjustment =
1589 getDIE(InputDieEntry),
false);
1591 HasLocationExpressionAddress = LocExprAddrAndRelocAdjustment.first;
1592 if (LocExprAddrAndRelocAdjustment.first &&
1593 LocExprAddrAndRelocAdjustment.second)
1594 VarAddressAdjustment = *LocExprAddrAndRelocAdjustment.second;
1597 ClonedDIE = PlainDIEGenerator.
createDIE(InputDieEntry->
getTag(), OutOffset);
1604 DIEAttributeCloner AttributesCloner(ClonedDIE, *
this,
this, InputDieEntry,
1605 PlainDIEGenerator, FuncAddressAdjustment,
1606 VarAddressAdjustment,
1607 HasLocationExpressionAddress);
1608 AttributesCloner.clone();
1611 AcceleratorRecordsSaver AccelRecordsSaver(
getGlobalData(), *
this,
this);
1612 AccelRecordsSaver.save(InputDieEntry, ClonedDIE, AttributesCloner.AttrInfo,
1616 AttributesCloner.finalizeAbbreviations(
Info.getKeepPlainChildren());
1622DIE *CompileUnit::allocateTypeDie(
TypeEntryBody *TypeDescriptor,
1625 bool IsParentDeclaration) {
1630 if (!IsDeclaration && !IsParentDeclaration) {
1633 if (Priority >= TypeDescriptor->
DiePriority.load(std::memory_order_relaxed))
1637 if (TypeDescriptor->
Die.load(std::memory_order_relaxed))
1641 while (TypeDescriptor->
Lock.test_and_set(std::memory_order_acquire))
1646 if (!IsDeclaration && !IsParentDeclaration) {
1649 TypeDescriptor->
DiePriority.load(std::memory_order_relaxed)) {
1650 TypeDescriptor->
DiePriority.store(Priority, std::memory_order_relaxed);
1652 TypeDescriptor->
Die.store(Result, std::memory_order_relaxed);
1654 }
else if (!TypeDescriptor->
Die.load(std::memory_order_relaxed)) {
1663 (BetterParent || Priority < TypeDescriptor->DeclarationDiePriority)) {
1667 TypeDescriptor->
DeclarationDie.store(Result, std::memory_order_relaxed);
1671 TypeDescriptor->
Lock.clear(std::memory_order_release);
1675TypeEntry *CompileUnit::createTypeDIEandCloneAttributes(
1676 const DWARFDebugInfoEntry *InputDieEntry,
DIEGenerator &TypeDIEGenerator,
1678 uint32_t SiblingOrdinal) {
1679 assert(ArtificialTypeUnit !=
nullptr);
1680 uint32_t InputDieIdx =
getDIEIndex(InputDieEntry);
1683 assert(Entry !=
nullptr);
1684 assert(ClonedParentTypeDIE !=
nullptr);
1685 TypeEntryBody *EntryBody =
1687 Entry, ClonedParentTypeDIE);
1694 if (std::optional<uint32_t> ParentIdx = InputDieEntry->
getParentIdx()) {
1696 if (ParentTag == dwarf::DW_TAG_structure_type ||
1697 ParentTag == dwarf::DW_TAG_class_type ||
1698 ParentTag == dwarf::DW_TAG_union_type ||
1699 ParentTag == dwarf::DW_TAG_interface_type) {
1700 uint32_t Prev = EntryBody->
SortKey.load(std::memory_order_relaxed);
1701 while (SiblingOrdinal < Prev &&
1702 !EntryBody->
SortKey.compare_exchange_weak(
1703 Prev, SiblingOrdinal, std::memory_order_relaxed,
1704 std::memory_order_relaxed))
1709 bool IsDeclaration =
1712 bool ParentIsDeclaration =
false;
1713 if (std::optional<uint32_t> ParentIdx = InputDieEntry->
getParentIdx())
1714 ParentIsDeclaration =
1718 allocateTypeDie(EntryBody, TypeDIEGenerator, InputDieEntry->
getTag(),
1719 IsDeclaration, ParentIsDeclaration);
1721 if (OutDIE !=
nullptr) {
1722 assert(ArtificialTypeUnit !=
nullptr);
1725 DIEAttributeCloner AttributesCloner(OutDIE, *
this, ArtificialTypeUnit,
1726 InputDieEntry, TypeDIEGenerator,
1727 std::nullopt, std::nullopt,
false);
1728 AttributesCloner.clone();
1731 AcceleratorRecordsSaver AccelRecordsSaver(
getGlobalData(), *
this,
1732 ArtificialTypeUnit);
1733 AccelRecordsSaver.save(InputDieEntry, OutDIE, AttributesCloner.AttrInfo,
1738 OutDIE->
setSize(AttributesCloner.getOutOffset() + 1);
1747 if (InputLineTable ==
nullptr) {
1749 warn(
"cann't load line table.");
1761 OutLineTable.
Rows = InputLineTable->
Rows;
1764 if (OutLineTable.
Rows.size() == 1 && OutLineTable.
Rows[0].EndSequence)
1765 OutLineTable.
Rows.clear();
1772 filterLineTableRows(*InputLineTable, OutLineTable.
Rows, OrigRowIndices);
1774 if (StmtSeqListAttributes.empty())
1794 &RowIndexToSeqStartOffset))
1798 buildStmtSeqOffsetToFirstRowIndex(*InputLineTable);
1799 patchStmtSeqAttributes(SeqOffsetToFirstRowIndex, RowIndexToSeqStartOffset);
1803void CompileUnit::filterLineTableRows(
1805 std::vector<DWARFDebugLine::Row> &NewRows,
1807 NewRows.reserve(InputLineTable.
Rows.size());
1808 NewRowIndices.
reserve(InputLineTable.
Rows.size());
1814 std::vector<DWARFDebugLine::Row> Seq;
1816 constexpr uint64_t InvalidRowIndex = std::numeric_limits<uint64_t>::max();
1819 std::optional<AddressRangeValuePair> CurrRange;
1839 if (!CurrRange || !CurrRange->Range.contains(Row.Address.Address)) {
1842 uint64_t StopAddress =
1843 CurrRange ? CurrRange->Range.end() + CurrRange->Value : -1ULL;
1844 CurrRange = FunctionRanges.getRangeThatContains(Row.Address.Address);
1845 if (StopAddress != -1ULL && !Seq.empty()) {
1850 auto NextLine = Seq.back();
1851 NextLine.Address.Address = StopAddress;
1852 NextLine.EndSequence = 1;
1853 NextLine.PrologueEnd = 0;
1854 NextLine.BasicBlock = 0;
1855 NextLine.EpilogueBegin = 0;
1856 Seq.push_back(NextLine);
1866 if (Row.EndSequence && Seq.empty())
1871 Seq.emplace_back(Row);
1874 if (Row.EndSequence)
1879void CompileUnit::patchStmtSeqAttributes(
1880 const DenseMap<uint64_t, uint64_t> &SeqOffsetToFirstRowIndex,
1881 const DenseMap<uint64_t, uint64_t> &RowIndexToSeqStartOffset) {
1884 for (
const CompileUnit::StmtSeqPatch &Patch : StmtSeqListAttributes) {
1885 uint64_t NewStmtSeq = InvalidOffset;
1886 auto RowIt = SeqOffsetToFirstRowIndex.
find(Patch.InputStmtSeqOffset);
1887 if (RowIt != SeqOffsetToFirstRowIndex.
end()) {
1888 auto OffIt = RowIndexToSeqStartOffset.
find(RowIt->second);
1889 if (OffIt != RowIndexToSeqStartOffset.
end())
1890 NewStmtSeq = OffIt->second;
1896 *Patch.Value = DIEValue(Patch.Value->getAttribute(), Patch.Value->getForm(),
1897 DIEInteger(NewStmtSeq));
1901DenseMap<uint64_t, uint64_t> CompileUnit::buildStmtSeqOffsetToFirstRowIndex(
1902 const DWARFDebugLine::LineTable &InputLineTable)
const {
1905 SmallVector<uint64_t> StmtAttrs;
1906 StmtAttrs.
reserve(StmtSeqListAttributes.size());
1907 for (
const StmtSeqPatch &Patch : StmtSeqListAttributes)
1908 StmtAttrs.
push_back(Patch.InputStmtSeqOffset);
1912 DenseMap<uint64_t, uint64_t>
Result;
1918void CompileUnit::insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1919 SmallVectorImpl<uint64_t> &SeqIndices,
1920 std::vector<DWARFDebugLine::Row> &Rows,
1921 SmallVectorImpl<uint64_t> &RowIndices) {
1923 "Seq and SeqIndices must be kept in lockstep");
1925 "Rows and RowIndices must be kept in lockstep");
1929 auto ClearSeq = [&] {
1934 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1941 object::SectionedAddress Front = Seq.front().Address;
1943 Rows, [=](
const DWARFDebugLine::Row &O) {
return O.Address < Front; });
1944 size_t InsertIdx = std::distance(Rows.begin(), InsertPoint);
1950 if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
1951 InsertPoint->EndSequence) {
1952 *InsertPoint = Seq.front();
1953 RowIndices[InsertIdx] = SeqIndices.
front();
1954 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
1955 RowIndices.
insert(RowIndices.
begin() + InsertIdx + 1,
1956 SeqIndices.
begin() + 1, SeqIndices.
end());
1958 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
1966#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1986 llvm::errs() <<
" KeepPlainChildren: " << getKeepPlainChildren();
1987 llvm::errs() <<
" KeepTypeChildren: " << getKeepTypeChildren();
1988 llvm::errs() <<
" IsInMouduleScope: " << getIsInMouduleScope();
1989 llvm::errs() <<
" IsInFunctionScope: " << getIsInFunctionScope();
1990 llvm::errs() <<
" IsInAnonNamespaceScope: " << getIsInAnonNamespaceScope();
1991 llvm::errs() <<
" ODRAvailable: " << getODRAvailable();
1992 llvm::errs() <<
" TrackLiveness: " << getTrackLiveness();
1997std::optional<std::pair<StringRef, StringRef>>
2008 return std::nullopt;
2013std::optional<std::pair<StringRef, StringRef>>
2016 FileNamesCache::iterator FileData =
FileNames.find(FileIdx);
2018 return {{
StringRef(FileData->second->first),
2023 if (LineTable->hasFileAtIndex(FileIdx)) {
2026 LineTable->Prologue.getFileNameEntry(FileIdx);
2031 return std::nullopt;
2034 std::string FileName = *
Name;
2036 FileName = File.remapPath(FileName);
2037 FileNamesCache::iterator FileData =
2040 std::make_unique<std::pair<std::string, std::string>>(
2041 std::string(
""), std::move(FileName))})
2043 return {{
StringRef(FileData->second->first),
2053 if ((Entry.DirIdx != 0) &&
2054 Entry.DirIdx < LineTable->Prologue.IncludeDirectories.size()) {
2056 LineTable->Prologue.IncludeDirectories[Entry.DirIdx]
2059 IncludeDir = *DirName;
2062 return std::nullopt;
2066 if (0 < Entry.DirIdx &&
2067 Entry.DirIdx <= LineTable->Prologue.IncludeDirectories.size()) {
2069 LineTable->Prologue.IncludeDirectories[Entry.DirIdx - 1]
2072 IncludeDir = *DirName;
2075 return std::nullopt;
2088 FileNamesCache::iterator FileData =
2091 std::make_unique<std::pair<std::string, std::string>>(
2092 File.remapPath(FilePath), std::move(FileName))})
2094 return {{
StringRef(FileData->second->first),
2099 return std::nullopt;
2102#define MAX_REFERENCIES_DEPTH 1000
2105 std::optional<UnitEntryPairTy> RefDiePair;
2109 CUDiePair.
DieEntry, dwarf::DW_AT_extension,
2111 if (!RefDiePair || !RefDiePair->DieEntry)
2114 CUDiePair = *RefDiePair;
2121 if (std::optional<uint32_t> ParentIdx =
DieEntry->getParentIdx())
2124 return std::nullopt;
2163 Dependencies->collectLiveRoots();
2167 bool InterCUProcessingStarted, std::atomic<bool> &HasNewInterconnectedCUs) {
2168 assert(Dependencies.get());
2170 return Dependencies->resolveDependenciesAndMarkLiveness(
2171 InterCUProcessingStarted, HasNewInterconnectedCUs);
2175 assert(Dependencies.get());
2177 return Dependencies->updateDependenciesCompleteness();
2181 assert(Dependencies.get());
2183 Dependencies->verifyKeepChain();
2188 dwarf::DW_AT_type, dwarf::DW_AT_specification,
2189 dwarf::DW_AT_abstract_origin, dwarf::DW_AT_import,
2190 dwarf::DW_AT_LLVM_alloc_type};
2192 return ODRAttributes;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const IROptions & getOptions(const Module *M)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define MAX_REFERENCIES_DEPTH
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
std::optional< T > getRangeThatContains(uint64_t Addr) const
void insert(AddressRange Range, int64_t Value)
The AddressRanges class helps normalize address range collections.
Collection::const_iterator insert(AddressRange Range)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
std::pair< KeyDataTy *, bool > insert(const KeyTy &NewValue)
Insert new value NewValue or return already existing entry.
A structured debug information entry.
DWARFDebugInfoEntry - A DIE with only the minimum required data.
dwarf::Tag getTag() const
std::optional< uint32_t > getParentIdx() const
Returns index of the parent die.
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
const DWARFDebugInfoEntry * getDebugInfoEntry() const
LLVM_ABI const char * getName(DINameKind Kind) const
Return the DIE name resolving DW_AT_specification or DW_AT_abstract_origin references if necessary.
LLVM_ABI std::optional< uint64_t > getLanguage() const
Returns the DW_LANG_ code for this DIE's DWARF unit, if it exists.
This class represents an Operation in the Expression.
Encoding
Size and signedness of expression operations' operands.
StringRef getData() const
const dwarf::FormParams & getFormParams() const
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
uint8_t getAddressByteSize() const
const char * getCompilationDir()
Expected< DWARFLocationExpressionsVector > findLoclistFromOffset(uint64_t Offset)
bool isLittleEndian() const
uint64_t getOffset() const
iterator find(const_arg_type_t< KeyT > Val)
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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.
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)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMapIterBase< ValueTy, false > iterator
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
constexpr bool empty() const
Check if the string is empty.
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.
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
AddressesMap represents information about valid addresses used by debug information.
std::optional< int64_t > getAddrIndexRelocAdjustment(DWARFUnit &U, const DWARFExpression::Operation &Op, bool Verbose)
Returns the relocation adjustment value for the .debug_addr entry that the DW_OP_addrx or DW_OP_const...
This class represents DWARF information for source file and it's address map.
std::unique_ptr< AddressesMap > Addresses
Helpful address information(list of valid address ranges, relocations).
UnitOffsetsCallbackTy UnitOffsetsFunc
Reports where a unit landed in the output .debug_info and .debug_addr, for the relocations saved rela...
std::function< void(uint64_t OriginalUnitOffset, uint64_t DebugInfoOffset, uint64_t DebugAddrOffset)> UnitOffsetsCallbackTy
std::unique_ptr< DWARFContext > Dwarf
Source DWARF information.
@ Pub
.debug_pubnames, .debug_pubtypes
std::map< std::string, std::string > SwiftInterfacesMapTy
Where the operations of an expression were cloned to.
CompileUnit(DWARFUnit &OrigUnit, const DWARFFile &File, unsigned ID, bool CanUseODR, StringRef ClangModuleName)
TypeUnit * getAsTypeUnit()
Returns TypeUnit if applicable.
DwarfUnit * operator->()
Accessor for common functionality.
PointerUnion< CompileUnit *, TypeUnit * > Ptr
CompileUnit * getAsCompileUnit()
Returns CompileUnit if applicable.
OutputUnitVariantPtr(CompileUnit *U)
void addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset)
Add the low_pc of a label that is relocated by applying offset PCOffset.
void collectLiveRoots()
Search for subprograms and variables referencing live code.
Error cloneAndEmitDebugLocations()
Clone and emit debug locations(.debug_loc/.debug_loclists).
void maybeResetToLoadedStage()
Reset compile units data(results of liveness analysis, clonning) if current stage greater than Stage:...
void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset)
Add a function range [LowPC, HighPC) that is relocated by applying offset PCOffset.
void analyzeImportedModule(const DWARFDebugInfoEntry *DieEntry)
Collect references to parseable Swift interfaces in imported DW_TAG_module blocks.
std::pair< DIE *, TypeEntry * > cloneDIE(const DWARFDebugInfoEntry *InputDieEntry, TypeEntry *ClonedParentTypeDIE, uint64_t OutOffset, std::optional< int64_t > FuncAddressAdjustment, std::optional< int64_t > VarAddressAdjustment, BumpPtrAllocator &Allocator, TypeUnit *ArtificialTypeUnit, uint32_t SiblingOrdinal=std::numeric_limits< uint32_t >::max())
void cleanupDataAfterClonning()
Cleanup unneeded resources after compile unit is cloned.
Error assignTypeNames(TypePool &TypePoolRef)
Search for type entries and assign names.
llvm::Error setPriority(uint64_t ObjFileIdx, uint64_t LocalIdx)
Set deterministic priority for type DIE allocation ordering.
void noteModuleAnchors()
Must run while the output offsets are still available, and once they are final.
void cloneDieAttrExpression(const DWARFExpression &InputExpression, SmallVectorImpl< uint8_t > &OutputExpression, SectionDescriptor &Section, std::optional< int64_t > VarAddressAdjustment, OffsetsPtrVector &PatchesOffsets, RelocationFixups::ClonedExpression *Cloned=nullptr, bool KeepAddrIndices=false)
Clone attribute location expression.
@ TypeTable
Corresponding DIE goes to the type table only.
@ PlainDwarf
Corresponding DIE goes to the plain dwarf only.
Error cloneAndEmitLineTable(const Triple &TargetTriple)
const DWARFFile & getContainingFile() const
Returns DWARFFile containing this compile unit.
Error cloneAndEmitRanges()
Clone and emit ranges.
void mergeSwiftInterfaces(DWARFLinkerBase::SwiftInterfacesMapTy &Map)
Merge the Swift interface entries collected by analyzeImportedModule into Map, emitting a warning for...
void updateDieRefPatchesWithClonedOffsets()
After cloning stage the output DIEs offsets are deallocated.
uint64_t getDebugAddrIndex(uint64_t Addr)
Returns index(inside .debug_addr) of an address.
void saveRelocations()
Saves the relocations, at offsets relative to the output of the unit, which reportUnitOffsets() tells...
bool resolveDependenciesAndMarkLiveness(bool InterCUProcessingStarted, std::atomic< bool > &HasNewInterconnectedCUs)
Discover the DIEs the live roots depend on.
bool updateDependenciesCompleteness()
Check dependend DIEs for incompatible placement.
bool loadInputDIEs()
Load DIEs of input compilation unit.
const RangesTy & getFunctionRanges() const
Returns function ranges of this unit.
Error cloneAndEmitDebugMacro()
Clone and emit debug macros(.debug_macinfo/.debug_macro).
Error cloneAndEmit(std::optional< std::reference_wrapper< const Triple > > TargetTriple, TypeUnit *ArtificialTypeUnit)
Clone and emit this compilation unit.
void setStage(Stage Stage)
Set stage of overall processing.
Stage getStage() const
Returns stage of overall processing.
CompileUnit(LinkingGlobalData &GlobalData, unsigned ID, StringRef ClangModuleName, DWARFFile &File, OffsetToUnitTy UnitFromOffset, dwarf::FormParams Format, llvm::endianness Endianess)
void verifyDependencies()
Check DIEs to have a consistent marking(keep marking, placement marking).
Stage
The stages of new compile unit processing.
@ Cloned
Output DWARF is generated.
@ CreatedNotLoaded
Created, linked with input DWARF file.
@ Loaded
Input DWARF is loaded.
std::optional< uint64_t > getLowPc() const
Returns value of DW_AT_low_pc attribute.
std::optional< std::pair< StringRef, StringRef > > getDirAndFilenameFromLineTable(const DWARFFormValue &FileIdxValue)
Returns directory and file from the line table by index.
std::optional< UnitEntryPairTy > resolveDIEReference(const DWARFFormValue &RefValue, ResolveInterCUReferencesMode CanResolveInterCUReferences)
Resolve the DIE attribute reference that has been extracted in RefValue.
void loadLineTable()
Loads unit line table.
bool getModulePath(const DWARFDebugInfoEntry *DieEntry, SmallVectorImpl< char > &Path)
Appends the names of the DW_TAG_module enclosing DieEntry, outermost first.
uint64_t getPriority() const
StringEntry * getFileName(unsigned FileIdx, StringPool &GlobalStrings)
Returns name of the file for the FileIdx from the unit`s line table.
This class is a helper to create output DIE tree.
void addChild(DIE *Child)
Adds a specified Child to the current DIE.
DIE * createDIE(dwarf::Tag DieTag, uint32_t OutOffset)
Creates a DIE of specified tag DieTag and OutOffset.
This class discovers DIEs dependencies: marks "live" DIEs, marks DIE locations (whether DIE should be...
std::string UnitName
The name of this unit.
LinkingGlobalData & getGlobalData()
Return global data.
std::vector< std::unique_ptr< DIEAbbrev > > Abbreviations
Storage for the unique Abbreviations.
DIE * OutUnitDIE
Output unit DIE.
std::string SysRoot
The DW_AT_LLVM_sysroot of this unit.
bool isClangModule() const
Return true if this compile unit is from Clang module.
std::mutex FileNamesMutex
Guards FileNames.
IndexedValuesMap< const StringEntry * > DebugStringIndexMap
Maps a string into the index inside .debug_str_offsets section.
unsigned ID
Unique ID for the unit.
const std::string & getClangModuleName() const
Return Clang module name;.
void setOutUnitDIE(DIE *UnitDie)
Set output unit DIE.
DwarfUnit(LinkingGlobalData &GlobalData, unsigned ID, StringRef ClangModuleName)
std::string ClangModuleName
If this is a Clang module, this holds the module's name.
FoldingSet< DIEAbbrev > AbbreviationsSet
FoldingSet that uniques the abbreviations.
StringRef getSysRoot()
Return the DW_AT_LLVM_sysroot of the compile unit or an empty StringRef.
DIE * getOutUnitDIE()
Returns output unit DIE.
This class keeps data and services common for the whole linking process.
ModulePool & getModulePool()
void set(StringRef Path, const ModuleAnchor &Location)
This class helps to assign indexes for DIE children.
LinkingGlobalData & GlobalData
dwarf::FormParams Format
Format for sections.
const dwarf::FormParams & getFormParams() const
Return size of address.
void eraseSections()
Erases data of all sections.
std::optional< const SectionDescriptor * > tryGetSectionDescriptor(DebugSectionKind SectionKind) const
Returns descriptor for the specified section of SectionKind.
void setOutputFormat(dwarf::FormParams Format, llvm::endianness Endianness)
Sets output format for all keeping sections.
uint16_t getVersion() const
Return DWARF version.
uint16_t getDebugInfoHeaderSize() const
Return size of header of debug_info table.
llvm::endianness getEndianness() const
Endiannes for the sections.
SectionDescriptor & getOrCreateSectionDescriptor(DebugSectionKind SectionKind)
Returns descriptor for the specified section of SectionKind.
const SectionDescriptor & getSectionDescriptor(DebugSectionKind SectionKind) const
Returns descriptor for the specified section of SectionKind.
The helper class to build type name based on DIE properties.
Error assignName(UnitEntryPairTy InputUnitEntryPair, std::optional< std::pair< size_t, size_t > > ChildIndex)
Create synthetic name for the specified DIE InputUnitEntryPair and assign created name to the DIE typ...
Keeps cloned data for the type DIE.
bool DeclarationParentIsDeclaration
uint64_t DeclarationDiePriority
std::atomic< uint32_t > SortKey
std::atomic< DIE * > DeclarationDie
std::atomic< DIE * > Die
TypeEntryBody keeps partially cloned DIEs corresponding to this type.
std::atomic< uint64_t > DiePriority
TypePool keeps type descriptors which contain partially cloned DIE correspinding to each type.
BumpPtrAllocator & getThreadLocalAllocator()
Return thread local allocator used by pool.
TypeEntryBody * getOrCreateTypeEntryBody(TypeEntry *Entry, TypeEntry *ParentEntry)
Create or return existing type entry body for the specified Entry.
TypeEntry * getRoot() const
Return root for all type entries.
Type Unit is used to represent an artificial compilation unit which keeps all type information.
TypePool & getTypePool()
Returns global type pool.
uint64_t tell() const
tell - Return the current offset with the file.
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
void rememberDieOutOffset(uint32_t Idx, uint64_t Offset)
Idx index of the DIE.
TypeEntry * getDieTypeEntry(uint32_t Idx)
Idx index of the DIE.
DIEInfo & getDIEInfo(unsigned Idx)
Idx index of the DIE.
uint64_t getDieOutOffset(uint32_t Idx)
Idx index of the DIE.
const DWARFDebugInfoEntry * getSiblingEntry(const DWARFDebugInfoEntry *Die) const
const DWARFDebugInfoEntry * getFirstChildEntry(const DWARFDebugInfoEntry *Die) const
std::optional< uint32_t > getDIEIndexForOffset(uint64_t Offset)
DWARFDie getDIE(const DWARFDebugInfoEntry *Die)
const DWARFDebugInfoEntry * getDebugInfoEntry(unsigned Index) const
DWARFUnit & getOrigUnit() const
Returns paired compile unit from input DWARF.
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
DWARFDie getParent(const DWARFDebugInfoEntry *Die)
uint32_t getDIEIndex(const DWARFDebugInfoEntry *Die) const
std::optional< DWARFFormValue > find(uint32_t DieIdx, ArrayRef< dwarf::Attribute > Attrs) const
Error emitDebugInfo(const Triple &TargetTriple)
Emit .debug_info section for unit DIEs.
Error emitDebugLine(const Triple &TargetTriple, const DWARFDebugLine::LineTable &OutLineTable, ArrayRef< uint64_t > OrigRowIndices={}, DenseMap< uint64_t, uint64_t > *RowIndexToSeqStartOffset=nullptr)
Emit .debug_line section.
Error emitDebugStringOffsetSection()
Emit the .debug_str_offsets section for current unit.
void emitPubAccelerators()
Emit .debug_pubnames and .debug_pubtypes for Unit.
void warn(const Twine &Warning, const DWARFDie *DIE=nullptr)
Error emitAbbreviations()
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool isODRLanguage(uint16_t Language)
function_ref< CompileUnit *(uint64_t Offset)> OffsetToUnitTy
SmallVector< uint64_t * > OffsetsPtrVector
Type for list of pointers to patches offsets.
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
ArrayRef< dwarf::Attribute > getODRAttributes()
ResolveInterCUReferencesMode
StringRef guessDeveloperDir(StringRef SysRoot)
Make a best effort to guess the Xcode.app/Contents/Developer path from an SDK path.
DebugSectionKind
List of tracked debug tables.
LLVM_ABI void buildStmtSeqOffsetToFirstRowIndex(const DWARFDebugLine::LineTable <, ArrayRef< uint64_t > SortedStmtSeqOffsets, DenseMap< uint64_t, uint64_t > &SeqOffToFirstRow)
Build a map from an input DW_AT_LLVM_stmt_sequence byte offset to the first-row index (in LT....
StringMapEntry< EmptyStringSetTag > StringEntry
StringEntry keeps data of the string: the length, external offset and a string body which is placed r...
bool isInToolchainDir(StringRef Path)
Make a best effort to determine whether Path is inside a toolchain.
bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path)
std::optional< uint64_t > toAddress(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an address.
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
std::optional< uint64_t > toSectionOffset(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
std::optional< uint64_t > toUnsigned(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
@ DW_ARANGES_VERSION
Section version number for .debug_aranges.
LLVM_ABI std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
void swapByteOrder(T &Value)
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
auto unique(Range &&R, Predicate P)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
static void insertLineSequence(std::vector< TrackedRow > &Seq, std::vector< TrackedRow > &Rows)
Insert the new line info sequence Seq into the current set of already linked line info Rows.
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
@ Dwarf
DWARF v5 .debug_names.
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...
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
bool isCompileUnit(const std::unique_ptr< DWARFUnit > &U)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
void consumeError(Error Err)
Consume a Error without doing anything.
dwarf::FormParams FormParams
Version, address size (starting in v5), and DWARF32/64 format; these parameters affect interpretation...
Standard .debug_line state machine structure.
object::SectionedAddress Address
The program-counter value corresponding to a machine instruction generated by the compiler and sectio...
Represents a single DWARF expression, whose value is location-dependent.
Information gathered about source DIEs.
LLVM_DUMP_METHOD void dump()
bool needToPlaceInTypeTable() const
DieOutputPlacement getPlacement() const
This structure is used to update a DW_AT_import reference to a DW_TAG_module.
This structure is used to update reference to the DIE.
uint64_t RefDieIdxOrClonedOffset
PointerIntPair< CompileUnit *, 1 > RefCU
This structure is used to update location list offset into .debug_loc/.debug_loclists.
int64_t AddrAdjustmentValue
This structure is used to update range list offset into .debug_ranges/.debug_rnglists.
bool IsCompileUnitRanges
Indicates patch which points to immediate compile unit's attribute.
This structure is used to update reference to the DIE of ULEB128 form.
uint64_t RefDieIdxOrClonedOffset
PointerIntPair< CompileUnit *, 1 > RefCU
Where the DW_TAG_module DIE describing a clang module ended up in the output.
uint64_t Priority
Priority of the unit which recorded this anchor.
SectionDescriptor * Section
dwarf::FormParams getFormParams() const
Returns FormParams used by section.
This structure is used to keep data of the concrete section.
raw_svector_ostream OS
Stream which stores data to the Contents.
void emitUnitLength(uint64_t Length)
Emit unit length into the current section contents.
void emitOffset(uint64_t Val)
Emit specified offset value into the current section contents.
void emitIntVal(uint64_t Val, unsigned Size)
Emit specified integer value into the current section contents.
void apply(uint64_t PatchOffset, dwarf::Form AttrForm, uint64_t Val)
Write specified Value of AttrForm to the PatchOffset.
uint64_t getIntVal(uint64_t PatchOffset, unsigned Size)
Returns integer value of Size located by specified PatchOffset.
This is a helper structure which keeps a debug info entry with it's containing compilation unit.
UnitEntryPairTy()=default
std::optional< UnitEntryPairTy > getParent()
UnitEntryPairTy getNamespaceOrigin()
const DWARFDebugInfoEntry * DieEntry