[llvm] [ADT] Reduce memory allocation in SmallPtrSet::reserve() (PR #153126)

via llvm-commits llvm-commits at lists.llvm.org
Mon Aug 11 19:58:12 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-adt

Author: Kazu Hirata (kazutakahirata)

<details>
<summary>Changes</summary>

Previously, reserve() allocated double the required number of buckets.
For example, for NumEntries in the range [49, 96], it would reserve
256 buckets when only 128 are needed to maintain the load factor.

This patch removes "+ 1" in the NewSize calculation.


---
Full diff: https://github.com/llvm/llvm-project/pull/153126.diff


2 Files Affected:

- (modified) llvm/include/llvm/ADT/SmallPtrSet.h (+1-1) 
- (modified) llvm/unittests/ADT/SmallPtrSetTest.cpp (+4) 


``````````diff
diff --git a/llvm/include/llvm/ADT/SmallPtrSet.h b/llvm/include/llvm/ADT/SmallPtrSet.h
index f0f28ac37761e..28a217afcd0a2 100644
--- a/llvm/include/llvm/ADT/SmallPtrSet.h
+++ b/llvm/include/llvm/ADT/SmallPtrSet.h
@@ -129,7 +129,7 @@ class SmallPtrSetImplBase : public DebugEpochBase {
     // We must Grow -- find the size where we'd be 75% full, then round up to
     // the next power of two.
     size_type NewSize = NumEntries + (NumEntries / 3);
-    NewSize = 1 << (Log2_32_Ceil(NewSize) + 1);
+    NewSize = 1 << Log2_32_Ceil(NewSize);
     // Like insert_imp_big, always allocate at least 128 elements.
     NewSize = std::max(128u, NewSize);
     Grow(NewSize);
diff --git a/llvm/unittests/ADT/SmallPtrSetTest.cpp b/llvm/unittests/ADT/SmallPtrSetTest.cpp
index 4ea7403b65abc..a627091b90c70 100644
--- a/llvm/unittests/ADT/SmallPtrSetTest.cpp
+++ b/llvm/unittests/ADT/SmallPtrSetTest.cpp
@@ -475,4 +475,8 @@ TEST(SmallPtrSetTest, Reserve) {
   EXPECT_EQ(Set.capacity(), 128u);
   EXPECT_EQ(Set.size(), 6u);
   EXPECT_THAT(Set, UnorderedElementsAre(&Vals[0], &Vals[1], &Vals[2], &Vals[3], &Vals[4], &Vals[5]));
+
+  // Reserving 192 should result in 256 buckets.
+  Set.reserve(192);
+  EXPECT_EQ(Set.capacity(), 256u);
 }

``````````

</details>


https://github.com/llvm/llvm-project/pull/153126


More information about the llvm-commits mailing list