1 //===- llvm/unittest/ADT/DenseMapMap.cpp - DenseMap unit tests --*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/ADT/DenseMap.h" 10 #include "llvm/ADT/DenseMapInfo.h" 11 #include "llvm/ADT/DenseMapInfoVariant.h" 12 #include "gmock/gmock.h" 13 #include "gtest/gtest.h" 14 #include <map> 15 #include <set> 16 #include <utility> 17 #include <variant> 18 19 using namespace llvm; 20 21 namespace { 22 23 uint32_t getTestKey(int i, uint32_t *) { return i; } 24 uint32_t getTestValue(int i, uint32_t *) { return 42 + i; } 25 26 uint32_t *getTestKey(int i, uint32_t **) { 27 static uint32_t dummy_arr1[8192]; 28 assert(i < 8192 && "Only support 8192 dummy keys."); 29 return &dummy_arr1[i]; 30 } 31 uint32_t *getTestValue(int i, uint32_t **) { 32 static uint32_t dummy_arr1[8192]; 33 assert(i < 8192 && "Only support 8192 dummy keys."); 34 return &dummy_arr1[i]; 35 } 36 37 /// A test class that tries to check that construction and destruction 38 /// occur correctly. 39 class CtorTester { 40 static std::set<CtorTester *> Constructed; 41 int Value; 42 43 public: 44 explicit CtorTester(int Value = 0) : Value(Value) { 45 EXPECT_TRUE(Constructed.insert(this).second); 46 } 47 CtorTester(uint32_t Value) : Value(Value) { 48 EXPECT_TRUE(Constructed.insert(this).second); 49 } 50 CtorTester(const CtorTester &Arg) : Value(Arg.Value) { 51 EXPECT_TRUE(Constructed.insert(this).second); 52 } 53 CtorTester &operator=(const CtorTester &) = default; 54 ~CtorTester() { 55 EXPECT_EQ(1u, Constructed.erase(this)); 56 } 57 operator uint32_t() const { return Value; } 58 59 int getValue() const { return Value; } 60 bool operator==(const CtorTester &RHS) const { return Value == RHS.Value; } 61 }; 62 63 std::set<CtorTester *> CtorTester::Constructed; 64 65 struct CtorTesterMapInfo { 66 static inline CtorTester getEmptyKey() { return CtorTester(-1); } 67 static inline CtorTester getTombstoneKey() { return CtorTester(-2); } 68 static unsigned getHashValue(const CtorTester &Val) { 69 return Val.getValue() * 37u; 70 } 71 static bool isEqual(const CtorTester &LHS, const CtorTester &RHS) { 72 return LHS == RHS; 73 } 74 }; 75 76 CtorTester getTestKey(int i, CtorTester *) { return CtorTester(i); } 77 CtorTester getTestValue(int i, CtorTester *) { return CtorTester(42 + i); } 78 79 // Test fixture, with helper functions implemented by forwarding to global 80 // function overloads selected by component types of the type parameter. This 81 // allows all of the map implementations to be tested with shared 82 // implementations of helper routines. 83 template <typename T> 84 class DenseMapTest : public ::testing::Test { 85 protected: 86 T Map; 87 88 static typename T::key_type *const dummy_key_ptr; 89 static typename T::mapped_type *const dummy_value_ptr; 90 91 typename T::key_type getKey(int i = 0) { 92 return getTestKey(i, dummy_key_ptr); 93 } 94 typename T::mapped_type getValue(int i = 0) { 95 return getTestValue(i, dummy_value_ptr); 96 } 97 }; 98 99 template <typename T> 100 typename T::key_type *const DenseMapTest<T>::dummy_key_ptr = nullptr; 101 template <typename T> 102 typename T::mapped_type *const DenseMapTest<T>::dummy_value_ptr = nullptr; 103 104 // Register these types for testing. 105 typedef ::testing::Types<DenseMap<uint32_t, uint32_t>, 106 DenseMap<uint32_t *, uint32_t *>, 107 DenseMap<CtorTester, CtorTester, CtorTesterMapInfo>, 108 SmallDenseMap<uint32_t, uint32_t>, 109 SmallDenseMap<uint32_t *, uint32_t *>, 110 SmallDenseMap<CtorTester, CtorTester, 4, 111 CtorTesterMapInfo> 112 > DenseMapTestTypes; 113 TYPED_TEST_SUITE(DenseMapTest, DenseMapTestTypes, ); 114 115 // Empty map tests 116 TYPED_TEST(DenseMapTest, EmptyIntMapTest) { 117 // Size tests 118 EXPECT_EQ(0u, this->Map.size()); 119 EXPECT_TRUE(this->Map.empty()); 120 121 // Iterator tests 122 EXPECT_TRUE(this->Map.begin() == this->Map.end()); 123 124 // Lookup tests 125 EXPECT_FALSE(this->Map.count(this->getKey())); 126 EXPECT_FALSE(this->Map.contains(this->getKey())); 127 EXPECT_TRUE(this->Map.find(this->getKey()) == this->Map.end()); 128 EXPECT_EQ(typename TypeParam::mapped_type(), 129 this->Map.lookup(this->getKey())); 130 } 131 132 // Constant map tests 133 TYPED_TEST(DenseMapTest, ConstEmptyMapTest) { 134 const TypeParam &ConstMap = this->Map; 135 EXPECT_EQ(0u, ConstMap.size()); 136 EXPECT_TRUE(ConstMap.empty()); 137 EXPECT_TRUE(ConstMap.begin() == ConstMap.end()); 138 } 139 140 // A map with a single entry 141 TYPED_TEST(DenseMapTest, SingleEntryMapTest) { 142 this->Map[this->getKey()] = this->getValue(); 143 144 // Size tests 145 EXPECT_EQ(1u, this->Map.size()); 146 EXPECT_FALSE(this->Map.begin() == this->Map.end()); 147 EXPECT_FALSE(this->Map.empty()); 148 149 // Iterator tests 150 typename TypeParam::iterator it = this->Map.begin(); 151 EXPECT_EQ(this->getKey(), it->first); 152 EXPECT_EQ(this->getValue(), it->second); 153 ++it; 154 EXPECT_TRUE(it == this->Map.end()); 155 156 // Lookup tests 157 EXPECT_TRUE(this->Map.count(this->getKey())); 158 EXPECT_TRUE(this->Map.contains(this->getKey())); 159 EXPECT_TRUE(this->Map.find(this->getKey()) == this->Map.begin()); 160 EXPECT_EQ(this->getValue(), this->Map.lookup(this->getKey())); 161 EXPECT_EQ(this->getValue(), this->Map[this->getKey()]); 162 } 163 164 TYPED_TEST(DenseMapTest, AtTest) { 165 this->Map[this->getKey(0)] = this->getValue(0); 166 this->Map[this->getKey(1)] = this->getValue(1); 167 this->Map[this->getKey(2)] = this->getValue(2); 168 EXPECT_EQ(this->getValue(0), this->Map.at(this->getKey(0))); 169 EXPECT_EQ(this->getValue(1), this->Map.at(this->getKey(1))); 170 EXPECT_EQ(this->getValue(2), this->Map.at(this->getKey(2))); 171 } 172 173 // Test clear() method 174 TYPED_TEST(DenseMapTest, ClearTest) { 175 this->Map[this->getKey()] = this->getValue(); 176 this->Map.clear(); 177 178 EXPECT_EQ(0u, this->Map.size()); 179 EXPECT_TRUE(this->Map.empty()); 180 EXPECT_TRUE(this->Map.begin() == this->Map.end()); 181 } 182 183 // Test erase(iterator) method 184 TYPED_TEST(DenseMapTest, EraseTest) { 185 this->Map[this->getKey()] = this->getValue(); 186 this->Map.erase(this->Map.begin()); 187 188 EXPECT_EQ(0u, this->Map.size()); 189 EXPECT_TRUE(this->Map.empty()); 190 EXPECT_TRUE(this->Map.begin() == this->Map.end()); 191 } 192 193 // Test erase(value) method 194 TYPED_TEST(DenseMapTest, EraseTest2) { 195 this->Map[this->getKey()] = this->getValue(); 196 this->Map.erase(this->getKey()); 197 198 EXPECT_EQ(0u, this->Map.size()); 199 EXPECT_TRUE(this->Map.empty()); 200 EXPECT_TRUE(this->Map.begin() == this->Map.end()); 201 } 202 203 // Test insert() method 204 TYPED_TEST(DenseMapTest, InsertTest) { 205 this->Map.insert(std::make_pair(this->getKey(), this->getValue())); 206 EXPECT_EQ(1u, this->Map.size()); 207 EXPECT_EQ(this->getValue(), this->Map[this->getKey()]); 208 } 209 210 // Test copy constructor method 211 TYPED_TEST(DenseMapTest, CopyConstructorTest) { 212 this->Map[this->getKey()] = this->getValue(); 213 TypeParam copyMap(this->Map); 214 215 EXPECT_EQ(1u, copyMap.size()); 216 EXPECT_EQ(this->getValue(), copyMap[this->getKey()]); 217 } 218 219 // Test copy constructor method where SmallDenseMap isn't small. 220 TYPED_TEST(DenseMapTest, CopyConstructorNotSmallTest) { 221 for (int Key = 0; Key < 5; ++Key) 222 this->Map[this->getKey(Key)] = this->getValue(Key); 223 TypeParam copyMap(this->Map); 224 225 EXPECT_EQ(5u, copyMap.size()); 226 for (int Key = 0; Key < 5; ++Key) 227 EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]); 228 } 229 230 // Test copying from a default-constructed map. 231 TYPED_TEST(DenseMapTest, CopyConstructorFromDefaultTest) { 232 TypeParam copyMap(this->Map); 233 234 EXPECT_TRUE(copyMap.empty()); 235 } 236 237 // Test copying from an empty map where SmallDenseMap isn't small. 238 TYPED_TEST(DenseMapTest, CopyConstructorFromEmptyTest) { 239 for (int Key = 0; Key < 5; ++Key) 240 this->Map[this->getKey(Key)] = this->getValue(Key); 241 this->Map.clear(); 242 TypeParam copyMap(this->Map); 243 244 EXPECT_TRUE(copyMap.empty()); 245 } 246 247 // Test assignment operator method 248 TYPED_TEST(DenseMapTest, AssignmentTest) { 249 this->Map[this->getKey()] = this->getValue(); 250 TypeParam copyMap = this->Map; 251 252 EXPECT_EQ(1u, copyMap.size()); 253 EXPECT_EQ(this->getValue(), copyMap[this->getKey()]); 254 255 // test self-assignment. 256 copyMap = static_cast<TypeParam &>(copyMap); 257 EXPECT_EQ(1u, copyMap.size()); 258 EXPECT_EQ(this->getValue(), copyMap[this->getKey()]); 259 } 260 261 TYPED_TEST(DenseMapTest, AssignmentTestNotSmall) { 262 for (int Key = 0; Key < 5; ++Key) 263 this->Map[this->getKey(Key)] = this->getValue(Key); 264 TypeParam copyMap = this->Map; 265 266 EXPECT_EQ(5u, copyMap.size()); 267 for (int Key = 0; Key < 5; ++Key) 268 EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]); 269 270 // test self-assignment. 271 copyMap = static_cast<TypeParam &>(copyMap); 272 EXPECT_EQ(5u, copyMap.size()); 273 for (int Key = 0; Key < 5; ++Key) 274 EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]); 275 } 276 277 // Test swap method 278 TYPED_TEST(DenseMapTest, SwapTest) { 279 this->Map[this->getKey()] = this->getValue(); 280 TypeParam otherMap; 281 282 this->Map.swap(otherMap); 283 EXPECT_EQ(0u, this->Map.size()); 284 EXPECT_TRUE(this->Map.empty()); 285 EXPECT_EQ(1u, otherMap.size()); 286 EXPECT_EQ(this->getValue(), otherMap[this->getKey()]); 287 288 this->Map.swap(otherMap); 289 EXPECT_EQ(0u, otherMap.size()); 290 EXPECT_TRUE(otherMap.empty()); 291 EXPECT_EQ(1u, this->Map.size()); 292 EXPECT_EQ(this->getValue(), this->Map[this->getKey()]); 293 294 // Make this more interesting by inserting 100 numbers into the map. 295 for (int i = 0; i < 100; ++i) 296 this->Map[this->getKey(i)] = this->getValue(i); 297 298 this->Map.swap(otherMap); 299 EXPECT_EQ(0u, this->Map.size()); 300 EXPECT_TRUE(this->Map.empty()); 301 EXPECT_EQ(100u, otherMap.size()); 302 for (int i = 0; i < 100; ++i) 303 EXPECT_EQ(this->getValue(i), otherMap[this->getKey(i)]); 304 305 this->Map.swap(otherMap); 306 EXPECT_EQ(0u, otherMap.size()); 307 EXPECT_TRUE(otherMap.empty()); 308 EXPECT_EQ(100u, this->Map.size()); 309 for (int i = 0; i < 100; ++i) 310 EXPECT_EQ(this->getValue(i), this->Map[this->getKey(i)]); 311 } 312 313 // A more complex iteration test 314 TYPED_TEST(DenseMapTest, IterationTest) { 315 bool visited[100]; 316 std::map<typename TypeParam::key_type, unsigned> visitedIndex; 317 318 // Insert 100 numbers into the map 319 for (int i = 0; i < 100; ++i) { 320 visited[i] = false; 321 visitedIndex[this->getKey(i)] = i; 322 323 this->Map[this->getKey(i)] = this->getValue(i); 324 } 325 326 // Iterate over all numbers and mark each one found. 327 for (typename TypeParam::iterator it = this->Map.begin(); 328 it != this->Map.end(); ++it) 329 visited[visitedIndex[it->first]] = true; 330 331 // Ensure every number was visited. 332 for (int i = 0; i < 100; ++i) 333 ASSERT_TRUE(visited[i]) << "Entry #" << i << " was never visited"; 334 } 335 336 // const_iterator test 337 TYPED_TEST(DenseMapTest, ConstIteratorTest) { 338 // Check conversion from iterator to const_iterator. 339 typename TypeParam::iterator it = this->Map.begin(); 340 typename TypeParam::const_iterator cit(it); 341 EXPECT_TRUE(it == cit); 342 343 // Check copying of const_iterators. 344 typename TypeParam::const_iterator cit2(cit); 345 EXPECT_TRUE(cit == cit2); 346 } 347 348 namespace { 349 // Simple class that counts how many moves and copy happens when growing a map 350 struct CountCopyAndMove { 351 static int Move; 352 static int Copy; 353 CountCopyAndMove() {} 354 355 CountCopyAndMove(const CountCopyAndMove &) { Copy++; } 356 CountCopyAndMove &operator=(const CountCopyAndMove &) { 357 Copy++; 358 return *this; 359 } 360 CountCopyAndMove(CountCopyAndMove &&) { Move++; } 361 CountCopyAndMove &operator=(const CountCopyAndMove &&) { 362 Move++; 363 return *this; 364 } 365 }; 366 int CountCopyAndMove::Copy = 0; 367 int CountCopyAndMove::Move = 0; 368 369 } // anonymous namespace 370 371 // Test initializer list construction. 372 TEST(DenseMapCustomTest, InitializerList) { 373 DenseMap<int, int> M({{0, 0}, {0, 1}, {1, 2}}); 374 EXPECT_EQ(2u, M.size()); 375 EXPECT_EQ(1u, M.count(0)); 376 EXPECT_EQ(0, M[0]); 377 EXPECT_EQ(1u, M.count(1)); 378 EXPECT_EQ(2, M[1]); 379 } 380 381 // Test initializer list construction. 382 TEST(DenseMapCustomTest, EqualityComparison) { 383 DenseMap<int, int> M1({{0, 0}, {1, 2}}); 384 DenseMap<int, int> M2({{0, 0}, {1, 2}}); 385 DenseMap<int, int> M3({{0, 0}, {1, 3}}); 386 387 EXPECT_EQ(M1, M2); 388 EXPECT_NE(M1, M3); 389 } 390 391 // Test for the default minimum size of a DenseMap 392 TEST(DenseMapCustomTest, DefaultMinReservedSizeTest) { 393 // IF THIS VALUE CHANGE, please update InitialSizeTest, InitFromIterator, and 394 // ReserveTest as well! 395 const int ExpectedInitialBucketCount = 64; 396 // Formula from DenseMap::getMinBucketToReserveForEntries() 397 const int ExpectedMaxInitialEntries = ExpectedInitialBucketCount * 3 / 4 - 1; 398 399 DenseMap<int, CountCopyAndMove> Map; 400 // Will allocate 64 buckets 401 Map.reserve(1); 402 unsigned MemorySize = Map.getMemorySize(); 403 CountCopyAndMove::Copy = 0; 404 CountCopyAndMove::Move = 0; 405 for (int i = 0; i < ExpectedMaxInitialEntries; ++i) 406 Map.insert(std::pair<int, CountCopyAndMove>(std::piecewise_construct, 407 std::forward_as_tuple(i), 408 std::forward_as_tuple())); 409 // Check that we didn't grow 410 EXPECT_EQ(MemorySize, Map.getMemorySize()); 411 // Check that move was called the expected number of times 412 EXPECT_EQ(ExpectedMaxInitialEntries, CountCopyAndMove::Move); 413 // Check that no copy occurred 414 EXPECT_EQ(0, CountCopyAndMove::Copy); 415 416 // Adding one extra element should grow the map 417 Map.insert(std::pair<int, CountCopyAndMove>( 418 std::piecewise_construct, 419 std::forward_as_tuple(ExpectedMaxInitialEntries), 420 std::forward_as_tuple())); 421 // Check that we grew 422 EXPECT_NE(MemorySize, Map.getMemorySize()); 423 // Check that move was called the expected number of times 424 // This relies on move-construction elision, and cannot be reliably tested. 425 // EXPECT_EQ(ExpectedMaxInitialEntries + 2, CountCopyAndMove::Move); 426 // Check that no copy occurred 427 EXPECT_EQ(0, CountCopyAndMove::Copy); 428 } 429 430 // Make sure creating the map with an initial size of N actually gives us enough 431 // buckets to insert N items without increasing allocation size. 432 TEST(DenseMapCustomTest, InitialSizeTest) { 433 // Test a few different sizes, 48 is *not* a random choice: we need a value 434 // that is 2/3 of a power of two to stress the grow() condition, and the power 435 // of two has to be at least 64 because of minimum size allocation in the 436 // DenseMap (see DefaultMinReservedSizeTest). 66 is a value just above the 437 // 64 default init. 438 for (auto Size : {1, 2, 48, 66}) { 439 DenseMap<int, CountCopyAndMove> Map(Size); 440 unsigned MemorySize = Map.getMemorySize(); 441 CountCopyAndMove::Copy = 0; 442 CountCopyAndMove::Move = 0; 443 for (int i = 0; i < Size; ++i) 444 Map.insert(std::pair<int, CountCopyAndMove>(std::piecewise_construct, 445 std::forward_as_tuple(i), 446 std::forward_as_tuple())); 447 // Check that we didn't grow 448 EXPECT_EQ(MemorySize, Map.getMemorySize()); 449 // Check that move was called the expected number of times 450 EXPECT_EQ(Size, CountCopyAndMove::Move); 451 // Check that no copy occurred 452 EXPECT_EQ(0, CountCopyAndMove::Copy); 453 } 454 } 455 456 // Make sure creating the map with a iterator range does not trigger grow() 457 TEST(DenseMapCustomTest, InitFromIterator) { 458 std::vector<std::pair<int, CountCopyAndMove>> Values; 459 // The size is a random value greater than 64 (hardcoded DenseMap min init) 460 const int Count = 65; 461 Values.reserve(Count); 462 for (int i = 0; i < Count; i++) 463 Values.emplace_back(i, CountCopyAndMove()); 464 465 CountCopyAndMove::Move = 0; 466 CountCopyAndMove::Copy = 0; 467 DenseMap<int, CountCopyAndMove> Map(Values.begin(), Values.end()); 468 // Check that no move occurred 469 EXPECT_EQ(0, CountCopyAndMove::Move); 470 // Check that copy was called the expected number of times 471 EXPECT_EQ(Count, CountCopyAndMove::Copy); 472 } 473 474 // Make sure reserve actually gives us enough buckets to insert N items 475 // without increasing allocation size. 476 TEST(DenseMapCustomTest, ReserveTest) { 477 // Test a few different size, 48 is *not* a random choice: we need a value 478 // that is 2/3 of a power of two to stress the grow() condition, and the power 479 // of two has to be at least 64 because of minimum size allocation in the 480 // DenseMap (see DefaultMinReservedSizeTest). 66 is a value just above the 481 // 64 default init. 482 for (auto Size : {1, 2, 48, 66}) { 483 DenseMap<int, CountCopyAndMove> Map; 484 Map.reserve(Size); 485 unsigned MemorySize = Map.getMemorySize(); 486 CountCopyAndMove::Copy = 0; 487 CountCopyAndMove::Move = 0; 488 for (int i = 0; i < Size; ++i) 489 Map.insert(std::pair<int, CountCopyAndMove>(std::piecewise_construct, 490 std::forward_as_tuple(i), 491 std::forward_as_tuple())); 492 // Check that we didn't grow 493 EXPECT_EQ(MemorySize, Map.getMemorySize()); 494 // Check that move was called the expected number of times 495 EXPECT_EQ(Size, CountCopyAndMove::Move); 496 // Check that no copy occurred 497 EXPECT_EQ(0, CountCopyAndMove::Copy); 498 } 499 } 500 501 // Make sure DenseMap works with StringRef keys. 502 TEST(DenseMapCustomTest, StringRefTest) { 503 DenseMap<StringRef, int> M; 504 505 M["a"] = 1; 506 M["b"] = 2; 507 M["c"] = 3; 508 509 EXPECT_EQ(3u, M.size()); 510 EXPECT_EQ(1, M.lookup("a")); 511 EXPECT_EQ(2, M.lookup("b")); 512 EXPECT_EQ(3, M.lookup("c")); 513 514 EXPECT_EQ(0, M.lookup("q")); 515 516 // Test the empty string, spelled various ways. 517 EXPECT_EQ(0, M.lookup("")); 518 EXPECT_EQ(0, M.lookup(StringRef())); 519 EXPECT_EQ(0, M.lookup(StringRef("a", 0))); 520 M[""] = 42; 521 EXPECT_EQ(42, M.lookup("")); 522 EXPECT_EQ(42, M.lookup(StringRef())); 523 EXPECT_EQ(42, M.lookup(StringRef("a", 0))); 524 } 525 526 // Key traits that allows lookup with either an unsigned or char* key; 527 // In the latter case, "a" == 0, "b" == 1 and so on. 528 struct TestDenseMapInfo { 529 static inline unsigned getEmptyKey() { return ~0; } 530 static inline unsigned getTombstoneKey() { return ~0U - 1; } 531 static unsigned getHashValue(const unsigned& Val) { return Val * 37U; } 532 static unsigned getHashValue(const char* Val) { 533 return (unsigned)(Val[0] - 'a') * 37U; 534 } 535 static bool isEqual(const unsigned& LHS, const unsigned& RHS) { 536 return LHS == RHS; 537 } 538 static bool isEqual(const char* LHS, const unsigned& RHS) { 539 return (unsigned)(LHS[0] - 'a') == RHS; 540 } 541 }; 542 543 // find_as() tests 544 TEST(DenseMapCustomTest, FindAsTest) { 545 DenseMap<unsigned, unsigned, TestDenseMapInfo> map; 546 map[0] = 1; 547 map[1] = 2; 548 map[2] = 3; 549 550 // Size tests 551 EXPECT_EQ(3u, map.size()); 552 553 // Normal lookup tests 554 EXPECT_EQ(1u, map.count(1)); 555 EXPECT_EQ(1u, map.find(0)->second); 556 EXPECT_EQ(2u, map.find(1)->second); 557 EXPECT_EQ(3u, map.find(2)->second); 558 EXPECT_TRUE(map.find(3) == map.end()); 559 560 // find_as() tests 561 EXPECT_EQ(1u, map.find_as("a")->second); 562 EXPECT_EQ(2u, map.find_as("b")->second); 563 EXPECT_EQ(3u, map.find_as("c")->second); 564 EXPECT_TRUE(map.find_as("d") == map.end()); 565 } 566 567 TEST(DenseMapCustomTest, SmallDenseMapInitializerList) { 568 SmallDenseMap<int, int> M = {{0, 0}, {0, 1}, {1, 2}}; 569 EXPECT_EQ(2u, M.size()); 570 EXPECT_EQ(1u, M.count(0)); 571 EXPECT_EQ(0, M[0]); 572 EXPECT_EQ(1u, M.count(1)); 573 EXPECT_EQ(2, M[1]); 574 } 575 576 struct ContiguousDenseMapInfo { 577 static inline unsigned getEmptyKey() { return ~0; } 578 static inline unsigned getTombstoneKey() { return ~0U - 1; } 579 static unsigned getHashValue(const unsigned& Val) { return Val; } 580 static bool isEqual(const unsigned& LHS, const unsigned& RHS) { 581 return LHS == RHS; 582 } 583 }; 584 585 // Test that filling a small dense map with exactly the number of elements in 586 // the map grows to have enough space for an empty bucket. 587 TEST(DenseMapCustomTest, SmallDenseMapGrowTest) { 588 SmallDenseMap<unsigned, unsigned, 32, ContiguousDenseMapInfo> map; 589 // Add some number of elements, then delete a few to leave us some tombstones. 590 // If we just filled the map with 32 elements we'd grow because of not enough 591 // tombstones which masks the issue here. 592 for (unsigned i = 0; i < 20; ++i) 593 map[i] = i + 1; 594 for (unsigned i = 0; i < 10; ++i) 595 map.erase(i); 596 for (unsigned i = 20; i < 32; ++i) 597 map[i] = i + 1; 598 599 // Size tests 600 EXPECT_EQ(22u, map.size()); 601 602 // Try to find an element which doesn't exist. There was a bug in 603 // SmallDenseMap which led to a map with num elements == small capacity not 604 // having an empty bucket any more. Finding an element not in the map would 605 // therefore never terminate. 606 EXPECT_TRUE(map.find(32) == map.end()); 607 } 608 609 TEST(DenseMapCustomTest, LargeSmallDenseMapCompaction) { 610 SmallDenseMap<unsigned, unsigned, 128, ContiguousDenseMapInfo> map; 611 // Fill to < 3/4 load. 612 for (unsigned i = 0; i < 95; ++i) 613 map[i] = i; 614 // And erase, leaving behind tombstones. 615 for (unsigned i = 0; i < 95; ++i) 616 map.erase(i); 617 // Fill further, so that less than 1/8 are empty, but still below 3/4 load. 618 for (unsigned i = 95; i < 128; ++i) 619 map[i] = i; 620 621 EXPECT_EQ(33u, map.size()); 622 // Similar to the previous test, check for a non-existing element, as an 623 // indirect check that tombstones have been removed. 624 EXPECT_TRUE(map.find(0) == map.end()); 625 } 626 627 TEST(DenseMapCustomTest, SmallDenseMapWithNumBucketsNonPowerOf2) { 628 // Is not power of 2. 629 const unsigned NumInitBuckets = 33; 630 // Power of 2 less then NumInitBuckets. 631 constexpr unsigned InlineBuckets = 4; 632 // Constructor should not trigger assert. 633 SmallDenseMap<int, int, InlineBuckets> map(NumInitBuckets); 634 } 635 636 TEST(DenseMapCustomTest, TryEmplaceTest) { 637 DenseMap<int, std::unique_ptr<int>> Map; 638 std::unique_ptr<int> P(new int(2)); 639 auto Try1 = Map.try_emplace(0, new int(1)); 640 EXPECT_TRUE(Try1.second); 641 auto Try2 = Map.try_emplace(0, std::move(P)); 642 EXPECT_FALSE(Try2.second); 643 EXPECT_EQ(Try1.first, Try2.first); 644 EXPECT_NE(nullptr, P); 645 } 646 647 TEST(DenseMapCustomTest, ConstTest) { 648 // Test that const pointers work okay for count and find, even when the 649 // underlying map is a non-const pointer. 650 DenseMap<int *, int> Map; 651 int A; 652 int *B = &A; 653 const int *C = &A; 654 Map.insert({B, 0}); 655 EXPECT_EQ(Map.count(B), 1u); 656 EXPECT_EQ(Map.count(C), 1u); 657 EXPECT_NE(Map.find(B), Map.end()); 658 EXPECT_NE(Map.find(C), Map.end()); 659 } 660 661 struct IncompleteStruct; 662 663 TEST(DenseMapCustomTest, OpaquePointerKey) { 664 // Test that we can use a pointer to an incomplete type as a DenseMap key. 665 // This is an important build time optimization, since many classes have 666 // DenseMap members. 667 DenseMap<IncompleteStruct *, int> Map; 668 int Keys[3] = {0, 0, 0}; 669 IncompleteStruct *K1 = reinterpret_cast<IncompleteStruct *>(&Keys[0]); 670 IncompleteStruct *K2 = reinterpret_cast<IncompleteStruct *>(&Keys[1]); 671 IncompleteStruct *K3 = reinterpret_cast<IncompleteStruct *>(&Keys[2]); 672 Map.insert({K1, 1}); 673 Map.insert({K2, 2}); 674 Map.insert({K3, 3}); 675 EXPECT_EQ(Map.count(K1), 1u); 676 EXPECT_EQ(Map[K1], 1); 677 EXPECT_EQ(Map[K2], 2); 678 EXPECT_EQ(Map[K3], 3); 679 Map.clear(); 680 EXPECT_EQ(Map.find(K1), Map.end()); 681 EXPECT_EQ(Map.find(K2), Map.end()); 682 EXPECT_EQ(Map.find(K3), Map.end()); 683 } 684 } // namespace 685 686 namespace { 687 struct A { 688 A(int value) : value(value) {} 689 int value; 690 }; 691 struct B : public A { 692 using A::A; 693 }; 694 695 struct AlwaysEqType { 696 bool operator==(const AlwaysEqType &RHS) const { return true; } 697 }; 698 } // namespace 699 700 namespace llvm { 701 template <typename T> 702 struct DenseMapInfo<T, std::enable_if_t<std::is_base_of_v<A, T>>> { 703 static inline T getEmptyKey() { return {static_cast<int>(~0)}; } 704 static inline T getTombstoneKey() { return {static_cast<int>(~0U - 1)}; } 705 static unsigned getHashValue(const T &Val) { return Val.value; } 706 static bool isEqual(const T &LHS, const T &RHS) { 707 return LHS.value == RHS.value; 708 } 709 }; 710 711 template <> struct DenseMapInfo<AlwaysEqType> { 712 using T = AlwaysEqType; 713 static inline T getEmptyKey() { return {}; } 714 static inline T getTombstoneKey() { return {}; } 715 static unsigned getHashValue(const T &Val) { return 0; } 716 static bool isEqual(const T &LHS, const T &RHS) { 717 return false; 718 } 719 }; 720 } // namespace llvm 721 722 namespace { 723 TEST(DenseMapCustomTest, SFINAEMapInfo) { 724 // Test that we can use a pointer to an incomplete type as a DenseMap key. 725 // This is an important build time optimization, since many classes have 726 // DenseMap members. 727 DenseMap<B, int> Map; 728 B Keys[3] = {{0}, {1}, {2}}; 729 Map.insert({Keys[0], 1}); 730 Map.insert({Keys[1], 2}); 731 Map.insert({Keys[2], 3}); 732 EXPECT_EQ(Map.count(Keys[0]), 1u); 733 EXPECT_EQ(Map[Keys[0]], 1); 734 EXPECT_EQ(Map[Keys[1]], 2); 735 EXPECT_EQ(Map[Keys[2]], 3); 736 Map.clear(); 737 EXPECT_EQ(Map.find(Keys[0]), Map.end()); 738 EXPECT_EQ(Map.find(Keys[1]), Map.end()); 739 EXPECT_EQ(Map.find(Keys[2]), Map.end()); 740 } 741 742 TEST(DenseMapCustomTest, VariantSupport) { 743 using variant = std::variant<int, int, AlwaysEqType>; 744 DenseMap<variant, int> Map; 745 variant Keys[] = { 746 variant(std::in_place_index<0>, 1), 747 variant(std::in_place_index<1>, 1), 748 variant(std::in_place_index<2>), 749 }; 750 Map.try_emplace(Keys[0], 0); 751 Map.try_emplace(Keys[1], 1); 752 EXPECT_THAT(Map, testing::SizeIs(2)); 753 EXPECT_NE(DenseMapInfo<variant>::getHashValue(Keys[0]), 754 DenseMapInfo<variant>::getHashValue(Keys[1])); 755 // Check that isEqual dispatches to isEqual of underlying type, and not to 756 // operator==. 757 EXPECT_FALSE(DenseMapInfo<variant>::isEqual(Keys[2], Keys[2])); 758 } 759 } // namespace 760