[llvm] Reduce llvm-gsymutil memory usage (lambda-free, and less locking) (PR #97640)

Kevin Frei via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 25 11:40:03 PDT 2024


https://github.com/kevinfrei updated https://github.com/llvm/llvm-project/pull/97640

>From a67886d17d9c90f6c85e3e63880cdd7ae696abea Mon Sep 17 00:00:00 2001
From: Kevin Frei <freik at meta.com>
Date: Thu, 19 Sep 2024 08:53:16 -0700
Subject: [PATCH 1/2] .note.meta.debuginfo section writing

---
 llvm/include/llvm/MC/MCObjectFileInfo.h     | 10 ++++++++++
 llvm/lib/DWP/DWP.cpp                        |  6 ++++++
 llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp | 15 +++++++++++++++
 llvm/lib/MC/MCObjectFileInfo.cpp            |  4 ++++
 4 files changed, 35 insertions(+)

diff --git a/llvm/include/llvm/MC/MCObjectFileInfo.h b/llvm/include/llvm/MC/MCObjectFileInfo.h
index e2a2c84e47910b..6c12b27dba8a19 100644
--- a/llvm/include/llvm/MC/MCObjectFileInfo.h
+++ b/llvm/include/llvm/MC/MCObjectFileInfo.h
@@ -186,6 +186,11 @@ class MCObjectFileInfo {
   MCSection *MergeableConst16Section = nullptr;
   MCSection *MergeableConst32Section = nullptr;
 
+  // facebook begin T169912720
+  /// A flag indicating whether the debug info has unique 32-bit offsets for strings
+  MCSection *MetaInfoSection = nullptr;
+  // facebook end T169912720
+
   // MachO specific sections.
 
   /// Section for thread local structure information.
@@ -323,6 +328,11 @@ class MCObjectFileInfo {
   MCSection *getDwarfStrOffDWOSection() const { return DwarfStrOffDWOSection; }
   MCSection *getDwarfStrOffSection() const { return DwarfStrOffSection; }
   MCSection *getDwarfAddrSection() const { return DwarfAddrSection; }
+
+  // facebook begin T169912720
+  MCSection *getMetaInfoSection() const { return MetaInfoSection; }
+  // facebook end T169912720  
+
   MCSection *getDwarfRnglistsDWOSection() const {
     return DwarfRnglistsDWOSection;
   }
diff --git a/llvm/lib/DWP/DWP.cpp b/llvm/lib/DWP/DWP.cpp
index fecd184ca68a86..252554a3859e7e 100644
--- a/llvm/lib/DWP/DWP.cpp
+++ b/llvm/lib/DWP/DWP.cpp
@@ -941,6 +941,12 @@ Error write(MCStreamer &Out, ArrayRef<std::string> Inputs,
   writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
              IndexEntries, IndexVersion);
 
+  // facebook begin T169912720
+  // Write the meta info section.
+  Out.switchSection(MCOFI.getMetaInfoSection());
+  Out.emitBytes("{\"debug-str-32-bit-overflow\":true}");
+  // facebook end T169912720
+
   return Error::success();
 }
 } // namespace llvm
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp b/llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp
index bc4badc7713802..e2dda63914a8fc 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFFormValue.cpp
@@ -619,6 +619,21 @@ Expected<const char *> DWARFFormValue::getAsCString() const {
   DataExtractor StrData =
       IsDebugLineString ? C->getLineStringExtractor()
                         : U ? U->getStringExtractor() : C->getStringExtractor();
+  // facebook begin T169912720
+  if (Offset > 0) {
+    // Use the null-terminator of the previous string to verify that Offset
+    // points at the beginning of a string.
+    // Otherwise, we assume Offset was larger than 4Gi and got truncated
+    // to 32-bits. So we lookup for another string starting beyond the 4Gi.
+    uint64_t NullTermOffset = Offset - 1;
+    while (StrData.isValidOffset(NullTermOffset) &&
+           StrData.getU8(&NullTermOffset) != '\0') {
+      NullTermOffset += 0xFFFFFFFFULL;
+    }
+    if (StrData.isValidOffset(NullTermOffset))
+      Offset = NullTermOffset;
+  }
+  // facebook end T169912720
   if (const char *Str = StrData.getCStr(&Offset))
     return Str;
   std::string Msg = FormEncodingString(Form).str();
diff --git a/llvm/lib/MC/MCObjectFileInfo.cpp b/llvm/lib/MC/MCObjectFileInfo.cpp
index f37e138edc36b1..92f4caeb018531 100644
--- a/llvm/lib/MC/MCObjectFileInfo.cpp
+++ b/llvm/lib/MC/MCObjectFileInfo.cpp
@@ -495,6 +495,10 @@ void MCObjectFileInfo::initELFMCObjectFileInfo(const Triple &T, bool Large) {
   DwarfRnglistsSection = Ctx->getELFSection(".debug_rnglists", DebugSecType, 0);
   DwarfLoclistsSection = Ctx->getELFSection(".debug_loclists", DebugSecType, 0);
 
+  // facebook begin T169912720
+  MetaInfoSection = Ctx->getELFSection(".note.meta.debuginfo", DebugSecType, 0);
+  // facebook end T169912720
+
   // Fission Sections
   DwarfInfoDWOSection =
       Ctx->getELFSection(".debug_info.dwo", DebugSecType, ELF::SHF_EXCLUDE);

>From 68c93087954a04116592fe7f44b8547e789a149c Mon Sep 17 00:00:00 2001
From: Kevin Frei <kevinfrei at users.noreply.github.com>
Date: Tue, 2 Jul 2024 10:14:26 -0700
Subject: [PATCH 2/2] Reduce llvm-gsymutil memory usage (#91023)

llvm-gsymutil eats a lot of RAM. On some large binaries, it causes OOM's on smaller hardware, consuming well over 64GB of RAM.
This change frees line tables once we're done with them, and frees DWARFUnits's DIE's when we finish processing each DU, though
they may get reconstituted if there are references from other DU's during processing. Once the conversion is complete, all DIE's
are freed. The reduction in peak memory usage from these changes showed between 7-12% in my tests.

There is a recursive mutex necessary to prevent accidental freeing of the DIE arrays while they're being extraced. It needs
to be recursive as there's a recursive path through the final section of the code (determineStringOffsetsTableContribution) that
may result in a call to this function.
---
 llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h |  9 ++++++---
 llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp        | 10 ++++++++++
 llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp  | 15 ++++++++++++++-
 3 files changed, 30 insertions(+), 4 deletions(-)

diff --git a/llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h b/llvm/include/llvm/DebugInfo/DWARF/DWARFUnit.h
index 80c27aea893123..be3c4fe7c4b198 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>
@@ -257,6 +258,8 @@ class DWARFUnit {
 
   std::shared_ptr<DWARFUnit> DWO;
 
+  mutable std::recursive_mutex FreeDIEsMutex;
+
 protected:
   friend dwarf_linker::parallel::CompileUnit;
 
@@ -566,6 +569,9 @@ class DWARFUnit {
 
   Error tryExtractDIEsIfNeeded(bool CUDieOnly);
 
+  /// clearDIEs - Clear parsed DIEs to keep memory usage low.
+  void clearDIEs(bool KeepCUDie);
+
 private:
   /// Size in bytes of the .debug_info data associated with this compile unit.
   size_t getDebugInfoSize() const {
@@ -581,9 +587,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 bdd04b00f557bd..0449d4a7b078a8 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
@@ -496,6 +496,12 @@ void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
 }
 
 Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {
+  // 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.
@@ -653,6 +659,10 @@ bool DWARFUnit::parseDWO(StringRef DWOAlternativeLocation) {
 }
 
 void DWARFUnit::clearDIEs(bool KeepCUDie) {
+  // We need to acquire the FreeDIEsMutex lock in write-mode, 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);
+
   // 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.
diff --git a/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp b/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp
index 894abf5777f161..0dd136b2aa7dbc 100644
--- a/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp
+++ b/llvm/lib/DebugInfo/GSYM/DwarfTransformer.cpp
@@ -587,6 +587,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
@@ -612,11 +617,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()) {
@@ -628,6 +638,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();



More information about the llvm-commits mailing list