WPILibC++ 2024.3.2
DenseMap.h
Go to the documentation of this file.
1//===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- 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/// \file
10/// This file defines the DenseMap class.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef WPIUTIL_WPI_DENSEMAP_H
15#define WPIUTIL_WPI_DENSEMAP_H
16
17#include "wpi/DenseMapInfo.h"
18#include "wpi/EpochTracker.h"
19#include "wpi/AlignOf.h"
20#include "wpi/Compiler.h"
21#include "wpi/MathExtras.h"
22#include "wpi/MemAlloc.h"
24#include "wpi/type_traits.h"
25#include <algorithm>
26#include <bit>
27#include <cassert>
28#include <cstddef>
29#include <cstring>
30#include <initializer_list>
31#include <iterator>
32#include <new>
33#include <type_traits>
34#include <utility>
35
36namespace wpi {
37
38namespace detail {
39
40// We extend a pair to allow users to override the bucket type with their own
41// implementation without requiring two members.
42template <typename KeyT, typename ValueT>
43struct DenseMapPair : public std::pair<KeyT, ValueT> {
44 using std::pair<KeyT, ValueT>::pair;
45
47 const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; }
48 ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; }
49 const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; }
50};
51
52} // end namespace detail
53
54template <typename KeyT, typename ValueT,
55 typename KeyInfoT = DenseMapInfo<KeyT>,
57 bool IsConst = false>
58class DenseMapIterator;
59
60template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
61 typename BucketT>
63 template <typename T>
64 using const_arg_type_t = typename const_pointer_or_const_ref<T>::type;
65
66public:
67 using size_type = unsigned;
68 using key_type = KeyT;
69 using mapped_type = ValueT;
70 using value_type = BucketT;
71
75
76 inline iterator begin() {
77 // When the map is empty, avoid the overhead of advancing/retreating past
78 // empty buckets.
79 if (empty())
80 return end();
81 if (shouldReverseIterate<KeyT>())
82 return makeIterator(getBucketsEnd() - 1, getBuckets(), *this);
83 return makeIterator(getBuckets(), getBucketsEnd(), *this);
84 }
85 inline iterator end() {
86 return makeIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
87 }
88 inline const_iterator begin() const {
89 if (empty())
90 return end();
91 if (shouldReverseIterate<KeyT>())
92 return makeConstIterator(getBucketsEnd() - 1, getBuckets(), *this);
93 return makeConstIterator(getBuckets(), getBucketsEnd(), *this);
94 }
95 inline const_iterator end() const {
96 return makeConstIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
97 }
98
99 [[nodiscard]] bool empty() const { return getNumEntries() == 0; }
100 unsigned size() const { return getNumEntries(); }
101
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())
108 grow(NumBuckets);
109 }
110
111 void clear() {
113 if (getNumEntries() == 0 && getNumTombstones() == 0) return;
114
115 // If the capacity of the array is huge, and the # elements used is small,
116 // shrink the array.
117 if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
118 shrink_and_clear();
119 return;
120 }
121
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;
127 } else {
128 [[maybe_unused]] 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();
133 --NumEntries;
134 }
135 P->getFirst() = EmptyKey;
136 }
137 }
138 assert(NumEntries == 0 && "Node count imbalance!");
139 (void)NumEntries;
140 }
141 setNumEntries(0);
142 setNumTombstones(0);
143 }
144
145 /// Return true if the specified key is in the map, false otherwise.
146 bool contains(const_arg_type_t<KeyT> Val) const {
147 const BucketT *TheBucket;
148 return LookupBucketFor(Val, TheBucket);
149 }
150
151 /// Return 1 if the specified key is in the map, 0 otherwise.
152 size_type count(const_arg_type_t<KeyT> Val) const {
153 return contains(Val) ? 1 : 0;
154 }
155
156 iterator find(const_arg_type_t<KeyT> Val) {
157 BucketT *TheBucket;
158 if (LookupBucketFor(Val, TheBucket))
159 return makeIterator(TheBucket,
160 shouldReverseIterate<KeyT>() ? getBuckets()
161 : getBucketsEnd(),
162 *this, true);
163 return end();
164 }
165 const_iterator find(const_arg_type_t<KeyT> Val) const {
166 const BucketT *TheBucket;
167 if (LookupBucketFor(Val, TheBucket))
168 return makeConstIterator(TheBucket,
169 shouldReverseIterate<KeyT>() ? getBuckets()
170 : getBucketsEnd(),
171 *this, true);
172 return end();
173 }
174
175 /// Alternate version of find() which allows a different, and possibly
176 /// less expensive, key type.
177 /// The DenseMapInfo is responsible for supplying methods
178 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
179 /// type used.
180 template<class LookupKeyT>
181 iterator find_as(const LookupKeyT &Val) {
182 BucketT *TheBucket;
183 if (LookupBucketFor(Val, TheBucket))
184 return makeIterator(TheBucket,
185 shouldReverseIterate<KeyT>() ? getBuckets()
186 : getBucketsEnd(),
187 *this, true);
188 return end();
189 }
190 template<class LookupKeyT>
191 const_iterator find_as(const LookupKeyT &Val) const {
192 const BucketT *TheBucket;
193 if (LookupBucketFor(Val, TheBucket))
194 return makeConstIterator(TheBucket,
195 shouldReverseIterate<KeyT>() ? getBuckets()
196 : getBucketsEnd(),
197 *this, true);
198 return end();
199 }
200
201 /// lookup - Return the entry for the specified key, or a default
202 /// constructed value if no such entry exists.
203 ValueT lookup(const_arg_type_t<KeyT> Val) const {
204 const BucketT *TheBucket;
205 if (LookupBucketFor(Val, TheBucket))
206 return TheBucket->getSecond();
207 return ValueT();
208 }
209
210 /// at - Return the entry for the specified key, or abort if no such
211 /// entry exists.
212 const ValueT &at(const_arg_type_t<KeyT> Val) const {
213 auto Iter = this->find(std::move(Val));
214 assert(Iter != this->end() && "DenseMap::at failed due to a missing key");
215 return Iter->second;
216 }
217
218 // Inserts key,value pair into the map if the key isn't already in the map.
219 // If the key is already in the map, it returns false and doesn't update the
220 // value.
221 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
222 return try_emplace(KV.first, KV.second);
223 }
224
225 // Inserts key,value pair into the map if the key isn't already in the map.
226 // If the key is already in the map, it returns false and doesn't update the
227 // value.
228 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
229 return try_emplace(std::move(KV.first), std::move(KV.second));
230 }
231
232 // Inserts key,value pair into the map if the key isn't already in the map.
233 // The value is constructed in-place if the key is not in the map, otherwise
234 // it is not moved.
235 template <typename... Ts>
236 std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&... Args) {
237 BucketT *TheBucket;
238 if (LookupBucketFor(Key, TheBucket))
239 return std::make_pair(makeIterator(TheBucket,
240 shouldReverseIterate<KeyT>()
241 ? getBuckets()
242 : getBucketsEnd(),
243 *this, true),
244 false); // Already in map.
245
246 // Otherwise, insert the new element.
247 TheBucket =
248 InsertIntoBucket(TheBucket, std::move(Key), std::forward<Ts>(Args)...);
249 return std::make_pair(makeIterator(TheBucket,
250 shouldReverseIterate<KeyT>()
251 ? getBuckets()
252 : getBucketsEnd(),
253 *this, true),
254 true);
255 }
256
257 // Inserts key,value pair into the map if the key isn't already in the map.
258 // The value is constructed in-place if the key is not in the map, otherwise
259 // it is not moved.
260 template <typename... Ts>
261 std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&... Args) {
262 BucketT *TheBucket;
263 if (LookupBucketFor(Key, TheBucket))
264 return std::make_pair(makeIterator(TheBucket,
265 shouldReverseIterate<KeyT>()
266 ? getBuckets()
267 : getBucketsEnd(),
268 *this, true),
269 false); // Already in map.
270
271 // Otherwise, insert the new element.
272 TheBucket = InsertIntoBucket(TheBucket, Key, std::forward<Ts>(Args)...);
273 return std::make_pair(makeIterator(TheBucket,
274 shouldReverseIterate<KeyT>()
275 ? getBuckets()
276 : getBucketsEnd(),
277 *this, true),
278 true);
279 }
280
281 /// Alternate version of insert() which allows a different, and possibly
282 /// less expensive, key type.
283 /// The DenseMapInfo is responsible for supplying methods
284 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
285 /// type used.
286 template <typename LookupKeyT>
287 std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV,
288 const LookupKeyT &Val) {
289 BucketT *TheBucket;
290 if (LookupBucketFor(Val, TheBucket))
291 return std::make_pair(makeIterator(TheBucket,
292 shouldReverseIterate<KeyT>()
293 ? getBuckets()
294 : getBucketsEnd(),
295 *this, true),
296 false); // Already in map.
297
298 // Otherwise, insert the new element.
299 TheBucket = InsertIntoBucketWithLookup(TheBucket, std::move(KV.first),
300 std::move(KV.second), Val);
301 return std::make_pair(makeIterator(TheBucket,
302 shouldReverseIterate<KeyT>()
303 ? getBuckets()
304 : getBucketsEnd(),
305 *this, true),
306 true);
307 }
308
309 /// insert - Range insertion of pairs.
310 template<typename InputIt>
311 void insert(InputIt I, InputIt E) {
312 for (; I != E; ++I)
313 insert(*I);
314 }
315
316 /// Returns the value associated to the key in the map if it exists. If it
317 /// does not exist, emplace a default value for the key and returns a
318 /// reference to the newly created value.
319 ValueT &getOrInsertDefault(KeyT &&Key) {
320 return try_emplace(Key).first->second;
321 }
322
323 /// Returns the value associated to the key in the map if it exists. If it
324 /// does not exist, emplace a default value for the key and returns a
325 /// reference to the newly created value.
326 ValueT &getOrInsertDefault(const KeyT &Key) {
327 return try_emplace(Key).first->second;
328 }
329
330 bool erase(const KeyT &Val) {
331 BucketT *TheBucket;
332 if (!LookupBucketFor(Val, TheBucket))
333 return false; // not in map.
334
335 TheBucket->getSecond().~ValueT();
336 TheBucket->getFirst() = getTombstoneKey();
337 decrementNumEntries();
338 incrementNumTombstones();
339 return true;
340 }
341 void erase(iterator I) {
342 BucketT *TheBucket = &*I;
343 TheBucket->getSecond().~ValueT();
344 TheBucket->getFirst() = getTombstoneKey();
345 decrementNumEntries();
346 incrementNumTombstones();
347 }
348
349 value_type& FindAndConstruct(const KeyT &Key) {
350 BucketT *TheBucket;
351 if (LookupBucketFor(Key, TheBucket))
352 return *TheBucket;
353
354 return *InsertIntoBucket(TheBucket, Key);
355 }
356
357 ValueT &operator[](const KeyT &Key) {
358 return FindAndConstruct(Key).second;
359 }
360
362 BucketT *TheBucket;
363 if (LookupBucketFor(Key, TheBucket))
364 return *TheBucket;
365
366 return *InsertIntoBucket(TheBucket, std::move(Key));
367 }
368
369 ValueT &operator[](KeyT &&Key) {
370 return FindAndConstruct(std::move(Key)).second;
371 }
372
373 /// isPointerIntoBucketsArray - Return true if the specified pointer points
374 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
375 /// value in the DenseMap).
376 bool isPointerIntoBucketsArray(const void *Ptr) const {
377 return Ptr >= getBuckets() && Ptr < getBucketsEnd();
378 }
379
380 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
381 /// array. In conjunction with the previous method, this can be used to
382 /// determine whether an insertion caused the DenseMap to reallocate.
383 const void *getPointerIntoBucketsArray() const { return getBuckets(); }
384
385protected:
386 DenseMapBase() = default;
387
388 void destroyAll() {
389 if (getNumBuckets() == 0) // Nothing to do.
390 return;
391
392 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
393 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
394 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
395 !KeyInfoT::isEqual(P->getFirst(), TombstoneKey))
396 P->getSecond().~ValueT();
397 P->getFirst().~KeyT();
398 }
399 }
400
401 void initEmpty() {
402 setNumEntries(0);
403 setNumTombstones(0);
404
405 assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
406 "# initial buckets must be a power of two!");
407 const KeyT EmptyKey = getEmptyKey();
408 for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
409 ::new (&B->getFirst()) KeyT(EmptyKey);
410 }
411
412 /// Returns the number of buckets to allocate to ensure that the DenseMap can
413 /// accommodate \p NumEntries without need to grow().
414 unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
415 // Ensure that "NumEntries * 4 < NumBuckets * 3"
416 if (NumEntries == 0)
417 return 0;
418 // +1 is required because of the strict equality.
419 // For example if NumEntries is 48, we need to return 401.
420 return static_cast<unsigned>(NextPowerOf2(NumEntries * 4 / 3 + 1));
421 }
422
423 void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
424 initEmpty();
425
426 // Insert all the old elements.
427 const KeyT EmptyKey = getEmptyKey();
428 const KeyT TombstoneKey = getTombstoneKey();
429 for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
430 if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) &&
431 !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) {
432 // Insert the key/value into the new table.
433 BucketT *DestBucket;
434 bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket);
435 (void)FoundVal; // silence warning.
436 assert(!FoundVal && "Key already in new map?");
437 DestBucket->getFirst() = std::move(B->getFirst());
438 ::new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond()));
439 incrementNumEntries();
440
441 // Free the value.
442 B->getSecond().~ValueT();
443 }
444 B->getFirst().~KeyT();
445 }
446 }
447
448 template <typename OtherBaseT>
451 assert(&other != this);
452 assert(getNumBuckets() == other.getNumBuckets());
453
454 setNumEntries(other.getNumEntries());
455 setNumTombstones(other.getNumTombstones());
456
457 if (std::is_trivially_copyable<KeyT>::value &&
458 std::is_trivially_copyable<ValueT>::value)
459 memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(),
460 getNumBuckets() * sizeof(BucketT));
461 else
462 for (size_t i = 0; i < getNumBuckets(); ++i) {
463 ::new (&getBuckets()[i].getFirst())
464 KeyT(other.getBuckets()[i].getFirst());
465 if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) &&
466 !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey()))
467 ::new (&getBuckets()[i].getSecond())
468 ValueT(other.getBuckets()[i].getSecond());
469 }
470 }
471
472 static unsigned getHashValue(const KeyT &Val) {
473 return KeyInfoT::getHashValue(Val);
474 }
475
476 template<typename LookupKeyT>
477 static unsigned getHashValue(const LookupKeyT &Val) {
478 return KeyInfoT::getHashValue(Val);
479 }
480
481 static const KeyT getEmptyKey() {
482 static_assert(std::is_base_of<DenseMapBase, DerivedT>::value,
483 "Must pass the derived type to this template!");
484 return KeyInfoT::getEmptyKey();
485 }
486
487 static const KeyT getTombstoneKey() {
488 return KeyInfoT::getTombstoneKey();
489 }
490
491private:
492 iterator makeIterator(BucketT *P, BucketT *E,
493 DebugEpochBase &Epoch,
494 bool NoAdvance=false) {
495 if (shouldReverseIterate<KeyT>()) {
496 BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
497 return iterator(B, E, Epoch, NoAdvance);
498 }
499 return iterator(P, E, Epoch, NoAdvance);
500 }
501
502 const_iterator makeConstIterator(const BucketT *P, const BucketT *E,
503 const DebugEpochBase &Epoch,
504 const bool NoAdvance=false) const {
505 if (shouldReverseIterate<KeyT>()) {
506 const BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
507 return const_iterator(B, E, Epoch, NoAdvance);
508 }
509 return const_iterator(P, E, Epoch, NoAdvance);
510 }
511
512 unsigned getNumEntries() const {
513 return static_cast<const DerivedT *>(this)->getNumEntries();
514 }
515
516 void setNumEntries(unsigned Num) {
517 static_cast<DerivedT *>(this)->setNumEntries(Num);
518 }
519
520 void incrementNumEntries() {
521 setNumEntries(getNumEntries() + 1);
522 }
523
524 void decrementNumEntries() {
525 setNumEntries(getNumEntries() - 1);
526 }
527
528 unsigned getNumTombstones() const {
529 return static_cast<const DerivedT *>(this)->getNumTombstones();
530 }
531
532 void setNumTombstones(unsigned Num) {
533 static_cast<DerivedT *>(this)->setNumTombstones(Num);
534 }
535
536 void incrementNumTombstones() {
537 setNumTombstones(getNumTombstones() + 1);
538 }
539
540 void decrementNumTombstones() {
541 setNumTombstones(getNumTombstones() - 1);
542 }
543
544 const BucketT *getBuckets() const {
545 return static_cast<const DerivedT *>(this)->getBuckets();
546 }
547
548 BucketT *getBuckets() {
549 return static_cast<DerivedT *>(this)->getBuckets();
550 }
551
552 unsigned getNumBuckets() const {
553 return static_cast<const DerivedT *>(this)->getNumBuckets();
554 }
555
556 BucketT *getBucketsEnd() {
557 return getBuckets() + getNumBuckets();
558 }
559
560 const BucketT *getBucketsEnd() const {
561 return getBuckets() + getNumBuckets();
562 }
563
564 void grow(unsigned AtLeast) {
565 static_cast<DerivedT *>(this)->grow(AtLeast);
566 }
567
568 void shrink_and_clear() {
569 static_cast<DerivedT *>(this)->shrink_and_clear();
570 }
571
572 template <typename KeyArg, typename... ValueArgs>
573 BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key,
574 ValueArgs &&... Values) {
575 TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket);
576
577 TheBucket->getFirst() = std::forward<KeyArg>(Key);
578 ::new (&TheBucket->getSecond()) ValueT(std::forward<ValueArgs>(Values)...);
579 return TheBucket;
580 }
581
582 template <typename LookupKeyT>
583 BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key,
584 ValueT &&Value, LookupKeyT &Lookup) {
585 TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket);
586
587 TheBucket->getFirst() = std::move(Key);
588 ::new (&TheBucket->getSecond()) ValueT(std::move(Value));
589 return TheBucket;
590 }
591
592 template <typename LookupKeyT>
593 BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup,
594 BucketT *TheBucket) {
596
597 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
598 // the buckets are empty (meaning that many are filled with tombstones),
599 // grow the table.
600 //
601 // The later case is tricky. For example, if we had one empty bucket with
602 // tons of tombstones, failing lookups (e.g. for insertion) would have to
603 // probe almost the entire table until it found the empty bucket. If the
604 // table completely filled with tombstones, no lookup would ever succeed,
605 // causing infinite loops in lookup.
606 unsigned NewNumEntries = getNumEntries() + 1;
607 unsigned NumBuckets = getNumBuckets();
608 if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) {
609 this->grow(NumBuckets * 2);
610 LookupBucketFor(Lookup, TheBucket);
611 NumBuckets = getNumBuckets();
612 } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <=
613 NumBuckets/8)) {
614 this->grow(NumBuckets);
615 LookupBucketFor(Lookup, TheBucket);
616 }
617 assert(TheBucket);
618
619 // Only update the state after we've grown our bucket space appropriately
620 // so that when growing buckets we have self-consistent entry count.
621 incrementNumEntries();
622
623 // If we are writing over a tombstone, remember this.
624 const KeyT EmptyKey = getEmptyKey();
625 if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey))
626 decrementNumTombstones();
627
628 return TheBucket;
629 }
630
631 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
632 /// FoundBucket. If the bucket contains the key and a value, this returns
633 /// true, otherwise it returns a bucket with an empty marker or tombstone and
634 /// returns false.
635 template<typename LookupKeyT>
636 bool LookupBucketFor(const LookupKeyT &Val,
637 const BucketT *&FoundBucket) const {
638 const BucketT *BucketsPtr = getBuckets();
639 const unsigned NumBuckets = getNumBuckets();
640
641 if (NumBuckets == 0) {
642 FoundBucket = nullptr;
643 return false;
644 }
645
646 // FoundTombstone - Keep track of whether we find a tombstone while probing.
647 const BucketT *FoundTombstone = nullptr;
648 const KeyT EmptyKey = getEmptyKey();
649 const KeyT TombstoneKey = getTombstoneKey();
650 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
651 !KeyInfoT::isEqual(Val, TombstoneKey) &&
652 "Empty/Tombstone value shouldn't be inserted into map!");
653
654 unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
655 unsigned ProbeAmt = 1;
656 while (true) {
657 const BucketT *ThisBucket = BucketsPtr + BucketNo;
658 // Found Val's bucket? If so, return it.
659 if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) {
660 FoundBucket = ThisBucket;
661 return true;
662 }
663
664 // If we found an empty bucket, the key doesn't exist in the set.
665 // Insert it and return the default value.
666 if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) {
667 // If we've already seen a tombstone while probing, fill it in instead
668 // of the empty bucket we eventually probed to.
669 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
670 return false;
671 }
672
673 // If this is a tombstone, remember it. If Val ends up not in the map, we
674 // prefer to return it than something that would require more probing.
675 if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
676 !FoundTombstone)
677 FoundTombstone = ThisBucket; // Remember the first tombstone found.
678
679 // Otherwise, it's a hash collision or a tombstone, continue quadratic
680 // probing.
681 BucketNo += ProbeAmt++;
682 BucketNo &= (NumBuckets-1);
683 }
684 }
685
686 template <typename LookupKeyT>
687 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
688 const BucketT *ConstFoundBucket;
689 bool Result = const_cast<const DenseMapBase *>(this)
690 ->LookupBucketFor(Val, ConstFoundBucket);
691 FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
692 return Result;
693 }
694
695public:
696 /// Return the approximate size (in bytes) of the actual map.
697 /// This is just the raw memory used by DenseMap.
698 /// If entries are pointers to objects, the size of the referenced objects
699 /// are not included.
700 size_t getMemorySize() const {
701 return getNumBuckets() * sizeof(BucketT);
702 }
703};
704
705/// Equality comparison for DenseMap.
706///
707/// Iterates over elements of LHS confirming that each (key, value) pair in LHS
708/// is also in RHS, and that no additional pairs are in RHS.
709/// Equivalent to N calls to RHS.find and N value comparisons. Amortized
710/// complexity is linear, worst case is O(N^2) (if every hash collides).
711template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
712 typename BucketT>
716 if (LHS.size() != RHS.size())
717 return false;
718
719 for (auto &KV : LHS) {
720 auto I = RHS.find(KV.first);
721 if (I == RHS.end() || I->second != KV.second)
722 return false;
723 }
724
725 return true;
726}
727
728/// Inequality comparison for DenseMap.
729///
730/// Equivalent to !(LHS == RHS). See operator== for performance notes.
731template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
732 typename BucketT>
736 return !(LHS == RHS);
737}
738
739template <typename KeyT, typename ValueT,
740 typename KeyInfoT = DenseMapInfo<KeyT>,
742class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
743 KeyT, ValueT, KeyInfoT, BucketT> {
744 friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
745
746 // Lift some types from the dependent base class into this class for
747 // simplicity of referring to them.
749
750 BucketT *Buckets;
751 unsigned NumEntries;
752 unsigned NumTombstones;
753 unsigned NumBuckets;
754
755public:
756 /// Create a DenseMap with an optional \p InitialReserve that guarantee that
757 /// this number of elements can be inserted in the map without grow()
758 explicit DenseMap(unsigned InitialReserve = 0) { init(InitialReserve); }
759
760 DenseMap(const DenseMap &other) : BaseT() {
761 init(0);
762 copyFrom(other);
763 }
764
765 DenseMap(DenseMap &&other) : BaseT() {
766 init(0);
767 swap(other);
768 }
769
770 template<typename InputIt>
771 DenseMap(const InputIt &I, const InputIt &E) {
772 init(std::distance(I, E));
773 this->insert(I, E);
774 }
775
776 DenseMap(std::initializer_list<typename BaseT::value_type> Vals) {
777 init(Vals.size());
778 this->insert(Vals.begin(), Vals.end());
779 }
780
782 this->destroyAll();
783 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
784 }
785
786 void swap(DenseMap& RHS) {
787 this->incrementEpoch();
788 RHS.incrementEpoch();
789 std::swap(Buckets, RHS.Buckets);
790 std::swap(NumEntries, RHS.NumEntries);
791 std::swap(NumTombstones, RHS.NumTombstones);
792 std::swap(NumBuckets, RHS.NumBuckets);
793 }
794
795 DenseMap& operator=(const DenseMap& other) {
796 if (&other != this)
797 copyFrom(other);
798 return *this;
799 }
800
802 this->destroyAll();
803 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
804 init(0);
805 swap(other);
806 return *this;
807 }
808
809 void copyFrom(const DenseMap& other) {
810 this->destroyAll();
811 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
812 if (allocateBuckets(other.NumBuckets)) {
813 this->BaseT::copyFrom(other);
814 } else {
815 NumEntries = 0;
816 NumTombstones = 0;
817 }
818 }
819
820 void init(unsigned InitNumEntries) {
821 auto InitBuckets = BaseT::getMinBucketToReserveForEntries(InitNumEntries);
822 if (allocateBuckets(InitBuckets)) {
823 this->BaseT::initEmpty();
824 } else {
825 NumEntries = 0;
826 NumTombstones = 0;
827 }
828 }
829
830 void grow(unsigned AtLeast) {
831 unsigned OldNumBuckets = NumBuckets;
832 BucketT *OldBuckets = Buckets;
833
834 allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
835 assert(Buckets);
836 if (!OldBuckets) {
837 this->BaseT::initEmpty();
838 return;
839 }
840
841 this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
842
843 // Free the old table.
844 deallocate_buffer(OldBuckets, sizeof(BucketT) * OldNumBuckets,
845 alignof(BucketT));
846 }
847
849 unsigned OldNumBuckets = NumBuckets;
850 unsigned OldNumEntries = NumEntries;
851 this->destroyAll();
852
853 // Reduce the number of buckets.
854 unsigned NewNumBuckets = 0;
855 if (OldNumEntries)
856 NewNumBuckets = (std::max)(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
857 if (NewNumBuckets == NumBuckets) {
858 this->BaseT::initEmpty();
859 return;
860 }
861
862 deallocate_buffer(Buckets, sizeof(BucketT) * OldNumBuckets,
863 alignof(BucketT));
864 init(NewNumBuckets);
865 }
866
867private:
868 unsigned getNumEntries() const {
869 return NumEntries;
870 }
871
872 void setNumEntries(unsigned Num) {
873 NumEntries = Num;
874 }
875
876 unsigned getNumTombstones() const {
877 return NumTombstones;
878 }
879
880 void setNumTombstones(unsigned Num) {
881 NumTombstones = Num;
882 }
883
884 BucketT *getBuckets() const {
885 return Buckets;
886 }
887
888 unsigned getNumBuckets() const {
889 return NumBuckets;
890 }
891
892 bool allocateBuckets(unsigned Num) {
893 NumBuckets = Num;
894 if (NumBuckets == 0) {
895 Buckets = nullptr;
896 return false;
897 }
898
899 Buckets = static_cast<BucketT *>(
900 allocate_buffer(sizeof(BucketT) * NumBuckets, alignof(BucketT)));
901 return true;
902 }
903};
904
905template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
906 typename KeyInfoT = DenseMapInfo<KeyT>,
909 : public DenseMapBase<
910 SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT,
911 ValueT, KeyInfoT, BucketT> {
912 friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
913
914 // Lift some types from the dependent base class into this class for
915 // simplicity of referring to them.
917
918 static_assert(isPowerOf2_64(InlineBuckets),
919 "InlineBuckets must be a power of 2.");
920
921 unsigned Small : 1;
922 unsigned NumEntries : 31;
923 unsigned NumTombstones;
924
925 struct LargeRep {
926 BucketT *Buckets;
927 unsigned NumBuckets;
928 };
929
930 /// A "union" of an inline bucket array and the struct representing
931 /// a large bucket. This union will be discriminated by the 'Small' bit.
933
934public:
935 explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
936 if (NumInitBuckets > InlineBuckets)
937 NumInitBuckets = std::bit_ceil(NumInitBuckets);
938 init(NumInitBuckets);
939 }
940
942 init(0);
943 copyFrom(other);
944 }
945
947 init(0);
948 swap(other);
949 }
950
951 template<typename InputIt>
952 SmallDenseMap(const InputIt &I, const InputIt &E) {
953 init(NextPowerOf2(std::distance(I, E)));
954 this->insert(I, E);
955 }
956
957 SmallDenseMap(std::initializer_list<typename BaseT::value_type> Vals)
958 : SmallDenseMap(Vals.begin(), Vals.end()) {}
959
961 this->destroyAll();
962 deallocateBuckets();
963 }
964
965 void swap(SmallDenseMap& RHS) {
966 unsigned TmpNumEntries = RHS.NumEntries;
967 RHS.NumEntries = NumEntries;
968 NumEntries = TmpNumEntries;
969 std::swap(NumTombstones, RHS.NumTombstones);
970
971 const KeyT EmptyKey = this->getEmptyKey();
972 const KeyT TombstoneKey = this->getTombstoneKey();
973 if (Small && RHS.Small) {
974 // If we're swapping inline bucket arrays, we have to cope with some of
975 // the tricky bits of DenseMap's storage system: the buckets are not
976 // fully initialized. Thus we swap every key, but we may have
977 // a one-directional move of the value.
978 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
979 BucketT *LHSB = &getInlineBuckets()[i],
980 *RHSB = &RHS.getInlineBuckets()[i];
981 bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
982 !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
983 bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
984 !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
985 if (hasLHSValue && hasRHSValue) {
986 // Swap together if we can...
987 std::swap(*LHSB, *RHSB);
988 continue;
989 }
990 // Swap separately and handle any asymmetry.
991 std::swap(LHSB->getFirst(), RHSB->getFirst());
992 if (hasLHSValue) {
993 ::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
994 LHSB->getSecond().~ValueT();
995 } else if (hasRHSValue) {
996 ::new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
997 RHSB->getSecond().~ValueT();
998 }
999 }
1000 return;
1001 }
1002 if (!Small && !RHS.Small) {
1003 std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
1004 std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
1005 return;
1006 }
1007
1008 SmallDenseMap &SmallSide = Small ? *this : RHS;
1009 SmallDenseMap &LargeSide = Small ? RHS : *this;
1010
1011 // First stash the large side's rep and move the small side across.
1012 LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
1013 LargeSide.getLargeRep()->~LargeRep();
1014 LargeSide.Small = true;
1015 // This is similar to the standard move-from-old-buckets, but the bucket
1016 // count hasn't actually rotated in this case. So we have to carefully
1017 // move construct the keys and values into their new locations, but there
1018 // is no need to re-hash things.
1019 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
1020 BucketT *NewB = &LargeSide.getInlineBuckets()[i],
1021 *OldB = &SmallSide.getInlineBuckets()[i];
1022 ::new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
1023 OldB->getFirst().~KeyT();
1024 if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
1025 !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
1026 ::new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
1027 OldB->getSecond().~ValueT();
1028 }
1029 }
1030
1031 // The hard part of moving the small buckets across is done, just move
1032 // the TmpRep into its new home.
1033 SmallSide.Small = false;
1034 new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
1035 }
1036
1038 if (&other != this)
1039 copyFrom(other);
1040 return *this;
1041 }
1042
1044 this->destroyAll();
1045 deallocateBuckets();
1046 init(0);
1047 swap(other);
1048 return *this;
1049 }
1050
1051 void copyFrom(const SmallDenseMap& other) {
1052 this->destroyAll();
1053 deallocateBuckets();
1054 Small = true;
1055 if (other.getNumBuckets() > InlineBuckets) {
1056 Small = false;
1057 new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
1058 }
1059 this->BaseT::copyFrom(other);
1060 }
1061
1062 void init(unsigned InitBuckets) {
1063 Small = true;
1064 if (InitBuckets > InlineBuckets) {
1065 Small = false;
1066 new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
1067 }
1068 this->BaseT::initEmpty();
1069 }
1070
1071 void grow(unsigned AtLeast) {
1072 if (AtLeast > InlineBuckets)
1073 AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
1074
1075 if (Small) {
1076 // First move the inline buckets into a temporary storage.
1078 BucketT *TmpBegin = reinterpret_cast<BucketT *>(&TmpStorage);
1079 BucketT *TmpEnd = TmpBegin;
1080
1081 // Loop over the buckets, moving non-empty, non-tombstones into the
1082 // temporary storage. Have the loop move the TmpEnd forward as it goes.
1083 const KeyT EmptyKey = this->getEmptyKey();
1084 const KeyT TombstoneKey = this->getTombstoneKey();
1085 for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
1086 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
1087 !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
1088 assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
1089 "Too many inline buckets!");
1090 ::new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst()));
1091 ::new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond()));
1092 ++TmpEnd;
1093 P->getSecond().~ValueT();
1094 }
1095 P->getFirst().~KeyT();
1096 }
1097
1098 // AtLeast == InlineBuckets can happen if there are many tombstones,
1099 // and grow() is used to remove them. Usually we always switch to the
1100 // large rep here.
1101 if (AtLeast > InlineBuckets) {
1102 Small = false;
1103 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
1104 }
1105 this->moveFromOldBuckets(TmpBegin, TmpEnd);
1106 return;
1107 }
1108
1109 LargeRep OldRep = std::move(*getLargeRep());
1110 getLargeRep()->~LargeRep();
1111 if (AtLeast <= InlineBuckets) {
1112 Small = true;
1113 } else {
1114 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
1115 }
1116
1117 this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
1118
1119 // Free the old table.
1120 deallocate_buffer(OldRep.Buckets, sizeof(BucketT) * OldRep.NumBuckets,
1121 alignof(BucketT));
1122 }
1123
1125 unsigned OldSize = this->size();
1126 this->destroyAll();
1127
1128 // Reduce the number of buckets.
1129 unsigned NewNumBuckets = 0;
1130 if (OldSize) {
1131 NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
1132 if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
1133 NewNumBuckets = 64;
1134 }
1135 if ((Small && NewNumBuckets <= InlineBuckets) ||
1136 (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
1137 this->BaseT::initEmpty();
1138 return;
1139 }
1140
1141 deallocateBuckets();
1142 init(NewNumBuckets);
1143 }
1144
1145private:
1146 unsigned getNumEntries() const {
1147 return NumEntries;
1148 }
1149
1150 void setNumEntries(unsigned Num) {
1151 // NumEntries is hardcoded to be 31 bits wide.
1152 assert(Num < (1U << 31) && "Cannot support more than 1<<31 entries");
1153 NumEntries = Num;
1154 }
1155
1156 unsigned getNumTombstones() const {
1157 return NumTombstones;
1158 }
1159
1160 void setNumTombstones(unsigned Num) {
1161 NumTombstones = Num;
1162 }
1163
1164 const BucketT *getInlineBuckets() const {
1165 assert(Small);
1166 // Note that this cast does not violate aliasing rules as we assert that
1167 // the memory's dynamic type is the small, inline bucket buffer, and the
1168 // 'storage' is a POD containing a char buffer.
1169 return reinterpret_cast<const BucketT *>(&storage);
1170 }
1171
1172 BucketT *getInlineBuckets() {
1173 return const_cast<BucketT *>(
1174 const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
1175 }
1176
1177 const LargeRep *getLargeRep() const {
1178 assert(!Small);
1179 // Note, same rule about aliasing as with getInlineBuckets.
1180 return reinterpret_cast<const LargeRep *>(&storage);
1181 }
1182
1183 LargeRep *getLargeRep() {
1184 return const_cast<LargeRep *>(
1185 const_cast<const SmallDenseMap *>(this)->getLargeRep());
1186 }
1187
1188 const BucketT *getBuckets() const {
1189 return Small ? getInlineBuckets() : getLargeRep()->Buckets;
1190 }
1191
1192 BucketT *getBuckets() {
1193 return const_cast<BucketT *>(
1194 const_cast<const SmallDenseMap *>(this)->getBuckets());
1195 }
1196
1197 unsigned getNumBuckets() const {
1198 return Small ? InlineBuckets : getLargeRep()->NumBuckets;
1199 }
1200
1201 void deallocateBuckets() {
1202 if (Small)
1203 return;
1204
1205 deallocate_buffer(getLargeRep()->Buckets,
1206 sizeof(BucketT) * getLargeRep()->NumBuckets,
1207 alignof(BucketT));
1208 getLargeRep()->~LargeRep();
1209 }
1210
1211 LargeRep allocateBuckets(unsigned Num) {
1212 assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
1213 LargeRep Rep = {static_cast<BucketT *>(allocate_buffer(
1214 sizeof(BucketT) * Num, alignof(BucketT))),
1215 Num};
1216 return Rep;
1217 }
1218};
1219
1220template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket,
1221 bool IsConst>
1223 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
1224 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;
1225
1226public:
1227 using difference_type = ptrdiff_t;
1228 using value_type = std::conditional_t<IsConst, const Bucket, Bucket>;
1231 using iterator_category = std::forward_iterator_tag;
1232
1233private:
1234 pointer Ptr = nullptr;
1235 pointer End = nullptr;
1236
1237public:
1238 DenseMapIterator() = default;
1239
1241 bool NoAdvance = false)
1242 : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) {
1243 assert(isHandleInSync() && "invalid construction!");
1244
1245 if (NoAdvance) return;
1246 if (shouldReverseIterate<KeyT>()) {
1247 RetreatPastEmptyBuckets();
1248 return;
1249 }
1250 AdvancePastEmptyBuckets();
1251 }
1252
1253 // Converting ctor from non-const iterators to const iterators. SFINAE'd out
1254 // for const iterator destinations so it doesn't end up as a user defined copy
1255 // constructor.
1256 template <bool IsConstSrc,
1257 typename = std::enable_if_t<!IsConstSrc && IsConst>>
1260 : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {}
1261
1263 assert(isHandleInSync() && "invalid iterator access!");
1264 assert(Ptr != End && "dereferencing end() iterator");
1265 if (shouldReverseIterate<KeyT>())
1266 return Ptr[-1];
1267 return *Ptr;
1268 }
1270 assert(isHandleInSync() && "invalid iterator access!");
1271 assert(Ptr != End && "dereferencing end() iterator");
1272 if (shouldReverseIterate<KeyT>())
1273 return &(Ptr[-1]);
1274 return Ptr;
1275 }
1276
1277 friend bool operator==(const DenseMapIterator &LHS,
1278 const DenseMapIterator &RHS) {
1279 assert((!LHS.Ptr || LHS.isHandleInSync()) && "handle not in sync!");
1280 assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
1281 assert(LHS.getEpochAddress() == RHS.getEpochAddress() &&
1282 "comparing incomparable iterators!");
1283 return LHS.Ptr == RHS.Ptr;
1284 }
1285
1286 friend bool operator!=(const DenseMapIterator &LHS,
1287 const DenseMapIterator &RHS) {
1288 return !(LHS == RHS);
1289 }
1290
1291 inline DenseMapIterator& operator++() { // Preincrement
1292 assert(isHandleInSync() && "invalid iterator access!");
1293 assert(Ptr != End && "incrementing end() iterator");
1294 if (shouldReverseIterate<KeyT>()) {
1295 --Ptr;
1296 RetreatPastEmptyBuckets();
1297 return *this;
1298 }
1299 ++Ptr;
1300 AdvancePastEmptyBuckets();
1301 return *this;
1302 }
1303 DenseMapIterator operator++(int) { // Postincrement
1304 assert(isHandleInSync() && "invalid iterator access!");
1305 DenseMapIterator tmp = *this; ++*this; return tmp;
1306 }
1307
1308private:
1309 void AdvancePastEmptyBuckets() {
1310 assert(Ptr <= End);
1311 const KeyT Empty = KeyInfoT::getEmptyKey();
1312 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1313
1314 while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
1315 KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
1316 ++Ptr;
1317 }
1318
1319 void RetreatPastEmptyBuckets() {
1320 assert(Ptr >= End);
1321 const KeyT Empty = KeyInfoT::getEmptyKey();
1322 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1323
1324 while (Ptr != End && (KeyInfoT::isEqual(Ptr[-1].getFirst(), Empty) ||
1325 KeyInfoT::isEqual(Ptr[-1].getFirst(), Tombstone)))
1326 --Ptr;
1327 }
1328};
1329
1330template <typename KeyT, typename ValueT, typename KeyInfoT>
1332 return X.getMemorySize();
1333}
1334
1335} // end namespace wpi
1336
1337#endif // WPIUTIL_WPI_DENSEMAP_H
#define LLVM_UNLIKELY(EXPR)
Definition: Compiler.h:234
#define LLVM_LIKELY(EXPR)
Definition: Compiler.h:233
This file defines DenseMapInfo traits for DenseMap.
This file defines the DebugEpochBase and DebugEpochBase::HandleBase classes.
This file defines counterparts of C library allocation functions defined in the namespace 'std'.
A base class for iterator classes ("handles") that wish to poll for iterator invalidating modificatio...
Definition: EpochTracker.h:58
A base class for data structure classes wishing to make iterators ("handles") pointing into themselve...
Definition: EpochTracker.h:36
void incrementEpoch()
Calling incrementEpoch invalidates all handles pointing into the calling instance.
Definition: EpochTracker.h:44
DebugEpochBase()=default
Definition: DenseMap.h:62
void copyFrom(const DenseMapBase< OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT > &other)
Definition: DenseMap.h:449
bool isPointerIntoBucketsArray(const void *Ptr) const
isPointerIntoBucketsArray - Return true if the specified pointer points somewhere into the DenseMap's...
Definition: DenseMap.h:376
const_iterator find_as(const LookupKeyT &Val) const
Definition: DenseMap.h:191
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition: DenseMap.h:72
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:236
iterator end()
Definition: DenseMap.h:85
std::pair< iterator, bool > insert(std::pair< KeyT, ValueT > &&KV)
Definition: DenseMap.h:228
static const KeyT getEmptyKey()
Definition: DenseMap.h:481
bool erase(const KeyT &Val)
Definition: DenseMap.h:330
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
ValueT mapped_type
Definition: DenseMap.h:69
void erase(iterator I)
Definition: DenseMap.h:341
void initEmpty()
Definition: DenseMap.h:401
unsigned size() const
Definition: DenseMap.h:100
static unsigned getHashValue(const KeyT &Val)
Definition: DenseMap.h:472
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition: DenseMap.h:104
ValueT & getOrInsertDefault(KeyT &&Key)
Returns the value associated to the key in the map if it exists.
Definition: DenseMap.h:319
void insert(InputIt I, InputIt E)
insert - Range insertion of pairs.
Definition: DenseMap.h:311
ValueT & getOrInsertDefault(const KeyT &Key)
Returns the value associated to the key in the map if it exists.
Definition: DenseMap.h:326
BucketT value_type
Definition: DenseMap.h:70
const void * getPointerIntoBucketsArray() const
getPointerIntoBucketsArray() - Return an opaque pointer into the buckets array.
Definition: DenseMap.h:383
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:221
const_iterator end() const
Definition: DenseMap.h:95
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:146
KeyT key_type
Definition: DenseMap.h:68
value_type & FindAndConstruct(const KeyT &Key)
Definition: DenseMap.h:349
void clear()
Definition: DenseMap.h:111
const ValueT & at(const_arg_type_t< KeyT > Val) const
at - Return the entry for the specified key, or abort if no such entry exists.
Definition: DenseMap.h:212
void destroyAll()
Definition: DenseMap.h:388
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition: DenseMap.h:74
iterator begin()
Definition: DenseMap.h:76
ValueT & operator[](const KeyT &Key)
Definition: DenseMap.h:357
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:203
static unsigned getHashValue(const LookupKeyT &Val)
Definition: DenseMap.h:477
DenseMapBase()=default
unsigned size_type
Definition: DenseMap.h:67
std::pair< iterator, bool > insert_as(std::pair< KeyT, ValueT > &&KV, const LookupKeyT &Val)
Alternate version of insert() which allows a different, and possibly less expensive,...
Definition: DenseMap.h:287
unsigned getMinBucketToReserveForEntries(unsigned NumEntries)
Returns the number of buckets to allocate to ensure that the DenseMap can accommodate NumEntries with...
Definition: DenseMap.h:414
void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd)
Definition: DenseMap.h:423
const_iterator find(const_arg_type_t< KeyT > Val) const
Definition: DenseMap.h:165
static const KeyT getTombstoneKey()
Definition: DenseMap.h:487
ValueT & operator[](KeyT &&Key)
Definition: DenseMap.h:369
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:156
value_type & FindAndConstruct(KeyT &&Key)
Definition: DenseMap.h:361
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition: DenseMap.h:181
size_t getMemorySize() const
Return the approximate size (in bytes) of the actual map.
Definition: DenseMap.h:700
const_iterator begin() const
Definition: DenseMap.h:88
bool empty() const
Definition: DenseMap.h:99
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&... Args)
Definition: DenseMap.h:261
Definition: DenseMap.h:743
void init(unsigned InitNumEntries)
Definition: DenseMap.h:820
void copyFrom(const DenseMap &other)
Definition: DenseMap.h:809
DenseMap & operator=(DenseMap &&other)
Definition: DenseMap.h:801
DenseMap & operator=(const DenseMap &other)
Definition: DenseMap.h:795
DenseMap(const DenseMap &other)
Definition: DenseMap.h:760
DenseMap(std::initializer_list< typename BaseT::value_type > Vals)
Definition: DenseMap.h:776
void grow(unsigned AtLeast)
Definition: DenseMap.h:830
void shrink_and_clear()
Definition: DenseMap.h:848
DenseMap(const InputIt &I, const InputIt &E)
Definition: DenseMap.h:771
void swap(DenseMap &RHS)
Definition: DenseMap.h:786
DenseMap(DenseMap &&other)
Definition: DenseMap.h:765
DenseMap(unsigned InitialReserve=0)
Create a DenseMap with an optional InitialReserve that guarantee that this number of elements can be ...
Definition: DenseMap.h:758
~DenseMap()
Definition: DenseMap.h:781
Definition: DenseMap.h:1222
DenseMapIterator & operator++()
Definition: DenseMap.h:1291
friend bool operator!=(const DenseMapIterator &LHS, const DenseMapIterator &RHS)
Definition: DenseMap.h:1286
DenseMapIterator(const DenseMapIterator< KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc > &I)
Definition: DenseMap.h:1258
reference operator*() const
Definition: DenseMap.h:1262
pointer operator->() const
Definition: DenseMap.h:1269
DenseMapIterator()=default
DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch, bool NoAdvance=false)
Definition: DenseMap.h:1240
std::forward_iterator_tag iterator_category
Definition: DenseMap.h:1231
ptrdiff_t difference_type
Definition: DenseMap.h:1227
std::conditional_t< IsConst, const Bucket, Bucket > value_type
Definition: DenseMap.h:1228
value_type * pointer
Definition: DenseMap.h:1229
DenseMapIterator operator++(int)
Definition: DenseMap.h:1303
friend bool operator==(const DenseMapIterator &LHS, const DenseMapIterator &RHS)
Definition: DenseMap.h:1277
value_type & reference
Definition: DenseMap.h:1230
Definition: DenseMap.h:911
~SmallDenseMap()
Definition: DenseMap.h:960
SmallDenseMap(unsigned NumInitBuckets=0)
Definition: DenseMap.h:935
void swap(SmallDenseMap &RHS)
Definition: DenseMap.h:965
void copyFrom(const SmallDenseMap &other)
Definition: DenseMap.h:1051
void init(unsigned InitBuckets)
Definition: DenseMap.h:1062
SmallDenseMap & operator=(SmallDenseMap &&other)
Definition: DenseMap.h:1043
SmallDenseMap(const SmallDenseMap &other)
Definition: DenseMap.h:941
SmallDenseMap(SmallDenseMap &&other)
Definition: DenseMap.h:946
void shrink_and_clear()
Definition: DenseMap.h:1124
void grow(unsigned AtLeast)
Definition: DenseMap.h:1071
SmallDenseMap(const InputIt &I, const InputIt &E)
Definition: DenseMap.h:952
SmallDenseMap(std::initializer_list< typename BaseT::value_type > Vals)
Definition: DenseMap.h:957
SmallDenseMap & operator=(const SmallDenseMap &other)
Definition: DenseMap.h:1037
detail namespace with internal helper functions
Definition: xchar.h:20
const T & first(const T &value, const Tail &...)
Definition: compile.h:60
Definition: array.h:89
WPI_BASIC_JSON_TPL_DECLARATION void swap(wpi::WPI_BASIC_JSON_TPL &j1, wpi::WPI_BASIC_JSON_TPL &j2) noexcept(//NOLINT(readability-inconsistent-declaration-parameter-name) is_nothrow_move_constructible< wpi::WPI_BASIC_JSON_TPL >::value &&//NOLINT(misc-redundant-expression) is_nothrow_move_assignable< wpi::WPI_BASIC_JSON_TPL >::value)
exchanges the values of two JSON objects
Definition: json.h:5219
static constexpr const charge::coulomb_t e(1.6021766208e-19)
elementary charge.
UnitTypeLhs() max(const UnitTypeLhs &lhs, const UnitTypeRhs &rhs)
Definition: base.h:3417
Definition: ntcore_cpp.h:26
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition: MathExtras.h:300
void swap(expected< T, E > &lhs, expected< T, E > &rhs) noexcept(noexcept(lhs.swap(rhs)))
Definition: expected:2438
void deallocate_buffer(void *Ptr, size_t Size, size_t Alignment)
Deallocate a buffer of memory with the given size and alignment.
size_t capacity_in_bytes(const DenseMap< KeyT, ValueT, KeyInfoT > &X)
Definition: DenseMap.h:1331
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:243
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:323
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * allocate_buffer(size_t Size, size_t Alignment)
Allocate a buffer of memory with the given size and alignment.
constexpr bool operator==(const unexpected< E > &lhs, const unexpected< E > &rhs)
Definition: expected:176
constexpr bool operator!=(const unexpected< E > &lhs, const unexpected< E > &rhs)
Definition: expected:180
A suitably aligned and sized character array member which can hold elements of any type.
Definition: AlignOf.h:27
const T & type
Definition: type_traits.h:64
Definition: DenseMap.h:43
KeyT & getFirst()
Definition: DenseMap.h:46
ValueT & getSecond()
Definition: DenseMap.h:48
const KeyT & getFirst() const
Definition: DenseMap.h:47
const ValueT & getSecond() const
Definition: DenseMap.h:49