[llvm] dde9477 - [NFC] Use unique_ptr in SparseSet (#116617)

via llvm-commits llvm-commits at lists.llvm.org
Fri Nov 22 03:25:00 PST 2024


Author: Akshat Oke
Date: 2024-11-22T16:54:56+05:30
New Revision: dde9477d8c0b85d445f10b08b0120f3d361cb77f

URL: https://github.com/llvm/llvm-project/commit/dde9477d8c0b85d445f10b08b0120f3d361cb77f
DIFF: https://github.com/llvm/llvm-project/commit/dde9477d8c0b85d445f10b08b0120f3d361cb77f.diff

LOG: [NFC] Use unique_ptr in SparseSet (#116617)

This allows implementing the move constructor.

Added: 
    

Modified: 
    llvm/include/llvm/ADT/SparseSet.h
    llvm/unittests/ADT/SparseSetTest.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/SparseSet.h b/llvm/include/llvm/ADT/SparseSet.h
index c7793117ff5408..d9ded9875d3779 100644
--- a/llvm/include/llvm/ADT/SparseSet.h
+++ b/llvm/include/llvm/ADT/SparseSet.h
@@ -129,7 +129,12 @@ class SparseSet {
   using DenseT = SmallVector<ValueT, 8>;
   using size_type = unsigned;
   DenseT Dense;
-  SparseT *Sparse = nullptr;
+
+  struct Deleter {
+    void operator()(SparseT *S) { free(S); }
+  };
+  std::unique_ptr<SparseT[], Deleter> Sparse;
+
   unsigned Universe = 0;
   KeyFunctorT KeyIndexOf;
   SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
@@ -144,7 +149,7 @@ class SparseSet {
   SparseSet() = default;
   SparseSet(const SparseSet &) = delete;
   SparseSet &operator=(const SparseSet &) = delete;
-  ~SparseSet() { free(Sparse); }
+  SparseSet(SparseSet &&) = default;
 
   /// setUniverse - Set the universe size which determines the largest key the
   /// set can hold.  The universe must be sized before any elements can be
@@ -159,11 +164,10 @@ class SparseSet {
     // Hysteresis prevents needless reallocations.
     if (U >= Universe/4 && U <= Universe)
       return;
-    free(Sparse);
     // The Sparse array doesn't actually need to be initialized, so malloc
     // would be enough here, but that will cause tools like valgrind to
     // complain about branching on uninitialized data.
-    Sparse = static_cast<SparseT*>(safe_calloc(U, sizeof(SparseT)));
+    Sparse.reset(static_cast<SparseT *>(safe_calloc(U, sizeof(SparseT))));
     Universe = U;
   }
 

diff  --git a/llvm/unittests/ADT/SparseSetTest.cpp b/llvm/unittests/ADT/SparseSetTest.cpp
index 3eea4bde8c07cc..4fbf1caa247b79 100644
--- a/llvm/unittests/ADT/SparseSetTest.cpp
+++ b/llvm/unittests/ADT/SparseSetTest.cpp
@@ -204,4 +204,16 @@ TEST(SparseSetTest, PopBack) {
   for (unsigned i = 0; i < UpperBound; ++i)
     ASSERT_TRUE(Set.insert(i).second);
 }
+
+TEST(SparseSetTest, MoveConstructor) {
+  USet Set;
+  Set.setUniverse(2);
+  Set.insert(1);
+  EXPECT_FALSE(Set.empty());
+  // Move and check original is empty.
+  USet OtherSet(std::move(Set));
+  EXPECT_TRUE(Set.empty());
+  EXPECT_TRUE(OtherSet.contains(1));
+}
+
 } // namespace


        


More information about the llvm-commits mailing list