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;
257 std::function<
void(
const Twine &,
const DWARFDie &)> ReportWarning) {
258 if (
CU.getLanguage() != dwarf::DW_LANG_Swift)
261 if (!ParseableSwiftInterfaces)
265 if (!Path.ends_with(
".swiftinterface"))
270 SysRoot =
CU.getSysRoot();
271 if (!SysRoot.
empty() && Path.starts_with(SysRoot))
276 if (!DeveloperDir.
empty() && Path.starts_with(DeveloperDir))
280 std::optional<const char *> Name =
284 auto &Entry = (*ParseableSwiftInterfaces)[*Name];
286 DWARFDie CUDie =
CU.getOrigUnit().getUnitDIE();
291 if (!Entry.empty() && Entry != ResolvedPath)
292 ReportWarning(
Twine(
"Conflicting parseable interfaces for Swift Module ") +
293 *Name +
": " + Entry +
" and " + Path,
295 Entry = std::string(ResolvedPath);
338 Info.Prune &= (Die.
getTag() == dwarf::DW_TAG_module) ||
344 if (ModulesEndOffset == 0)
345 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
347 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
348 Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
356 Info.Prune &= ChildInfo.
Prune;
372 std::function<
void(
const Twine &,
const DWARFDie &)> ReportWarning) {
374 std::vector<ContextWorklistItem> Worklist;
375 Worklist.emplace_back(
DIE, CurrentDeclContext, ParentIdx,
false);
377 while (!Worklist.empty()) {
381 switch (Current.
Type) {
392 unsigned Idx =
CU.getOrigUnit().getDIEIndex(Current.
Die);
407 if (Current.
Die.
getTag() == dwarf::DW_TAG_module &&
410 CU.getClangModuleName()) {
418 if (
CU.hasODR() || Info.InModuleScope) {
422 Current.
Context = PtrInvalidPair.getPointer();
424 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
428 Info.Ctxt = Current.
Context =
nullptr;
437 Worklist.emplace_back(
439 Worklist.emplace_back(Child, Current.
Context, Idx,
449 case dwarf::DW_TAG_class_type:
450 case dwarf::DW_TAG_common_block:
451 case dwarf::DW_TAG_lexical_block:
452 case dwarf::DW_TAG_structure_type:
453 case dwarf::DW_TAG_subprogram:
454 case dwarf::DW_TAG_subroutine_type:
455 case dwarf::DW_TAG_union_type:
461void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
464 for (DIEBlock *
I : DIEBlocks)
466 for (DIELoc *
I : DIELocs)
479 std::map<uint64_t, unsigned> LineTableMapping;
487 auto StmtAttrs = Unit.getStmtSeqListAttributes();
489 return A.get() <
B.get();
492 std::vector<unsigned> SeqStartRows;
493 SeqStartRows.push_back(0);
496 SeqStartRows.push_back(
I + 1);
528 ArrayRef SeqStartRowsRef(SeqStartRows);
533 constexpr unsigned DummyVal = UINT32_MAX;
534 LineTableMapping[DummyKey] = DummyVal;
536 for (
auto [NextSeqOff, NextRow] : LineTableMapping) {
539 auto StmtAttrSmallerThanNext = [
N = NextSeqOff](
const PatchLocation &SA) {
542 auto SeqStartSmallerThanNext = [
N = NextRow](
const unsigned &Row) {
548 while (!StmtAttrsRef.
empty() && !SeqStartRowsRef.
empty() &&
549 StmtAttrSmallerThanNext(StmtAttrsRef.
front()) &&
550 SeqStartSmallerThanNext(SeqStartRowsRef.
front())) {
557 StmtAttrsRef = StmtAttrsRef.
drop_while(StmtAttrSmallerThanNext);
558 SeqStartRowsRef = SeqStartRowsRef.
drop_while(SeqStartSmallerThanNext);
561 if (NextSeqOff != DummyKey) {
562 SeqOffToOrigRow[NextSeqOff] = NextRow;
578 if (!StmtAttrsRef.
empty() && StmtAttrsRef.
front().get() == NextSeqOff)
580 if (!SeqStartRowsRef.
empty() && SeqStartRowsRef.
front() == NextRow)
585std::pair<bool, std::optional<int64_t>>
586DWARFLinker::getVariableRelocAdjustment(AddressesMap &RelocMgr,
587 const DWARFDie &DIE) {
588 assert((DIE.getTag() == dwarf::DW_TAG_variable ||
589 DIE.getTag() == dwarf::DW_TAG_constant) &&
590 "Wrong type of input die");
592 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
595 DWARFUnit *U = DIE.getDwarfUnit();
596 std::optional<uint32_t> LocationIdx =
597 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
599 return std::make_pair(
false, std::nullopt);
603 Abbrev->getAttributeOffsetFromIndex(*LocationIdx, DIE.getOffset(), *U);
606 std::optional<DWARFFormValue> LocationValue =
607 Abbrev->getAttributeValueFromOffset(*LocationIdx, AttrOffset, *U);
609 return std::make_pair(
false, std::nullopt);
614 std::optional<ArrayRef<uint8_t>> Expr = LocationValue->getAsBlock();
616 return std::make_pair(
false, std::nullopt);
619 DataExtractor
Data(
toStringRef(*Expr), U->getContext().isLittleEndian(),
620 U->getAddressByteSize());
621 DWARFExpression Expression(
Data, U->getAddressByteSize(),
622 U->getFormParams().Format);
624 bool HasLocationAddress =
false;
626 for (DWARFExpression::iterator It = Expression.begin();
627 It != Expression.end(); ++It) {
628 DWARFExpression::iterator NextIt = It;
631 const DWARFExpression::Operation &
Op = *It;
633 case dwarf::DW_OP_const2u:
634 case dwarf::DW_OP_const4u:
635 case dwarf::DW_OP_const8u:
636 case dwarf::DW_OP_const2s:
637 case dwarf::DW_OP_const4s:
638 case dwarf::DW_OP_const8s:
639 if (NextIt == Expression.end() ||
643 case dwarf::DW_OP_addr: {
644 HasLocationAddress =
true;
646 if (std::optional<int64_t> RelocAdjustment =
647 RelocMgr.getExprOpAddressRelocAdjustment(
648 *U,
Op, AttrOffset + CurExprOffset,
650 return std::make_pair(HasLocationAddress, *RelocAdjustment);
652 case dwarf::DW_OP_constx:
653 case dwarf::DW_OP_addrx: {
654 HasLocationAddress =
true;
655 if (std::optional<uint64_t> AddressOffset =
656 DIE.getDwarfUnit()->getIndexedAddressOffset(
659 if (std::optional<int64_t> RelocAdjustment =
660 RelocMgr.getExprOpAddressRelocAdjustment(
661 *U,
Op, *AddressOffset,
662 *AddressOffset + DIE.getDwarfUnit()->getAddressByteSize(),
664 return std::make_pair(HasLocationAddress, *RelocAdjustment);
674 return std::make_pair(HasLocationAddress, std::nullopt);
679unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
681 CompileUnit::DIEInfo &MyInfo,
683 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
686 if (!(Flags & TF_InFunctionScope) &&
687 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
688 MyInfo.InDebugMap =
true;
689 return Flags | TF_Keep;
697 std::pair<bool, std::optional<int64_t>> LocExprAddrAndRelocAdjustment =
698 getVariableRelocAdjustment(RelocMgr, DIE);
700 if (LocExprAddrAndRelocAdjustment.first)
701 MyInfo.HasLocationExpressionAddr =
true;
703 if (!LocExprAddrAndRelocAdjustment.second)
706 MyInfo.AddrAdjust = *LocExprAddrAndRelocAdjustment.second;
707 MyInfo.InDebugMap =
true;
709 if (((Flags & TF_InFunctionScope) &&
713 if (Options.Verbose) {
714 outs() <<
"Keeping variable DIE:";
715 DIDumpOptions DumpOpts;
716 DumpOpts.ChildRecurseDepth = 0;
717 DumpOpts.Verbose = Options.Verbose;
718 DIE.dump(
outs(), 8 , DumpOpts);
721 return Flags | TF_Keep;
726unsigned DWARFLinker::shouldKeepSubprogramDIE(
727 AddressesMap &RelocMgr,
const DWARFDie &DIE,
const DWARFFile &File,
728 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
unsigned Flags) {
729 Flags |= TF_InFunctionScope;
735 assert(LowPc &&
"low_pc attribute is not an address.");
736 std::optional<int64_t> RelocAdjustment =
737 RelocMgr.getSubprogramRelocAdjustment(DIE, Options.Verbose);
738 if (!RelocAdjustment)
741 MyInfo.AddrAdjust = *RelocAdjustment;
742 MyInfo.InDebugMap =
true;
744 if (Options.Verbose) {
745 outs() <<
"Keeping subprogram DIE:";
746 DIDumpOptions DumpOpts;
747 DumpOpts.ChildRecurseDepth = 0;
748 DumpOpts.Verbose = Options.Verbose;
749 DIE.dump(
outs(), 8 , DumpOpts);
752 if (DIE.getTag() == dwarf::DW_TAG_label) {
753 if (
Unit.hasLabelAt(*LowPc))
756 DWARFUnit &OrigUnit =
Unit.getOrigUnit();
766 if (
Unit.getLanguage() == dwarf::DW_LANG_Mips_Assembler ||
767 Unit.getLanguage() == dwarf::DW_LANG_Assembly) {
768 if (
auto Range = RelocMgr.getAssemblyRangeForAddress(*LowPc)) {
769 Unit.addFunctionRange(
Range->LowPC,
Range->HighPC, MyInfo.AddrAdjust);
771 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
774 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
776 return Flags | TF_Keep;
781 std::optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
783 reportWarning(
"Function without high_pc. Range will be discarded.\n", File,
787 if (*LowPc > *HighPc) {
788 reportWarning(
"low_pc greater than high_pc. Range will be discarded.\n",
794 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
800unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr,
const DWARFDie &DIE,
801 const DWARFFile &File, CompileUnit &Unit,
802 CompileUnit::DIEInfo &MyInfo,
804 switch (DIE.getTag()) {
805 case dwarf::DW_TAG_constant:
806 case dwarf::DW_TAG_variable:
807 return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
808 case dwarf::DW_TAG_subprogram:
809 case dwarf::DW_TAG_label:
810 return shouldKeepSubprogramDIE(RelocMgr, DIE, File, Unit, MyInfo, Flags);
811 case dwarf::DW_TAG_base_type:
814 case dwarf::DW_TAG_imported_module:
815 case dwarf::DW_TAG_imported_declaration:
816 case dwarf::DW_TAG_imported_unit:
818 return Flags | TF_Keep;
832 case dwarf::DW_TAG_structure_type:
833 case dwarf::DW_TAG_class_type:
834 case dwarf::DW_TAG_union_type:
852 case dwarf::DW_TAG_typedef:
853 case dwarf::DW_TAG_member:
854 case dwarf::DW_TAG_reference_type:
855 case dwarf::DW_TAG_ptr_to_member_type:
856 case dwarf::DW_TAG_pointer_type:
873void DWARFLinker::lookForChildDIEsToKeep(
874 const DWARFDie &Die, CompileUnit &
CU,
unsigned Flags,
875 SmallVectorImpl<WorklistItem> &Worklist) {
882 Flags &= ~DWARFLinker::TF_ParentWalk;
886 if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
891 for (
auto Child :
reverse(Die.children())) {
894 CompileUnit::DIEInfo &ChildInfo =
CU.getInfo(Child);
895 Worklist.emplace_back(Die,
CU, WorklistItemType::UpdateChildIncompleteness,
897 Worklist.emplace_back(Child,
CU, Flags);
904 if (!Info.Ctxt || (Die.
getTag() == dwarf::DW_TAG_namespace))
907 if (!
CU.hasODR() && !Info.InModuleScope)
910 return !Info.Incomplete && Info.Ctxt !=
CU.getInfo(Info.ParentIdx).Ctxt;
913void DWARFLinker::markODRCanonicalDie(
const DWARFDie &Die, CompileUnit &
CU) {
914 CompileUnit::DIEInfo &Info =
CU.getInfo(Die);
916 Info.ODRMarkingDone =
true;
918 !Info.Ctxt->hasCanonicalDIE())
919 Info.Ctxt->setHasCanonicalDIE();
924void DWARFLinker::lookForRefDIEsToKeep(
925 const DWARFDie &Die, CompileUnit &CU,
unsigned Flags,
926 const UnitListTy &Units,
const DWARFFile &File,
927 SmallVectorImpl<WorklistItem> &Worklist) {
928 bool UseOdr = (
Flags & DWARFLinker::TF_DependencyWalk)
929 ? (Flags & DWARFLinker::TF_ODR)
931 DWARFUnit &
Unit = CU.getOrigUnit();
932 DWARFDataExtractor
Data =
Unit.getDebugInfoExtractor();
933 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
937 for (
const auto &AttrSpec : Abbrev->attributes()) {
938 DWARFFormValue Val(AttrSpec.Form);
940 AttrSpec.Attr == dwarf::DW_AT_sibling) {
942 Unit.getFormParams());
947 CompileUnit *ReferencedCU;
949 resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
950 CompileUnit::DIEInfo &
Info = ReferencedCU->getInfo(RefDie);
961 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr &&
963 Info.Ctxt->hasCanonicalDIE())
968 Info.Ctxt->hasCanonicalDIE()))
970 ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
974 unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
978 for (
auto &
P :
reverse(ReferencedDIEs)) {
981 CompileUnit::DIEInfo &
Info =
P.second.getInfo(
P.first);
982 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
984 Worklist.emplace_back(
P.first,
P.second,
985 DWARFLinker::TF_Keep |
986 DWARFLinker::TF_DependencyWalk | ODRFlag);
991void DWARFLinker::lookForParentDIEsToKeep(
992 unsigned AncestorIdx, CompileUnit &CU,
unsigned Flags,
993 SmallVectorImpl<WorklistItem> &Worklist) {
995 if (CU.getInfo(AncestorIdx).Keep)
998 DWARFUnit &
Unit = CU.getOrigUnit();
999 DWARFDie ParentDIE =
Unit.getDIEAtIndex(AncestorIdx);
1000 Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
1001 Worklist.emplace_back(ParentDIE, CU, Flags);
1029void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
1031 const DWARFDie &Die,
const DWARFFile &File,
1032 CompileUnit &Cu,
unsigned Flags) {
1035 Worklist.emplace_back(Die, Cu, Flags);
1037 while (!Worklist.empty()) {
1038 WorklistItem Current = Worklist.pop_back_val();
1041 switch (Current.Type) {
1042 case WorklistItemType::UpdateChildIncompleteness:
1045 case WorklistItemType::UpdateRefIncompleteness:
1048 case WorklistItemType::LookForChildDIEsToKeep:
1049 lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
1051 case WorklistItemType::LookForRefDIEsToKeep:
1052 lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
1055 case WorklistItemType::LookForParentDIEsToKeep:
1056 lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
1059 case WorklistItemType::MarkODRCanonicalDie:
1060 markODRCanonicalDie(Current.Die, Current.CU);
1062 case WorklistItemType::LookForDIEsToKeep:
1066 unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
1067 CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
1072 if (Current.Flags & TF_DependencyWalk)
1073 MyInfo.Prune =
false;
1080 bool AlreadyKept = MyInfo.Keep;
1081 if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
1084 if (!(Current.Flags & TF_DependencyWalk))
1085 Current.Flags = shouldKeepDIE(AddressesMap, Current.Die, File, Current.CU,
1086 MyInfo, Current.Flags);
1091 if (!(Current.Flags & TF_DependencyWalk) ||
1092 (MyInfo.ODRMarkingDone && !MyInfo.Keep)) {
1093 if (Current.CU.hasODR() || MyInfo.InModuleScope)
1094 Worklist.emplace_back(Current.Die, Current.CU,
1095 WorklistItemType::MarkODRCanonicalDie);
1101 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
1102 WorklistItemType::LookForChildDIEsToKeep);
1104 if (AlreadyKept || !(Current.Flags & TF_Keep))
1113 Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
1114 Current.Die.getTag() != dwarf::DW_TAG_member &&
1120 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
1121 WorklistItemType::LookForRefDIEsToKeep);
1123 bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
1124 : Current.CU.hasODR();
1125 unsigned ODRFlag = UseOdr ? TF_ODR : 0;
1126 unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
1129 Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
1145 std::vector<DWARFDie> Worklist;
1146 Worklist.push_back(
CU.getOrigUnit().getUnitDIE());
1149 std::vector<BrokenLink> BrokenLinks;
1151 while (!Worklist.empty()) {
1152 const DWARFDie Current = Worklist.back();
1153 Worklist.pop_back();
1155 const bool CurrentDieIsKept =
CU.getInfo(Current).Keep;
1158 Worklist.push_back(Child);
1160 const bool ChildDieIsKept =
CU.getInfo(Child).Keep;
1161 if (!CurrentDieIsKept && ChildDieIsKept)
1162 BrokenLinks.emplace_back(Current, Child);
1166 if (!BrokenLinks.empty()) {
1169 "Found invalid link in keep chain between {0:x} and {1:x}\n",
1170 Link.Parent.getOffset(), Link.Child.getOffset());
1172 errs() <<
"Parent:";
1173 Link.Parent.dump(
errs(), 0, {});
1174 CU.getInfo(Link.Parent).dump();
1177 Link.Child.dump(
errs(), 2, {});
1178 CU.getInfo(Link.Child).dump();
1191void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
1193 FoldingSetNodeID
ID;
1196 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(
ID, InsertToken);
1201 Abbrev.setNumber(InSet->getNumber());
1204 Abbreviations.push_back(
1205 std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
1206 for (
const auto &Attr : Abbrev.getData())
1207 Abbreviations.back()->AddAttribute(Attr);
1208 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
1210 Abbrev.setNumber(Abbreviations.size());
1211 Abbreviations.back()->setNumber(Abbreviations.size());
1215unsigned DWARFLinker::DIECloner::cloneStringAttribute(DIE &Die,
1216 AttributeSpec AttrSpec,
1217 const DWARFFormValue &Val,
1219 AttributesInfo &Info) {
1224 if (AttrSpec.Form == dwarf::DW_FORM_line_strp) {
1229 if (AttrSpec.Attr == dwarf::DW_AT_APPLE_origin) {
1230 Info.HasAppleOrigin =
true;
1231 if (std::optional<StringRef> FileName =
1232 ObjFile.Addresses->getLibraryInstallName()) {
1238 if (AttrSpec.Attr == dwarf::DW_AT_name)
1240 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
1241 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
1243 if (
U.getVersion() >= 5) {
1245 auto StringOffsetIndex =
1246 StringOffsetPool.getValueIndex(
StringEntry.getOffset());
1249 dwarf::DW_FORM_strx, DIEInteger(StringOffsetIndex))
1250 ->sizeOf(
U.getFormParams());
1253 AttrSpec.Form = dwarf::DW_FORM_strp;
1260unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
1261 DIE &Die,
const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1262 unsigned AttrSize,
const DWARFFormValue &Val,
const DWARFFile &File,
1263 CompileUnit &Unit) {
1264 const DWARFUnit &
U =
Unit.getOrigUnit();
1266 if (std::optional<uint64_t> Off = Val.getAsRelativeReference())
1267 Ref = Val.getUnit()->getOffset() + *
Off;
1268 else if (Off = Val.getAsDebugInfoReference(); Off)
1273 DIE *NewRefDie =
nullptr;
1274 CompileUnit *RefUnit =
nullptr;
1277 Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
1280 if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
1283 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
1288 RefInfo.Ctxt->getCanonicalDIEOffset()) {
1289 assert(RefInfo.Ctxt->hasCanonicalDIE() &&
1290 "Offset to canonical die is set, but context is not marked");
1291 DIEInteger Attr(RefInfo.Ctxt->getCanonicalDIEOffset());
1293 dwarf::DW_FORM_ref_addr, Attr);
1294 return U.getRefAddrByteSize();
1297 if (!RefInfo.Clone) {
1300 RefInfo.UnclonedReference =
true;
1303 NewRefDie = RefInfo.Clone;
1305 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
1307 if (
Ref < InputDIE.getOffset() && !RefInfo.UnclonedReference) {
1312 dwarf::DW_FORM_ref_addr, DIEEntry(*NewRefDie));
1318 Unit.noteForwardReference(
1319 NewRefDie, RefUnit, RefInfo.Ctxt,
1321 dwarf::DW_FORM_ref_addr, DIEInteger(
UINT64_MAX)));
1323 return U.getRefAddrByteSize();
1327 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
1332void DWARFLinker::DIECloner::cloneExpression(
1333 DataExtractor &
Data, DWARFExpression Expression,
const DWARFFile &File,
1334 CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer,
1335 int64_t AddrRelocAdjustment,
bool IsLittleEndian) {
1338 uint8_t OrigAddressByteSize =
Unit.getOrigUnit().getAddressByteSize();
1340 uint64_t OpOffset = 0;
1341 for (
auto &
Op : Expression) {
1347 Desc.
Op[0] != Encoding::Size1))
1348 Linker.reportWarning(
"Unsupported DW_OP encoding.", File);
1352 Desc.
Op[0] == Encoding::Size1)) {
1372 if (RefOffset > 0 ||
Op.
getCode() != dwarf::DW_OP_convert) {
1373 RefOffset +=
Unit.getOrigUnit().getOffset();
1374 auto RefDie =
Unit.getOrigUnit().getDIEForOffset(RefOffset);
1375 CompileUnit::DIEInfo &
Info =
Unit.getInfo(RefDie);
1376 if (DIE *Clone =
Info.Clone)
1377 Offset = Clone->getOffset();
1379 Linker.reportWarning(
1380 "base type ref doesn't point to DW_TAG_base_type.", File);
1384 if (RealSize > ULEBsize) {
1387 Linker.reportWarning(
"base type ref doesn't fit.", File);
1389 assert(RealSize == ULEBsize &&
"padding failed");
1390 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1391 OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
1392 }
else if (!Linker.Options.Update &&
Op.
getCode() == dwarf::DW_OP_addrx) {
1393 if (std::optional<object::SectionedAddress> SA =
1394 Unit.getOrigUnit().getAddrOffsetSectionItem(
1400 OutputBuffer.push_back(dwarf::DW_OP_addr);
1401 uint64_t LinkedAddress = SA->Address + AddrRelocAdjustment;
1404 ArrayRef<uint8_t> AddressBytes(
1405 reinterpret_cast<const uint8_t *
>(&LinkedAddress),
1406 OrigAddressByteSize);
1407 OutputBuffer.append(AddressBytes.begin(), AddressBytes.end());
1409 Linker.reportWarning(
"cannot read DW_OP_addrx operand.", File);
1410 }
else if (!Linker.Options.Update &&
Op.
getCode() == dwarf::DW_OP_constx) {
1411 if (std::optional<object::SectionedAddress> SA =
1412 Unit.getOrigUnit().getAddrOffsetSectionItem(
1418 std::optional<uint8_t> OutOperandKind;
1419 switch (OrigAddressByteSize) {
1421 OutOperandKind = dwarf::DW_OP_const4u;
1424 OutOperandKind = dwarf::DW_OP_const8u;
1427 Linker.reportWarning(
1428 formatv((
"unsupported address size: {0}."), OrigAddressByteSize),
1433 if (OutOperandKind) {
1434 OutputBuffer.push_back(*OutOperandKind);
1435 uint64_t LinkedAddress = SA->Address + AddrRelocAdjustment;
1438 ArrayRef<uint8_t> AddressBytes(
1439 reinterpret_cast<const uint8_t *
>(&LinkedAddress),
1440 OrigAddressByteSize);
1441 OutputBuffer.append(AddressBytes.begin(), AddressBytes.end());
1444 Linker.reportWarning(
"cannot read DW_OP_constx operand.", File);
1448 OutputBuffer.append(Bytes.begin(), Bytes.end());
1454unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
1455 DIE &Die,
const DWARFDie &InputDIE,
const DWARFFile &File,
1456 CompileUnit &Unit, AttributeSpec AttrSpec,
const DWARFFormValue &Val,
1457 bool IsLittleEndian) {
1460 DIELoc *Loc =
nullptr;
1461 DIEBlock *
Block =
nullptr;
1462 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1463 Loc =
new (DIEAlloc) DIELoc;
1464 Linker.DIELocs.push_back(Loc);
1466 Block =
new (DIEAlloc) DIEBlock;
1467 Linker.DIEBlocks.push_back(
Block);
1469 Attr = Loc ?
static_cast<DIEValueList *
>(Loc)
1470 : static_cast<DIEValueList *>(
Block);
1472 DWARFUnit &OrigUnit =
Unit.getOrigUnit();
1475 SmallVector<uint8_t, 32> Buffer;
1476 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1480 DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
1481 IsLittleEndian, OrigUnit.getAddressByteSize());
1482 DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
1483 OrigUnit.getFormParams().Format);
1484 cloneExpression(Data, Expr, File, Unit, Buffer,
1485 Unit.getInfo(InputDIE).AddrAdjust, IsLittleEndian);
1488 for (
auto Byte : Bytes)
1490 dwarf::DW_FORM_data1, DIEInteger(Byte));
1496 Loc->setSize(Bytes.size());
1498 Block->setSize(Bytes.size());
1506 if ((AttrSpec.Form == dwarf::DW_FORM_block1 &&
1507 (Bytes.size() > UINT8_MAX)) ||
1508 (AttrSpec.Form == dwarf::DW_FORM_block2 &&
1509 (Bytes.size() > UINT16_MAX)) ||
1510 (AttrSpec.Form == dwarf::DW_FORM_block4 && (Bytes.size() > UINT32_MAX)))
1511 AttrSpec.Form = dwarf::DW_FORM_block;
1513 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1514 dwarf::Form(AttrSpec.Form), Block);
1517 return Die.addValue(DIEAlloc,
Value)->sizeOf(OrigUnit.getFormParams());
1520unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1521 DIE &Die,
const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1522 unsigned AttrSize,
const DWARFFormValue &Val,
const CompileUnit &Unit,
1523 AttributesInfo &Info) {
1524 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1525 Info.HasLowPc =
true;
1529 dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
1545 std::optional<DWARFFormValue> AddrAttribute = InputDIE.find(AttrSpec.Attr);
1549 std::optional<uint64_t> Addr = AddrAttribute->getAsAddress();
1551 Linker.reportWarning(
"Cann't read address attribute value.", ObjFile);
1555 if (InputDIE.getTag() == dwarf::DW_TAG_compile_unit &&
1556 AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1557 if (std::optional<uint64_t> LowPC =
Unit.getLowPc())
1561 }
else if (InputDIE.getTag() == dwarf::DW_TAG_compile_unit &&
1562 AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1563 if (uint64_t HighPc =
Unit.getHighPc())
1568 *Addr +=
Info.PCOffset;
1571 if (AttrSpec.Form == dwarf::DW_FORM_addr) {
1573 AttrSpec.Form, DIEInteger(*Addr));
1574 return Unit.getOrigUnit().getAddressByteSize();
1577 auto AddrIndex = AddrPool.getValueIndex(*Addr);
1581 dwarf::Form::DW_FORM_addrx, DIEInteger(AddrIndex))
1582 ->sizeOf(
Unit.getOrigUnit().getFormParams());
1585unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1586 DIE &Die,
const DWARFDie &InputDIE,
const DWARFFile &File,
1587 CompileUnit &Unit, AttributeSpec AttrSpec,
const DWARFFormValue &Val,
1588 unsigned AttrSize, AttributesInfo &Info) {
1593 if (AttrSpec.Attr == dwarf::DW_AT_GNU_dwo_id ||
1594 AttrSpec.Attr == dwarf::DW_AT_dwo_id)
1599 if (AttrSpec.Attr == dwarf::DW_AT_macro_info) {
1600 if (std::optional<uint64_t>
Offset = Val.getAsSectionOffset()) {
1601 const llvm::DWARFDebugMacro *
Macro =
File.Dwarf->getDebugMacinfo();
1607 if (AttrSpec.Attr == dwarf::DW_AT_macros) {
1608 if (std::optional<uint64_t>
Offset = Val.getAsSectionOffset()) {
1609 const llvm::DWARFDebugMacro *
Macro =
File.Dwarf->getDebugMacro();
1615 if (AttrSpec.Attr == dwarf::DW_AT_str_offsets_base) {
1619 Info.AttrStrOffsetBaseSeen =
true;
1621 .addValue(DIEAlloc, dwarf::DW_AT_str_offsets_base,
1622 dwarf::DW_FORM_sec_offset, DIEInteger(8))
1623 ->sizeOf(
Unit.getOrigUnit().getFormParams());
1626 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence) {
1629 dwarf::DW_FORM_sec_offset,
1630 DIEInteger(*Val.getAsSectionOffset()));
1633 Unit.noteStmtSeqListAttribute(Patch);
1635 return Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1639 if (
auto OptionalValue = Val.getAsUnsignedConstant())
1640 Value = *OptionalValue;
1641 else if (
auto OptionalValue = Val.getAsSignedConstant())
1642 Value = *OptionalValue;
1643 else if (
auto OptionalValue = Val.getAsSectionOffset())
1644 Value = *OptionalValue;
1646 Linker.reportWarning(
1647 "Unsupported scalar attribute form. Dropping attribute.", File,
1651 if (AttrSpec.Attr == dwarf::DW_AT_declaration &&
Value)
1652 Info.IsDeclaration =
true;
1654 if (AttrSpec.Form == dwarf::DW_FORM_loclistx)
1663 [[maybe_unused]]
dwarf::Form OriginalForm = AttrSpec.Form;
1664 if (AttrSpec.Form == dwarf::DW_FORM_rnglistx) {
1668 std::optional<uint64_t>
Index = Val.getAsSectionOffset();
1670 Linker.reportWarning(
"Cannot read the attribute. Dropping.", File,
1674 std::optional<uint64_t>
Offset =
1675 Unit.getOrigUnit().getRnglistOffset(*Index);
1677 Linker.reportWarning(
"Cannot read the attribute. Dropping.", File,
1683 AttrSpec.Form = dwarf::DW_FORM_sec_offset;
1684 AttrSize =
Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1685 }
else if (AttrSpec.Form == dwarf::DW_FORM_loclistx) {
1689 std::optional<uint64_t>
Index = Val.getAsSectionOffset();
1691 Linker.reportWarning(
"Cannot read the attribute. Dropping.", File,
1695 std::optional<uint64_t>
Offset =
1696 Unit.getOrigUnit().getLoclistOffset(*Index);
1698 Linker.reportWarning(
"Cannot read the attribute. Dropping.", File,
1704 AttrSpec.Form = dwarf::DW_FORM_sec_offset;
1705 AttrSize =
Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1706 }
else if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1707 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1708 std::optional<uint64_t> LowPC =
Unit.getLowPc();
1713 }
else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1714 Value = *Val.getAsSectionOffset();
1715 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1716 Value = *Val.getAsSignedConstant();
1717 else if (
auto OptionalValue = Val.getAsUnsignedConstant())
1718 Value = *OptionalValue;
1720 Linker.reportWarning(
1721 "Unsupported scalar attribute form. Dropping attribute.", File,
1726 DIE::value_iterator Patch =
1729 if (AttrSpec.Attr == dwarf::DW_AT_ranges ||
1730 AttrSpec.Attr == dwarf::DW_AT_start_scope) {
1731 Unit.noteRangeAttribute(Die, Patch);
1732 Info.HasRanges =
true;
1736 Unit.getOrigUnit().getVersion())) {
1738 CompileUnit::DIEInfo &LocationDieInfo =
Unit.getInfo(InputDIE);
1739 Unit.noteLocationAttribute({Patch, LocationDieInfo.InDebugMap
1740 ? LocationDieInfo.AddrAdjust
1742 }
else if (AttrSpec.Attr == dwarf::DW_AT_declaration &&
Value)
1743 Info.IsDeclaration =
true;
1746 assert((
Info.HasRanges || (OriginalForm != dwarf::DW_FORM_rnglistx)) &&
1747 "Unhandled DW_FORM_rnglistx attribute");
1755unsigned DWARFLinker::DIECloner::cloneAttribute(
1756 DIE &Die,
const DWARFDie &InputDIE,
const DWARFFile &File,
1757 CompileUnit &Unit,
const DWARFFormValue &Val,
const AttributeSpec AttrSpec,
1758 unsigned AttrSize, AttributesInfo &Info,
bool IsLittleEndian) {
1759 const DWARFUnit &
U =
Unit.getOrigUnit();
1761 switch (AttrSpec.Form) {
1762 case dwarf::DW_FORM_strp:
1763 case dwarf::DW_FORM_line_strp:
1764 case dwarf::DW_FORM_string:
1765 case dwarf::DW_FORM_strx:
1766 case dwarf::DW_FORM_strx1:
1767 case dwarf::DW_FORM_strx2:
1768 case dwarf::DW_FORM_strx3:
1769 case dwarf::DW_FORM_strx4:
1770 return cloneStringAttribute(Die, AttrSpec, Val, U, Info);
1771 case dwarf::DW_FORM_ref_addr:
1772 case dwarf::DW_FORM_ref1:
1773 case dwarf::DW_FORM_ref2:
1774 case dwarf::DW_FORM_ref4:
1775 case dwarf::DW_FORM_ref8:
1776 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1778 case dwarf::DW_FORM_block:
1779 case dwarf::DW_FORM_block1:
1780 case dwarf::DW_FORM_block2:
1781 case dwarf::DW_FORM_block4:
1782 case dwarf::DW_FORM_exprloc:
1783 return cloneBlockAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1785 case dwarf::DW_FORM_addr:
1786 case dwarf::DW_FORM_addrx:
1787 case dwarf::DW_FORM_addrx1:
1788 case dwarf::DW_FORM_addrx2:
1789 case dwarf::DW_FORM_addrx3:
1790 case dwarf::DW_FORM_addrx4:
1791 return cloneAddressAttribute(Die, InputDIE, AttrSpec, AttrSize, Val, Unit,
1793 case dwarf::DW_FORM_data1:
1794 case dwarf::DW_FORM_data2:
1795 case dwarf::DW_FORM_data4:
1796 case dwarf::DW_FORM_data8:
1797 case dwarf::DW_FORM_udata:
1798 case dwarf::DW_FORM_sdata:
1799 case dwarf::DW_FORM_sec_offset:
1800 case dwarf::DW_FORM_flag:
1801 case dwarf::DW_FORM_flag_present:
1802 case dwarf::DW_FORM_rnglistx:
1803 case dwarf::DW_FORM_loclistx:
1804 case dwarf::DW_FORM_implicit_const:
1805 return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1808 Linker.reportWarning(
"Unsupported attribute form " +
1810 " in cloneAttribute. Dropping.",
1817void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1819 DwarfStringPoolEntryRef Name,
1821 bool SkipPubSection) {
1822 std::optional<ObjCSelectorNames> Names =
1826 Unit.addNameAccelerator(Die, StringPool.getEntry(Names->Selector),
1828 Unit.addObjCAccelerator(Die, StringPool.getEntry(Names->ClassName),
1830 if (Names->ClassNameNoCategory)
1831 Unit.addObjCAccelerator(
1832 Die, StringPool.getEntry(*Names->ClassNameNoCategory), SkipPubSection);
1833 if (Names->MethodNameNoCategory)
1834 Unit.addNameAccelerator(
1835 Die, StringPool.getEntry(*Names->MethodNameNoCategory), SkipPubSection);
1842 switch (AttrSpec.
Attr) {
1845 case dwarf::DW_AT_low_pc:
1846 case dwarf::DW_AT_high_pc:
1847 case dwarf::DW_AT_ranges:
1848 return !Update && SkipPC;
1849 case dwarf::DW_AT_rnglists_base:
1855 case dwarf::DW_AT_loclists_base:
1861 case dwarf::DW_AT_location:
1862 case dwarf::DW_AT_frame_base:
1863 return !Update && SkipPC;
1873DIE *DWARFLinker::DIECloner::cloneDIE(
const DWARFDie &InputDIE,
1875 int64_t PCOffset,
uint32_t OutOffset,
1876 unsigned Flags,
bool IsLittleEndian,
1879 unsigned Idx = U.getDIEIndex(InputDIE);
1883 if (!Unit.getInfo(Idx).Keep)
1887 assert(!(Die && Info.Clone) &&
"Can't supply a DIE and a cloned DIE");
1899 (Info.Ctxt->getCanonicalDIEOffset() == 0)) {
1900 if (!Info.Ctxt->hasCanonicalDIE())
1901 Info.Ctxt->setHasCanonicalDIE();
1905 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1909 DWARFDataExtractor
Data =
U.getDebugInfoExtractor();
1913 uint64_t NextOffset = (Idx + 1 <
U.getNumDIEs())
1914 ?
U.getDIEAtIndex(Idx + 1).getOffset()
1915 :
U.getNextUnitOffset();
1916 AttributesInfo AttrInfo;
1921 SmallString<40> DIECopy(
Data.getData().substr(
Offset, NextOffset -
Offset));
1923 DWARFDataExtractor(DIECopy,
Data.isLittleEndian(),
Data.getAddressSize());
1926 ObjFile.Addresses->applyValidRelocs(DIECopy,
Offset,
Data.isLittleEndian());
1936 if (Die->
getTag() == dwarf::DW_TAG_subprogram)
1937 PCOffset =
Info.AddrAdjust;
1938 AttrInfo.PCOffset = PCOffset;
1940 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1941 Flags |= TF_InFunctionScope;
1944 }
else if (Abbrev->getTag() == dwarf::DW_TAG_variable) {
1947 if ((Flags & TF_InFunctionScope) &&
Info.InDebugMap)
1948 Flags &= ~TF_SkipPC;
1951 else if (!
Info.InDebugMap &&
Info.HasLocationExpressionAddr &&
1956 std::optional<StringRef> LibraryInstallName =
1957 ObjFile.Addresses->getLibraryInstallName();
1959 for (
const auto &AttrSpec : Abbrev->attributes()) {
1966 AttributeLinkedOffsetFixup CurAttrFixup;
1968 CurAttrFixup.LinkedOffsetFixupVal =
1969 Unit.getStartOffset() + OutOffset - CurAttrFixup.InputAttrStartOffset;
1971 DWARFFormValue Val = AttrSpec.getFormValue();
1972 uint64_t AttrSize =
Offset;
1973 Val.extractValue(
Data, &
Offset,
U.getFormParams(), &U);
1975 AttrSize =
Offset - AttrSize;
1977 uint64_t FinalAttrSize =
1978 cloneAttribute(*Die, InputDIE, File, Unit, Val, AttrSpec, AttrSize,
1979 AttrInfo, IsLittleEndian);
1980 if (FinalAttrSize != 0 && ObjFile.Addresses->needToSaveValidRelocs())
1981 AttributesFixups.push_back(CurAttrFixup);
1983 OutOffset += FinalAttrSize;
1989 const bool NeedsAppleOrigin = (
Tag == dwarf::DW_TAG_compile_unit) &&
1990 LibraryInstallName.has_value() &&
1991 !AttrInfo.HasAppleOrigin;
1992 if (NeedsAppleOrigin) {
1993 auto StringEntry = DebugStrPool.getEntry(LibraryInstallName.value());
1995 dwarf::DW_FORM_strp, DIEInteger(
StringEntry.getOffset()));
2004 if ((
Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
2005 Tag != dwarf::DW_TAG_compile_unit &&
2006 getDIENames(InputDIE, AttrInfo, DebugStrPool, File, Unit,
2007 Tag != dwarf::DW_TAG_inlined_subroutine)) {
2008 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2009 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2010 Tag == dwarf::DW_TAG_inlined_subroutine);
2011 if (AttrInfo.Name) {
2012 if (AttrInfo.NameWithoutTemplate)
2013 Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
2015 Unit.addNameAccelerator(Die, AttrInfo.Name,
2016 Tag == dwarf::DW_TAG_inlined_subroutine);
2019 addObjCAccelerator(Unit, Die, AttrInfo.Name, DebugStrPool,
2022 }
else if (
Tag == dwarf::DW_TAG_namespace) {
2024 AttrInfo.Name = DebugStrPool.getEntry(
"(anonymous namespace)");
2025 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
2026 }
else if (
Tag == dwarf::DW_TAG_imported_declaration && AttrInfo.Name) {
2027 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
2028 }
else if (
isTypeTag(
Tag) && !AttrInfo.IsDeclaration) {
2029 bool Success = getDIENames(InputDIE, AttrInfo, DebugStrPool, File, Unit);
2030 uint64_t RuntimeLang =
2033 bool ObjCClassIsImplementation =
2034 (RuntimeLang == dwarf::DW_LANG_ObjC ||
2035 RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
2038 if (
Success && AttrInfo.Name && !AttrInfo.Name.getString().empty()) {
2040 Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
2045 if (
Success && AttrInfo.MangledName &&
2046 RuntimeLang == dwarf::DW_LANG_Swift &&
2047 !AttrInfo.MangledName.getString().empty() &&
2048 AttrInfo.MangledName != AttrInfo.Name) {
2049 auto Hash =
djbHash(AttrInfo.MangledName.getString().data());
2050 Unit.addTypeAccelerator(Die, AttrInfo.MangledName,
2051 ObjCClassIsImplementation, Hash);
2056 bool HasChildren =
false;
2057 for (
auto Child : InputDIE.
children()) {
2058 unsigned Idx =
U.getDIEIndex(Child);
2059 if (
Unit.getInfo(Idx).Keep) {
2065 if (
Unit.getOrigUnit().getVersion() >= 5 && !AttrInfo.AttrStrOffsetBaseSeen &&
2066 Die->
getTag() == dwarf::DW_TAG_compile_unit) {
2068 Die->
addValue(DIEAlloc, dwarf::DW_AT_str_offsets_base,
2069 dwarf::DW_FORM_sec_offset, DIEInteger(8));
2077 Linker.assignAbbrev(NewAbbrev);
2083 OutOffset += AbbrevNumberSize;
2086 for (AttributeLinkedOffsetFixup &
F : AttributesFixups)
2087 F.LinkedOffsetFixupVal += AbbrevNumberSize;
2089 for (AttributeLinkedOffsetFixup &
F : AttributesFixups)
2090 ObjFile.Addresses->updateAndSaveValidRelocs(
2091 Unit.getOrigUnit().getVersion() >= 5,
Unit.getOrigUnit().getOffset(),
2092 F.LinkedOffsetFixupVal,
F.InputAttrStartOffset,
F.InputAttrEndOffset);
2101 for (
auto Child : InputDIE.
children()) {
2102 if (DIE *Clone = cloneDIE(Child, File, Unit, PCOffset, OutOffset, Flags,
2105 OutOffset = Clone->getOffset() + Clone->getSize();
2110 OutOffset +=
sizeof(int8_t);
2119Error DWARFLinker::generateUnitRanges(CompileUnit &Unit,
const DWARFFile &File,
2124 const auto &FunctionRanges =
Unit.getFunctionRanges();
2127 AddressRanges LinkedFunctionRanges;
2128 for (
const AddressRangeValuePair &
Range : FunctionRanges)
2129 LinkedFunctionRanges.insert(
2133 if (!LinkedFunctionRanges.empty())
2134 TheDwarfEmitter->emitDwarfDebugArangesTable(Unit, LinkedFunctionRanges);
2137 std::optional<PatchLocation> UnitRngListAttribute =
2138 Unit.getUnitRangesAttribute();
2140 if (!AllRngListAttributes.empty() || UnitRngListAttribute) {
2141 std::optional<AddressRangeValuePair> CachedRange;
2142 MCSymbol *EndLabel = TheDwarfEmitter->emitDwarfDebugRangeListHeader(Unit);
2146 for (PatchLocation &AttributePatch : AllRngListAttributes) {
2149 AddressRanges LinkedRanges;
2150 if (Expected<DWARFAddressRangesVector> OriginalRanges =
2151 Unit.getOrigUnit().findRnglistFromOffset(AttributePatch.get())) {
2153 for (
const auto &
Range : *OriginalRanges) {
2154 if (!CachedRange || !CachedRange->Range.contains(
Range.LowPC))
2155 CachedRange = FunctionRanges.getRangeThatContains(
Range.LowPC);
2159 reportWarning(
"inconsistent range data.", File);
2164 LinkedRanges.insert({
Range.LowPC + CachedRange->Value,
2165 Range.HighPC + CachedRange->Value});
2169 reportWarning(
"invalid range list ignored.", File);
2173 if (
Error E = TheDwarfEmitter->emitDwarfDebugRangeListFragment(
2174 Unit, LinkedRanges, AttributePatch, AddrPool))
2179 if (UnitRngListAttribute.has_value())
2180 if (
Error E = TheDwarfEmitter->emitDwarfDebugRangeListFragment(
2181 Unit, LinkedFunctionRanges, *UnitRngListAttribute, AddrPool))
2185 TheDwarfEmitter->emitDwarfDebugRangeListFooter(Unit, EndLabel);
2191Error DWARFLinker::DIECloner::generateUnitLocations(
2192 CompileUnit &Unit,
const DWARFFile &File,
2193 ExpressionHandlerRef ExprHandler) {
2198 Unit.getLocationAttributes();
2200 if (AllLocListAttributes.empty())
2206 for (
auto &CurLocAttr : AllLocListAttributes) {
2209 Expected<DWARFLocationExpressionsVector> OriginalLocations =
2210 Unit.getOrigUnit().findLoclistFromOffset(CurLocAttr.get());
2212 if (!OriginalLocations) {
2214 Linker.reportWarning(
"Invalid location attribute ignored.", File);
2219 for (DWARFLocationExpression &CurExpression : *OriginalLocations) {
2220 DWARFLocationExpression LinkedExpression;
2222 if (CurExpression.Range) {
2224 LinkedExpression.Range = {
2225 CurExpression.Range->LowPC + CurLocAttr.RelocAdjustment,
2226 CurExpression.Range->HighPC + CurLocAttr.RelocAdjustment};
2230 LinkedExpression.Expr.reserve(CurExpression.Expr.size());
2231 ExprHandler(CurExpression.Expr, LinkedExpression.Expr,
2232 CurLocAttr.RelocAdjustment);
2234 LinkedLocationExpressions.push_back(LinkedExpression);
2239 Unit, LinkedLocationExpressions, CurLocAttr, AddrPool))
2244 Emitter->emitDwarfDebugLocListFooter(Unit, EndLabel);
2250 for (
auto &V : Die.
values())
2251 if (V.getAttribute() == dwarf::DW_AT_addr_base) {
2259Error DWARFLinker::DIECloner::emitDebugAddrSection(
2260 CompileUnit &Unit,
const uint16_t DwarfVersion)
const {
2265 if (DwarfVersion < 5)
2268 if (AddrPool.getValues().empty())
2271 MCSymbol *EndLabel =
Emitter->emitDwarfDebugAddrsHeader(Unit);
2273 dwarf::FormParams
FP = Unit.getOrigUnit().getFormParams();
2274 if (AddrOffset >
FP.getDwarfMaxOffset())
2278 patchAddrBase(*Unit.getOutputUnitDIE(), DIEInteger(AddrOffset));
2279 Emitter->emitDwarfDebugAddrs(AddrPool.getValues(),
2280 Unit.getOrigUnit().getAddressByteSize());
2281 Emitter->emitDwarfDebugAddrsFooter(Unit, EndLabel);
2299 std::vector<TrackedRow> &Rows) {
2305 Seq.front().isStartSeqInOutput =
true;
2307 if (!Rows.empty() && Rows.back().Row.Address < Seq.front().Row.Address) {
2315 Rows, [=](
const TrackedRow &O) {
return O.Row.Address < Front; });
2324 Rows.insert(
InsertPoint + 1, Seq.begin() + 1, Seq.end());
2333 for (
auto &V : Die.
values())
2334 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2342void DWARFLinker::DIECloner::rememberUnitForMacroOffset(CompileUnit &Unit) {
2343 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2344 DWARFDie OrigUnitDie = OrigUnit.getUnitDIE();
2346 if (std::optional<uint64_t> MacroAttr =
2348 UnitMacroMap.insert(std::make_pair(*MacroAttr, &Unit));
2352 if (std::optional<uint64_t> MacroAttr =
2354 UnitMacroMap.insert(std::make_pair(*MacroAttr, &Unit));
2359Error DWARFLinker::DIECloner::generateLineTableForUnit(CompileUnit &Unit) {
2364 DWARFDie CUDie =
Unit.getOrigUnit().getUnitDIE();
2370 if (
auto *OutputDIE =
Unit.getOutputUnitDIE()) {
2371 uint64_t StmtOffset =
Emitter->getLineSectionSize();
2372 dwarf::FormParams
FP =
Unit.getOrigUnit().getFormParams();
2373 if (StmtOffset >
FP.getDwarfMaxOffset())
2380 if (
const DWARFDebugLine::LineTable *LT =
2381 ObjFile.Dwarf->getLineTableForUnit(&
Unit.getOrigUnit())) {
2383 DWARFDebugLine::LineTable LineTable;
2386 LineTable.Prologue =
LT->Prologue;
2389 if (Linker.Options.Update) {
2390 LineTable.Rows =
LT->Rows;
2393 if (LineTable.Rows.size() == 1 && LineTable.Rows[0].EndSequence)
2394 LineTable.Rows.clear();
2396 LineTable.Sequences =
LT->Sequences;
2398 Emitter->emitLineTableForUnit(LineTable, Unit, DebugStrPool,
2402 std::vector<TrackedRow> InputRows;
2403 InputRows.reserve(
LT->Rows.size());
2404 for (
size_t i = 0; i <
LT->Rows.size(); i++)
2405 InputRows.emplace_back(TrackedRow{LT->Rows[i], i, false});
2408 std::vector<TrackedRow> OutputRows;
2409 OutputRows.reserve(InputRows.size());
2413 std::vector<TrackedRow> Seq;
2414 Seq.reserve(InputRows.size());
2416 const auto &FunctionRanges =
Unit.getFunctionRanges();
2417 std::optional<AddressRangeValuePair> CurrRange;
2430 for (
size_t i = 0; i < InputRows.size(); i++) {
2431 TrackedRow TR = InputRows[i];
2438 if (!CurrRange || !CurrRange->Range.contains(TR.Row.Address.Address)) {
2441 uint64_t StopAddress =
2442 CurrRange ? CurrRange->Range.end() + CurrRange->Value : -1ULL;
2444 FunctionRanges.getRangeThatContains(TR.Row.Address.Address);
2445 if (StopAddress != -1ULL && !Seq.empty()) {
2448 auto NextLine = Seq.back();
2449 NextLine.Row.Address.Address = StopAddress;
2450 NextLine.Row.EndSequence = 1;
2451 NextLine.Row.PrologueEnd = 0;
2452 NextLine.Row.BasicBlock = 0;
2453 NextLine.Row.EpilogueBegin = 0;
2454 Seq.push_back(NextLine);
2463 if (TR.Row.EndSequence && Seq.empty())
2467 TR.Row.Address.Address += CurrRange->Value;
2470 if (TR.Row.EndSequence)
2481 if (!OutputRows.empty()) {
2482 OutputRows[0].isStartSeqInOutput =
true;
2483 for (
size_t i = 1; i < OutputRows.size(); ++i)
2484 OutputRows[i].isStartSeqInOutput = OutputRows[i - 1].Row.EndSequence;
2488 LineTable.Rows.clear();
2489 LineTable.Rows.reserve(OutputRows.size());
2490 for (
auto &TR : OutputRows)
2491 LineTable.Rows.push_back(TR.Row);
2495 std::vector<uint64_t> OutputRowOffsets;
2499 bool hasStmtSeq =
Unit.getStmtSeqListAttributes().size() > 0;
2500 Emitter->emitLineTableForUnit(LineTable, Unit, DebugStrPool,
2502 hasStmtSeq ? &OutputRowOffsets :
nullptr);
2505 assert(OutputRowOffsets.size() == OutputRows.size() &&
2506 "must have an offset for each row");
2509 DenseMap<uint64_t, unsigned> SeqOffToOrigRow;
2514 if (!
LT->Rows.empty())
2522 DenseMap<size_t, size_t> OrigRowToOutputRow;
2523 std::vector<size_t> OutputRowToSeqStart(OutputRows.size());
2525 size_t CurrentSeqStart = 0;
2526 for (
size_t i = 0; i < OutputRows.size(); ++i) {
2528 if (OutputRows[i].isStartSeqInOutput)
2529 CurrentSeqStart = i;
2530 OutputRowToSeqStart[i] = CurrentSeqStart;
2533 OrigRowToOutputRow[OutputRows[i].OriginalRowIndex] = i;
2538 for (
const auto &StmtSeq :
Unit.getStmtSeqListAttributes()) {
2539 uint64_t OrigStmtSeq = StmtSeq.get();
2541 auto OrigRowIter = SeqOffToOrigRow.find(OrigStmtSeq);
2542 const uint64_t InvalidOffset =
2543 Unit.getOrigUnit().getFormParams().getDwarfMaxOffset();
2547 if (OrigRowIter == SeqOffToOrigRow.end()) {
2548 StmtSeq.set(InvalidOffset);
2551 size_t OrigRowIndex = OrigRowIter->second;
2554 auto OutputRowIter = OrigRowToOutputRow.find(OrigRowIndex);
2555 if (OutputRowIter == OrigRowToOutputRow.end()) {
2557 StmtSeq.set(InvalidOffset);
2560 size_t OutputRowIdx = OutputRowIter->second;
2565 size_t SeqStartIdx = OutputRowToSeqStart[OutputRowIdx];
2569 assert(SeqStartIdx < OutputRowOffsets.size() &&
2570 "Sequence start index out of bounds");
2571 uint64_t NewStmtSeqOffset = OutputRowOffsets[SeqStartIdx];
2574 StmtSeq.set(NewStmtSeqOffset);
2580 Linker.reportWarning(
"Cann't load line table.", ObjFile);
2585void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2590 for (
const auto &Namespace :
Unit.getNamespaces())
2592 Unit.getStartOffset());
2594 for (
const auto &Pubname :
Unit.getPubnames())
2595 AppleNames.addName(Pubname.Name,
2596 Pubname.Die->getOffset() +
Unit.getStartOffset());
2598 for (
const auto &Pubtype :
Unit.getPubtypes())
2600 Pubtype.Name, Pubtype.Die->getOffset() +
Unit.getStartOffset(),
2601 Pubtype.Die->getTag(),
2604 Pubtype.QualifiedNameHash);
2606 for (
const auto &ObjC :
Unit.getObjC())
2607 AppleObjc.addName(ObjC.Name,
2608 ObjC.Die->getOffset() +
Unit.getStartOffset());
2611 TheDwarfEmitter->emitPubNamesForUnit(Unit);
2612 TheDwarfEmitter->emitPubTypesForUnit(Unit);
2615 for (
const auto &Namespace :
Unit.getNamespaces())
2620 Unit.getTag() == dwarf::DW_TAG_type_unit);
2621 for (
const auto &Pubname :
Unit.getPubnames())
2623 Pubname.Name, Pubname.Die->getOffset(),
2625 Pubname.Die->getTag(),
Unit.getUniqueID(),
2626 Unit.getTag() == dwarf::DW_TAG_type_unit);
2627 for (
const auto &Pubtype :
Unit.getPubtypes())
2629 Pubtype.Name, Pubtype.Die->getOffset(),
2631 Pubtype.Die->getTag(),
Unit.getUniqueID(),
2632 Unit.getTag() == dwarf::DW_TAG_type_unit);
2644void DWARFLinker::patchFrameInfoForObject(LinkContext &
Context) {
2645 DWARFContext &OrigDwarf = *
Context.File.Dwarf;
2646 unsigned SrcAddrSize = OrigDwarf.getDWARFObj().getAddressSize();
2648 StringRef
FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
2653 for (std::unique_ptr<CompileUnit> &Unit :
Context.CompileUnits) {
2654 for (
auto CurRange :
Unit->getFunctionRanges())
2655 AllUnitsRanges.insert(CurRange.Range, CurRange.Value);
2658 DataExtractor
Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2659 uint64_t InputOffset = 0;
2663 DenseMap<uint64_t, StringRef> LocalCIES;
2665 while (
Data.isValidOffset(InputOffset)) {
2666 uint64_t EntryOffset = InputOffset;
2667 uint32_t InitialLength =
Data.getU32(&InputOffset);
2668 if (InitialLength == 0xFFFFFFFF)
2669 return reportWarning(
"Dwarf64 bits no supported",
Context.File);
2671 uint32_t CIEId =
Data.getU32(&InputOffset);
2672 if (CIEId == 0xFFFFFFFF) {
2674 StringRef CIEData =
FrameData.substr(EntryOffset, InitialLength + 4);
2675 LocalCIES[EntryOffset] = CIEData;
2677 InputOffset += InitialLength - 4;
2681 uint64_t Loc =
Data.getUnsigned(&InputOffset, SrcAddrSize);
2687 std::optional<AddressRangeValuePair>
Range =
2688 AllUnitsRanges.getRangeThatContains(Loc);
2691 InputOffset = EntryOffset + InitialLength + 4;
2697 StringRef CIEData = LocalCIES[CIEId];
2698 if (CIEData.empty())
2699 return reportWarning(
"Inconsistent debug_frame content. Dropping.",
2704 auto IteratorInserted = EmittedCIEs.insert(
2705 std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
2707 if (IteratorInserted.second) {
2708 LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
2709 IteratorInserted.first->getValue() = LastCIEOffset;
2710 TheDwarfEmitter->emitCIE(CIEData);
2716 unsigned FDERemainingBytes = InitialLength - (4 + SrcAddrSize);
2717 TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), SrcAddrSize,
2719 FrameData.substr(InputOffset, FDERemainingBytes));
2720 InputOffset += FDERemainingBytes;
2724uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
2726 const DWARFFile &File,
2727 int ChildRecurseDepth) {
2728 const char *
Name =
nullptr;
2729 DWARFUnit *OrigUnit = &
U.getOrigUnit();
2730 CompileUnit *CU = &
U;
2731 std::optional<DWARFFormValue>
Ref;
2737 if (!(
Ref = DIE.find(dwarf::DW_AT_specification)) &&
2738 !(
Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
2746 Linker.resolveDIEReference(File, CompileUnits, *
Ref, DIE, RefCU)) {
2748 OrigUnit = &RefCU->getOrigUnit();
2753 unsigned Idx = OrigUnit->getDIEIndex(DIE);
2754 if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
2755 Name =
"(anonymous namespace)";
2757 if (CU->getInfo(Idx).ParentIdx == 0 ||
2759 CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
2760 dwarf::DW_TAG_module)
2761 return djbHash(Name ? Name :
"",
djbHash(ChildRecurseDepth ?
"" :
"::"));
2763 DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
2772 CUDie.
find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
2781 if (ObjectPrefixMap.empty())
2785 for (
const auto &Entry : ObjectPrefixMap)
2788 return p.str().str();
2795 CUDie.
find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
"");
2797 if (PCMFile.empty())
2800 if (ObjectPrefixMap)
2801 PCMFile =
remapPath(PCMFile, *ObjectPrefixMap);
2806std::pair<bool, bool> DWARFLinker::isClangModuleRef(
const DWARFDie &CUDie,
2807 std::string &PCMFile,
2808 LinkContext &Context,
2811 if (PCMFile.empty())
2812 return std::make_pair(
false,
false);
2817 std::string Name =
dwarf::toString(CUDie.find(dwarf::DW_AT_name),
"");
2820 reportWarning(
"Anonymous module skeleton CU for " + PCMFile,
2822 return std::make_pair(
true,
true);
2825 if (!
Quiet && Options.Verbose) {
2827 outs() <<
"Found clang module reference " << PCMFile;
2830 auto Cached = ClangModules.find(PCMFile);
2831 if (Cached != ClangModules.end()) {
2835 if (!
Quiet && Options.Verbose && (Cached->second != DwoId))
2836 reportWarning(Twine(
"hash mismatch: this object file was built against a "
2837 "different version of the module ") +
2840 if (!
Quiet && Options.Verbose)
2841 outs() <<
" [cached].\n";
2842 return std::make_pair(
true,
true);
2845 return std::make_pair(
true,
false);
2848bool DWARFLinker::registerModuleReference(
const DWARFDie &CUDie,
2853 std::string PCMFile =
getPCMFile(CUDie, Options.ObjectPrefixMap);
2854 std::pair<bool, bool> IsClangModuleRef =
2855 isClangModuleRef(CUDie, PCMFile,
Context, Indent,
false);
2857 if (!IsClangModuleRef.first)
2860 if (IsClangModuleRef.second)
2863 if (Options.Verbose)
2868 ClangModules.insert({PCMFile,
getDwoId(CUDie)});
2870 if (
Error E = loadClangModule(Loader, CUDie, PCMFile,
Context, OnCUDieLoaded,
2878Error DWARFLinker::loadClangModule(
2879 ObjFileLoaderTy Loader,
const DWARFDie &CUDie,
const std::string &PCMFile,
2883 std::string ModuleName =
dwarf::toString(CUDie.find(dwarf::DW_AT_name),
"");
2886 SmallString<0>
Path(Options.PrependPath);
2893 if (Loader ==
nullptr) {
2894 reportError(
"Could not load clang module: loader is not specified.\n",
2899 auto ErrOrObj = Loader(
Context.File.FileName, Path);
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);
2922 uint64_t PCMDwoId =
getDwoId(ChildCUDie);
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, UniqueUnitID++, !Options.NoODR,
2941 Context.ModuleUnits.emplace_back(RefModuleUnit{*ErrOrObj, std::move(Unit)});
2946Expected<uint64_t> DWARFLinker::DIECloner::cloneAllCompileUnits(
2947 DWARFContext &DwarfContext,
const DWARFFile &File,
bool IsLittleEndian) {
2948 uint64_t OutputDebugInfoSize =
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);
2958 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2961 if (CurrentUnit->getInfo(0).Keep) {
2964 CurrentUnit->createOutputDIE();
2965 rememberUnitForMacroOffset(*CurrentUnit);
2966 cloneDIE(InputDIE, File, *CurrentUnit, 0 , UnitHeaderSize,
2967 0, IsLittleEndian, CurrentUnit->getOutputUnitDIE());
2970 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2974 if (
Error E = generateLineTableForUnit(*CurrentUnit))
2977 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2982 if (
Error E = Linker.generateUnitRanges(*CurrentUnit, File, AddrPool))
2985 auto ProcessExpr = [&](SmallVectorImpl<uint8_t> &SrcBytes,
2986 SmallVectorImpl<uint8_t> &OutBytes,
2987 int64_t RelocAdjustment) {
2988 DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2989 DataExtractor
Data(SrcBytes, IsLittleEndian,
2990 OrigUnit.getAddressByteSize());
2991 cloneExpression(
Data,
2992 DWARFExpression(
Data, OrigUnit.getAddressByteSize(),
2993 OrigUnit.getFormParams().Format),
2994 File, *CurrentUnit, OutBytes, RelocAdjustment,
2997 if (
Error E = generateUnitLocations(*CurrentUnit, File, ProcessExpr))
2999 if (
Error E = emitDebugAddrSection(*CurrentUnit, DwarfVersion))
3008 Emitter->emitMacroTables(
File.Dwarf.get(), UnitMacroMap, DebugStrPool);
3011 for (
auto &CurrentUnit : CompileUnits) {
3012 CurrentUnit->fixupForwardReferences();
3014 if (!CurrentUnit->getOutputUnitDIE())
3017 unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
3020 CurrentUnit->getStartOffset());
3021 Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
3022 Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
3024 CurrentUnit->computeNextUnitOffset(DwarfVersion));
3028 return OutputDebugInfoSize - StartOutputDebugInfoSize;
3031void DWARFLinker::copyInvariantDebugSection(DWARFContext &
Dwarf) {
3032 TheDwarfEmitter->emitSectionContents(
Dwarf.getDWARFObj().getLocSection().Data,
3034 TheDwarfEmitter->emitSectionContents(
3035 Dwarf.getDWARFObj().getRangesSection().Data,
3037 TheDwarfEmitter->emitSectionContents(
3039 TheDwarfEmitter->emitSectionContents(
Dwarf.getDWARFObj().getArangesSection(),
3041 TheDwarfEmitter->emitSectionContents(
3043 TheDwarfEmitter->emitSectionContents(
3044 Dwarf.getDWARFObj().getRnglistsSection().Data,
3046 TheDwarfEmitter->emitSectionContents(
3047 Dwarf.getDWARFObj().getLoclistsSection().Data,
3053 ObjectContexts.emplace_back(LinkContext(File));
3055 if (ObjectContexts.back().File.Dwarf) {
3056 for (
const std::unique_ptr<DWARFUnit> &
CU :
3057 ObjectContexts.back().File.Dwarf->compile_units()) {
3066 registerModuleReference(CUDie, ObjectContexts.back(), Loader,
3073 assert((Options.TargetDWARFVersion != 0) &&
3074 "TargetDWARFVersion should be set");
3078 unsigned NumObjects = ObjectContexts.size();
3090 for (LinkContext &OptContext : ObjectContexts) {
3091 if (Options.Verbose)
3092 outs() <<
"DEBUG MAP OBJECT: " << OptContext.File.FileName <<
"\n";
3094 if (!OptContext.File.Dwarf)
3097 if (Options.VerifyInputDWARF)
3098 verifyInput(OptContext.File);
3105 !OptContext.File.Addresses->hasValidRelocs()) {
3106 if (Options.Verbose)
3107 outs() <<
"No valid relocations found. Skipping.\n";
3111 OptContext.Skip =
true;
3116 if (!OptContext.File.Dwarf)
3120 if (!OptContext.File.Dwarf->types_section_units().empty()) {
3121 reportWarning(
"type units are not currently supported: file will "
3124 OptContext.Skip =
true;
3130 OptContext.CompileUnits.reserve(
3131 OptContext.File.Dwarf->getNumCompileUnits());
3132 for (
const auto &
CU : OptContext.File.Dwarf->compile_units()) {
3133 auto CUDie =
CU->getUnitDIE(
true);
3134 if (Options.Verbose) {
3135 outs() <<
"Input compilation unit:";
3138 DumpOpts.
Verbose = Options.Verbose;
3139 CUDie.dump(
outs(), 0, DumpOpts);
3143 for (
auto &
CU : OptContext.ModuleUnits) {
3144 if (
Error Err = cloneModuleUnit(OptContext,
CU, ODRContexts, DebugStrPool,
3145 DebugLineStrPool, StringOffsetPool))
3146 reportWarning(
toString(std::move(Err)),
CU.File);
3156 (TheDwarfEmitter ==
nullptr) ? 0
3157 : TheDwarfEmitter->getDebugInfoSectionSize();
3161 std::mutex ProcessedFilesMutex;
3162 std::condition_variable ProcessedFilesConditionVariable;
3163 BitVector ProcessedFiles(NumObjects,
false);
3167 auto AnalyzeLambda = [&](
size_t I) {
3168 auto &Context = ObjectContexts[
I];
3170 if (Context.Skip || !Context.File.Dwarf)
3173 for (
const auto &
CU : Context.File.Dwarf->compile_units()) {
3176 auto CUDie =
CU->getUnitDIE(
false);
3177 std::string PCMFile =
getPCMFile(CUDie, Options.ObjectPrefixMap);
3180 !isClangModuleRef(CUDie, PCMFile, Context, 0,
true).first) {
3181 Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
3182 *
CU, UniqueUnitID++, !Options.NoODR && !Options.Update,
""));
3187 for (
auto &CurrentUnit : Context.CompileUnits) {
3188 auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
3192 *CurrentUnit, &ODRContexts.
getRoot(), ODRContexts,
3193 ModulesEndOffset, Options.ParseableSwiftInterfaces,
3195 reportWarning(Warning, Context.File, &DIE);
3208 auto &OptContext = ObjectContexts[
I];
3209 if (OptContext.Skip || !OptContext.File.Dwarf)
3218 for (
auto &CurrentUnit : OptContext.CompileUnits)
3219 CurrentUnit->markEverythingAsKept();
3220 copyInvariantDebugSection(*OptContext.File.Dwarf);
3222 for (
auto &CurrentUnit : OptContext.CompileUnits) {
3223 lookForDIEsToKeep(*OptContext.File.Addresses, OptContext.CompileUnits,
3224 CurrentUnit->getOrigUnit().getUnitDIE(),
3225 OptContext.File, *CurrentUnit, 0);
3235 if (OptContext.File.Addresses->hasValidRelocs() ||
3237 SizeByObject[OptContext.File.FileName].Input =
3240 DIECloner(*
this, TheDwarfEmitter, OptContext.File, DIEAlloc,
3241 OptContext.CompileUnits, Options.Update, DebugStrPool,
3242 DebugLineStrPool, StringOffsetPool)
3243 .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
3244 OptContext.File.Dwarf->isLittleEndian());
3249 SizeByObject[OptContext.File.FileName].Output = *SizeOrErr;
3251 if ((TheDwarfEmitter !=
nullptr) && !OptContext.CompileUnits.empty() &&
3253 patchFrameInfoForObject(OptContext);
3256 cleanupAuxiliarryData(OptContext);
3259 auto EmitLambda = [&]() {
3261 if (TheDwarfEmitter !=
nullptr) {
3262 TheDwarfEmitter->emitAbbrevs(Abbreviations, Options.TargetDWARFVersion);
3263 TheDwarfEmitter->emitStrings(DebugStrPool);
3264 TheDwarfEmitter->emitStringOffsets(StringOffsetPool.
getValues(),
3265 Options.TargetDWARFVersion);
3266 TheDwarfEmitter->emitLineStrings(DebugLineStrPool);
3268 switch (TableKind) {
3270 TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
3271 TheDwarfEmitter->emitAppleNames(AppleNames);
3272 TheDwarfEmitter->emitAppleTypes(AppleTypes);
3273 TheDwarfEmitter->emitAppleObjc(AppleObjc);
3280 TheDwarfEmitter->emitDebugNames(DebugNames);
3287 auto AnalyzeAll = [&]() {
3288 for (
unsigned I = 0,
E = NumObjects;
I !=
E; ++
I) {
3291 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
3292 ProcessedFiles.
set(
I);
3293 ProcessedFilesConditionVariable.notify_one();
3298 for (
unsigned I = 0,
E = NumObjects;
I !=
E; ++
I) {
3300 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
3301 if (!ProcessedFiles[
I]) {
3302 ProcessedFilesConditionVariable.wait(
3303 LockGuard, [&]() {
return ProcessedFiles[
I]; });
3319 if (Options.Threads == 1) {
3320 for (
unsigned I = 0,
E = NumObjects;
I !=
E; ++
I) {
3330 Pool.
async(AnalyzeAll);
3331 Pool.
async(CloneAll, std::reference_wrapper<Error>(CE));
3338 if (Options.Statistics) {
3340 std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
3341 for (
auto &
E : SizeByObject)
3342 Sorted.emplace_back(
E.first(),
E.second);
3344 return LHS.second.Output >
RHS.second.Output;
3347 auto ComputePercentange = [](int64_t
Input, int64_t Output) ->
float {
3348 const float Difference = Output -
Input;
3349 const float Sum =
Input + Output;
3352 return (Difference / (Sum / 2));
3355 int64_t InputTotal = 0;
3356 int64_t OutputTotal = 0;
3357 const char *FormatStr =
"{0,-45} {1,10}b {2,10}b {3,8:P}\n";
3360 outs() <<
".debug_info section size (in bytes)\n";
3361 outs() <<
"----------------------------------------------------------------"
3362 "---------------\n";
3363 outs() <<
"Filename Object "
3365 outs() <<
"----------------------------------------------------------------"
3366 "---------------\n";
3369 for (
auto &
E : Sorted) {
3370 InputTotal +=
E.second.Input;
3371 OutputTotal +=
E.second.Output;
3374 E.second.Output, ComputePercentange(
E.second.Input,
E.second.Output));
3377 outs() <<
"----------------------------------------------------------------"
3378 "---------------\n";
3380 ComputePercentange(InputTotal, OutputTotal));
3381 outs() <<
"----------------------------------------------------------------"
3382 "---------------\n\n";
3388Error DWARFLinker::cloneModuleUnit(LinkContext &Context, RefModuleUnit &Unit,
3394 assert(Unit.Unit.get() !=
nullptr);
3396 if (!Unit.Unit->getOrigUnit().getUnitDIE().hasChildren())
3401 outs() <<
"cloning .debug_info from " << Unit.File.FileName <<
"\n";
3406 &ODRContexts.
getRoot(), ODRContexts, 0,
3407 Options.ParseableSwiftInterfaces,
3409 reportWarning(Warning, Context.File, &DIE);
3412 Unit.Unit->markEverythingAsKept();
3416 CompileUnits.emplace_back(std::move(Unit.Unit));
3419 DIECloner(*
this, TheDwarfEmitter, Unit.File, DIEAlloc, CompileUnits,
3420 Options.Update, DebugStrPool, DebugLineStrPool,
3422 .cloneAllCompileUnits(*Unit.File.Dwarf, Unit.File,
3423 Unit.File.Dwarf->isLittleEndian());
3429void DWARFLinker::verifyInput(
const DWARFFile &File) {
3436 if (
Options.InputVerificationHandler)
3437 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!")
static uint32_t hashFullyQualifiedName(CompileUnit &InputCU, DWARFDie &InputDIE, int ChildRecurseDepth=0)
This file implements the BitVector class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
#define LLVM_LIKELY(EXPR)
dxil DXContainer Global Emitter
Provides ErrorOr<T> smart pointer.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
ArrayRef< T > drop_while(PredicateT Pred) const
Return a copy of *this with the first N elements satisfying the given predicate removed.
const T & front() const
front - Get the first element.
bool empty() const
empty - Check if the array is empty.
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
void setChildrenFlag(bool hasChild)
value_iterator addValue(BumpPtrAllocator &Alloc, const DIEValue &V)
A structured debug information entry.
unsigned getAbbrevNumber() const
DIE & addChild(DIE *Child)
Add a child to the DIE.
LLVM_ABI DIEAbbrev generateAbbrev() const
Generate the abbreviation for this DIE.
static DIE * get(BumpPtrAllocator &Alloc, dwarf::Tag Tag)
void setAbbrevNumber(unsigned I)
Set the abbreviation number for this DIE.
unsigned getOffset() const
Get the compile/type unit relative offset of this DIE.
void setOffset(unsigned O)
dwarf::Tag getTag() const
static LLVM_ABI 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.
uint64_t getOffset() const
Get the absolute offset into the debug info or types section.
iterator_range< iterator > children() const
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
Get the abbreviation declaration for 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...
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - 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.
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.
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)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
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.
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 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.
FunctionAddr VTableAddr Value
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...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
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 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.
static void resolveRelativeObjectPath(SmallVectorImpl< char > &Buf, DWARFDie CU)
Resolve the relative path to a build artifact referenced by DWARF by applying DW_AT_comp_dir.
static std::string getPCMFile(const DWARFDie &CUDie, const DWARFLinkerBase::ObjectPrefixMapTy *ObjectPrefixMap)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
static bool shouldSkipAttribute(bool Update, DWARFAbbreviationDeclaration::AttributeSpec AttrSpec, bool SkipPC)
auto reverse(ContainerTy &&C)
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.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
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)
ArrayRef(const T &OneElt) -> ArrayRef< T >
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.
void consumeError(Error Err)
Consume a Error without doing anything.
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
static bool isODRAttribute(uint16_t Attr)
static void constructSeqOffsettoOrigRowMapping(CompileUnit &Unit, const DWARFDebugLine::LineTable <, DenseMap< uint64_t, unsigned > &SeqOffToOrigRow)
static void patchStmtList(DIE &Die, DIEInteger Offset)
std::vector< DWARFLocationExpression > DWARFLocationExpressionsVector
Represents a set of absolute location expressions.
int64_t LinkedOffsetFixupVal
uint64_t InputAttrStartOffset
uint64_t InputAttrEndOffset
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.
Represents a series of contiguous machine instructions.
uint64_t StmtSeqOffset
The offset into the line table where this sequence begins.
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?