1 //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the DenseMap class.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_ADT_DENSEMAP_H
14 #define LLVM_ADT_DENSEMAP_H
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/ADT/EpochTracker.h"
18 #include "llvm/Support/AlignOf.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/MemAlloc.h"
22 #include "llvm/Support/ReverseIteration.h"
23 #include "llvm/Support/type_traits.h"
28 #include <initializer_list>
31 #include <type_traits>
38 // We extend a pair to allow users to override the bucket type with their own
39 // implementation without requiring two members.
40 template <typename KeyT, typename ValueT>
41 struct DenseMapPair : public std::pair<KeyT, ValueT> {
42 using std::pair<KeyT, ValueT>::pair;
44 KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; }
45 const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; }
46 ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; }
47 const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; }
50 } // end namespace detail
52 template <typename KeyT, typename ValueT,
53 typename KeyInfoT = DenseMapInfo<KeyT>,
54 typename Bucket = llvm::detail::DenseMapPair<KeyT, ValueT>,
56 class DenseMapIterator;
58 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
60 class DenseMapBase : public DebugEpochBase {
62 using const_arg_type_t = typename const_pointer_or_const_ref<T>::type;
65 using size_type = unsigned;
66 using key_type = KeyT;
67 using mapped_type = ValueT;
68 using value_type = BucketT;
70 using iterator = DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT>;
71 using const_iterator =
72 DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT, true>;
74 inline iterator begin() {
75 // When the map is empty, avoid the overhead of advancing/retreating past
79 if (shouldReverseIterate<KeyT>())
80 return makeIterator(getBucketsEnd() - 1, getBuckets(), *this);
81 return makeIterator(getBuckets(), getBucketsEnd(), *this);
83 inline iterator end() {
84 return makeIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
86 inline const_iterator begin() const {
89 if (shouldReverseIterate<KeyT>())
90 return makeConstIterator(getBucketsEnd() - 1, getBuckets(), *this);
91 return makeConstIterator(getBuckets(), getBucketsEnd(), *this);
93 inline const_iterator end() const {
94 return makeConstIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
97 LLVM_NODISCARD bool empty() const {
98 return getNumEntries() == 0;
100 unsigned size() const { return getNumEntries(); }
102 /// Grow the densemap so that it can contain at least \p NumEntries items
103 /// before resizing again.
104 void reserve(size_type NumEntries) {
105 auto NumBuckets = getMinBucketToReserveForEntries(NumEntries);
107 if (NumBuckets > getNumBuckets())
113 if (getNumEntries() == 0 && getNumTombstones() == 0) return;
115 // If the capacity of the array is huge, and the # elements used is small,
117 if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
122 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
123 if (std::is_trivially_destructible<ValueT>::value) {
124 // Use a simpler loop when values don't need destruction.
125 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P)
126 P->getFirst() = EmptyKey;
128 unsigned NumEntries = getNumEntries();
129 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
130 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
131 if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
132 P->getSecond().~ValueT();
135 P->getFirst() = EmptyKey;
138 assert(NumEntries == 0 && "Node count imbalance!");
144 /// Return 1 if the specified key is in the map, 0 otherwise.
145 size_type count(const_arg_type_t<KeyT> Val) const {
146 const BucketT *TheBucket;
147 return LookupBucketFor(Val, TheBucket) ? 1 : 0;
150 iterator find(const_arg_type_t<KeyT> Val) {
152 if (LookupBucketFor(Val, TheBucket))
153 return makeIterator(TheBucket,
154 shouldReverseIterate<KeyT>() ? getBuckets()
159 const_iterator find(const_arg_type_t<KeyT> Val) const {
160 const BucketT *TheBucket;
161 if (LookupBucketFor(Val, TheBucket))
162 return makeConstIterator(TheBucket,
163 shouldReverseIterate<KeyT>() ? getBuckets()
169 /// Alternate version of find() which allows a different, and possibly
170 /// less expensive, key type.
171 /// The DenseMapInfo is responsible for supplying methods
172 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
174 template<class LookupKeyT>
175 iterator find_as(const LookupKeyT &Val) {
177 if (LookupBucketFor(Val, TheBucket))
178 return makeIterator(TheBucket,
179 shouldReverseIterate<KeyT>() ? getBuckets()
184 template<class LookupKeyT>
185 const_iterator find_as(const LookupKeyT &Val) const {
186 const BucketT *TheBucket;
187 if (LookupBucketFor(Val, TheBucket))
188 return makeConstIterator(TheBucket,
189 shouldReverseIterate<KeyT>() ? getBuckets()
195 /// lookup - Return the entry for the specified key, or a default
196 /// constructed value if no such entry exists.
197 ValueT lookup(const_arg_type_t<KeyT> Val) const {
198 const BucketT *TheBucket;
199 if (LookupBucketFor(Val, TheBucket))
200 return TheBucket->getSecond();
204 // Inserts key,value pair into the map if the key isn't already in the map.
205 // If the key is already in the map, it returns false and doesn't update the
207 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
208 return try_emplace(KV.first, KV.second);
211 // Inserts key,value pair into the map if the key isn't already in the map.
212 // If the key is already in the map, it returns false and doesn't update the
214 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
215 return try_emplace(std::move(KV.first), std::move(KV.second));
218 // Inserts key,value pair into the map if the key isn't already in the map.
219 // The value is constructed in-place if the key is not in the map, otherwise
221 template <typename... Ts>
222 std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&... Args) {
224 if (LookupBucketFor(Key, TheBucket))
225 return std::make_pair(makeIterator(TheBucket,
226 shouldReverseIterate<KeyT>()
230 false); // Already in map.
232 // Otherwise, insert the new element.
234 InsertIntoBucket(TheBucket, std::move(Key), std::forward<Ts>(Args)...);
235 return std::make_pair(makeIterator(TheBucket,
236 shouldReverseIterate<KeyT>()
243 // Inserts key,value pair into the map if the key isn't already in the map.
244 // The value is constructed in-place if the key is not in the map, otherwise
246 template <typename... Ts>
247 std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&... Args) {
249 if (LookupBucketFor(Key, TheBucket))
250 return std::make_pair(makeIterator(TheBucket,
251 shouldReverseIterate<KeyT>()
255 false); // Already in map.
257 // Otherwise, insert the new element.
258 TheBucket = InsertIntoBucket(TheBucket, Key, std::forward<Ts>(Args)...);
259 return std::make_pair(makeIterator(TheBucket,
260 shouldReverseIterate<KeyT>()
267 /// Alternate version of insert() which allows a different, and possibly
268 /// less expensive, key type.
269 /// The DenseMapInfo is responsible for supplying methods
270 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
272 template <typename LookupKeyT>
273 std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV,
274 const LookupKeyT &Val) {
276 if (LookupBucketFor(Val, TheBucket))
277 return std::make_pair(makeIterator(TheBucket,
278 shouldReverseIterate<KeyT>()
282 false); // Already in map.
284 // Otherwise, insert the new element.
285 TheBucket = InsertIntoBucketWithLookup(TheBucket, std::move(KV.first),
286 std::move(KV.second), Val);
287 return std::make_pair(makeIterator(TheBucket,
288 shouldReverseIterate<KeyT>()
295 /// insert - Range insertion of pairs.
296 template<typename InputIt>
297 void insert(InputIt I, InputIt E) {
302 bool erase(const KeyT &Val) {
304 if (!LookupBucketFor(Val, TheBucket))
305 return false; // not in map.
307 TheBucket->getSecond().~ValueT();
308 TheBucket->getFirst() = getTombstoneKey();
309 decrementNumEntries();
310 incrementNumTombstones();
313 void erase(iterator I) {
314 BucketT *TheBucket = &*I;
315 TheBucket->getSecond().~ValueT();
316 TheBucket->getFirst() = getTombstoneKey();
317 decrementNumEntries();
318 incrementNumTombstones();
321 value_type& FindAndConstruct(const KeyT &Key) {
323 if (LookupBucketFor(Key, TheBucket))
326 return *InsertIntoBucket(TheBucket, Key);
329 ValueT &operator[](const KeyT &Key) {
330 return FindAndConstruct(Key).second;
333 value_type& FindAndConstruct(KeyT &&Key) {
335 if (LookupBucketFor(Key, TheBucket))
338 return *InsertIntoBucket(TheBucket, std::move(Key));
341 ValueT &operator[](KeyT &&Key) {
342 return FindAndConstruct(std::move(Key)).second;
345 /// isPointerIntoBucketsArray - Return true if the specified pointer points
346 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
347 /// value in the DenseMap).
348 bool isPointerIntoBucketsArray(const void *Ptr) const {
349 return Ptr >= getBuckets() && Ptr < getBucketsEnd();
352 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
353 /// array. In conjunction with the previous method, this can be used to
354 /// determine whether an insertion caused the DenseMap to reallocate.
355 const void *getPointerIntoBucketsArray() const { return getBuckets(); }
358 DenseMapBase() = default;
361 if (getNumBuckets() == 0) // Nothing to do.
364 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
365 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
366 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
367 !KeyInfoT::isEqual(P->getFirst(), TombstoneKey))
368 P->getSecond().~ValueT();
369 P->getFirst().~KeyT();
377 assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
378 "# initial buckets must be a power of two!");
379 const KeyT EmptyKey = getEmptyKey();
380 for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
381 ::new (&B->getFirst()) KeyT(EmptyKey);
384 /// Returns the number of buckets to allocate to ensure that the DenseMap can
385 /// accommodate \p NumEntries without need to grow().
386 unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
387 // Ensure that "NumEntries * 4 < NumBuckets * 3"
390 // +1 is required because of the strict equality.
391 // For example if NumEntries is 48, we need to return 401.
392 return NextPowerOf2(NumEntries * 4 / 3 + 1);
395 void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
398 // Insert all the old elements.
399 const KeyT EmptyKey = getEmptyKey();
400 const KeyT TombstoneKey = getTombstoneKey();
401 for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
402 if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) &&
403 !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) {
404 // Insert the key/value into the new table.
406 bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket);
407 (void)FoundVal; // silence warning.
408 assert(!FoundVal && "Key already in new map?");
409 DestBucket->getFirst() = std::move(B->getFirst());
410 ::new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond()));
411 incrementNumEntries();
414 B->getSecond().~ValueT();
416 B->getFirst().~KeyT();
420 template <typename OtherBaseT>
422 const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT> &other) {
423 assert(&other != this);
424 assert(getNumBuckets() == other.getNumBuckets());
426 setNumEntries(other.getNumEntries());
427 setNumTombstones(other.getNumTombstones());
429 if (is_trivially_copyable<KeyT>::value &&
430 is_trivially_copyable<ValueT>::value)
431 memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(),
432 getNumBuckets() * sizeof(BucketT));
434 for (size_t i = 0; i < getNumBuckets(); ++i) {
435 ::new (&getBuckets()[i].getFirst())
436 KeyT(other.getBuckets()[i].getFirst());
437 if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) &&
438 !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey()))
439 ::new (&getBuckets()[i].getSecond())
440 ValueT(other.getBuckets()[i].getSecond());
444 static unsigned getHashValue(const KeyT &Val) {
445 return KeyInfoT::getHashValue(Val);
448 template<typename LookupKeyT>
449 static unsigned getHashValue(const LookupKeyT &Val) {
450 return KeyInfoT::getHashValue(Val);
453 static const KeyT getEmptyKey() {
454 static_assert(std::is_base_of<DenseMapBase, DerivedT>::value,
455 "Must pass the derived type to this template!");
456 return KeyInfoT::getEmptyKey();
459 static const KeyT getTombstoneKey() {
460 return KeyInfoT::getTombstoneKey();
464 iterator makeIterator(BucketT *P, BucketT *E,
465 DebugEpochBase &Epoch,
466 bool NoAdvance=false) {
467 if (shouldReverseIterate<KeyT>()) {
468 BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
469 return iterator(B, E, Epoch, NoAdvance);
471 return iterator(P, E, Epoch, NoAdvance);
474 const_iterator makeConstIterator(const BucketT *P, const BucketT *E,
475 const DebugEpochBase &Epoch,
476 const bool NoAdvance=false) const {
477 if (shouldReverseIterate<KeyT>()) {
478 const BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
479 return const_iterator(B, E, Epoch, NoAdvance);
481 return const_iterator(P, E, Epoch, NoAdvance);
484 unsigned getNumEntries() const {
485 return static_cast<const DerivedT *>(this)->getNumEntries();
488 void setNumEntries(unsigned Num) {
489 static_cast<DerivedT *>(this)->setNumEntries(Num);
492 void incrementNumEntries() {
493 setNumEntries(getNumEntries() + 1);
496 void decrementNumEntries() {
497 setNumEntries(getNumEntries() - 1);
500 unsigned getNumTombstones() const {
501 return static_cast<const DerivedT *>(this)->getNumTombstones();
504 void setNumTombstones(unsigned Num) {
505 static_cast<DerivedT *>(this)->setNumTombstones(Num);
508 void incrementNumTombstones() {
509 setNumTombstones(getNumTombstones() + 1);
512 void decrementNumTombstones() {
513 setNumTombstones(getNumTombstones() - 1);
516 const BucketT *getBuckets() const {
517 return static_cast<const DerivedT *>(this)->getBuckets();
520 BucketT *getBuckets() {
521 return static_cast<DerivedT *>(this)->getBuckets();
524 unsigned getNumBuckets() const {
525 return static_cast<const DerivedT *>(this)->getNumBuckets();
528 BucketT *getBucketsEnd() {
529 return getBuckets() + getNumBuckets();
532 const BucketT *getBucketsEnd() const {
533 return getBuckets() + getNumBuckets();
536 void grow(unsigned AtLeast) {
537 static_cast<DerivedT *>(this)->grow(AtLeast);
540 void shrink_and_clear() {
541 static_cast<DerivedT *>(this)->shrink_and_clear();
544 template <typename KeyArg, typename... ValueArgs>
545 BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key,
546 ValueArgs &&... Values) {
547 TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket);
549 TheBucket->getFirst() = std::forward<KeyArg>(Key);
550 ::new (&TheBucket->getSecond()) ValueT(std::forward<ValueArgs>(Values)...);
554 template <typename LookupKeyT>
555 BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key,
556 ValueT &&Value, LookupKeyT &Lookup) {
557 TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket);
559 TheBucket->getFirst() = std::move(Key);
560 ::new (&TheBucket->getSecond()) ValueT(std::move(Value));
564 template <typename LookupKeyT>
565 BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup,
566 BucketT *TheBucket) {
569 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
570 // the buckets are empty (meaning that many are filled with tombstones),
573 // The later case is tricky. For example, if we had one empty bucket with
574 // tons of tombstones, failing lookups (e.g. for insertion) would have to
575 // probe almost the entire table until it found the empty bucket. If the
576 // table completely filled with tombstones, no lookup would ever succeed,
577 // causing infinite loops in lookup.
578 unsigned NewNumEntries = getNumEntries() + 1;
579 unsigned NumBuckets = getNumBuckets();
580 if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) {
581 this->grow(NumBuckets * 2);
582 LookupBucketFor(Lookup, TheBucket);
583 NumBuckets = getNumBuckets();
584 } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <=
586 this->grow(NumBuckets);
587 LookupBucketFor(Lookup, TheBucket);
591 // Only update the state after we've grown our bucket space appropriately
592 // so that when growing buckets we have self-consistent entry count.
593 incrementNumEntries();
595 // If we are writing over a tombstone, remember this.
596 const KeyT EmptyKey = getEmptyKey();
597 if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey))
598 decrementNumTombstones();
603 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
604 /// FoundBucket. If the bucket contains the key and a value, this returns
605 /// true, otherwise it returns a bucket with an empty marker or tombstone and
607 template<typename LookupKeyT>
608 bool LookupBucketFor(const LookupKeyT &Val,
609 const BucketT *&FoundBucket) const {
610 const BucketT *BucketsPtr = getBuckets();
611 const unsigned NumBuckets = getNumBuckets();
613 if (NumBuckets == 0) {
614 FoundBucket = nullptr;
618 // FoundTombstone - Keep track of whether we find a tombstone while probing.
619 const BucketT *FoundTombstone = nullptr;
620 const KeyT EmptyKey = getEmptyKey();
621 const KeyT TombstoneKey = getTombstoneKey();
622 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
623 !KeyInfoT::isEqual(Val, TombstoneKey) &&
624 "Empty/Tombstone value shouldn't be inserted into map!");
626 unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
627 unsigned ProbeAmt = 1;
629 const BucketT *ThisBucket = BucketsPtr + BucketNo;
630 // Found Val's bucket? If so, return it.
631 if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) {
632 FoundBucket = ThisBucket;
636 // If we found an empty bucket, the key doesn't exist in the set.
637 // Insert it and return the default value.
638 if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) {
639 // If we've already seen a tombstone while probing, fill it in instead
640 // of the empty bucket we eventually probed to.
641 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
645 // If this is a tombstone, remember it. If Val ends up not in the map, we
646 // prefer to return it than something that would require more probing.
647 if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
649 FoundTombstone = ThisBucket; // Remember the first tombstone found.
651 // Otherwise, it's a hash collision or a tombstone, continue quadratic
653 BucketNo += ProbeAmt++;
654 BucketNo &= (NumBuckets-1);
658 template <typename LookupKeyT>
659 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
660 const BucketT *ConstFoundBucket;
661 bool Result = const_cast<const DenseMapBase *>(this)
662 ->LookupBucketFor(Val, ConstFoundBucket);
663 FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
668 /// Return the approximate size (in bytes) of the actual map.
669 /// This is just the raw memory used by DenseMap.
670 /// If entries are pointers to objects, the size of the referenced objects
671 /// are not included.
672 size_t getMemorySize() const {
673 return getNumBuckets() * sizeof(BucketT);
677 /// Equality comparison for DenseMap.
679 /// Iterates over elements of LHS confirming that each (key, value) pair in LHS
680 /// is also in RHS, and that no additional pairs are in RHS.
681 /// Equivalent to N calls to RHS.find and N value comparisons. Amortized
682 /// complexity is linear, worst case is O(N^2) (if every hash collides).
683 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
686 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
687 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
688 if (LHS.size() != RHS.size())
691 for (auto &KV : LHS) {
692 auto I = RHS.find(KV.first);
693 if (I == RHS.end() || I->second != KV.second)
700 /// Inequality comparison for DenseMap.
702 /// Equivalent to !(LHS == RHS). See operator== for performance notes.
703 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
706 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
707 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
708 return !(LHS == RHS);
711 template <typename KeyT, typename ValueT,
712 typename KeyInfoT = DenseMapInfo<KeyT>,
713 typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>>
714 class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
715 KeyT, ValueT, KeyInfoT, BucketT> {
716 friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
718 // Lift some types from the dependent base class into this class for
719 // simplicity of referring to them.
720 using BaseT = DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
724 unsigned NumTombstones;
728 /// Create a DenseMap with an optional \p InitialReserve that guarantee that
729 /// this number of elements can be inserted in the map without grow()
730 explicit DenseMap(unsigned InitialReserve = 0) { init(InitialReserve); }
732 DenseMap(const DenseMap &other) : BaseT() {
737 DenseMap(DenseMap &&other) : BaseT() {
742 template<typename InputIt>
743 DenseMap(const InputIt &I, const InputIt &E) {
744 init(std::distance(I, E));
748 DenseMap(std::initializer_list<typename BaseT::value_type> Vals) {
750 this->insert(Vals.begin(), Vals.end());
755 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
758 void swap(DenseMap& RHS) {
759 this->incrementEpoch();
760 RHS.incrementEpoch();
761 std::swap(Buckets, RHS.Buckets);
762 std::swap(NumEntries, RHS.NumEntries);
763 std::swap(NumTombstones, RHS.NumTombstones);
764 std::swap(NumBuckets, RHS.NumBuckets);
767 DenseMap& operator=(const DenseMap& other) {
773 DenseMap& operator=(DenseMap &&other) {
775 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
781 void copyFrom(const DenseMap& other) {
783 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
784 if (allocateBuckets(other.NumBuckets)) {
785 this->BaseT::copyFrom(other);
792 void init(unsigned InitNumEntries) {
793 auto InitBuckets = BaseT::getMinBucketToReserveForEntries(InitNumEntries);
794 if (allocateBuckets(InitBuckets)) {
795 this->BaseT::initEmpty();
802 void grow(unsigned AtLeast) {
803 unsigned OldNumBuckets = NumBuckets;
804 BucketT *OldBuckets = Buckets;
806 allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
809 this->BaseT::initEmpty();
813 this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
815 // Free the old table.
816 deallocate_buffer(OldBuckets, sizeof(BucketT) * OldNumBuckets,
820 void shrink_and_clear() {
821 unsigned OldNumBuckets = NumBuckets;
822 unsigned OldNumEntries = NumEntries;
825 // Reduce the number of buckets.
826 unsigned NewNumBuckets = 0;
828 NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
829 if (NewNumBuckets == NumBuckets) {
830 this->BaseT::initEmpty();
834 deallocate_buffer(Buckets, sizeof(BucketT) * OldNumBuckets,
840 unsigned getNumEntries() const {
844 void setNumEntries(unsigned Num) {
848 unsigned getNumTombstones() const {
849 return NumTombstones;
852 void setNumTombstones(unsigned Num) {
856 BucketT *getBuckets() const {
860 unsigned getNumBuckets() const {
864 bool allocateBuckets(unsigned Num) {
866 if (NumBuckets == 0) {
871 Buckets = static_cast<BucketT *>(
872 allocate_buffer(sizeof(BucketT) * NumBuckets, alignof(BucketT)));
877 template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
878 typename KeyInfoT = DenseMapInfo<KeyT>,
879 typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>>
881 : public DenseMapBase<
882 SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT,
883 ValueT, KeyInfoT, BucketT> {
884 friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
886 // Lift some types from the dependent base class into this class for
887 // simplicity of referring to them.
888 using BaseT = DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
890 static_assert(isPowerOf2_64(InlineBuckets),
891 "InlineBuckets must be a power of 2.");
894 unsigned NumEntries : 31;
895 unsigned NumTombstones;
902 /// A "union" of an inline bucket array and the struct representing
903 /// a large bucket. This union will be discriminated by the 'Small' bit.
904 AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
907 explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
908 init(NumInitBuckets);
911 SmallDenseMap(const SmallDenseMap &other) : BaseT() {
916 SmallDenseMap(SmallDenseMap &&other) : BaseT() {
921 template<typename InputIt>
922 SmallDenseMap(const InputIt &I, const InputIt &E) {
923 init(NextPowerOf2(std::distance(I, E)));
932 void swap(SmallDenseMap& RHS) {
933 unsigned TmpNumEntries = RHS.NumEntries;
934 RHS.NumEntries = NumEntries;
935 NumEntries = TmpNumEntries;
936 std::swap(NumTombstones, RHS.NumTombstones);
938 const KeyT EmptyKey = this->getEmptyKey();
939 const KeyT TombstoneKey = this->getTombstoneKey();
940 if (Small && RHS.Small) {
941 // If we're swapping inline bucket arrays, we have to cope with some of
942 // the tricky bits of DenseMap's storage system: the buckets are not
943 // fully initialized. Thus we swap every key, but we may have
944 // a one-directional move of the value.
945 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
946 BucketT *LHSB = &getInlineBuckets()[i],
947 *RHSB = &RHS.getInlineBuckets()[i];
948 bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
949 !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
950 bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
951 !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
952 if (hasLHSValue && hasRHSValue) {
953 // Swap together if we can...
954 std::swap(*LHSB, *RHSB);
957 // Swap separately and handle any assymetry.
958 std::swap(LHSB->getFirst(), RHSB->getFirst());
960 ::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
961 LHSB->getSecond().~ValueT();
962 } else if (hasRHSValue) {
963 ::new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
964 RHSB->getSecond().~ValueT();
969 if (!Small && !RHS.Small) {
970 std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
971 std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
975 SmallDenseMap &SmallSide = Small ? *this : RHS;
976 SmallDenseMap &LargeSide = Small ? RHS : *this;
978 // First stash the large side's rep and move the small side across.
979 LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
980 LargeSide.getLargeRep()->~LargeRep();
981 LargeSide.Small = true;
982 // This is similar to the standard move-from-old-buckets, but the bucket
983 // count hasn't actually rotated in this case. So we have to carefully
984 // move construct the keys and values into their new locations, but there
985 // is no need to re-hash things.
986 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
987 BucketT *NewB = &LargeSide.getInlineBuckets()[i],
988 *OldB = &SmallSide.getInlineBuckets()[i];
989 ::new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
990 OldB->getFirst().~KeyT();
991 if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
992 !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
993 ::new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
994 OldB->getSecond().~ValueT();
998 // The hard part of moving the small buckets across is done, just move
999 // the TmpRep into its new home.
1000 SmallSide.Small = false;
1001 new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
1004 SmallDenseMap& operator=(const SmallDenseMap& other) {
1010 SmallDenseMap& operator=(SmallDenseMap &&other) {
1012 deallocateBuckets();
1018 void copyFrom(const SmallDenseMap& other) {
1020 deallocateBuckets();
1022 if (other.getNumBuckets() > InlineBuckets) {
1024 new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
1026 this->BaseT::copyFrom(other);
1029 void init(unsigned InitBuckets) {
1031 if (InitBuckets > InlineBuckets) {
1033 new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
1035 this->BaseT::initEmpty();
1038 void grow(unsigned AtLeast) {
1039 if (AtLeast > InlineBuckets)
1040 AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
1043 // First move the inline buckets into a temporary storage.
1044 AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
1045 BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
1046 BucketT *TmpEnd = TmpBegin;
1048 // Loop over the buckets, moving non-empty, non-tombstones into the
1049 // temporary storage. Have the loop move the TmpEnd forward as it goes.
1050 const KeyT EmptyKey = this->getEmptyKey();
1051 const KeyT TombstoneKey = this->getTombstoneKey();
1052 for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
1053 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
1054 !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
1055 assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
1056 "Too many inline buckets!");
1057 ::new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst()));
1058 ::new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond()));
1060 P->getSecond().~ValueT();
1062 P->getFirst().~KeyT();
1065 // AtLeast == InlineBuckets can happen if there are many tombstones,
1066 // and grow() is used to remove them. Usually we always switch to the
1068 if (AtLeast > InlineBuckets) {
1070 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
1072 this->moveFromOldBuckets(TmpBegin, TmpEnd);
1076 LargeRep OldRep = std::move(*getLargeRep());
1077 getLargeRep()->~LargeRep();
1078 if (AtLeast <= InlineBuckets) {
1081 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
1084 this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
1086 // Free the old table.
1087 deallocate_buffer(OldRep.Buckets, sizeof(BucketT) * OldRep.NumBuckets,
1091 void shrink_and_clear() {
1092 unsigned OldSize = this->size();
1095 // Reduce the number of buckets.
1096 unsigned NewNumBuckets = 0;
1098 NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
1099 if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
1102 if ((Small && NewNumBuckets <= InlineBuckets) ||
1103 (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
1104 this->BaseT::initEmpty();
1108 deallocateBuckets();
1109 init(NewNumBuckets);
1113 unsigned getNumEntries() const {
1117 void setNumEntries(unsigned Num) {
1118 // NumEntries is hardcoded to be 31 bits wide.
1119 assert(Num < (1U << 31) && "Cannot support more than 1<<31 entries");
1123 unsigned getNumTombstones() const {
1124 return NumTombstones;
1127 void setNumTombstones(unsigned Num) {
1128 NumTombstones = Num;
1131 const BucketT *getInlineBuckets() const {
1133 // Note that this cast does not violate aliasing rules as we assert that
1134 // the memory's dynamic type is the small, inline bucket buffer, and the
1135 // 'storage.buffer' static type is 'char *'.
1136 return reinterpret_cast<const BucketT *>(storage.buffer);
1139 BucketT *getInlineBuckets() {
1140 return const_cast<BucketT *>(
1141 const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
1144 const LargeRep *getLargeRep() const {
1146 // Note, same rule about aliasing as with getInlineBuckets.
1147 return reinterpret_cast<const LargeRep *>(storage.buffer);
1150 LargeRep *getLargeRep() {
1151 return const_cast<LargeRep *>(
1152 const_cast<const SmallDenseMap *>(this)->getLargeRep());
1155 const BucketT *getBuckets() const {
1156 return Small ? getInlineBuckets() : getLargeRep()->Buckets;
1159 BucketT *getBuckets() {
1160 return const_cast<BucketT *>(
1161 const_cast<const SmallDenseMap *>(this)->getBuckets());
1164 unsigned getNumBuckets() const {
1165 return Small ? InlineBuckets : getLargeRep()->NumBuckets;
1168 void deallocateBuckets() {
1172 deallocate_buffer(getLargeRep()->Buckets,
1173 sizeof(BucketT) * getLargeRep()->NumBuckets,
1175 getLargeRep()->~LargeRep();
1178 LargeRep allocateBuckets(unsigned Num) {
1179 assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
1180 LargeRep Rep = {static_cast<BucketT *>(allocate_buffer(
1181 sizeof(BucketT) * Num, alignof(BucketT))),
1187 template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket,
1189 class DenseMapIterator : DebugEpochBase::HandleBase {
1190 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
1191 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;
1193 using ConstIterator = DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
1196 using difference_type = ptrdiff_t;
1198 typename std::conditional<IsConst, const Bucket, Bucket>::type;
1199 using pointer = value_type *;
1200 using reference = value_type &;
1201 using iterator_category = std::forward_iterator_tag;
1204 pointer Ptr = nullptr;
1205 pointer End = nullptr;
1208 DenseMapIterator() = default;
1210 DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch,
1211 bool NoAdvance = false)
1212 : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) {
1213 assert(isHandleInSync() && "invalid construction!");
1215 if (NoAdvance) return;
1216 if (shouldReverseIterate<KeyT>()) {
1217 RetreatPastEmptyBuckets();
1220 AdvancePastEmptyBuckets();
1223 // Converting ctor from non-const iterators to const iterators. SFINAE'd out
1224 // for const iterator destinations so it doesn't end up as a user defined copy
1226 template <bool IsConstSrc,
1227 typename = std::enable_if_t<!IsConstSrc && IsConst>>
1229 const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I)
1230 : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {}
1232 reference operator*() const {
1233 assert(isHandleInSync() && "invalid iterator access!");
1234 assert(Ptr != End && "dereferencing end() iterator");
1235 if (shouldReverseIterate<KeyT>())
1239 pointer operator->() const {
1240 assert(isHandleInSync() && "invalid iterator access!");
1241 assert(Ptr != End && "dereferencing end() iterator");
1242 if (shouldReverseIterate<KeyT>())
1247 bool operator==(const ConstIterator &RHS) const {
1248 assert((!Ptr || isHandleInSync()) && "handle not in sync!");
1249 assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
1250 assert(getEpochAddress() == RHS.getEpochAddress() &&
1251 "comparing incomparable iterators!");
1252 return Ptr == RHS.Ptr;
1254 bool operator!=(const ConstIterator &RHS) const {
1255 assert((!Ptr || isHandleInSync()) && "handle not in sync!");
1256 assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
1257 assert(getEpochAddress() == RHS.getEpochAddress() &&
1258 "comparing incomparable iterators!");
1259 return Ptr != RHS.Ptr;
1262 inline DenseMapIterator& operator++() { // Preincrement
1263 assert(isHandleInSync() && "invalid iterator access!");
1264 assert(Ptr != End && "incrementing end() iterator");
1265 if (shouldReverseIterate<KeyT>()) {
1267 RetreatPastEmptyBuckets();
1271 AdvancePastEmptyBuckets();
1274 DenseMapIterator operator++(int) { // Postincrement
1275 assert(isHandleInSync() && "invalid iterator access!");
1276 DenseMapIterator tmp = *this; ++*this; return tmp;
1280 void AdvancePastEmptyBuckets() {
1282 const KeyT Empty = KeyInfoT::getEmptyKey();
1283 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1285 while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
1286 KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
1290 void RetreatPastEmptyBuckets() {
1292 const KeyT Empty = KeyInfoT::getEmptyKey();
1293 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1295 while (Ptr != End && (KeyInfoT::isEqual(Ptr[-1].getFirst(), Empty) ||
1296 KeyInfoT::isEqual(Ptr[-1].getFirst(), Tombstone)))
1301 template <typename KeyT, typename ValueT, typename KeyInfoT>
1302 inline size_t capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
1303 return X.getMemorySize();
1306 } // end namespace llvm
1308 #endif // LLVM_ADT_DENSEMAP_H