Fix assertion in SmallDenseMap constructor with reserve from non-power-of-2 buckets...
authorVladislav Dzhidzhoev <vdzhidzhoev@accesssoftek.com>
Mon, 25 Jul 2022 16:39:46 +0000 (16:39 +0000)
committerDavid Blaikie <dblaikie@gmail.com>
Mon, 25 Jul 2022 17:09:44 +0000 (17:09 +0000)
`SmallDenseMap` constructor with reserve gets an arbitrary `NumInitBuckets` value and passes it below to `init` method.

If `NumInitBuckets` is greater then `InlineBuckets`, then `SmallDenseMap` initializes to large representation passing `NumInitBuckets` below to `DenseMap` initialization. `DenseMap::initEmpty` method asserts that initial buckets count must be a power of 2.

Proposed solution is to update `NumInitBuckets` value in `SmallDenseMap` constructor till the next power of 2. It should satisfy both `DenseMap` preconditions and required minimum buckets count for reservation.

Reviewed By: atrick

Differential Revision: https://reviews.llvm.org/D129825

llvm/include/llvm/ADT/DenseMap.h
llvm/unittests/ADT/DenseMapTest.cpp

index c14414c..a6d19d3 100644 (file)
@@ -907,6 +907,8 @@ class SmallDenseMap
 
 public:
   explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
+    if (NumInitBuckets > InlineBuckets)
+      NumInitBuckets = NextPowerOf2(NumInitBuckets - 1);
     init(NumInitBuckets);
   }
 
index 4dd314c..619ddb0 100644 (file)
@@ -607,6 +607,15 @@ TEST(DenseMapCustomTest, LargeSmallDenseMapCompaction) {
   EXPECT_TRUE(map.find(0) == map.end());
 }
 
+TEST(DenseMapCustomTest, SmallDenseMapWithNumBucketsNonPowerOf2) {
+  // Is not power of 2.
+  const unsigned NumInitBuckets = 33;
+  // Power of 2 less then NumInitBuckets.
+  constexpr unsigned InlineBuckets = 4;
+  // Constructor should not trigger assert.
+  SmallDenseMap<int, int, InlineBuckets> map(NumInitBuckets);
+}
+
 TEST(DenseMapCustomTest, TryEmplaceTest) {
   DenseMap<int, std::unique_ptr<int>> Map;
   std::unique_ptr<int> P(new int(2));