55 for (
auto &Unit :
Dwarf.compile_units()) {
56 Size += Unit->getLength();
66 return LHS <
RHS->getOrigUnit().getNextUnitOffset();
68 return CU != Units.end() ?
CU->get() :
nullptr;
74DWARFDie DWARFLinker::resolveDIEReference(
const DWARFFile &File,
76 const DWARFFormValue &RefValue,
78 CompileUnit *&RefCU) {
81 if (std::optional<uint64_t>
Off = RefValue.getAsRelativeReference()) {
82 RefOffset = RefValue.getUnit()->getOffset() + *
Off;
83 }
else if (
Off = RefValue.getAsDebugInfoReference();
Off) {
86 reportWarning(
"Unsupported reference type", File, &DIE);
90 if (
const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
97 reportWarning(
"could not find referenced DIE", File, &DIE);
107 case dwarf::DW_AT_type:
108 case dwarf::DW_AT_containing_type:
109 case dwarf::DW_AT_specification:
110 case dwarf::DW_AT_abstract_origin:
111 case dwarf::DW_AT_import:
112 case dwarf::DW_AT_LLVM_alloc_type:
120 case dwarf::DW_TAG_array_type:
121 case dwarf::DW_TAG_class_type:
122 case dwarf::DW_TAG_enumeration_type:
123 case dwarf::DW_TAG_pointer_type:
124 case dwarf::DW_TAG_reference_type:
125 case dwarf::DW_TAG_string_type:
126 case dwarf::DW_TAG_structure_type:
127 case dwarf::DW_TAG_subroutine_type:
128 case dwarf::DW_TAG_template_alias:
129 case dwarf::DW_TAG_typedef:
130 case dwarf::DW_TAG_union_type:
131 case dwarf::DW_TAG_ptr_to_member_type:
132 case dwarf::DW_TAG_set_type:
133 case dwarf::DW_TAG_subrange_type:
134 case dwarf::DW_TAG_base_type:
135 case dwarf::DW_TAG_const_type:
136 case dwarf::DW_TAG_constant:
137 case dwarf::DW_TAG_file_type:
138 case dwarf::DW_TAG_namelist:
139 case dwarf::DW_TAG_packed_type:
140 case dwarf::DW_TAG_volatile_type:
141 case dwarf::DW_TAG_restrict_type:
142 case dwarf::DW_TAG_atomic_type:
143 case dwarf::DW_TAG_interface_type:
144 case dwarf::DW_TAG_unspecified_type:
145 case dwarf::DW_TAG_shared_type:
146 case dwarf::DW_TAG_immutable_type:
157DWARFLinker::DIECloner::getCanonicalDIEName(DWARFDie Die,
const DWARFFile &File,
162 std::optional<DWARFFormValue>
Ref;
164 auto GetDieName = [](
const DWARFDie &
D) -> llvm::StringRef {
165 auto NameForm =
D.find(llvm::dwarf::DW_AT_name);
169 auto NameOrErr = NameForm->getAsCString();
178 llvm::StringRef
Name = GetDieName(Die);
183 if (!(
Ref = Die.find(llvm::dwarf::DW_AT_specification)) &&
184 !(
Ref = Die.find(llvm::dwarf::DW_AT_abstract_origin)))
187 Die = Linker.resolveDIEReference(File, CompileUnits, *
Ref, Die, Unit);
193 unsigned SpecIdx =
Unit->getOrigUnit().getDIEIndex(Die);
194 CompileUnit::DIEInfo &SpecInfo =
Unit->getInfo(SpecIdx);
195 if (SpecInfo.Ctxt && SpecInfo.Ctxt->hasCanonicalDIE()) {
196 if (!SpecInfo.Ctxt->getCanonicalName().empty()) {
197 Name = SpecInfo.Ctxt->getCanonicalName();
202 Name = GetDieName(Die);
210bool DWARFLinker::DIECloner::getDIENames(
212 const DWARFFile &File, CompileUnit &Unit,
bool StripTemplate) {
216 if (Die.getTag() == dwarf::DW_TAG_lexical_block)
222 if (!
Info.MangledName)
223 if (
const char *MangledName = Die.getLinkageName())
224 Info.MangledName = StringPool.getEntry(MangledName);
230 if (llvm::StringRef Name = getCanonicalDIEName(Die, File, &Unit);
232 Info.Name = StringPool.getEntry(Name);
234 if (!
Info.MangledName)
237 if (StripTemplate &&
Info.Name &&
Info.MangledName !=
Info.Name) {
238 StringRef
Name =
Info.Name.getString();
240 Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
243 return Info.Name ||
Info.MangledName;
259 std::function<
void(
const Twine &,
const DWARFDie &)> ReportWarning) {
260 if (
CU.getLanguage() != dwarf::DW_LANG_Swift)
263 if (!ParseableSwiftInterfaces)
267 if (!Path.ends_with(
".swiftinterface"))
271 std::string RemappedPath = File.remapPath(Path);
276 SysRoot =
CU.getSysRoot();
277 std::string RemappedSysRoot = File.remapPath(SysRoot);
278 SysRoot = RemappedSysRoot;
279 if (!SysRoot.
empty() && Path.starts_with(SysRoot))
284 if (!DeveloperDir.
empty() && Path.starts_with(DeveloperDir))
288 std::optional<const char *> Name =
292 auto &Entry = (*ParseableSwiftInterfaces)[*Name];
294 DWARFDie CUDie =
CU.getOrigUnit().getUnitDIE();
299 if (!Entry.empty() && Entry != ResolvedPath)
300 ReportWarning(
Twine(
"Conflicting parseable interfaces for Swift Module ") +
301 *Name +
": " + Entry +
" and " + Path,
303 Entry = std::string(ResolvedPath);
346 Info.Prune &= (Die.
getTag() == dwarf::DW_TAG_module) ||
352 if (ModulesEndOffset == 0)
353 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
355 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
356 Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
364 Info.Prune &= ChildInfo.
Prune;
380 std::function<
void(
const Twine &,
const DWARFDie &)> ReportWarning) {
382 std::vector<ContextWorklistItem> Worklist;
383 Worklist.emplace_back(
DIE, CurrentDeclContext, ParentIdx,
false);
385 while (!Worklist.empty()) {
389 switch (Current.
Type) {
400 unsigned Idx =
CU.getOrigUnit().getDIEIndex(Current.
Die);
415 if (Current.
Die.
getTag() == dwarf::DW_TAG_module &&
418 CU.getClangModuleName()) {
426 if (
CU.hasODR() || Info.InModuleScope) {
430 Current.
Context = PtrInvalidPair.getPointer();
432 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
436 Info.Ctxt = Current.
Context =
nullptr;
445 Worklist.emplace_back(
447 Worklist.emplace_back(Child, Current.
Context, Idx,
457 case dwarf::DW_TAG_class_type:
458 case dwarf::DW_TAG_common_block:
459 case dwarf::DW_TAG_enumeration_type:
460 case dwarf::DW_TAG_lexical_block:
461 case dwarf::DW_TAG_structure_type:
462 case dwarf::DW_TAG_subprogram:
463 case dwarf::DW_TAG_subroutine_type:
464 case dwarf::DW_TAG_union_type:
470void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
473 for (DIEBlock *
I : DIEBlocks)
475 for (DIELoc *
I : DIELocs)
489 auto StmtAttrs = Unit.getStmtSeqListAttributes();
491 SortedOffsets.
reserve(StmtAttrs.size());
501std::pair<bool, std::optional<int64_t>>
502DWARFLinker::getVariableRelocAdjustment(AddressesMap &RelocMgr,
503 const DWARFDie &DIE) {
504 assert((DIE.getTag() == dwarf::DW_TAG_variable ||
505 DIE.getTag() == dwarf::DW_TAG_constant) &&
506 "Wrong type of input die");
508 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
511 DWARFUnit *U = DIE.getDwarfUnit();
512 std::optional<uint32_t> LocationIdx =
513 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
515 return std::make_pair(
false, std::nullopt);
519 Abbrev->getAttributeOffsetFromIndex(*LocationIdx, DIE.getOffset(), *U);
522 std::optional<DWARFFormValue> LocationValue =
523 Abbrev->getAttributeValueFromOffset(*LocationIdx, AttrOffset, *U);
525 return std::make_pair(
false, std::nullopt);
530 std::optional<ArrayRef<uint8_t>> Expr = LocationValue->getAsBlock();
532 return std::make_pair(
false, std::nullopt);
535 DataExtractor
Data(*Expr, U->getContext().isLittleEndian());
536 DWARFExpression Expression(
Data, U->getAddressByteSize(),
537 U->getFormParams().Format);
542 U->getDebugInfoExtractor(), &ExprOffset,
544 ExprOffset -= Expr->size();
546 bool HasLocationAddress =
false;
548 for (DWARFExpression::iterator It = Expression.begin();
549 It != Expression.end(); ++It) {
550 DWARFExpression::iterator NextIt = It;
553 const DWARFExpression::Operation &
Op = *It;
555 case dwarf::DW_OP_const2u:
556 case dwarf::DW_OP_const4u:
557 case dwarf::DW_OP_const8u:
558 case dwarf::DW_OP_const2s:
559 case dwarf::DW_OP_const4s:
560 case dwarf::DW_OP_const8s:
561 if (NextIt == Expression.end() ||
565 case dwarf::DW_OP_addr: {
566 HasLocationAddress =
true;
568 if (std::optional<int64_t> RelocAdjustment =
569 RelocMgr.getExprOpAddressRelocAdjustment(
570 *U,
Op, ExprOffset + CurExprOffset,
572 return std::make_pair(HasLocationAddress, *RelocAdjustment);
574 case dwarf::DW_OP_constx:
575 case dwarf::DW_OP_addrx: {
576 HasLocationAddress =
true;
577 if (std::optional<uint64_t> AddressOffset =
578 DIE.getDwarfUnit()->getIndexedAddressOffset(
581 if (std::optional<int64_t> RelocAdjustment =
582 RelocMgr.getExprOpAddressRelocAdjustment(
583 *U,
Op, *AddressOffset,
584 *AddressOffset + DIE.getDwarfUnit()->getAddressByteSize(),
586 return std::make_pair(HasLocationAddress, *RelocAdjustment);
596 return std::make_pair(HasLocationAddress, std::nullopt);
601unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
603 CompileUnit::DIEInfo &MyInfo,
605 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
608 if (!(Flags & TF_InFunctionScope) &&
609 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
610 MyInfo.InDebugMap =
true;
611 return Flags | TF_Keep;
619 std::pair<bool, std::optional<int64_t>> LocExprAddrAndRelocAdjustment =
620 getVariableRelocAdjustment(RelocMgr, DIE);
622 if (LocExprAddrAndRelocAdjustment.first)
623 MyInfo.HasLocationExpressionAddr =
true;
625 if (!LocExprAddrAndRelocAdjustment.second)
628 MyInfo.AddrAdjust = *LocExprAddrAndRelocAdjustment.second;
629 MyInfo.InDebugMap =
true;
631 if (((Flags & TF_InFunctionScope) &&
635 if (Options.Verbose) {
636 outs() <<
"Keeping variable DIE:";
637 DIDumpOptions DumpOpts;
638 DumpOpts.ChildRecurseDepth = 0;
639 DumpOpts.Verbose = Options.Verbose;
640 DIE.dump(
outs(), 8 , DumpOpts);
643 return Flags | TF_Keep;
648unsigned DWARFLinker::shouldKeepSubprogramDIE(
649 AddressesMap &RelocMgr,
const DWARFDie &DIE,
const DWARFFile &File,
650 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
unsigned Flags) {
651 Flags |= TF_InFunctionScope;
657 assert(LowPc &&
"low_pc attribute is not an address.");
658 std::optional<int64_t> RelocAdjustment =
659 RelocMgr.getSubprogramRelocAdjustment(DIE, Options.Verbose);
660 if (!RelocAdjustment)
663 MyInfo.AddrAdjust = *RelocAdjustment;
664 MyInfo.InDebugMap =
true;
666 if (Options.Verbose) {
667 outs() <<
"Keeping subprogram DIE:";
668 DIDumpOptions DumpOpts;
669 DumpOpts.ChildRecurseDepth = 0;
670 DumpOpts.Verbose = Options.Verbose;
671 DIE.dump(
outs(), 8 , DumpOpts);
674 if (DIE.getTag() == dwarf::DW_TAG_label) {
675 if (
Unit.hasLabelAt(*LowPc))
678 DWARFUnit &OrigUnit =
Unit.getOrigUnit();
688 if (
Unit.getLanguage() == dwarf::DW_LANG_Mips_Assembler ||
689 Unit.getLanguage() == dwarf::DW_LANG_Assembly) {
690 if (
auto Range = RelocMgr.getSymbolRangeForAddress(*LowPc)) {
691 Unit.addFunctionRange(
Range->LowPC,
Range->HighPC, MyInfo.AddrAdjust);
693 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
696 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
698 return Flags | TF_Keep;
703 std::optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
705 reportWarning(
"Function without high_pc. Range will be discarded.\n", File,
709 if (*LowPc > *HighPc) {
710 reportWarning(
"low_pc greater than high_pc. Range will be discarded.\n",
716 Unit.addFunctionRange(
718 RelocMgr.constrainCodeRangeHighPC(*LowPc, *HighPc, MyInfo.AddrAdjust),
725unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr,
const DWARFDie &DIE,
726 const DWARFFile &File, CompileUnit &Unit,
727 CompileUnit::DIEInfo &MyInfo,
729 switch (DIE.getTag()) {
730 case dwarf::DW_TAG_constant:
731 case dwarf::DW_TAG_variable:
732 return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
733 case dwarf::DW_TAG_subprogram:
734 case dwarf::DW_TAG_label:
735 return shouldKeepSubprogramDIE(RelocMgr, DIE, File, Unit, MyInfo, Flags);
736 case dwarf::DW_TAG_base_type:
739 case dwarf::DW_TAG_imported_module:
740 case dwarf::DW_TAG_imported_declaration:
741 case dwarf::DW_TAG_imported_unit:
743 return Flags | TF_Keep;
757 case dwarf::DW_TAG_structure_type:
758 case dwarf::DW_TAG_class_type:
759 case dwarf::DW_TAG_union_type:
777 case dwarf::DW_TAG_typedef:
778 case dwarf::DW_TAG_member:
779 case dwarf::DW_TAG_reference_type:
780 case dwarf::DW_TAG_ptr_to_member_type:
781 case dwarf::DW_TAG_pointer_type:
798void DWARFLinker::lookForChildDIEsToKeep(
799 const DWARFDie &Die, CompileUnit &
CU,
unsigned Flags,
800 SmallVectorImpl<WorklistItem> &Worklist) {
807 Flags &= ~DWARFLinker::TF_ParentWalk;
811 if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
816 for (
auto Child :
reverse(Die.children())) {
819 CompileUnit::DIEInfo &ChildInfo =
CU.getInfo(Child);
820 Worklist.emplace_back(Die,
CU, WorklistItemType::UpdateChildIncompleteness,
822 Worklist.emplace_back(Child,
CU, Flags);
829 if (!Info.Ctxt || (Die.
getTag() == dwarf::DW_TAG_namespace))
832 if (!
CU.hasODR() && !Info.InModuleScope)
835 return !Info.Incomplete && Info.Ctxt !=
CU.getInfo(Info.ParentIdx).Ctxt;
838void DWARFLinker::markODRCanonicalDie(
const DWARFDie &Die, CompileUnit &
CU) {
839 CompileUnit::DIEInfo &Info =
CU.getInfo(Die);
841 Info.ODRMarkingDone =
true;
843 !Info.Ctxt->hasCanonicalDIE())
844 Info.Ctxt->setHasCanonicalDIE();
849void DWARFLinker::lookForRefDIEsToKeep(
850 const DWARFDie &Die, CompileUnit &CU,
unsigned Flags,
851 const UnitListTy &Units,
const DWARFFile &File,
852 SmallVectorImpl<WorklistItem> &Worklist) {
853 bool UseOdr = (
Flags & DWARFLinker::TF_DependencyWalk)
854 ? (Flags & DWARFLinker::TF_ODR)
856 DWARFUnit &
Unit = CU.getOrigUnit();
857 DWARFDataExtractor
Data =
Unit.getDebugInfoExtractor();
858 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
862 for (
const auto &AttrSpec : Abbrev->attributes()) {
863 DWARFFormValue Val(AttrSpec.Form);
865 AttrSpec.Attr == dwarf::DW_AT_sibling) {
867 Unit.getFormParams());
872 CompileUnit *ReferencedCU;
874 resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
875 CompileUnit::DIEInfo &
Info = ReferencedCU->getInfo(RefDie);
886 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr &&
888 Info.Ctxt->hasCanonicalDIE())
893 Info.Ctxt->hasCanonicalDIE()))
895 ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
899 unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
903 for (
auto &
P :
reverse(ReferencedDIEs)) {
906 CompileUnit::DIEInfo &
Info =
P.second.getInfo(
P.first);
907 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
909 Worklist.emplace_back(
P.first,
P.second,
910 DWARFLinker::TF_Keep |
911 DWARFLinker::TF_DependencyWalk | ODRFlag);
916void DWARFLinker::lookForParentDIEsToKeep(
917 unsigned AncestorIdx, CompileUnit &CU,
unsigned Flags,
918 SmallVectorImpl<WorklistItem> &Worklist) {
920 if (CU.getInfo(AncestorIdx).Keep)
923 DWARFUnit &
Unit = CU.getOrigUnit();
924 DWARFDie ParentDIE =
Unit.getDIEAtIndex(AncestorIdx);
925 Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
926 Worklist.emplace_back(ParentDIE, CU, Flags);
954void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
956 const DWARFDie &Die,
const DWARFFile &File,
957 CompileUnit &Cu,
unsigned Flags) {
960 Worklist.emplace_back(Die, Cu, Flags);
962 while (!Worklist.empty()) {
963 WorklistItem Current = Worklist.pop_back_val();
966 switch (Current.Type) {
967 case WorklistItemType::UpdateChildIncompleteness:
970 case WorklistItemType::UpdateRefIncompleteness:
973 case WorklistItemType::LookForChildDIEsToKeep:
974 lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
976 case WorklistItemType::LookForRefDIEsToKeep:
977 lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
980 case WorklistItemType::LookForParentDIEsToKeep:
981 lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
984 case WorklistItemType::MarkODRCanonicalDie:
985 markODRCanonicalDie(Current.Die, Current.CU);
987 case WorklistItemType::LookForDIEsToKeep:
991 unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
992 CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
997 if (Current.Flags & TF_DependencyWalk)
998 MyInfo.Prune =
false;
1005 bool AlreadyKept = MyInfo.Keep;
1006 if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
1009 if (!(Current.Flags & TF_DependencyWalk))
1010 Current.Flags = shouldKeepDIE(AddressesMap, Current.Die, File, Current.CU,
1011 MyInfo, Current.Flags);
1016 if (!(Current.Flags & TF_DependencyWalk) ||
1017 (MyInfo.ODRMarkingDone && !MyInfo.Keep)) {
1018 if (Current.CU.hasODR() || MyInfo.InModuleScope)
1019 Worklist.emplace_back(Current.Die, Current.CU,
1020 WorklistItemType::MarkODRCanonicalDie);
1026 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
1027 WorklistItemType::LookForChildDIEsToKeep);
1029 if (AlreadyKept || !(Current.Flags & TF_Keep))
1038 Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
1039 Current.Die.getTag() != dwarf::DW_TAG_member &&
1045 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
1046 WorklistItemType::LookForRefDIEsToKeep);
1048 bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
1049 : Current.CU.hasODR();
1050 unsigned ODRFlag = UseOdr ? TF_ODR : 0;
1051 unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
1054 Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
1070 std::vector<DWARFDie> Worklist;
1071 Worklist.push_back(
CU.getOrigUnit().getUnitDIE());
1074 std::vector<BrokenLink> BrokenLinks;
1076 while (!Worklist.empty()) {
1077 const DWARFDie Current = Worklist.back();
1078 Worklist.pop_back();
1080 const bool CurrentDieIsKept =
CU.getInfo(Current).Keep;
1083 Worklist.push_back(Child);
1085 const bool ChildDieIsKept =
CU.getInfo(Child).Keep;
1086 if (!CurrentDieIsKept && ChildDieIsKept)
1087 BrokenLinks.emplace_back(Current, Child);
1091 if (!BrokenLinks.empty()) {
1094 "Found invalid link in keep chain between {0:x} and {1:x}\n",
1095 Link.Parent.getOffset(), Link.Child.getOffset());
1097 errs() <<
"Parent:";
1098 Link.Parent.dump(
errs(), 0, {});
1099 CU.getInfo(Link.Parent).dump();
1102 Link.Child.dump(
errs(), 2, {});
1103 CU.getInfo(Link.Child).dump();
1116void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
1118 FoldingSetNodeID ID;
1120 FoldingSetInsertToken Token;
1121 DIEAbbrev *InSet = AbbreviationsSet.lookup(ID, Token);
1126 Abbrev.setNumber(InSet->getNumber());
1129 Abbreviations.push_back(
1130 std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
1131 for (
const auto &Attr : Abbrev.getData())
1132 Abbreviations.back()->AddAttribute(Attr);
1133 AbbreviationsSet.insert(Abbreviations.back().get(), Token);
1135 Abbrev.setNumber(Abbreviations.size());
1136 Abbreviations.back()->setNumber(Abbreviations.size());
1140unsigned DWARFLinker::DIECloner::cloneStringAttribute(DIE &Die,
1141 AttributeSpec AttrSpec,
1142 const DWARFFormValue &Val,
1144 AttributesInfo &Info) {
1148 std::string RemappedPath;
1149 if (ObjFile.PrefixMap &&
isPathAttribute(Die.getTag(), AttrSpec.Attr)) {
1150 RemappedPath = ObjFile.remapPath(*
String);
1151 String = RemappedPath.c_str();
1154 if (AttrSpec.Form == dwarf::DW_FORM_line_strp) {
1159 if (AttrSpec.Attr == dwarf::DW_AT_APPLE_origin) {
1160 Info.HasAppleOrigin =
true;
1161 if (std::optional<StringRef> FileName =
1162 ObjFile.Addresses->getLibraryInstallName()) {
1168 if (AttrSpec.Attr == dwarf::DW_AT_name)
1170 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
1171 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
1173 if (
U.getVersion() >= 5) {
1175 auto StringOffsetIndex =
1176 StringOffsetPool.getValueIndex(
StringEntry.getOffset());
1179 dwarf::DW_FORM_strx, DIEInteger(StringOffsetIndex))
1180 ->sizeOf(
U.getFormParams());
1183 AttrSpec.Form = dwarf::DW_FORM_strp;
1190unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
1191 DIE &Die,
const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1192 unsigned AttrSize,
const DWARFFormValue &Val,
const DWARFFile &File,
1193 CompileUnit &Unit) {
1194 const DWARFUnit &
U =
Unit.getOrigUnit();
1196 if (std::optional<uint64_t>
Off = Val.getAsRelativeReference())
1197 Ref = Val.getUnit()->getOffset() + *
Off;
1198 else if (
Off = Val.getAsDebugInfoReference();
Off)
1203 DIE *NewRefDie =
nullptr;
1204 CompileUnit *RefUnit =
nullptr;
1207 Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
1210 if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
1213 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
1218 RefInfo.Ctxt->getCanonicalDIEOffset()) {
1219 assert(RefInfo.Ctxt->hasCanonicalDIE() &&
1220 "Offset to canonical die is set, but context is not marked");
1221 DIEInteger Attr(RefInfo.Ctxt->getCanonicalDIEOffset());
1223 dwarf::DW_FORM_ref_addr, Attr);
1224 return U.getRefAddrByteSize();
1227 if (!RefInfo.Clone) {
1230 RefInfo.UnclonedReference =
true;
1233 NewRefDie = RefInfo.Clone;
1235 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
1237 if (
Ref < InputDIE.getOffset() && !RefInfo.UnclonedReference) {
1242 dwarf::DW_FORM_ref_addr, DIEEntry(*NewRefDie));
1248 Unit.noteForwardReference(
1249 NewRefDie, RefUnit, RefInfo.Ctxt,
1251 dwarf::DW_FORM_ref_addr, DIEInteger(
UINT64_MAX)));
1253 return U.getRefAddrByteSize();
1257 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
1262void DWARFLinker::DIECloner::cloneExpression(
1263 DataExtractor &
Data, DWARFExpression Expression,
const DWARFFile &File,
1264 CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer,
1265 int64_t AddrRelocAdjustment,
bool IsLittleEndian,
1266 RelocationFixups::ClonedExpression *Cloned,
bool KeepAddrIndices) {
1269 uint8_t OrigAddressByteSize =
Unit.getOrigUnit().getAddressByteSize();
1271 auto NoteDebugAddrOperand = [&](
const DWARFExpression::Operation &
Op) {
1274 std::optional<uint64_t> AddrOffset =
1277 Cloned->noteDebugAddrOperand(*AddrOffset, OrigAddressByteSize,
1278 OutputBuffer.size());
1281 auto RelocateAddress = [&](
const DWARFExpression::Operation &
Op,
1283 std::optional<int64_t> Adjustment =
1284 File.Addresses->getAddrIndexRelocAdjustment(
Unit.getOrigUnit(),
Op,
1286 return Address + Adjustment.value_or(AddrRelocAdjustment);
1290 for (
auto &
Op : Expression) {
1297 "cannot decode a DW_OP, copying the rest of the expression "
1300 StringRef Bytes =
Data.getData().substr(OpOffset);
1302 Cloned->noteCopiedBytes(OpOffset, Bytes.size(), OutputBuffer.size());
1303 OutputBuffer.append(Bytes.begin(), Bytes.end());
1311 Desc.
Op[0] != Encoding::Size1))
1312 Linker.reportWarning(
"Unsupported DW_OP encoding.", File);
1316 Desc.
Op[0] == Encoding::Size1)) {
1336 if (RefOffset > 0 ||
Op.
getCode() != dwarf::DW_OP_convert) {
1337 RefOffset +=
Unit.getOrigUnit().getOffset();
1338 auto RefDie =
Unit.getOrigUnit().getDIEForOffset(RefOffset);
1339 CompileUnit::DIEInfo &
Info =
Unit.getInfo(RefDie);
1340 if (DIE *Clone =
Info.Clone)
1341 Offset = Clone->getOffset();
1344 "base type ref doesn't point to DW_TAG_base_type.", File);
1348 if (RealSize > ULEBsize) {
1351 Linker.reportWarning(
"base type ref doesn't fit.", File);
1353 assert(RealSize == ULEBsize &&
"padding failed");
1354 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1355 OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
1356 }
else if (KeepAddrIndices && (
Op.
getCode() == dwarf::DW_OP_addrx ||
1358 std::optional<object::SectionedAddress> SA =
1362 AddrPool.getValueIndex(RelocateAddress(
Op, SA->Address));
1366 OutputBuffer.append(ULEB, ULEB + ULEBSize);
1367 std::optional<uint64_t> AddrOffset =
1370 RelocFixups.noteDebugAddrEntry({*AddrOffset,
Index});
1372 Linker.reportWarning(
"cannot read " +
1376 }
else if (!
Linker.Options.Update &&
Op.
getCode() == dwarf::DW_OP_addrx) {
1377 if (std::optional<object::SectionedAddress> SA =
1378 Unit.getOrigUnit().getAddrOffsetSectionItem(
1384 OutputBuffer.push_back(dwarf::DW_OP_addr);
1385 uint64_t LinkedAddress = RelocateAddress(
Op, SA->Address);
1388 ArrayRef<uint8_t> AddressBytes(
1389 reinterpret_cast<const uint8_t *
>(&LinkedAddress),
1390 OrigAddressByteSize);
1391 NoteDebugAddrOperand(
Op);
1392 OutputBuffer.append(AddressBytes.begin(), AddressBytes.end());
1394 Linker.reportWarning(
"cannot read DW_OP_addrx operand.", File);
1395 }
else if (!
Linker.Options.Update &&
Op.
getCode() == dwarf::DW_OP_constx) {
1396 if (std::optional<object::SectionedAddress> SA =
1397 Unit.getOrigUnit().getAddrOffsetSectionItem(
1403 std::optional<uint8_t> OutOperandKind;
1404 switch (OrigAddressByteSize) {
1406 OutOperandKind = dwarf::DW_OP_const4u;
1409 OutOperandKind = dwarf::DW_OP_const8u;
1413 formatv((
"unsupported address size: {0}."), OrigAddressByteSize),
1418 if (OutOperandKind) {
1419 OutputBuffer.push_back(*OutOperandKind);
1420 uint64_t LinkedAddress = RelocateAddress(
Op, SA->Address);
1423 ArrayRef<uint8_t> AddressBytes(
1424 reinterpret_cast<const uint8_t *
>(&LinkedAddress),
1425 OrigAddressByteSize);
1426 NoteDebugAddrOperand(
Op);
1427 OutputBuffer.append(AddressBytes.begin(), AddressBytes.end());
1430 Linker.reportWarning(
"cannot read DW_OP_constx operand.", File);
1435 Cloned->noteCopiedBytes(OpOffset, Bytes.size(), OutputBuffer.size());
1436 OutputBuffer.append(Bytes.begin(), Bytes.end());
1442unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
1443 DIE &Die,
const DWARFDie &InputDIE,
const DWARFFile &File,
1444 CompileUnit &Unit, AttributeSpec AttrSpec,
const DWARFFormValue &Val,
1445 AttributesInfo &Info,
bool IsLittleEndian) {
1448 DIELoc *Loc =
nullptr;
1449 DIEBlock *
Block =
nullptr;
1450 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1451 Loc =
new (DIEAlloc) DIELoc;
1452 Linker.DIELocs.push_back(Loc);
1454 Block =
new (DIEAlloc) DIEBlock;
1457 Attr = Loc ?
static_cast<DIEValueList *
>(Loc)
1458 : static_cast<DIEValueList *>(
Block);
1460 DWARFUnit &OrigUnit =
Unit.getOrigUnit();
1463 SmallVector<uint8_t, 32> Buffer;
1464 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1468 DataExtractor Data(Bytes, IsLittleEndian);
1469 DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
1470 OrigUnit.getFormParams().Format);
1471 if (ObjFile.Addresses->needToSaveValidRelocs())
1472 Info.Source.Expression.emplace(Bytes.size());
1473 cloneExpression(Data, Expr, File, Unit, Buffer,
1474 Unit.getInfo(InputDIE).AddrAdjust, IsLittleEndian,
1475 Info.Source.Expression ? &*Info.Source.Expression
1479 for (
auto Byte : Bytes)
1481 dwarf::DW_FORM_data1, DIEInteger(Byte));
1487 Loc->setSize(Bytes.size());
1489 Block->setSize(Bytes.size());
1497 if ((AttrSpec.Form == dwarf::DW_FORM_block1 &&
1498 (Bytes.size() > UINT8_MAX)) ||
1499 (AttrSpec.Form == dwarf::DW_FORM_block2 &&
1500 (Bytes.size() > UINT16_MAX)) ||
1501 (AttrSpec.Form == dwarf::DW_FORM_block4 && (Bytes.size() > UINT32_MAX)))
1502 AttrSpec.Form = dwarf::DW_FORM_block;
1504 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1505 dwarf::Form(AttrSpec.Form), Block);
1509 Die.addValue(DIEAlloc,
Value)->sizeOf(OrigUnit.getFormParams());
1510 if (
Info.Source.Expression)
1511 Info.Source.Expression->addOutputPrefix(AttrSize - Bytes.size());
1523 bool IsLength, int64_t PCOffset,
1525 std::optional<uint64_t> LowPC =
1530 *LowPC, IsLength ? *LowPC + HighPC : HighPC, PCOffset);
1531 return IsLength ? Constrained - *LowPC : Constrained;
1534unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1535 DIE &Die,
const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1536 unsigned AttrSize,
const DWARFFormValue &Val,
const CompileUnit &Unit,
1537 AttributesInfo &Info) {
1538 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1539 Info.HasLowPc =
true;
1543 dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
1559 std::optional<DWARFFormValue> AddrAttribute = InputDIE.find(AttrSpec.Attr);
1563 std::optional<uint64_t> Addr = AddrAttribute->getAsAddress();
1565 Linker.reportWarning(
"Cann't read address attribute value.", ObjFile);
1569 if (InputDIE.getTag() == dwarf::DW_TAG_compile_unit &&
1570 AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1571 if (std::optional<uint64_t> LowPC =
Unit.getLowPc())
1575 }
else if (InputDIE.getTag() == dwarf::DW_TAG_compile_unit &&
1576 AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1582 if (AttrSpec.Attr == dwarf::DW_AT_high_pc)
1584 *ObjFile.Addresses);
1585 *Addr +=
Info.PCOffset;
1588 if (AttrSpec.Form == dwarf::DW_FORM_addr) {
1590 AttrSpec.Form, DIEInteger(*Addr));
1591 return Unit.getOrigUnit().getAddressByteSize();
1594 auto AddrIndex = AddrPool.getValueIndex(*Addr);
1596 std::optional<uint64_t> InputOffset =
1597 Unit.getOrigUnit().getIndexedAddressOffset(Val.getRawUValue());
1600 RelocationFixups::DebugAddrEntry{*InputOffset, AddrIndex};
1604 dwarf::Form::DW_FORM_addrx, DIEInteger(AddrIndex))
1605 ->sizeOf(
Unit.getOrigUnit().getFormParams());
1608unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1609 DIE &Die,
const DWARFDie &InputDIE,
const DWARFFile &File,
1610 CompileUnit &Unit, AttributeSpec AttrSpec,
const DWARFFormValue &Val,
1611 unsigned AttrSize, AttributesInfo &Info) {
1616 if (AttrSpec.Attr == dwarf::DW_AT_GNU_dwo_id ||
1617 AttrSpec.Attr == dwarf::DW_AT_dwo_id)
1622 if (AttrSpec.Attr == dwarf::DW_AT_macro_info) {
1623 if (std::optional<uint64_t>
Offset = Val.getAsSectionOffset()) {
1624 const llvm::DWARFDebugMacro *
Macro =
File.Dwarf->getDebugMacinfo();
1630 if (AttrSpec.Attr == dwarf::DW_AT_macros) {
1631 if (std::optional<uint64_t>
Offset = Val.getAsSectionOffset()) {
1632 const llvm::DWARFDebugMacro *
Macro =
File.Dwarf->getDebugMacro();
1638 if (AttrSpec.Attr == dwarf::DW_AT_str_offsets_base) {
1642 Info.AttrStrOffsetBaseSeen =
true;
1644 .addValue(DIEAlloc, dwarf::DW_AT_str_offsets_base,
1645 dwarf::DW_FORM_sec_offset, DIEInteger(8))
1646 ->sizeOf(
Unit.getOrigUnit().getFormParams());
1649 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence) {
1652 dwarf::DW_FORM_sec_offset,
1653 DIEInteger(*Val.getAsSectionOffset()));
1656 Unit.noteStmtSeqListAttribute(Patch);
1658 return Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1662 if (
auto OptionalValue = Val.getAsUnsignedConstant())
1663 Value = *OptionalValue;
1664 else if (
auto OptionalValue = Val.getAsSignedConstant())
1665 Value = *OptionalValue;
1666 else if (
auto OptionalValue = Val.getAsSectionOffset())
1667 Value = *OptionalValue;
1670 "Unsupported scalar attribute form. Dropping attribute.", File,
1674 if (AttrSpec.Attr == dwarf::DW_AT_declaration &&
Value)
1675 Info.IsDeclaration =
true;
1677 if (AttrSpec.Form == dwarf::DW_FORM_loclistx)
1686 [[maybe_unused]]
dwarf::Form OriginalForm = AttrSpec.Form;
1687 if (AttrSpec.Form == dwarf::DW_FORM_rnglistx) {
1691 std::optional<uint64_t>
Index = Val.getAsSectionOffset();
1693 Linker.reportWarning(
"Cannot read the attribute. Dropping.", File,
1697 std::optional<uint64_t>
Offset =
1698 Unit.getOrigUnit().getRnglistOffset(*Index);
1700 Linker.reportWarning(
"Cannot read the attribute. Dropping.", File,
1706 AttrSpec.Form = dwarf::DW_FORM_sec_offset;
1707 AttrSize =
Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1708 }
else if (AttrSpec.Form == dwarf::DW_FORM_loclistx) {
1712 std::optional<uint64_t>
Index = Val.getAsSectionOffset();
1714 Linker.reportWarning(
"Cannot read the attribute. Dropping.", File,
1718 std::optional<uint64_t>
Offset =
1719 Unit.getOrigUnit().getLoclistOffset(*Index);
1721 Linker.reportWarning(
"Cannot read the attribute. Dropping.", File,
1727 AttrSpec.Form = dwarf::DW_FORM_sec_offset;
1728 AttrSize =
Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1729 }
else if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1730 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1731 std::optional<uint64_t> LowPC =
Unit.getLowPc();
1736 }
else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1737 Value = *Val.getAsSectionOffset();
1738 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1739 Value = *Val.getAsSignedConstant();
1740 else if (
auto OptionalValue = Val.getAsUnsignedConstant())
1741 Value = *OptionalValue;
1744 "Unsupported scalar attribute form. Dropping attribute.", File,
1751 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1752 Die.getTag() != dwarf::DW_TAG_compile_unit)
1756 DIE::value_iterator Patch =
1759 if (AttrSpec.Attr == dwarf::DW_AT_ranges ||
1760 AttrSpec.Attr == dwarf::DW_AT_start_scope) {
1761 Unit.noteRangeAttribute(Die, Patch);
1762 Info.HasRanges =
true;
1766 Unit.getOrigUnit().getVersion())) {
1768 CompileUnit::DIEInfo &LocationDieInfo =
Unit.getInfo(InputDIE);
1769 Unit.noteLocationAttribute({Patch, LocationDieInfo.InDebugMap
1770 ? LocationDieInfo.AddrAdjust
1772 }
else if (AttrSpec.Attr == dwarf::DW_AT_declaration &&
Value)
1773 Info.IsDeclaration =
true;
1776 assert((
Info.HasRanges || (OriginalForm != dwarf::DW_FORM_rnglistx)) &&
1777 "Unhandled DW_FORM_rnglistx attribute");
1785unsigned DWARFLinker::DIECloner::cloneAttribute(
1786 DIE &Die,
const DWARFDie &InputDIE,
const DWARFFile &File,
1787 CompileUnit &Unit,
const DWARFFormValue &Val,
const AttributeSpec AttrSpec,
1788 unsigned AttrSize, AttributesInfo &Info,
bool IsLittleEndian) {
1789 const DWARFUnit &
U =
Unit.getOrigUnit();
1791 switch (AttrSpec.Form) {
1792 case dwarf::DW_FORM_strp:
1793 case dwarf::DW_FORM_line_strp:
1794 case dwarf::DW_FORM_string:
1795 case dwarf::DW_FORM_strx:
1796 case dwarf::DW_FORM_strx1:
1797 case dwarf::DW_FORM_strx2:
1798 case dwarf::DW_FORM_strx3:
1799 case dwarf::DW_FORM_strx4:
1800 return cloneStringAttribute(Die, AttrSpec, Val, U, Info);
1801 case dwarf::DW_FORM_ref_addr:
1802 case dwarf::DW_FORM_ref1:
1803 case dwarf::DW_FORM_ref2:
1804 case dwarf::DW_FORM_ref4:
1805 case dwarf::DW_FORM_ref8:
1806 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1808 case dwarf::DW_FORM_block:
1809 case dwarf::DW_FORM_block1:
1810 case dwarf::DW_FORM_block2:
1811 case dwarf::DW_FORM_block4:
1812 case dwarf::DW_FORM_exprloc:
1813 return cloneBlockAttribute(Die, InputDIE, File, Unit, AttrSpec, Val, Info,
1815 case dwarf::DW_FORM_addr:
1816 case dwarf::DW_FORM_addrx:
1817 case dwarf::DW_FORM_addrx1:
1818 case dwarf::DW_FORM_addrx2:
1819 case dwarf::DW_FORM_addrx3:
1820 case dwarf::DW_FORM_addrx4:
1821 return cloneAddressAttribute(Die, InputDIE, AttrSpec, AttrSize, Val, Unit,
1823 case dwarf::DW_FORM_data1:
1824 case dwarf::DW_FORM_data2:
1825 case dwarf::DW_FORM_data4:
1826 case dwarf::DW_FORM_data8:
1827 case dwarf::DW_FORM_udata:
1828 case dwarf::DW_FORM_sdata:
1829 case dwarf::DW_FORM_sec_offset:
1830 case dwarf::DW_FORM_flag:
1831 case dwarf::DW_FORM_flag_present:
1832 case dwarf::DW_FORM_rnglistx:
1833 case dwarf::DW_FORM_loclistx:
1834 case dwarf::DW_FORM_implicit_const:
1835 return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1838 Linker.reportWarning(
"Unsupported attribute form " +
1840 " in cloneAttribute. Dropping.",
1847void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1849 DwarfStringPoolEntryRef Name,
1851 bool SkipPubSection) {
1852 std::optional<ObjCSelectorNames> Names =
1856 Unit.addNameAccelerator(Die, StringPool.getEntry(Names->Selector),
1858 Unit.addObjCAccelerator(Die, StringPool.getEntry(Names->ClassName),
1860 if (Names->ClassNameNoCategory)
1861 Unit.addObjCAccelerator(
1862 Die, StringPool.getEntry(*Names->ClassNameNoCategory), SkipPubSection);
1863 if (Names->MethodNameNoCategory)
1864 Unit.addNameAccelerator(
1865 Die, StringPool.getEntry(*Names->MethodNameNoCategory), SkipPubSection);
1872 switch (AttrSpec.
Attr) {
1875 case dwarf::DW_AT_low_pc:
1876 case dwarf::DW_AT_high_pc:
1877 case dwarf::DW_AT_ranges:
1878 return !Update && SkipPC;
1879 case dwarf::DW_AT_rnglists_base:
1885 case dwarf::DW_AT_loclists_base:
1891 case dwarf::DW_AT_location:
1892 case dwarf::DW_AT_frame_base:
1893 return !Update && SkipPC;
1897DIE *DWARFLinker::DIECloner::cloneDIE(
const DWARFDie &InputDIE,
1898 const DWARFFile &File, CompileUnit &Unit,
1899 int64_t PCOffset,
uint32_t OutOffset,
1900 unsigned Flags,
bool IsLittleEndian,
1902 DWARFUnit &U = Unit.getOrigUnit();
1903 unsigned Idx = U.getDIEIndex(InputDIE);
1904 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1907 if (!Unit.getInfo(Idx).Keep)
1911 assert(!(Die && Info.Clone) &&
"Can't supply a DIE and a cloned DIE");
1920 assert(Die->getTag() == InputDIE.getTag());
1921 Die->setOffset(OutOffset);
1923 (
Info.Ctxt->getCanonicalDIEOffset() == 0)) {
1924 if (!
Info.Ctxt->hasCanonicalDIE())
1925 Info.Ctxt->setHasCanonicalDIE();
1929 Info.Ctxt->setCanonicalDIEOffset(OutOffset +
Unit.getStartOffset());
1933 DWARFDataExtractor
Data =
U.getDebugInfoExtractor();
1938 ?
U.getDIEAtIndex(Idx + 1).getOffset()
1939 :
U.getNextUnitOffset();
1940 AttributesInfo AttrInfo;
1945 SmallString<40> DIECopy(
Data.getData().substr(
Offset, NextOffset -
Offset));
1947 DWARFDataExtractor(DIECopy,
Data.isLittleEndian(),
Data.getAddressSize());
1950 ObjFile.Addresses->applyValidRelocs(DIECopy,
Offset,
Data.isLittleEndian());
1956 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1960 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1961 PCOffset =
Info.AddrAdjust;
1962 AttrInfo.PCOffset = PCOffset;
1964 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1965 Flags |= TF_InFunctionScope;
1967 if (
Info.InDebugMap)
1968 Flags &= ~TF_SkipPC;
1972 }
else if (Abbrev->getTag() == dwarf::DW_TAG_variable) {
1975 if ((Flags & TF_InFunctionScope) &&
Info.InDebugMap)
1976 Flags &= ~TF_SkipPC;
1979 else if (!
Info.InDebugMap &&
Info.HasLocationExpressionAddr &&
1984 std::optional<StringRef> LibraryInstallName =
1985 ObjFile.Addresses->getLibraryInstallName();
1986 for (
const auto &AttrSpec : Abbrev->attributes()) {
1994 DWARFFormValue Val = AttrSpec.getFormValue();
1996 Val.extractValue(
Data, &
Offset,
U.getFormParams(), &U);
1998 AttrSize =
Offset - AttrSize;
2001 cloneAttribute(*Die, InputDIE, File, Unit, Val, AttrSpec, AttrSize,
2002 AttrInfo, IsLittleEndian);
2003 if (FinalAttrSize != 0 && ObjFile.Addresses->needToSaveValidRelocs())
2004 RelocFixups.noteAttribute(InputDIE.getTag(), AttrSpec.Attr, InputStart,
2005 InputEnd,
Unit.getStartOffset() + OutOffset,
2007 AttrInfo.Source.clear();
2009 OutOffset += FinalAttrSize;
2012 uint16_t
Tag = InputDIE.getTag();
2015 const bool NeedsAppleOrigin = (
Tag == dwarf::DW_TAG_compile_unit) &&
2016 LibraryInstallName.has_value() &&
2017 !AttrInfo.HasAppleOrigin;
2018 if (NeedsAppleOrigin) {
2019 auto StringEntry = DebugStrPool.getEntry(LibraryInstallName.value());
2021 dwarf::DW_FORM_strp, DIEInteger(
StringEntry.getOffset()));
2030 if ((
Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
2031 Tag != dwarf::DW_TAG_compile_unit &&
2032 !(
Tag == dwarf::DW_TAG_variable &&
2034 getDIENames(InputDIE, AttrInfo, DebugStrPool, File, Unit,
2035 Tag != dwarf::DW_TAG_inlined_subroutine)) {
2036 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2037 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2038 Tag == dwarf::DW_TAG_inlined_subroutine);
2039 if (AttrInfo.Name) {
2040 if (AttrInfo.NameWithoutTemplate)
2041 Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
2043 Unit.addNameAccelerator(Die, AttrInfo.Name,
2044 Tag == dwarf::DW_TAG_inlined_subroutine);
2047 addObjCAccelerator(Unit, Die, AttrInfo.Name, DebugStrPool,
2050 }
else if (
Tag == dwarf::DW_TAG_namespace) {
2052 AttrInfo.Name = DebugStrPool.getEntry(
"(anonymous namespace)");
2053 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
2054 }
else if (
Tag == dwarf::DW_TAG_imported_declaration && AttrInfo.Name) {
2055 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
2056 }
else if (
isTypeTag(
Tag) && !AttrInfo.IsDeclaration) {
2057 bool Success = getDIENames(InputDIE, AttrInfo, DebugStrPool, File, Unit);
2061 bool ObjCClassIsImplementation =
2062 (RuntimeLang == dwarf::DW_LANG_ObjC ||
2063 RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
2066 if (
Success && AttrInfo.Name && !AttrInfo.Name.getString().empty()) {
2068 InputDIE, [&](
const DWARFDie &Referrer,
const DWARFFormValue &
Ref) {
2070 return Linker.resolveDIEReference(File, CompileUnits,
Ref, Referrer,
2073 Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
2078 if (
Success && AttrInfo.MangledName &&
2079 RuntimeLang == dwarf::DW_LANG_Swift &&
2080 !AttrInfo.MangledName.getString().empty() &&
2081 AttrInfo.MangledName != AttrInfo.Name) {
2082 auto Hash =
djbHash(AttrInfo.MangledName.getString().data());
2083 Unit.addTypeAccelerator(Die, AttrInfo.MangledName,
2084 ObjCClassIsImplementation, Hash);
2089 bool HasChildren =
false;
2090 for (
auto Child : InputDIE.children()) {
2091 unsigned Idx =
U.getDIEIndex(Child);
2092 if (
Unit.getInfo(Idx).Keep) {
2098 if (Die ==
Unit.getOutputUnitDIE() &&
Unit.getOrigUnit().getVersion() >= 5 &&
2099 !AttrInfo.AttrStrOffsetBaseSeen) {
2101 Die->addValue(DIEAlloc, dwarf::DW_AT_str_offsets_base,
2102 dwarf::DW_FORM_sec_offset, DIEInteger(8));
2108 if (!Update && Die ==
Unit.getOutputUnitDIE() &&
U.getVersion() >= 5 &&
2109 !Die->findAttribute(dwarf::DW_AT_addr_base)) {
2110 OutOffset += Die->addValue(DIEAlloc, dwarf::DW_AT_addr_base,
2111 dwarf::DW_FORM_sec_offset, DIEInteger(0))
2112 ->sizeOf(
U.getFormParams());
2115 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2119 Linker.assignAbbrev(NewAbbrev);
2120 Die->setAbbrevNumber(NewAbbrev.getNumber());
2125 OutOffset += AbbrevNumberSize;
2127 RelocFixups.finishDIE(AbbrevNumberSize);
2131 Die->setSize(OutOffset - Die->getOffset());
2136 for (
auto Child : InputDIE.children()) {
2137 if (DIE *Clone = cloneDIE(Child, File, Unit, PCOffset, OutOffset, Flags,
2139 Die->addChild(Clone);
2140 OutOffset = Clone->getOffset() + Clone->getSize();
2145 OutOffset +=
sizeof(int8_t);
2147 Die->setSize(OutOffset - Die->getOffset());
2154Error DWARFLinker::generateUnitRanges(CompileUnit &Unit,
const DWARFFile &File,
2159 const auto &FunctionRanges =
Unit.getFunctionRanges();
2162 AddressRanges LinkedFunctionRanges;
2163 for (
const AddressRangeValuePair &
Range : FunctionRanges)
2164 LinkedFunctionRanges.insert(
2168 if (!LinkedFunctionRanges.empty())
2169 TheDwarfEmitter->emitDwarfDebugArangesTable(Unit, LinkedFunctionRanges);
2172 std::optional<PatchLocation> UnitRngListAttribute =
2173 Unit.getUnitRangesAttribute();
2175 if (!AllRngListAttributes.empty() || UnitRngListAttribute) {
2176 std::optional<AddressRangeValuePair> CachedRange;
2177 MCSymbol *EndLabel = TheDwarfEmitter->emitDwarfDebugRangeListHeader(Unit);
2181 for (PatchLocation &AttributePatch : AllRngListAttributes) {
2184 AddressRanges LinkedRanges;
2185 if (Expected<DWARFAddressRangesVector> OriginalRanges =
2186 Unit.getOrigUnit().findRnglistFromOffset(AttributePatch.get())) {
2188 for (
const auto &
Range : *OriginalRanges) {
2189 if (!CachedRange || !CachedRange->Range.contains(
Range.LowPC))
2190 CachedRange = FunctionRanges.getRangeThatContains(
Range.LowPC);
2194 reportWarning(
"inconsistent range data.", File);
2199 LinkedRanges.insert({
Range.LowPC + CachedRange->Value,
2200 Range.HighPC + CachedRange->Value});
2204 reportWarning(
"invalid range list ignored.", File);
2208 if (
Error E = TheDwarfEmitter->emitDwarfDebugRangeListFragment(
2209 Unit, LinkedRanges, AttributePatch, AddrPool))
2214 if (UnitRngListAttribute.has_value())
2215 if (
Error E = TheDwarfEmitter->emitDwarfDebugRangeListFragment(
2216 Unit, LinkedFunctionRanges, *UnitRngListAttribute, AddrPool))
2220 TheDwarfEmitter->emitDwarfDebugRangeListFooter(Unit, EndLabel);
2226Error DWARFLinker::DIECloner::generateUnitLocations(
2227 CompileUnit &Unit,
const DWARFFile &File,
2228 ExpressionHandlerRef ExprHandler) {
2233 Unit.getLocationAttributes();
2235 if (AllLocListAttributes.empty())
2241 for (
auto &CurLocAttr : AllLocListAttributes) {
2244 Expected<DWARFLocationExpressionsVector> OriginalLocations =
2245 Unit.getOrigUnit().findLoclistFromOffset(CurLocAttr.get());
2247 if (!OriginalLocations) {
2249 Linker.reportWarning(
"Invalid location attribute ignored.", File);
2254 for (DWARFLocationExpression &CurExpression : *OriginalLocations) {
2255 DWARFLocationExpression LinkedExpression;
2257 if (CurExpression.Range) {
2259 LinkedExpression.Range = {
2260 CurExpression.Range->LowPC + CurLocAttr.RelocAdjustment,
2261 CurExpression.Range->HighPC + CurLocAttr.RelocAdjustment};
2265 LinkedExpression.Expr.reserve(CurExpression.Expr.size());
2266 ExprHandler(CurExpression.Expr, LinkedExpression.Expr,
2267 CurLocAttr.RelocAdjustment);
2269 LinkedLocationExpressions.push_back(LinkedExpression);
2274 Unit, LinkedLocationExpressions, CurLocAttr, AddrPool))
2279 Emitter->emitDwarfDebugLocListFooter(Unit, EndLabel);
2286 if (
V.getAttribute() == dwarf::DW_AT_addr_base) {
2294Error DWARFLinker::DIECloner::emitDebugAddrSection(
2295 CompileUnit &Unit,
const uint16_t DwarfVersion) {
2300 if (DwarfVersion < 5)
2305 DIE *OutputUnitDIE = Unit.getOutputUnitDIE();
2306 if (OutputUnitDIE ==
nullptr)
2309 MCSymbol *EndLabel =
Emitter->emitDwarfDebugAddrsHeader(Unit);
2311 dwarf::FormParams
FP = Unit.getOrigUnit().getFormParams();
2312 if (AddrOffset >
FP.getDwarfMaxOffset())
2317 Emitter->emitDwarfDebugAddrs(AddrPool.getValues(),
2318 Unit.getOrigUnit().getAddressByteSize());
2319 Emitter->emitDwarfDebugAddrsFooter(Unit, EndLabel);
2320 RelocFixups.setDebugAddrTableOffset(AddrOffset);
2338 std::vector<TrackedRow> &Rows) {
2344 Seq.front().isStartSeqInOutput =
true;
2346 if (!Rows.empty() && Rows.back().Row.Address < Seq.front().Row.Address) {
2354 Rows, [=](
const TrackedRow &O) {
return O.Row.Address < Front; });
2363 Rows.insert(
InsertPoint + 1, Seq.begin() + 1, Seq.end());
2373 if (
V.getAttribute() == dwarf::DW_AT_stmt_list) {
2381void DWARFLinker::DIECloner::rememberUnitForMacroOffset(CompileUnit &Unit) {
2382 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2383 DWARFDie OrigUnitDie = OrigUnit.getUnitDIE();
2385 if (std::optional<uint64_t> MacroAttr =
2387 UnitMacroMap.insert(std::make_pair(*MacroAttr, &Unit));
2391 if (std::optional<uint64_t> MacroAttr =
2393 UnitMacroMap.insert(std::make_pair(*MacroAttr, &Unit));
2398Error DWARFLinker::DIECloner::generateLineTableForUnit(CompileUnit &Unit) {
2403 DWARFDie CUDie =
Unit.getOrigUnit().getUnitDIE();
2409 if (
auto *OutputDIE =
Unit.getOutputUnitDIE()) {
2411 dwarf::FormParams
FP =
Unit.getOrigUnit().getFormParams();
2412 if (StmtOffset >
FP.getDwarfMaxOffset())
2419 if (
const DWARFDebugLine::LineTable *LT =
2420 ObjFile.Dwarf->getLineTableForUnit(&
Unit.getOrigUnit())) {
2422 DWARFDebugLine::LineTable LineTable;
2425 LineTable.Prologue =
LT->Prologue;
2428 if (
Linker.Options.Update) {
2429 LineTable.Rows =
LT->Rows;
2432 if (LineTable.Rows.size() == 1 && LineTable.Rows[0].EndSequence)
2433 LineTable.Rows.clear();
2435 LineTable.Sequences =
LT->Sequences;
2437 Emitter->emitLineTableForUnit(LineTable, Unit, DebugStrPool,
2441 std::vector<TrackedRow> InputRows;
2442 InputRows.reserve(
LT->Rows.size());
2443 for (
size_t i = 0; i <
LT->Rows.size(); i++)
2444 InputRows.emplace_back(TrackedRow{LT->Rows[i], i, false});
2447 std::vector<TrackedRow> OutputRows;
2448 OutputRows.reserve(InputRows.size());
2452 std::vector<TrackedRow> Seq;
2453 Seq.reserve(InputRows.size());
2455 const auto &FunctionRanges =
Unit.getFunctionRanges();
2456 std::optional<AddressRangeValuePair> CurrRange;
2469 for (
size_t i = 0; i < InputRows.size(); i++) {
2470 TrackedRow
TR = InputRows[i];
2477 if (!CurrRange || !CurrRange->Range.contains(
TR.Row.Address.Address)) {
2481 CurrRange ? CurrRange->Range.end() + CurrRange->Value : -1ULL;
2483 FunctionRanges.getRangeThatContains(
TR.Row.Address.Address);
2484 if (StopAddress != -1ULL && !Seq.empty()) {
2487 auto NextLine = Seq.back();
2488 NextLine.Row.Address.Address = StopAddress;
2489 NextLine.Row.EndSequence = 1;
2490 NextLine.Row.PrologueEnd = 0;
2491 NextLine.Row.BasicBlock = 0;
2492 NextLine.Row.EpilogueBegin = 0;
2493 Seq.push_back(NextLine);
2502 if (
TR.Row.EndSequence && Seq.empty())
2506 TR.Row.Address.Address += CurrRange->Value;
2509 if (
TR.Row.EndSequence)
2520 if (!OutputRows.empty()) {
2521 OutputRows[0].isStartSeqInOutput =
true;
2522 for (
size_t i = 1; i < OutputRows.size(); ++i)
2523 OutputRows[i].isStartSeqInOutput = OutputRows[i - 1].Row.EndSequence;
2527 LineTable.Rows.clear();
2528 LineTable.Rows.reserve(OutputRows.size());
2529 for (
auto &TR : OutputRows)
2530 LineTable.Rows.push_back(
TR.Row);
2534 std::vector<uint64_t> OutputRowOffsets;
2538 bool hasStmtSeq =
Unit.getStmtSeqListAttributes().size() > 0;
2539 Emitter->emitLineTableForUnit(LineTable, Unit, DebugStrPool,
2541 hasStmtSeq ? &OutputRowOffsets :
nullptr);
2544 assert(OutputRowOffsets.size() == OutputRows.size() &&
2545 "must have an offset for each row");
2548 DenseMap<uint64_t, uint64_t> SeqOffToOrigRow;
2553 if (!
LT->Rows.empty())
2561 DenseMap<size_t, size_t> OrigRowToOutputRow;
2562 std::vector<size_t> OutputRowToSeqStart(OutputRows.size());
2564 size_t CurrentSeqStart = 0;
2565 for (
size_t i = 0; i < OutputRows.size(); ++i) {
2567 if (OutputRows[i].isStartSeqInOutput)
2568 CurrentSeqStart = i;
2569 OutputRowToSeqStart[i] = CurrentSeqStart;
2572 OrigRowToOutputRow[OutputRows[i].OriginalRowIndex] = i;
2577 for (
const auto &StmtSeq :
Unit.getStmtSeqListAttributes()) {
2578 uint64_t OrigStmtSeq = StmtSeq.get();
2580 auto OrigRowIter = SeqOffToOrigRow.find(OrigStmtSeq);
2582 Unit.getOrigUnit().getFormParams().getDwarfMaxOffset();
2586 if (OrigRowIter == SeqOffToOrigRow.end()) {
2587 StmtSeq.set(InvalidOffset);
2590 size_t OrigRowIndex = OrigRowIter->second;
2593 auto OutputRowIter = OrigRowToOutputRow.find(OrigRowIndex);
2594 if (OutputRowIter == OrigRowToOutputRow.end()) {
2596 StmtSeq.set(InvalidOffset);
2599 size_t OutputRowIdx = OutputRowIter->second;
2604 size_t SeqStartIdx = OutputRowToSeqStart[OutputRowIdx];
2608 assert(SeqStartIdx < OutputRowOffsets.size() &&
2609 "Sequence start index out of bounds");
2610 uint64_t NewStmtSeqOffset = OutputRowOffsets[SeqStartIdx];
2613 StmtSeq.set(NewStmtSeqOffset);
2619 Linker.reportWarning(
"Cann't load line table.", ObjFile);
2624void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2629 for (
const auto &Namespace :
Unit.getNamespaces())
2631 Unit.getStartOffset());
2633 for (
const auto &Pubname :
Unit.getPubnames())
2634 AppleNames.addName(Pubname.Name,
2635 Pubname.Die->getOffset() +
Unit.getStartOffset());
2637 for (
const auto &Pubtype :
Unit.getPubtypes())
2639 Pubtype.Name, Pubtype.Die->getOffset() +
Unit.getStartOffset(),
2640 Pubtype.Die->getTag(),
2643 Pubtype.QualifiedNameHash);
2645 for (
const auto &ObjC :
Unit.getObjC())
2646 AppleObjc.addName(ObjC.Name,
2647 ObjC.Die->getOffset() +
Unit.getStartOffset());
2650 TheDwarfEmitter->emitPubNamesForUnit(Unit);
2651 TheDwarfEmitter->emitPubTypesForUnit(Unit);
2654 for (
const auto &Namespace :
Unit.getNamespaces())
2659 Unit.getTag() == dwarf::DW_TAG_type_unit);
2660 for (
const auto &Pubname :
Unit.getPubnames())
2662 Pubname.Name, Pubname.Die->getOffset(),
2664 Pubname.Die->getTag(),
Unit.getUniqueID(),
2665 Unit.getTag() == dwarf::DW_TAG_type_unit);
2666 for (
const auto &Pubtype :
Unit.getPubtypes())
2668 Pubtype.Name, Pubtype.Die->getOffset(),
2670 Pubtype.Die->getTag(),
Unit.getUniqueID(),
2671 Unit.getTag() == dwarf::DW_TAG_type_unit);
2683void DWARFLinker::patchFrameInfoForObject(LinkContext &
Context) {
2684 DWARFContext &OrigDwarf = *
Context.File.Dwarf;
2685 unsigned SrcAddrSize = OrigDwarf.getDWARFObj().getAddressSize();
2687 StringRef
FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
2692 for (std::unique_ptr<CompileUnit> &Unit :
Context.CompileUnits) {
2693 for (
auto CurRange :
Unit->getFunctionRanges())
2694 AllUnitsRanges.insert(CurRange.Range, CurRange.Value);
2697 DataExtractor
Data(FrameData, OrigDwarf.isLittleEndian());
2702 DenseMap<uint64_t, StringRef> LocalCIES;
2704 while (
Data.isValidOffset(InputOffset)) {
2705 uint64_t EntryOffset = InputOffset;
2706 uint32_t InitialLength =
Data.getU32(&InputOffset);
2707 if (InitialLength == 0xFFFFFFFF)
2708 return reportWarning(
"Dwarf64 bits no supported",
Context.File);
2710 uint32_t CIEId =
Data.getU32(&InputOffset);
2711 if (CIEId == 0xFFFFFFFF) {
2713 StringRef CIEData =
FrameData.substr(EntryOffset, InitialLength + 4);
2714 LocalCIES[EntryOffset] = CIEData;
2716 InputOffset += InitialLength - 4;
2720 uint64_t Loc =
Data.getUnsigned(&InputOffset, SrcAddrSize);
2726 std::optional<AddressRangeValuePair>
Range =
2727 AllUnitsRanges.getRangeThatContains(Loc);
2730 InputOffset = EntryOffset + InitialLength + 4;
2736 StringRef CIEData = LocalCIES[CIEId];
2737 if (CIEData.empty())
2738 return reportWarning(
"Inconsistent debug_frame content. Dropping.",
2743 auto IteratorInserted = EmittedCIEs.insert(
2744 std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
2746 if (IteratorInserted.second) {
2747 LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
2748 IteratorInserted.first->getValue() = LastCIEOffset;
2749 TheDwarfEmitter->emitCIE(CIEData);
2755 unsigned FDERemainingBytes = InitialLength - (4 + SrcAddrSize);
2756 TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), SrcAddrSize,
2758 FrameData.substr(InputOffset, FDERemainingBytes));
2759 InputOffset += FDERemainingBytes;
2765 CUDie.
find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
2774 if (ObjectPrefixMap.empty())
2778 for (
const auto &Entry : ObjectPrefixMap)
2781 return p.str().str();
2789 CUDie.
find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
"");
2791 if (PCMFile.empty())
2794 if (ObjectPrefixMap)
2795 PCMFile =
remapPath(PCMFile, *ObjectPrefixMap);
2797 return File.remapPath(PCMFile);
2800std::pair<bool, bool> DWARFLinker::isClangModuleRef(
const DWARFDie &CUDie,
2801 std::string &PCMFile,
2802 LinkContext &Context,
2805 if (PCMFile.empty())
2806 return std::make_pair(
false,
false);
2811 std::string Name =
dwarf::toString(CUDie.find(dwarf::DW_AT_name),
"");
2814 reportWarning(
"Anonymous module skeleton CU for " + PCMFile,
2816 return std::make_pair(
true,
true);
2819 if (!
Quiet && Options.Verbose) {
2821 outs() <<
"Found clang module reference " << PCMFile;
2824 auto Cached = ClangModules.find(PCMFile);
2825 if (Cached != ClangModules.end()) {
2829 if (!
Quiet && Options.Verbose && (Cached->second != DwoId))
2830 reportWarning(Twine(
"hash mismatch: this object file was built against a "
2831 "different version of the module ") +
2834 if (!
Quiet && Options.Verbose)
2835 outs() <<
" [cached].\n";
2836 return std::make_pair(
true,
true);
2839 return std::make_pair(
true,
false);
2842bool DWARFLinker::registerModuleReference(
const DWARFDie &CUDie,
2847 std::string PCMFile =
2849 std::pair<bool, bool> IsClangModuleRef =
2850 isClangModuleRef(CUDie, PCMFile,
Context, Indent,
false);
2852 if (!IsClangModuleRef.first)
2855 if (IsClangModuleRef.second)
2858 if (Options.Verbose)
2863 ClangModules.insert({PCMFile,
getDwoId(CUDie)});
2865 if (
Error E = loadClangModule(Loader, CUDie, PCMFile,
Context, OnCUDieLoaded,
2873Error DWARFLinker::loadClangModule(
2874 ObjFileLoaderTy Loader,
const DWARFDie &CUDie,
const std::string &PCMFile,
2878 std::string ModuleName =
dwarf::toString(CUDie.find(dwarf::DW_AT_name),
"");
2881 SmallString<0>
Path(Options.PrependPath);
2888 if (Loader ==
nullptr) {
2889 reportError(
"Could not load clang module: loader is not specified.\n",
2894 auto ErrOrObj = Loader(
Context.File.FileName, Path);
2900 if (!ErrOrObj->PrefixMap)
2901 ErrOrObj->PrefixMap =
Context.File.PrefixMap;
2903 std::unique_ptr<CompileUnit>
Unit;
2904 for (
const auto &CU : ErrOrObj->Dwarf->compile_units()) {
2907 auto ChildCUDie = CU->getUnitDIE();
2910 if (!registerModuleReference(ChildCUDie,
Context, Loader, OnCUDieLoaded,
2915 ": Clang modules are expected to have exactly 1 compile unit.\n");
2916 reportError(Err,
Context.File);
2923 if (PCMDwoId != DwoId) {
2924 if (Options.Verbose)
2926 Twine(
"hash mismatch: this object file was built against a "
2927 "different version of the module ") +
2931 ClangModules[PCMFile] = PCMDwoId;
2935 Unit = std::make_unique<CompileUnit>(*CU, *ErrOrObj, UniqueUnitID++,
2936 !Options.NoODR, ModuleName);
2941 Context.ModuleUnits.emplace_back(RefModuleUnit{*ErrOrObj, std::move(Unit)});
2946Expected<uint64_t> DWARFLinker::DIECloner::cloneAllCompileUnits(
2947 DWARFContext &DwarfContext,
const DWARFFile &File,
bool IsLittleEndian) {
2950 const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
2952 for (
auto &CurrentUnit : CompileUnits) {
2953 const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2954 const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
2955 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2956 CurrentUnit->setStartOffset(OutputDebugInfoSize);
2957 RelocFixups.clear();
2959 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2962 if (CurrentUnit->getInfo(0).Keep) {
2965 CurrentUnit->createOutputDIE();
2966 rememberUnitForMacroOffset(*CurrentUnit);
2967 cloneDIE(InputDIE, File, *CurrentUnit, 0 , UnitHeaderSize,
2968 0, IsLittleEndian, CurrentUnit->getOutputUnitDIE());
2971 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2975 if (
Error E = generateLineTableForUnit(*CurrentUnit))
2978 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2983 if (
Error E =
Linker.generateUnitRanges(*CurrentUnit, File, AddrPool))
2986 auto ProcessExpr = [&](SmallVectorImpl<uint8_t> &SrcBytes,
2987 SmallVectorImpl<uint8_t> &OutBytes,
2988 int64_t RelocAdjustment) {
2989 DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2990 DataExtractor
Data(SrcBytes, IsLittleEndian);
2991 cloneExpression(
Data,
2992 DWARFExpression(
Data, OrigUnit.getAddressByteSize(),
2993 OrigUnit.getFormParams().Format),
2994 File, *CurrentUnit, OutBytes, RelocAdjustment,
2995 IsLittleEndian,
nullptr,
2996 File.Addresses->needToSaveValidRelocs());
2998 if (
Error E = generateUnitLocations(*CurrentUnit, File, ProcessExpr))
3000 if (
Error E = emitDebugAddrSection(*CurrentUnit, DwarfVersion))
3003 RelocFixups.save(*
File.Addresses, CurrentUnit->getOrigUnit().getOffset(),
3004 CurrentUnit->getOrigUnit().getAddressByteSize());
3011 Emitter->emitMacroTables(
File.Dwarf.get(), UnitMacroMap, DebugStrPool);
3014 for (
auto &CurrentUnit : CompileUnits) {
3015 CurrentUnit->fixupForwardReferences();
3017 if (!CurrentUnit->getOutputUnitDIE())
3020 unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
3023 CurrentUnit->getStartOffset());
3024 Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
3025 Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
3027 CurrentUnit->computeNextUnitOffset(DwarfVersion));
3031 return OutputDebugInfoSize - StartOutputDebugInfoSize;
3034void DWARFLinker::copyInvariantDebugSection(DWARFContext &
Dwarf) {
3035 TheDwarfEmitter->emitSectionContents(
Dwarf.getDWARFObj().getLocSection().Data,
3037 TheDwarfEmitter->emitSectionContents(
3038 Dwarf.getDWARFObj().getRangesSection().Data,
3040 TheDwarfEmitter->emitSectionContents(
3042 TheDwarfEmitter->emitSectionContents(
Dwarf.getDWARFObj().getArangesSection(),
3044 TheDwarfEmitter->emitSectionContents(
3046 TheDwarfEmitter->emitSectionContents(
3047 Dwarf.getDWARFObj().getRnglistsSection().Data,
3049 TheDwarfEmitter->emitSectionContents(
3050 Dwarf.getDWARFObj().getLoclistsSection().Data,
3056 ObjectContexts.emplace_back(LinkContext(File));
3058 if (ObjectContexts.back().File.Dwarf) {
3059 for (
const std::unique_ptr<DWARFUnit> &
CU :
3060 ObjectContexts.back().File.Dwarf->compile_units()) {
3069 registerModuleReference(CUDie, ObjectContexts.back(), Loader,
3076 assert((Options.TargetDWARFVersion != 0) &&
3077 "TargetDWARFVersion should be set");
3081 unsigned NumObjects = ObjectContexts.size();
3093 for (LinkContext &OptContext : ObjectContexts) {
3094 if (Options.Verbose)
3095 outs() <<
"DEBUG MAP OBJECT: " << OptContext.File.FileName <<
"\n";
3097 if (!OptContext.File.Dwarf)
3100 if (Options.VerifyInputDWARF)
3101 verifyInput(OptContext.File);
3108 !OptContext.File.Addresses->hasValidRelocs()) {
3109 if (Options.Verbose)
3110 outs() <<
"No valid relocations found. Skipping.\n";
3114 OptContext.Skip =
true;
3119 if (!OptContext.File.Dwarf)
3123 if (!OptContext.File.Dwarf->types_section_units().empty()) {
3124 reportWarning(
"type units are not currently supported: file will "
3127 OptContext.Skip =
true;
3133 OptContext.CompileUnits.reserve(
3134 OptContext.File.Dwarf->getNumCompileUnits());
3135 for (
const auto &
CU : OptContext.File.Dwarf->compile_units()) {
3136 auto CUDie =
CU->getUnitDIE(
true);
3137 if (Options.Verbose) {
3138 outs() <<
"Input compilation unit:";
3141 DumpOpts.
Verbose = Options.Verbose;
3142 CUDie.dump(
outs(), 0, DumpOpts);
3146 for (
auto &
CU : OptContext.ModuleUnits) {
3147 if (
Error Err = cloneModuleUnit(OptContext,
CU, ODRContexts, DebugStrPool,
3148 DebugLineStrPool, StringOffsetPool))
3149 reportWarning(
toString(std::move(Err)),
CU.File);
3159 (TheDwarfEmitter ==
nullptr) ? 0
3160 : TheDwarfEmitter->getDebugInfoSectionSize();
3164 std::mutex ProcessedFilesMutex;
3165 std::condition_variable ProcessedFilesConditionVariable;
3166 BitVector ProcessedFiles(NumObjects,
false);
3170 auto AnalyzeLambda = [&](
size_t I) {
3176 for (
const auto &
CU :
Context.File.Dwarf->compile_units()) {
3179 auto CUDie =
CU->getUnitDIE(
false);
3180 std::string PCMFile =
3184 !isClangModuleRef(CUDie, PCMFile,
Context, 0,
true).first) {
3185 Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
3187 !Options.NoODR && !Options.Update,
""));
3192 for (
auto &CurrentUnit :
Context.CompileUnits) {
3193 auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
3197 *CurrentUnit, &ODRContexts.
getRoot(), ODRContexts,
3198 ModulesEndOffset, Options.ParseableSwiftInterfaces,
3200 reportWarning(Warning, Context.File, &DIE);
3213 auto &OptContext = ObjectContexts[
I];
3214 if (OptContext.Skip || !OptContext.File.Dwarf)
3223 for (
auto &CurrentUnit : OptContext.CompileUnits)
3224 CurrentUnit->markEverythingAsKept();
3225 copyInvariantDebugSection(*OptContext.File.Dwarf);
3227 for (
auto &CurrentUnit : OptContext.CompileUnits) {
3228 lookForDIEsToKeep(*OptContext.File.Addresses, OptContext.CompileUnits,
3229 CurrentUnit->getOrigUnit().getUnitDIE(),
3230 OptContext.File, *CurrentUnit, 0);
3240 if (OptContext.File.Addresses->hasValidRelocs() ||
3242 SizeByObject[OptContext.File.FileName].Input =
3245 DIECloner(*
this, TheDwarfEmitter, OptContext.File, DIEAlloc,
3246 OptContext.CompileUnits, Options.Update, DebugStrPool,
3247 DebugLineStrPool, StringOffsetPool)
3248 .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
3249 OptContext.File.Dwarf->isLittleEndian());
3254 SizeByObject[OptContext.File.FileName].Output = *SizeOrErr;
3256 if ((TheDwarfEmitter !=
nullptr) && !OptContext.CompileUnits.empty() &&
3258 patchFrameInfoForObject(OptContext);
3261 cleanupAuxiliarryData(OptContext);
3264 auto EmitLambda = [&]() {
3266 if (TheDwarfEmitter !=
nullptr) {
3267 TheDwarfEmitter->emitAbbrevs(Abbreviations, Options.TargetDWARFVersion);
3268 TheDwarfEmitter->emitStrings(DebugStrPool);
3269 TheDwarfEmitter->emitStringOffsets(StringOffsetPool.
getValues(),
3270 Options.TargetDWARFVersion);
3271 TheDwarfEmitter->emitLineStrings(DebugLineStrPool);
3273 switch (TableKind) {
3275 TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
3276 TheDwarfEmitter->emitAppleNames(AppleNames);
3277 TheDwarfEmitter->emitAppleTypes(AppleTypes);
3278 TheDwarfEmitter->emitAppleObjc(AppleObjc);
3285 TheDwarfEmitter->emitDebugNames(DebugNames);
3292 auto AnalyzeAll = [&]() {
3293 for (
unsigned I = 0,
E = NumObjects;
I !=
E; ++
I) {
3296 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
3297 ProcessedFiles.
set(
I);
3298 ProcessedFilesConditionVariable.notify_one();
3303 for (
unsigned I = 0,
E = NumObjects;
I !=
E; ++
I) {
3305 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
3306 if (!ProcessedFiles[
I]) {
3307 ProcessedFilesConditionVariable.wait(
3308 LockGuard, [&]() {
return ProcessedFiles[
I]; });
3324 if (Options.Threads == 1) {
3325 for (
unsigned I = 0,
E = NumObjects;
I !=
E; ++
I) {
3335 Pool.
async(AnalyzeAll);
3336 Pool.
async(CloneAll, std::reference_wrapper<Error>(CE));
3343 if (Options.Statistics) {
3345 std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
3346 for (
auto &
E : SizeByObject)
3347 Sorted.emplace_back(
E.first(),
E.second);
3349 return LHS.second.Output >
RHS.second.Output;
3352 auto ComputePercentange = [](int64_t
Input, int64_t Output) ->
float {
3353 const float Difference = Output -
Input;
3354 const float Sum =
Input + Output;
3357 return (Difference / (Sum / 2));
3360 int64_t InputTotal = 0;
3361 int64_t OutputTotal = 0;
3362 const char *FormatStr =
"{0,-45} {1,10}b {2,10}b {3,8:P}\n";
3365 outs() <<
".debug_info section size (in bytes)\n";
3366 outs() <<
"----------------------------------------------------------------"
3367 "---------------\n";
3368 outs() <<
"Filename Object "
3370 outs() <<
"----------------------------------------------------------------"
3371 "---------------\n";
3374 for (
auto &
E : Sorted) {
3375 InputTotal +=
E.second.Input;
3376 OutputTotal +=
E.second.Output;
3379 E.second.Output, ComputePercentange(
E.second.Input,
E.second.Output));
3382 outs() <<
"----------------------------------------------------------------"
3383 "---------------\n";
3385 ComputePercentange(InputTotal, OutputTotal));
3386 outs() <<
"----------------------------------------------------------------"
3387 "---------------\n\n";
3393Error DWARFLinker::cloneModuleUnit(LinkContext &
Context, RefModuleUnit &Unit,
3399 assert(Unit.Unit.get() !=
nullptr);
3401 if (!Unit.Unit->getOrigUnit().getUnitDIE().hasChildren())
3406 outs() <<
"cloning .debug_info from " << Unit.File.FileName <<
"\n";
3411 &ODRContexts.
getRoot(), ODRContexts, 0,
3412 Options.ParseableSwiftInterfaces,
3414 reportWarning(Warning, Context.File, &DIE);
3417 Unit.Unit->markEverythingAsKept();
3421 CompileUnits.emplace_back(std::move(Unit.Unit));
3424 DIECloner(*
this, TheDwarfEmitter, Unit.File, DIEAlloc, CompileUnits,
3425 Options.Update, DebugStrPool, DebugLineStrPool,
3427 .cloneAllCompileUnits(*Unit.File.Dwarf, Unit.File,
3428 Unit.File.Dwarf->isLittleEndian());
3434void DWARFLinker::verifyInput(
const DWARFFile &File) {
3441 if (
Options.InputVerificationHandler)
3442 Options.InputVerificationHandler(File, OS.str());
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the BitVector class.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_LIKELY(EXPR)
dxil container DXContainer Global Emitter
Provides ErrorOr<T> smart pointer.
if(!TBB||Cond.size()< 1) return false
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
BitVector & set()
Set all bits in the bitvector.
A structured debug information entry.
static DIE * get(BumpPtrAllocator &Alloc, dwarf::Tag Tag)
static std::optional< uint64_t > getDefiningParentDieOffset(const DIE &Die)
If Die has a non-null parent and the parent is not a declaration, return its offset.
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
iterator_range< iterator > children() const
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
dwarf::Tag getTag() const
LLVM_ABI std::optional< unsigned > getSubCode() const
uint64_t getEndOffset() const
Encoding
Size and signedness of expression operations' operands.
const Description & getDescription() const
uint64_t getRawOperand(unsigned Idx) const
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.
void wait() override
Blocking wait for all the tasks to execute first.
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 push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
auto async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static Twine utohexstr(uint64_t Val)
static LLVM_ABI raw_ostream & error()
Convenience method for printing "error: " to stderr.
AddressesMap represents information about valid addresses used by debug information.
uint64_t constrainCodeRangeHighPC(uint64_t LowPC, uint64_t HighPC, int64_t Adjustment)
Constrains the end of the code range starting at LowPC, whose addresses shift by Adjustment in the ou...
This class represents DWARF information for source file and it's address map.
std::map< std::string, std::string > ObjectPrefixMapTy
function_ref< void(const DWARFUnit &Unit)> CompileUnitHandlerTy
AccelTableKind
The kind of accelerator tables to be emitted.
@ DebugNames
.debug_names.
@ Apple
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
@ Pub
.debug_pubnames, .debug_pubtypes
std::map< std::string, std::string > SwiftInterfacesMapTy
std::function< ErrorOr< DWARFFile & >( StringRef ContainerName, StringRef Path)> ObjFileLoaderTy
const SmallVector< T > & getValues() const
Stores all information relating to a compile unit, be it in its original instance in the object file ...
void addObjectFile(DWARFFile &File, ObjFileLoaderTy Loader=nullptr, CompileUnitHandlerTy OnCUDieLoaded=[](const DWARFUnit &) {}) override
Add object file to be linked.
Error link() override
Link debug info for added objFiles. Object files are linked all together.
This class gives a tree-like API to the DenseMap that stores the DeclContext objects.
LLVM_ABI PointerIntPair< DeclContext *, 1 > getChildDeclContext(DeclContext &Context, const DWARFDie &DIE, CompileUnit &Unit, bool InClangModule)
Get the child of Context described by DIE in Unit.
A DeclContext is a named program scope that is used for ODR uniquing of types.
void setDefinedInClangModule(bool Val)
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
LLVM_ABI StringRef FormEncodingString(unsigned Encoding)
LLVM_ABI StringRef FormatString(DwarfFormat Format)
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SmallVector< PatchLocation > RngListAttributesTy
std::vector< std::unique_ptr< CompileUnit > > UnitListTy
IndexedValuesMap< uint64_t > DebugDieValuePool
AddressRangesMap RangesTy
Mapped value in the address map is the offset to apply to the linked address.
SmallVector< PatchLocation > LocListAttributesTy
StringRef guessDeveloperDir(StringRef SysRoot)
Make a best effort to guess the Xcode.app/Contents/Developer path from an SDK path.
LLVM_ABI bool hasImplicitAddressLocation(const DWARFDie &Die)
Test if the location of variable Die contains a global address but only uses to compute the variable'...
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...
LLVM_ABI uint32_t hashFullyQualifiedName(DWARFDie Die, function_ref< DWARFDie(const DWARFDie &, const DWARFFormValue &)> ResolveRef)
Hash the fully qualified name of type Die for the Apple accelerator tables.
bool isInToolchainDir(StringRef Path)
Make a best effort to determine whether Path is inside a toolchain.
bool isPathAttribute(dwarf::Tag Tag, dwarf::Attribute Attr)
bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path)
bool isTlsAddressOp(uint8_t O)
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.
LLVM_ABI bool doesFormBelongToClass(dwarf::Form Form, DWARFFormValue::FormClass FC, uint16_t DwarfVersion)
Check whether specified Form belongs to the FC class.
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.
@ DW_FLAG_type_implementation
std::optional< uint64_t > toUnsigned(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
constexpr bool IsLittleEndianHost
void swapByteOrder(T &Value)
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy hardware_concurrency(unsigned ThreadCount=0)
Returns a default thread strategy where all available hardware resources are to be used,...
static void verifyKeepChain(CompileUnit &CU)
Verify the keep chain by looking for DIEs that are kept but who's parent isn't.
static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &RefInfo)
Helper that updates the completeness of the current DIE based on the completeness of the DIEs it refe...
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
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.
static void patchAddrBase(DIE &Die, DIEInteger Offset)
static std::string getPCMFile(const DWARFDie &CUDie, const DWARFLinkerBase::ObjectPrefixMapTy *ObjectPrefixMap, const DWARFFile &File)
auto unique(Range &&R, Predicate P)
static std::string remapPath(StringRef Path, const DWARFLinkerBase::ObjectPrefixMapTy &ObjectPrefixMap)
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
static CompileUnit * getUnitForOffset(const UnitListTy &Units, uint64_t Offset)
Similar to DWARFUnitSection::getUnitForOffset(), but returning our CompileUnit object instead.
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
static bool shouldSkipAttribute(bool Update, DWARFAbbreviationDeclaration::AttributeSpec AttrSpec, bool SkipPC)
auto reverse(ContainerTy &&C)
@ Off
Use window algorithm after SMS algorithm fails.
void sort(IteratorTy Start, IteratorTy End)
static uint64_t getDebugInfoSize(DWARFContext &Dwarf)
Compute the total size of the debug info.
static bool isTypeTag(uint16_t Tag)
@ Dwarf
DWARF v5 .debug_names.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI std::optional< StringRef > StripTemplateParameters(StringRef Name)
If Name is the name of a templated function that includes template parameters, returns a substring of...
static uint64_t getDwoId(const DWARFDie &CUDie)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
static bool updatePruning(const DWARFDie &Die, CompileUnit &CU, uint64_t ModulesEndOffset)
@ Success
The lock was released successfully.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
LLVM_ABI unsigned getULEB128Size(uint64_t Value)
Utility function to get the size of the ULEB128-encoded value.
static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &ChildInfo)
Helper that updates the completeness of the current DIE based on the completeness of one of its child...
SingleThreadExecutor DefaultThreadPool
DWARFExpression::Operation Op
static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &ChildInfo)
uint32_t djbHash(StringRef Buffer, uint32_t H=5381)
The Bernstein hash function used by the DWARF accelerator tables.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI std::optional< ObjCSelectorNames > getObjCNamesIfSelector(StringRef Name)
If Name is the AT_name of a DIE which refers to an Objective-C selector, returns an instance of ObjCS...
static void analyzeContextInfo(const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU, DeclContext *CurrentDeclContext, DeclContextTree &Contexts, uint64_t ModulesEndOffset, DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces, std::function< void(const Twine &, const DWARFDie &)> ReportWarning)
Recursive helper to build the global DeclContext information and gather the child->parent relationshi...
static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag)
StrongType< NonRelocatableStringpool, OffsetsTag > OffsetsStringPool
static bool isODRCanonicalCandidate(const DWARFDie &Die, CompileUnit &CU)
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
static void analyzeImportedModule(const DWARFDie &DIE, CompileUnit &CU, DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces, std::function< void(const Twine &, const DWARFDie &)> ReportWarning)
Collect references to parseable Swift interfaces in imported DW_TAG_module blocks.
ContextWorklistItemType
The distinct types of work performed by the work loop in analyzeContextInfo.
static void resolveRelativeObjectPath(SmallVectorImpl< char > &Buf, DWARFDie CU, const DWARFFile &File)
Resolve the relative path to a build artifact referenced by DWARF of File by applying DW_AT_comp_dir.
static uint64_t constrainHighPC(const DWARFDie &InputDIE, uint64_t HighPC, bool IsLength, int64_t PCOffset, AddressesMap &Addresses)
Returns InputDIE's DW_AT_high_pc value HighPC, constrained so the code range it ends stays clear of t...
void consumeError(Error Err)
Consume a Error without doing anything.
static bool isODRAttribute(uint16_t Attr)
static void patchStmtList(DIE &Die, DIEInteger Offset)
static void constructSeqOffsettoOrigRowMapping(CompileUnit &Unit, const DWARFDebugLine::LineTable <, DenseMap< uint64_t, uint64_t > &SeqOffToOrigRow)
std::vector< DWARFLocationExpression > DWARFLocationExpressionsVector
Represents a set of absolute location expressions.
A broken link in the keep chain.
BrokenLink(DWARFDie Parent, DWARFDie Child)
This class represents an item in the work list.
CompileUnit::DIEInfo * OtherInfo
ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx, bool InImportedModule)
ContextWorklistItemType Type
ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T, CompileUnit::DIEInfo *OtherInfo=nullptr)
Container for dump options that control which debug information will be dumped.
DIDumpOptions noImplicitRecursion() const
Return the options with RecurseDepth set to 0 unless explicitly required.
unsigned ChildRecurseDepth
static LLVM_ABI bool mayHaveLocationList(dwarf::Attribute Attr)
Identify DWARF attributes that may contain a pointer to a location list.
static LLVM_ABI bool mayHaveLocationExpr(dwarf::Attribute Attr)
Identifies DWARF attributes that may contain a reference to a DWARF expression.
Standard .debug_line state machine structure.
SmallVector< Encoding > Op
Encoding for Op operands.
Hold the input and output of the debug info size in bytes.
A helper struct to help keep track of the association between the input and output rows during line t...
Information gathered about a DIE in the object file.
bool Prune
Is this a pure forward declaration we can strip?
bool Incomplete
Does DIE transitively refer an incomplete decl?