https://github.com/ilovepi updated 
https://github.com/llvm/llvm-project/pull/243321

>From 9ee0c765cce7cbd51ef919cda484d91b07339311 Mon Sep 17 00:00:00 2001
From: Paul Kirth <[email protected]>
Date: Thu, 12 Nov 2026 21:14:47 -0800
Subject: [PATCH] [clang-doc] Add ConcurrentStringPool implementation

This replaces the existing simple wrapper over the UniqueStringSaver
with a proper ConcurrentStringPool.

The new ConcurrentStringPool lifts ideas liberally from other places in
LLVM. More specifically, it takes design elements from
ConcurrentHashTableByPtr, as well as LLD's MergeNoTailSection and
GHashTable, while trying to avoid some of the known problems in
DWARFLinker's StringPool implementation. It also uses a similar strategy
to folly's AtomicHashMap by using atomic operations to avoid per-shard
locking. The new implementation tries to make its internal data layout
cache friendly, both in its choice of size and alignment.

The new ConcurrentStringPool allows clang-doc to run over the sources in
clang/lib in about 156s vs 236s for the baseline (a 34% reduction in
wall time). The micro-benchmarks also show marked improvement as the
core count increases, both over the baseline and over the DWARFLinker
implementation.

Assisted-by: Gemini
---
 .../clang-doc/ConcurrentStringPool.h          | 174 ++++++++++++++++++
 clang-tools-extra/clang-doc/Representation.h  |  36 +---
 .../benchmarks/ClangDocBenchmark.cpp          |  57 ++++++
 .../unittests/clang-doc/CMakeLists.txt        |   1 +
 .../clang-doc/ConcurrentStringPoolTest.cpp    | 154 ++++++++++++++++
 5 files changed, 389 insertions(+), 33 deletions(-)
 create mode 100644 clang-tools-extra/clang-doc/ConcurrentStringPool.h
 create mode 100644 
clang-tools-extra/unittests/clang-doc/ConcurrentStringPoolTest.cpp

diff --git a/clang-tools-extra/clang-doc/ConcurrentStringPool.h 
b/clang-tools-extra/clang-doc/ConcurrentStringPool.h
new file mode 100644
index 00000000000000..85339fe88d93e4
--- /dev/null
+++ b/clang-tools-extra/clang-doc/ConcurrentStringPool.h
@@ -0,0 +1,174 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file defines ConcurrentStringPool, a lock-free deduplicating string
+/// saver for clang-doc.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_DOC_CONCURRENTSTRINGPOOL_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_DOC_CONCURRENTSTRINGPOOL_H
+
+#include "llvm/ADT/LazyAtomicPointer.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/PerThreadBumpPtrAllocator.h"
+#include "llvm/Support/xxhash.h"
+
+#include <array>
+#include <cassert>
+#include <cstddef>
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <string>
+
+namespace clang {
+namespace doc {
+
+/// A thread-safe string pool that deduplicates strings into a
+/// PerThreadBumpPtrAllocator.
+///
+/// Keys are sharded by the upper bits of their hash. Each shard holds an array
+/// with a power-of-two number of slabs which are allocated on demand via
+/// LazyAtomicPointer. Lookups probe a small window in each slab and move to
+/// the next level when the window is full, avoiding locks and table rehashing.
+///
+/// \tparam ShardBits Number of upper hash bits used to select a shard (1..31).
+/// \tparam InitialSlabCapacity Power-of-two capacity of level 0.
+/// \tparam ProbeWindow Linear probe window per level (1..InitialSlabCapacity).
+/// \tparam NumLevels Number of doubling slab levels per shard; the largest
+///   slab (InitialSlabCapacity << (NumLevels - 1)) must not exceed
+///   2^(32 - ShardBits), the bits of ProbeHash not consumed by ShardBits.
+template <size_t ShardBits = 10, uint32_t InitialSlabCapacity = 256,
+          uint32_t ProbeWindow = 8, size_t NumLevels = 15>
+class ConcurrentStringPoolImpl {
+  static_assert(ShardBits > 0 && ShardBits < 32,
+                "ShardBits must be between 1 and 31");
+  static_assert(llvm::isPowerOf2_32(InitialSlabCapacity),
+                "InitialSlabCapacity must be a power of two");
+  static_assert(ProbeWindow > 0 && ProbeWindow <= InitialSlabCapacity,
+                "ProbeWindow must fit within InitialSlabCapacity");
+  static_assert(NumLevels > 0 && NumLevels < 32,
+                "NumLevels must be between 1 and 31");
+
+  static constexpr size_t NumShards = 1ULL << ShardBits;
+  static constexpr size_t ProbeBits = 32 - ShardBits;
+  static constexpr uint64_t MaxSlabCapacity = 1ULL << ProbeBits;
+  static constexpr uint64_t LargestSlabCapacity = uint64_t(InitialSlabCapacity)
+                                                  << (NumLevels - 1);
+  static constexpr size_t CacheLineBytes = 64;
+
+  static_assert(LargestSlabCapacity <= MaxSlabCapacity,
+                "Slab capacity must not overlap ShardBits");
+
+  // Store Size and Hash alongside Data so probe mismatches don't chase the
+  // string pointer into the arena.
+  struct Bucket {
+    llvm::LazyAtomicPointer<const char> Data;
+    uint32_t Size = 0;
+    uint32_t Hash = 0;
+  };
+  static_assert(sizeof(Bucket) <= CacheLineBytes / 4,
+                "a cache line should fit at least 4 Buckets");
+
+  // Align shards to cache lines to avoid false sharing.
+  struct alignas(CacheLineBytes) Shard {
+    std::array<llvm::LazyAtomicPointer<Bucket>, NumLevels> Slabs{};
+
+    ~Shard() {
+      for (llvm::LazyAtomicPointer<Bucket> &SlabPtr : Slabs)
+        delete[] SlabPtr.load();
+    }
+  };
+
+public:
+  ConcurrentStringPoolImpl() = default;
+  ~ConcurrentStringPoolImpl() = default;
+
+  ConcurrentStringPoolImpl(const ConcurrentStringPoolImpl &) = delete;
+  ConcurrentStringPoolImpl &
+  operator=(const ConcurrentStringPoolImpl &) = delete;
+
+  /// Save string \p S in the arena.
+  /// \return a reference to the interned string.
+  llvm::StringRef save(const char *S) { return save(llvm::StringRef(S)); }
+
+  llvm::StringRef save(const std::string &S) {
+    return save(llvm::StringRef(S));
+  }
+
+  llvm::StringRef save(const llvm::Twine &S) {
+    if (S.isTriviallyEmpty())
+      return llvm::StringRef();
+    if (S.isSingleStringRef())
+      return save(S.getSingleStringRef());
+    return saveTwineSlow(S);
+  }
+
+  llvm::StringRef save(llvm::StringRef S) {
+    if (S.empty())
+      return llvm::StringRef();
+    return insert(S);
+  }
+
+private:
+  LLVM_ATTRIBUTE_NOINLINE llvm::StringRef saveTwineSlow(const llvm::Twine &S) {
+    llvm::SmallString<128> Storage;
+    S.toVector(Storage);
+    return save(llvm::StringRef(Storage.data(), Storage.size()));
+  }
+
+  llvm::StringRef insert(llvm::StringRef S) {
+    assert(S.size() <= std::numeric_limits<uint32_t>::max() &&
+           "String exceeds 32-bit size limit");
+
+    // Hash the string and select the shard.
+    uint64_t Hash = llvm::xxh3_64bits(S);
+    uint32_t HashTag = static_cast<uint32_t>(Hash);
+    uint32_t ProbeHash = static_cast<uint32_t>(Hash >> 32);
+    Shard &Sh = (*Shards)[Hash >> (64 - ShardBits)];
+
+    // Find the right bucket in the shard to intern into via probing.
+    for (size_t Level = 0; Level < NumLevels; ++Level) {
+      uint32_t SlabCapacity = InitialSlabCapacity << Level;
+      Bucket *CurSlab = &Sh.Slabs[Level].loadOrGenerate(
+          [SlabCapacity] { return new Bucket[SlabCapacity](); });
+      uint32_t Mask = SlabCapacity - 1;
+      uint32_t StartIdx = ProbeHash & Mask;
+      for (uint32_t P = 0; P < ProbeWindow; ++P) {
+        Bucket &B = CurSlab[(StartIdx + P) & Mask];
+        const char &First = B.Data.loadOrGenerate([&] {
+          B.Size = static_cast<uint32_t>(S.size());
+          B.Hash = HashTag;
+          return S.copy(Allocator).data();
+        });
+        llvm::StringRef Entry(&First, B.Size);
+        if (LLVM_LIKELY(B.Hash == HashTag && Entry == S))
+          return Entry;
+      }
+    }
+    llvm_unreachable("ConcurrentStringPool capacity exhausted");
+  }
+
+  using ShardArray = std::array<Shard, NumShards>;
+  std::unique_ptr<ShardArray> Shards = std::make_unique<ShardArray>();
+  llvm::parallel::PerThreadBumpPtrAllocator Allocator;
+};
+
+using ConcurrentStringPool = ConcurrentStringPoolImpl<>;
+
+} // namespace doc
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_DOC_CONCURRENTSTRINGPOOL_H
diff --git a/clang-tools-extra/clang-doc/Representation.h 
b/clang-tools-extra/clang-doc/Representation.h
index 74ac26442018f8..030156188e8112 100644
--- a/clang-tools-extra/clang-doc/Representation.h
+++ b/clang-tools-extra/clang-doc/Representation.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_DOC_REPRESENTATION_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_DOC_REPRESENTATION_H
 
+#include "ConcurrentStringPool.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/Specifiers.h"
@@ -24,8 +25,7 @@
 #include "llvm/ADT/simple_ilist.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Casting.h"
-#include "llvm/Support/Mutex.h"
-#include "llvm/Support/StringSaver.h"
+
 #include <array>
 #include <memory>
 #include <optional>
@@ -34,43 +34,13 @@
 namespace clang {
 namespace doc {
 
-class ConcurrentStringPool {
-public:
-  StringRef intern(StringRef Name) {
-    if (Name.empty())
-      return StringRef();
-
-    llvm::sys::SmartScopedLock<true> Lock(PoolMutex);
-    return Saver.save(Name);
-  }
-
-private:
-  llvm::sys::SmartMutex<true> PoolMutex;
-  llvm::BumpPtrAllocator Alloc;
-  llvm::UniqueStringSaver Saver{Alloc};
-};
-
 ConcurrentStringPool &getGlobalStringPool();
 
 llvm::BumpPtrAllocator &getTransientArena();
 llvm::BumpPtrAllocator &getPersistentArena();
 
 inline StringRef internString(const Twine &T) {
-  if (T.isTriviallyEmpty())
-    return StringRef();
-
-  if (T.isSingleStringRef()) {
-    StringRef S = T.getSingleStringRef();
-    if (S.empty())
-      return StringRef();
-    return getGlobalStringPool().intern(S);
-  }
-
-  SmallString<128> Buffer;
-  StringRef S = T.toStringRef(Buffer);
-  if (S.empty())
-    return StringRef();
-  return getGlobalStringPool().intern(S);
+  return getGlobalStringPool().save(T);
 }
 
 template <typename T>
diff --git a/clang-tools-extra/clang-doc/benchmarks/ClangDocBenchmark.cpp 
b/clang-tools-extra/clang-doc/benchmarks/ClangDocBenchmark.cpp
index 79f5f2315a94a5..2c431177b230b9 100644
--- a/clang-tools-extra/clang-doc/benchmarks/ClangDocBenchmark.cpp
+++ b/clang-tools-extra/clang-doc/benchmarks/ClangDocBenchmark.cpp
@@ -24,6 +24,8 @@
 #include "clang/Tooling/Execution.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/Bitstream/BitstreamWriter.h"
+#include <memory>
+#include <random>
 #include <string>
 #include <vector>
 
@@ -228,6 +230,61 @@ static void BM_Index_Insertion(benchmark::State &State) {
 }
 BENCHMARK(BM_Index_Insertion)->Range(10, 10000);
 
+// --- String Pool Benchmarks ---
+
+static std::unique_ptr<ConcurrentStringPool> &getBenchmarkStringPool() {
+  static std::unique_ptr<ConcurrentStringPool> Pool;
+  return Pool;
+}
+
+static const std::vector<llvm::StringRef> &getBenchmarkTrace() {
+  static const std::vector<std::string> Corpus = [] {
+    constexpr size_t NumUniqueStrings = 1 << 18;
+    std::vector<std::string> V(NumUniqueStrings);
+    for (size_t I = 0; I < V.size(); ++I)
+      V[I] = "/usr/local/include/clang/AST/Decl_" + std::to_string(I) + ".h";
+    return V;
+  }();
+
+  static const std::vector<llvm::StringRef> Trace = [] {
+    constexpr size_t NumHotStrings = 64;
+    constexpr size_t TraceSize = 1 << 20;
+    std::minstd_rand Rng;
+    std::bernoulli_distribution IsHot(0.8);
+    std::uniform_int_distribution<size_t> HotDist(0, NumHotStrings - 1);
+    std::uniform_int_distribution<size_t> ColdDist(0, Corpus.size() - 1);
+
+    std::vector<llvm::StringRef> T(TraceSize);
+    for (llvm::StringRef &S : T)
+      S = Corpus[IsHot(Rng) ? HotDist(Rng) : ColdDist(Rng)];
+    return T;
+  }();
+  return Trace;
+}
+
+static void BM_StringPool_ConcurrentStringPool(benchmark::State &State) {
+  auto &SharedPool = *getBenchmarkStringPool();
+  const auto &Trace = getBenchmarkTrace();
+  const size_t Mask = Trace.size() - 1;
+  size_t Idx = State.thread_index() * (Trace.size() / State.threads());
+
+  for (auto _ : State) {
+    llvm::StringRef Res = SharedPool.save(Trace[Idx & Mask]);
+    benchmark::DoNotOptimize(Res);
+    ++Idx;
+  }
+}
+
+BENCHMARK(BM_StringPool_ConcurrentStringPool)
+    ->ThreadRange(1, 128)
+    ->UseRealTime()
+    ->Setup([](const benchmark::State &) {
+      getBenchmarkStringPool() = std::make_unique<ConcurrentStringPool>();
+    })
+    ->Teardown([](const benchmark::State &) {
+      getBenchmarkStringPool().reset();
+    });
+
 } // namespace doc
 } // namespace clang
 
diff --git a/clang-tools-extra/unittests/clang-doc/CMakeLists.txt 
b/clang-tools-extra/unittests/clang-doc/CMakeLists.txt
index dc5110bffb9aee..d144bd023ae98c 100644
--- a/clang-tools-extra/unittests/clang-doc/CMakeLists.txt
+++ b/clang-tools-extra/unittests/clang-doc/CMakeLists.txt
@@ -24,6 +24,7 @@ include_directories(
 add_extra_unittest(ClangDocTests
   BitcodeTest.cpp
   ClangDocTest.cpp
+  ConcurrentStringPoolTest.cpp
   GeneratorTest.cpp
   HTMLGeneratorTest.cpp
   MergeTest.cpp
diff --git a/clang-tools-extra/unittests/clang-doc/ConcurrentStringPoolTest.cpp 
b/clang-tools-extra/unittests/clang-doc/ConcurrentStringPoolTest.cpp
new file mode 100644
index 00000000000000..c23547ace367d7
--- /dev/null
+++ b/clang-tools-extra/unittests/clang-doc/ConcurrentStringPoolTest.cpp
@@ -0,0 +1,154 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Unit tests for clang::doc::ConcurrentStringPool.
+///
+//===----------------------------------------------------------------------===//
+
+#include "ConcurrentStringPool.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/Parallel.h"
+#include "gtest/gtest.h"
+#include <string>
+#include <vector>
+
+using namespace llvm;
+using namespace clang::doc;
+
+namespace {
+
+TEST(ConcurrentStringPoolTest, SaveOverloadsAndEmpty) {
+  ConcurrentStringPool Pool;
+
+  EXPECT_TRUE(Pool.save("").empty());
+  EXPECT_TRUE(Pool.save(StringRef()).empty());
+  EXPECT_TRUE(Pool.save(std::string()).empty());
+  EXPECT_TRUE(Pool.save(Twine()).empty());
+  EXPECT_TRUE(Pool.save(Twine("")).empty());
+  EXPECT_TRUE(Pool.save(Twine("") + Twine("")).empty());
+
+  const char *CStr = "hello_world";
+  std::string StdStr = "hello_world";
+  StringRef RefStr = "hello_world";
+
+  StringRef SavedCStr = Pool.save(CStr);
+  StringRef SavedStd = Pool.save(StdStr);
+  StringRef SavedRef = Pool.save(RefStr);
+  StringRef SavedSingleTwine = Pool.save(Twine(RefStr));
+  StringRef SavedConcatTwine = Pool.save(Twine("hello_") + "world");
+
+  EXPECT_EQ(SavedCStr, "hello_world");
+  EXPECT_EQ(SavedStd.data(), SavedCStr.data());
+  EXPECT_EQ(SavedRef.data(), SavedCStr.data());
+  EXPECT_EQ(SavedSingleTwine.data(), SavedCStr.data());
+  EXPECT_EQ(SavedConcatTwine.data(), SavedCStr.data());
+}
+
+TEST(ConcurrentStringPoolTest, AddStringEntries) {
+  ConcurrentStringPool Pool;
+
+  StringRef Res1 = Pool.save("1");
+  EXPECT_EQ(Res1, "1");
+
+  StringRef Res2 = Pool.save("2");
+  EXPECT_EQ(Res1, "1");
+  EXPECT_EQ(Res2, "2");
+  EXPECT_NE(Res1.data(), Res2.data());
+
+  StringRef Res3 = Pool.save("3");
+  EXPECT_EQ(Res3, "3");
+  EXPECT_NE(Res1.data(), Res3.data());
+  EXPECT_NE(Res2.data(), Res3.data());
+
+  StringRef Res4 = Pool.save("1");
+  EXPECT_EQ(Res4, "1");
+  EXPECT_EQ(Res1.data(), Res4.data());
+}
+
+TEST(ConcurrentStringPoolTest, EmbeddedNulls) {
+  ConcurrentStringPool Pool;
+
+  StringRef WithNull1("foo\0bar", 7);
+  StringRef WithNull2("foo\0baz", 7);
+  StringRef Prefix("foo", 3);
+
+  StringRef Saved1 = Pool.save(WithNull1);
+  StringRef Saved2 = Pool.save(WithNull2);
+  StringRef SavedPrefix = Pool.save(Prefix);
+
+  EXPECT_EQ(Saved1.size(), 7u);
+  EXPECT_EQ(Saved1, WithNull1);
+  EXPECT_EQ(Saved2, WithNull2);
+  EXPECT_EQ(SavedPrefix, Prefix);
+  EXPECT_NE(Saved1.data(), Saved2.data());
+  EXPECT_NE(Saved1.data(), SavedPrefix.data());
+  EXPECT_EQ(Pool.save(WithNull1).data(), Saved1.data());
+  EXPECT_EQ(Pool.save(WithNull2).data(), Saved2.data());
+}
+
+TEST(ConcurrentStringPoolTest, AddStringMultipleEntriesWithSlabGrowth) {
+  ConcurrentStringPoolImpl<1, 8, 2> Pool;
+  constexpr size_t NumElements = 500;
+  std::vector<StringRef> Inserted(NumElements);
+
+  for (size_t I = 0; I < NumElements; ++I) {
+    std::string S = formatv("{0} {1}", I, I + 100);
+    Inserted[I] = Pool.save(S);
+    EXPECT_EQ(Inserted[I], S);
+  }
+
+  for (size_t I = 0; I < NumElements; ++I) {
+    std::string S = formatv("{0} {1}", I, I + 100);
+    StringRef Dup = Pool.save(S);
+    EXPECT_EQ(Dup, S);
+    EXPECT_EQ(Dup.data(), Inserted[I].data());
+  }
+}
+
+TEST(ConcurrentStringPoolTest, AddStringEntriesParallel) {
+  ConcurrentStringPool Pool;
+  constexpr size_t NumElements = 10000;
+  std::vector<StringRef> Inserted(NumElements);
+
+  parallelFor(0, NumElements, [&](size_t I) {
+    std::string S = formatv("{0}", I);
+    StringRef Entry = Pool.save(S);
+    EXPECT_EQ(Entry, S);
+    Inserted[I] = Entry;
+  });
+
+  parallelFor(0, NumElements, [&](size_t I) {
+    std::string S = formatv("{0}", I);
+    StringRef Entry = Pool.save(S);
+    EXPECT_EQ(Entry, S);
+    EXPECT_EQ(Entry.data(), Inserted[I].data());
+  });
+}
+
+TEST(ConcurrentStringPoolTest, AddStringEntriesParallelWithSlabGrowth) {
+  ConcurrentStringPoolImpl<6, 8, 2> Pool;
+  constexpr size_t NumElements = 4000;
+  std::vector<StringRef> Inserted(NumElements);
+
+  parallelFor(0, NumElements, [&](size_t I) {
+    std::string S = formatv("{0}", I);
+    StringRef Entry = Pool.save(S);
+    EXPECT_EQ(Entry, S);
+    Inserted[I] = Entry;
+  });
+
+  parallelFor(0, NumElements, [&](size_t I) {
+    std::string S = formatv("{0}", I);
+    StringRef Entry = Pool.save(S);
+    EXPECT_EQ(Entry, S);
+    EXPECT_EQ(Entry.data(), Inserted[I].data());
+  });
+}
+
+} // namespace

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to