-
Notifications
You must be signed in to change notification settings - Fork 13.5k
Reduce llvm-gsymutil memory usage #139907
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the LLVM GitHub User Guide. You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums. |
@llvm/pr-subscribers-debuginfo Author: None (peremyach) ChangesFor large binaries gsymutil ends up using too much memory. This diff adds DIE tree cleanup per compile unit to reduce memory usage. P. S. Not sure about formatting. Maybe it hasn't been run in a while, or I have misconfigured something.
Full diff: https://github.com/llvm/llvm-project/pull/139907.diff 3 Files Affected:
diff --git a/llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h b/llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h
index 80c27aea89312..75a800bdf017a 100644
--- a/llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h
+++ b/llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h
@@ -27,6 +27,7 @@
#include <cstdint>
#include <map>
#include <memory>
+#include <mutex>
#include <set>
#include <utility>
#include <vector>
@@ -125,7 +126,8 @@ bool isCompileUnit(const std::unique_ptr<DWARFUnit> &U);
/// Describe a collection of units. Intended to hold all units either from
/// .debug_info and .debug_types, or from .debug_info.dwo and .debug_types.dwo.
-class DWARFUnitVector final : public SmallVector<std::unique_ptr<DWARFUnit>, 1> {
+class DWARFUnitVector final
+ : public SmallVector<std::unique_ptr<DWARFUnit>, 1> {
std::function<std::unique_ptr<DWARFUnit>(uint64_t, DWARFSectionKind,
const DWARFSection *,
const DWARFUnitIndex::Entry *)>
@@ -137,8 +139,8 @@ class DWARFUnitVector final : public SmallVector<std::unique_ptr<DWARFUnit>, 1>
using iterator = typename UnitVector::iterator;
using iterator_range = llvm::iterator_range<typename UnitVector::iterator>;
- using compile_unit_range =
- decltype(make_filter_range(std::declval<iterator_range>(), isCompileUnit));
+ using compile_unit_range = decltype(make_filter_range(
+ std::declval<iterator_range>(), isCompileUnit));
DWARFUnit *getUnitForOffset(uint64_t Offset) const;
DWARFUnit *getUnitForIndexEntry(const DWARFUnitIndex::Entry &E);
@@ -257,6 +259,8 @@ class DWARFUnit {
std::shared_ptr<DWARFUnit> DWO;
+ mutable std::recursive_mutex FreeDIEsMutex;
+
protected:
friend dwarf_linker::parallel::CompileUnit;
@@ -316,7 +320,7 @@ class DWARFUnit {
bool isLittleEndian() const { return IsLittleEndian; }
bool isDWOUnit() const { return IsDWO; }
- DWARFContext& getContext() const { return Context; }
+ DWARFContext &getContext() const { return Context; }
const DWARFSection &getInfoSection() const { return InfoSection; }
uint64_t getOffset() const { return Header.getOffset(); }
const dwarf::FormParams &getFormParams() const {
@@ -377,9 +381,7 @@ class DWARFUnit {
RangeSectionBase = Base;
}
- uint64_t getLocSectionBase() const {
- return LocSectionBase;
- }
+ uint64_t getLocSectionBase() const { return LocSectionBase; }
std::optional<object::SectionedAddress>
getAddrOffsetSectionItem(uint32_t Index) const;
@@ -566,6 +568,9 @@ class DWARFUnit {
Error tryExtractDIEsIfNeeded(bool CUDieOnly);
+ /// clearDIEs - Clear parsed DIEs to keep memory usage low.
+ void clearDIEs(bool KeepCUDie, bool KeepDWODies = false);
+
private:
/// Size in bytes of the .debug_info data associated with this compile unit.
size_t getDebugInfoSize() const {
@@ -581,9 +586,6 @@ class DWARFUnit {
void extractDIEsToVector(bool AppendCUDie, bool AppendNonCUDIEs,
std::vector<DWARFDebugInfoEntry> &DIEs) const;
- /// clearDIEs - Clear parsed DIEs to keep memory usage low.
- void clearDIEs(bool KeepCUDie);
-
/// parseDWO - Parses .dwo file for current compile unit. Returns true if
/// it was actually constructed.
/// The \p AlternativeLocation specifies an alternative location to get
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp b/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
index bdd04b00f557b..43055c411d3d9 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
@@ -44,10 +44,9 @@ void DWARFUnitVector::addUnitsForSection(DWARFContext &C,
DWARFSectionKind SectionKind) {
const DWARFObject &D = C.getDWARFObj();
addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(),
- &D.getLocSection(), D.getStrSection(),
- D.getStrOffsetsSection(), &D.getAddrSection(),
- D.getLineSection(), D.isLittleEndian(), false, false,
- SectionKind);
+ &D.getLocSection(), D.getStrSection(), D.getStrOffsetsSection(),
+ &D.getAddrSection(), D.getLineSection(), D.isLittleEndian(),
+ false, false, SectionKind);
}
void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,
@@ -55,11 +54,11 @@ void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,
DWARFSectionKind SectionKind,
bool Lazy) {
const DWARFObject &D = C.getDWARFObj();
- addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(),
- &D.getLocDWOSection(), D.getStrDWOSection(),
- D.getStrOffsetsDWOSection(), &D.getAddrSection(),
- D.getLineDWOSection(), C.isLittleEndian(), true, Lazy,
- SectionKind);
+ addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(),
+ &D.getRangesDWOSection(), &D.getLocDWOSection(),
+ D.getStrDWOSection(), D.getStrOffsetsDWOSection(),
+ &D.getAddrSection(), D.getLineDWOSection(), C.isLittleEndian(),
+ true, Lazy, SectionKind);
}
void DWARFUnitVector::addUnitsImpl(
@@ -107,12 +106,12 @@ void DWARFUnitVector::addUnitsImpl(
std::unique_ptr<DWARFUnit> U;
if (Header.isTypeUnit())
U = std::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,
- RS, LocSection, SS, SOS, AOS, LS,
- LE, IsDWO, *this);
+ RS, LocSection, SS, SOS, AOS, LS,
+ LE, IsDWO, *this);
else
- U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header,
- DA, RS, LocSection, SS, SOS,
- AOS, LS, LE, IsDWO, *this);
+ U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header, DA,
+ RS, LocSection, SS, SOS, AOS, LS,
+ LE, IsDWO, *this);
return U;
};
}
@@ -496,8 +495,12 @@ void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
}
Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {
- if ((CUDieOnly && !DieArray.empty()) ||
- DieArray.size() > 1)
+ // Acquire the FreeDIEsMutex recursive lock to prevent a different thread
+ // from freeing the DIE arrays while they're being extracted. It needs to
+ // be recursive, as there is a potentially recursive path through
+ // determineStringOffsetsTableContribution.
+ std::lock_guard<std::recursive_mutex> FreeLock(FreeDIEsMutex);
+ if ((CUDieOnly && !DieArray.empty()) || DieArray.size() > 1)
return Error::success(); // Already parsed.
bool HasCUDie = !DieArray.empty();
@@ -652,7 +655,13 @@ bool DWARFUnit::parseDWO(StringRef DWOAlternativeLocation) {
return true;
}
-void DWARFUnit::clearDIEs(bool KeepCUDie) {
+void DWARFUnit::clearDIEs(bool KeepCUDie, bool KeepDWODies) {
+ // We need to acquire the FreeDIEsMutex lock because we are
+ // going to free the DIEs, when other threads might be trying to create them.
+ std::lock_guard<std::recursive_mutex> FreeLock(FreeDIEsMutex);
+ if (!KeepDWODies && DWO) {
+ DWO->clearDIEs(KeepCUDie, KeepDWODies);
+ }
// Do not use resize() + shrink_to_fit() to free memory occupied by dies.
// shrink_to_fit() is a *non-binding* request to reduce capacity() to size().
// It depends on the implementation whether the request is fulfilled.
@@ -868,9 +877,8 @@ DWARFDie DWARFUnit::getVariableForAddress(uint64_t Address) {
return R->second.second;
}
-void
-DWARFUnit::getInlinedChainForAddress(uint64_t Address,
- SmallVectorImpl<DWARFDie> &InlinedChain) {
+void DWARFUnit::getInlinedChainForAddress(
+ uint64_t Address, SmallVectorImpl<DWARFDie> &InlinedChain) {
assert(InlinedChain.empty());
// Try to look for subprogram DIEs in the DWO file.
parseDWO();
@@ -886,7 +894,7 @@ DWARFUnit::getInlinedChainForAddress(uint64_t Address,
}
if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
InlinedChain.push_back(SubroutineDIE);
- SubroutineDIE = SubroutineDIE.getParent();
+ SubroutineDIE = SubroutineDIE.getParent();
}
}
@@ -1087,7 +1095,8 @@ StrOffsetsContributionDescriptor::validateContributionSize(
if (ValidationSize >= Size)
if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
return *this;
- return createStringError(errc::invalid_argument, "length exceeds section size");
+ return createStringError(errc::invalid_argument,
+ "length exceeds section size");
}
// Look for a DWARF64-formatted contribution to the string offsets table
@@ -1095,10 +1104,13 @@ StrOffsetsContributionDescriptor::validateContributionSize(
static Expected<StrOffsetsContributionDescriptor>
parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
if (!DA.isValidOffsetForDataOfSize(Offset, 16))
- return createStringError(errc::invalid_argument, "section offset exceeds section size");
+ return createStringError(errc::invalid_argument,
+ "section offset exceeds section size");
if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)
- return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");
+ return createStringError(
+ errc::invalid_argument,
+ "32 bit contribution referenced from a 64 bit unit");
uint64_t Size = DA.getU64(&Offset);
uint8_t Version = DA.getU16(&Offset);
@@ -1113,7 +1125,8 @@ parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
static Expected<StrOffsetsContributionDescriptor>
parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
if (!DA.isValidOffsetForDataOfSize(Offset, 8))
- return createStringError(errc::invalid_argument, "section offset exceeds section size");
+ return createStringError(errc::invalid_argument,
+ "section offset exceeds section size");
uint32_t ContributionSize = DA.getU32(&Offset);
if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)
@@ -1135,7 +1148,8 @@ parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
switch (Format) {
case dwarf::DwarfFormat::DWARF64: {
if (Offset < 16)
- return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");
+ return createStringError(errc::invalid_argument,
+ "insufficient space for 64 bit header prefix");
auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);
if (!DescOrError)
return DescOrError.takeError();
@@ -1144,7 +1158,8 @@ parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
}
case dwarf::DwarfFormat::DWARF32: {
if (Offset < 8)
- return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");
+ return createStringError(errc::invalid_argument,
+ "insufficient space for 32 bit header prefix");
auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);
if (!DescOrError)
return DescOrError.takeError();
@@ -1182,7 +1197,8 @@ DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA) {
return std::nullopt;
Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16;
// Look for a valid contribution at the given offset.
- auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);
+ auto DescOrError =
+ parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);
if (!DescOrError)
return DescOrError.takeError();
return *DescOrError;
diff --git a/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp b/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp
index 7a0256f10ea60..cba59955131b4 100644
--- a/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp
+++ b/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp
@@ -82,7 +82,6 @@ struct llvm::gsym::CUInfo {
}
};
-
static DWARFDie GetParentDeclContextDIE(DWARFDie &Die) {
if (DWARFDie SpecDie =
Die.getAttributeValueAsReferencedDie(dwarf::DW_AT_specification)) {
@@ -170,7 +169,7 @@ getQualifiedNameIndex(DWARFDie &Die, uint64_t Language, GsymCreator &Gsym) {
// templates
if (ParentName.front() == '<' && ParentName.back() == '>')
Name = "{" + ParentName.substr(1, ParentName.size() - 2).str() + "}" +
- "::" + Name;
+ "::" + Name;
else
Name = ParentName.str() + "::" + Name;
}
@@ -432,7 +431,7 @@ static void convertFunctionLineTable(OutputAggregator &Out, CUInfo &CUI,
// Skip multiple line entries for the same file and line.
auto LastLE = FI.OptLineTable->last();
if (LastLE && LastLE->File == FileIdx && LastLE->Line == Row.Line)
- continue;
+ continue;
// Only push a row if it isn't an end sequence. End sequence markers are
// included for the last address in a function or the last contiguous
// address in a sequence.
@@ -656,6 +655,11 @@ Error DwarfTransformer::convert(uint32_t NumThreads, OutputAggregator &Out) {
DWARFDie Die = getDie(*CU);
CUInfo CUI(DICtx, dyn_cast<DWARFCompileUnit>(CU.get()));
handleDie(Out, CUI, Die);
+ // Release the line table, once we're done.
+ DICtx.clearLineTableForUnit(CU.get());
+ // Free any DIEs that were allocated by the DWARF parser.
+ // If/when they're needed by other CU's, they'll be recreated.
+ CU->clearDIEs(/*KeepCUDie=*/false);
}
} else {
// LLVM Dwarf parser is not thread-safe and we need to parse all DWARF up
@@ -668,12 +672,7 @@ Error DwarfTransformer::convert(uint32_t NumThreads, OutputAggregator &Out) {
for (const auto &CU : DICtx.compile_units())
CU->getAbbreviations();
- // Now parse all DIEs in case we have cross compile unit references in a
- // thread pool.
DefaultThreadPool pool(hardware_concurrency(NumThreads));
- for (const auto &CU : DICtx.compile_units())
- pool.async([&CU]() { CU->getUnitDIE(false /*CUDieOnly*/); });
- pool.wait();
// Now convert all DWARF to GSYM in a thread pool.
std::mutex LogMutex;
@@ -681,11 +680,16 @@ Error DwarfTransformer::convert(uint32_t NumThreads, OutputAggregator &Out) {
DWARFDie Die = getDie(*CU);
if (Die) {
CUInfo CUI(DICtx, dyn_cast<DWARFCompileUnit>(CU.get()));
- pool.async([this, CUI, &LogMutex, &Out, Die]() mutable {
+ pool.async([this, CUI, &CU, &LogMutex, &Out, Die]() mutable {
std::string storage;
raw_string_ostream StrStream(storage);
OutputAggregator ThreadOut(Out.GetOS() ? &StrStream : nullptr);
handleDie(ThreadOut, CUI, Die);
+ // Release the line table once we're done.
+ DICtx.clearLineTableForUnit(CU.get());
+ // Free any DIEs that were allocated by the DWARF parser.
+ // If/when they're needed by other CU's, they'll be recreated.
+ CU->clearDIEs(/*KeepCUDie=*/false);
// Print ThreadLogStorage lines into an actual stream under a lock
std::lock_guard<std::mutex> guard(LogMutex);
if (Out.GetOS()) {
@@ -697,6 +701,9 @@ Error DwarfTransformer::convert(uint32_t NumThreads, OutputAggregator &Out) {
}
pool.wait();
}
+ // Now get rid of all the DIEs that may have been recreated
+ for (const auto &CU : DICtx.compile_units())
+ CU->clearDIEs(/*KeepCUDie=*/false);
size_t FunctionsAddedCount = Gsym.getNumFunctionInfos() - NumBefore;
Out << "Loaded " << FunctionsAddedCount << " functions from DWARF.\n";
return Error::success();
@@ -718,8 +725,8 @@ llvm::Error DwarfTransformer::verify(StringRef GsymPath,
for (uint32_t I = 0; I < NumAddrs; ++I) {
auto FuncAddr = Gsym->getAddress(I);
if (!FuncAddr)
- return createStringError(std::errc::invalid_argument,
- "failed to extract address[%i]", I);
+ return createStringError(std::errc::invalid_argument,
+ "failed to extract address[%i]", I);
auto FI = Gsym->getFunctionInfo(*FuncAddr);
if (!FI)
@@ -734,8 +741,7 @@ llvm::Error DwarfTransformer::verify(StringRef GsymPath,
if (!LR)
return LR.takeError();
- auto DwarfInlineInfos =
- DICtx.getInliningInfoForAddress(SectAddr, DLIS);
+ auto DwarfInlineInfos = DICtx.getInliningInfoForAddress(SectAddr, DLIS);
uint32_t NumDwarfInlineInfos = DwarfInlineInfos.getNumberOfFrames();
if (NumDwarfInlineInfos == 0) {
DwarfInlineInfos.addFrame(
@@ -773,8 +779,7 @@ llvm::Error DwarfTransformer::verify(StringRef GsymPath,
continue;
}
- for (size_t Idx = 0, count = LR->Locations.size(); Idx < count;
- ++Idx) {
+ for (size_t Idx = 0, count = LR->Locations.size(); Idx < count; ++Idx) {
const auto &gii = LR->Locations[Idx];
if (Idx < NumDwarfInlineInfos) {
const auto &dii = DwarfInlineInfos.getFrame(Idx);
|
mutable std::recursive_mutex FreeDIEsMutex; | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Previously we tried pretty hard to keep the multithreading support isolated in the ThreadSafeDWARFContext or something like that - could you try to do the same now? (move the locking to the ThreadSafeDWARFContext, probably)
(& yeah, please undo the unrelated formatting changes in this file - it's hard to review with them in)
3eeae4d
to
7f18052
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
doWorkThreadSafely
feels like a bit of a big/generic hammer to wedge into the generic interface, when the goal was for that interface to not know/care about thread safety... But given the various callers into DwarfUnit trying to parse DIEs, not sure there's much more to it (short of defining thread safe DwarfUnit wrappers, etc)
Guess this'll go on the tech debt ledger for a future dwarf parser rewrite..
✅ With the latest revision this PR passed the C/C++ code formatter. |
@peremyach Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail here. If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! |
For large binaries gsymutil ends up using too much memory. This diff adds DIE tree cleanup per compile unit to reduce memory usage.
P. S. Not sure about formatting. Maybe it hasn't been run in a while, or I have misconfigured something.
$ git clang-format HEAD~1 clang-format did not modify any files $ clang-format --version clang-format version 21.0.0git (git@github.com:peremyach/llvm-project.git 8d945c8357e1bd9872a34f92620d4916bfd27482)