LLVM 23.0.0git
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 LLVM_ADT_DENSEMAP_H
15#define LLVM_ADT_DENSEMAP_H
16
17#include "llvm/ADT/ADL.h"
20#include "llvm/ADT/STLExtras.h"
28#include <algorithm>
29#include <cassert>
30#include <cstddef>
31#include <cstring>
32#include <initializer_list>
33#include <iterator>
34#include <new>
35#include <type_traits>
36#include <utility>
37
38namespace llvm {
39
40namespace detail {
41
42// We extend a pair to allow users to override the bucket type with their own
43// implementation without requiring two members.
44template <typename KeyT, typename ValueT>
45struct DenseMapPair : std::pair<KeyT, ValueT> {
46 using std::pair<KeyT, ValueT>::pair;
47
48 KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; }
49 const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; }
50 ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; }
51 const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; }
52};
53
54} // end namespace detail
55
56template <typename KeyT, typename ValueT,
57 typename KeyInfoT = DenseMapInfo<KeyT>,
59 bool IsConst = false>
60class DenseMapIterator;
61
62template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
63 typename BucketT>
65 template <typename T>
66 using const_arg_type_t = typename const_pointer_or_const_ref<T>::type;
67
68public:
70 using key_type = KeyT;
71 using mapped_type = ValueT;
72 using value_type = BucketT;
73
77
78 [[nodiscard]] inline iterator begin() {
79 return iterator::makeBegin(buckets(), empty(), *this);
80 }
81 [[nodiscard]] inline iterator end() {
82 return iterator::makeEnd(buckets(), *this);
83 }
84 [[nodiscard]] inline const_iterator begin() const {
85 return const_iterator::makeBegin(buckets(), empty(), *this);
86 }
87 [[nodiscard]] inline const_iterator end() const {
88 return const_iterator::makeEnd(buckets(), *this);
89 }
90
91 // Return an iterator to iterate over keys in the map.
92 [[nodiscard]] inline auto keys() {
93 return map_range(*this, [](const BucketT &P) { return P.getFirst(); });
94 }
95
96 // Return an iterator to iterate over values in the map.
97 [[nodiscard]] inline auto values() {
98 return map_range(*this, [](const BucketT &P) { return P.getSecond(); });
99 }
100
101 [[nodiscard]] inline auto keys() const {
102 return map_range(*this, [](const BucketT &P) { return P.getFirst(); });
103 }
104
105 [[nodiscard]] inline auto values() const {
106 return map_range(*this, [](const BucketT &P) { return P.getSecond(); });
107 }
108
109 [[nodiscard]] bool empty() const { return getNumEntries() == 0; }
110 [[nodiscard]] unsigned size() const { return getNumEntries(); }
111
112 /// Grow the densemap so that it can contain at least \p NumEntries items
113 /// before resizing again.
114 void reserve(size_type NumEntries) {
115 auto NumBuckets = getMinBucketToReserveForEntries(NumEntries);
117 if (NumBuckets > getNumBuckets())
118 grow(NumBuckets);
119 }
120
121 void clear() {
123 if (getNumEntries() == 0 && getNumTombstones() == 0)
124 return;
125
126 // If the capacity of the array is huge, and the # elements used is small,
127 // shrink the array.
128 if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
130 return;
131 }
132
133 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
134 if constexpr (std::is_trivially_destructible_v<ValueT>) {
135 // Use a simpler loop when values don't need destruction.
136 for (BucketT &B : buckets())
137 B.getFirst() = EmptyKey;
138 } else {
139 const KeyT TombstoneKey = KeyInfoT::getTombstoneKey();
140 unsigned NumEntries = getNumEntries();
141 for (BucketT &B : buckets()) {
142 if (!KeyInfoT::isEqual(B.getFirst(), EmptyKey)) {
143 if (!KeyInfoT::isEqual(B.getFirst(), TombstoneKey)) {
144 B.getSecond().~ValueT();
145 --NumEntries;
146 }
147 B.getFirst() = EmptyKey;
148 }
149 }
150 assert(NumEntries == 0 && "Node count imbalance!");
151 (void)NumEntries;
152 }
153 setNumEntries(0);
154 setNumTombstones(0);
155 }
156
158 auto [Reallocate, NewNumBuckets] = derived().planShrinkAndClear();
159 destroyAll();
160 if (!Reallocate) {
161 initEmpty();
162 return;
163 }
164 derived().deallocateBuckets();
165 initWithExactBucketCount(NewNumBuckets);
166 }
167
168 /// Return true if the specified key is in the map, false otherwise.
169 [[nodiscard]] bool contains(const_arg_type_t<KeyT> Val) const {
170 return doFind(Val) != nullptr;
171 }
172
173 /// Return 1 if the specified key is in the map, 0 otherwise.
174 [[nodiscard]] size_type count(const_arg_type_t<KeyT> Val) const {
175 return contains(Val) ? 1 : 0;
176 }
177
178 [[nodiscard]] iterator find(const_arg_type_t<KeyT> Val) {
179 return find_as(Val);
180 }
181 [[nodiscard]] const_iterator find(const_arg_type_t<KeyT> Val) const {
182 return find_as(Val);
183 }
184
185 /// Alternate version of find() which allows a different, and possibly
186 /// less expensive, key type.
187 /// The DenseMapInfo is responsible for supplying methods
188 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
189 /// type used.
190 template <class LookupKeyT>
191 [[nodiscard]] iterator find_as(const LookupKeyT &Val) {
192 if (BucketT *Bucket = doFind(Val))
193 return makeIterator(Bucket);
194 return end();
195 }
196 template <class LookupKeyT>
197 [[nodiscard]] const_iterator find_as(const LookupKeyT &Val) const {
198 if (const BucketT *Bucket = doFind(Val))
199 return makeConstIterator(Bucket);
200 return end();
201 }
202
203 /// Return the entry for the specified key, or a default constructed value if
204 /// no such entry exists.
205 [[nodiscard]] ValueT lookup(const_arg_type_t<KeyT> Val) const {
206 if (const BucketT *Bucket = doFind(Val))
207 return Bucket->getSecond();
208 return ValueT();
209 }
210
211 // Return the entry with the specified key, or \p Default. This variant is
212 // useful, because `lookup` cannot be used with non-default-constructible
213 // values.
214 template <typename U = std::remove_cv_t<ValueT>>
215 [[nodiscard]] ValueT lookup_or(const_arg_type_t<KeyT> Val,
216 U &&Default) const {
217 if (const BucketT *Bucket = doFind(Val))
218 return Bucket->getSecond();
219 return Default;
220 }
221
222 /// Return the entry for the specified key, or abort if no such entry exists.
223 [[nodiscard]] ValueT &at(const_arg_type_t<KeyT> Val) {
224 auto Iter = this->find(std::move(Val));
225 assert(Iter != this->end() && "DenseMap::at failed due to a missing key");
226 return Iter->second;
227 }
228
229 /// Return the entry for the specified key, or abort if no such entry exists.
230 [[nodiscard]] const ValueT &at(const_arg_type_t<KeyT> Val) const {
231 auto Iter = this->find(std::move(Val));
232 assert(Iter != this->end() && "DenseMap::at failed due to a missing key");
233 return Iter->second;
234 }
235
236 // Inserts key,value pair into the map if the key isn't already in the map.
237 // If the key is already in the map, it returns false and doesn't update the
238 // value.
239 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
240 return try_emplace_impl(KV.first, KV.second);
241 }
242
243 // Inserts key,value pair into the map if the key isn't already in the map.
244 // If the key is already in the map, it returns false and doesn't update the
245 // value.
246 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
247 return try_emplace_impl(std::move(KV.first), std::move(KV.second));
248 }
249
250 // Inserts key,value pair into the map if the key isn't already in the map.
251 // The value is constructed in-place if the key is not in the map, otherwise
252 // it is not moved.
253 template <typename... Ts>
254 std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&...Args) {
255 return try_emplace_impl(std::move(Key), std::forward<Ts>(Args)...);
256 }
257
258 // Inserts key,value pair into the map if the key isn't already in the map.
259 // The value is constructed in-place if the key is not in the map, otherwise
260 // it is not moved.
261 template <typename... Ts>
262 std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&...Args) {
263 return try_emplace_impl(Key, std::forward<Ts>(Args)...);
264 }
265
266 /// Alternate version of insert() which allows a different, and possibly
267 /// less expensive, key type.
268 /// The DenseMapInfo is responsible for supplying methods
269 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
270 /// type used.
271 template <typename LookupKeyT>
272 std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV,
273 const LookupKeyT &Val) {
274 BucketT *TheBucket;
275 if (LookupBucketFor(Val, TheBucket))
276 return {makeIterator(TheBucket), false}; // Already in map.
277
278 // Otherwise, insert the new element.
279 TheBucket = findBucketForInsertion(Val, TheBucket);
280 TheBucket->getFirst() = std::move(KV.first);
281 ::new (&TheBucket->getSecond()) ValueT(std::move(KV.second));
282 return {makeIterator(TheBucket), true};
283 }
284
285 /// Range insertion of pairs.
286 template <typename InputIt> void insert(InputIt I, InputIt E) {
287 for (; I != E; ++I)
288 insert(*I);
289 }
290
291 /// Inserts range of 'std::pair<KeyT, ValueT>' values into the map.
292 template <typename Range> void insert_range(Range &&R) {
293 insert(adl_begin(R), adl_end(R));
294 }
295
296 template <typename V>
297 std::pair<iterator, bool> insert_or_assign(const KeyT &Key, V &&Val) {
298 auto Ret = try_emplace(Key, std::forward<V>(Val));
299 if (!Ret.second)
300 Ret.first->second = std::forward<V>(Val);
301 return Ret;
302 }
303
304 template <typename V>
305 std::pair<iterator, bool> insert_or_assign(KeyT &&Key, V &&Val) {
306 auto Ret = try_emplace(std::move(Key), std::forward<V>(Val));
307 if (!Ret.second)
308 Ret.first->second = std::forward<V>(Val);
309 return Ret;
310 }
311
312 template <typename... Ts>
313 std::pair<iterator, bool> emplace_or_assign(const KeyT &Key, Ts &&...Args) {
314 auto Ret = try_emplace(Key, std::forward<Ts>(Args)...);
315 if (!Ret.second)
316 Ret.first->second = ValueT(std::forward<Ts>(Args)...);
317 return Ret;
318 }
319
320 template <typename... Ts>
321 std::pair<iterator, bool> emplace_or_assign(KeyT &&Key, Ts &&...Args) {
322 auto Ret = try_emplace(std::move(Key), std::forward<Ts>(Args)...);
323 if (!Ret.second)
324 Ret.first->second = ValueT(std::forward<Ts>(Args)...);
325 return Ret;
326 }
327
328 bool erase(const KeyT &Val) {
329 BucketT *TheBucket = doFind(Val);
330 if (!TheBucket)
331 return false; // not in map.
332
333 TheBucket->getSecond().~ValueT();
334 TheBucket->getFirst() = KeyInfoT::getTombstoneKey();
335 decrementNumEntries();
336 incrementNumTombstones();
337 return true;
338 }
340 BucketT *TheBucket = &*I;
341 TheBucket->getSecond().~ValueT();
342 TheBucket->getFirst() = KeyInfoT::getTombstoneKey();
343 decrementNumEntries();
344 incrementNumTombstones();
345 }
346
347 /// Remove entries that match the given predicate. \p Pred is invoked
348 /// with a reference to each live bucket and must not access the map being
349 /// modified. This is the safe replacement for erase-while-iterating.
350 ///
351 /// Returns whether anything was removed. If so, all iterators and references
352 /// into the map are invalidated.
353 template <typename Predicate> bool remove_if(Predicate Pred) {
354 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
355 const KeyT TombstoneKey = KeyInfoT::getTombstoneKey();
356 bool Removed = false;
357 for (BucketT &B : buckets()) {
358 if (KeyInfoT::isEqual(B.getFirst(), EmptyKey) ||
359 KeyInfoT::isEqual(B.getFirst(), TombstoneKey))
360 continue;
361 if (Pred(B)) {
362 B.getSecond().~ValueT();
363 B.getFirst() = TombstoneKey;
364 decrementNumEntries();
365 incrementNumTombstones();
366 Removed = true;
367 }
368 }
369 if (Removed)
371 return Removed;
372 }
373
374 ValueT &operator[](const KeyT &Key) {
375 return lookupOrInsertIntoBucket(Key).first->second;
376 }
377
378 ValueT &operator[](KeyT &&Key) {
379 return lookupOrInsertIntoBucket(std::move(Key)).first->second;
380 }
381
382 /// Return true if the specified pointer points somewhere into the DenseMap's
383 /// array of buckets (i.e. either to a key or value in the DenseMap).
384 [[nodiscard]] bool isPointerIntoBucketsArray(const void *Ptr) const {
385 return Ptr >= getBuckets() && Ptr < getBucketsEnd();
386 }
387
388 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
389 /// array. In conjunction with the previous method, this can be used to
390 /// determine whether an insertion caused the DenseMap to reallocate.
391 [[nodiscard]] const void *getPointerIntoBucketsArray() const {
392 return getBuckets();
393 }
394
395 void swap(DerivedT &RHS) {
396 this->incrementEpoch();
397 RHS.incrementEpoch();
398 derived().swapImpl(RHS);
399 }
400
401protected:
402 DenseMapBase() = default;
403
405
406 void initWithExactBucketCount(unsigned NewNumBuckets) {
407 if (derived().allocateBuckets(NewNumBuckets)) {
408 initEmpty();
409 } else {
410 setNumEntries(0);
411 setNumTombstones(0);
412 }
413 }
414
415 void destroyAll() {
416 // No need to iterate through the buckets if both KeyT and ValueT are
417 // trivially destructible.
418 if constexpr (std::is_trivially_destructible_v<KeyT> &&
419 std::is_trivially_destructible_v<ValueT>)
420 return;
421
422 if (getNumBuckets() == 0) // Nothing to do.
423 return;
424
425 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
426 const KeyT TombstoneKey = KeyInfoT::getTombstoneKey();
427 for (BucketT &B : buckets()) {
428 if (!KeyInfoT::isEqual(B.getFirst(), EmptyKey) &&
429 !KeyInfoT::isEqual(B.getFirst(), TombstoneKey))
430 B.getSecond().~ValueT();
431 B.getFirst().~KeyT();
432 }
433 }
434
435 void initEmpty() {
436 static_assert(std::is_base_of_v<DenseMapBase, DerivedT>,
437 "Must pass the derived type to this template!");
438 setNumEntries(0);
439 setNumTombstones(0);
440
441 assert((getNumBuckets() & (getNumBuckets() - 1)) == 0 &&
442 "# initial buckets must be a power of two!");
443 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
444 for (BucketT &B : buckets())
445 ::new (&B.getFirst()) KeyT(EmptyKey);
446 }
447
448 /// Returns the number of buckets to allocate to ensure that the DenseMap can
449 /// accommodate \p NumEntries without need to grow().
450 unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
451 // Ensure that "NumEntries * 4 < NumBuckets * 3"
452 if (NumEntries == 0)
453 return 0;
454 // +1 is required because of the strict inequality.
455 // For example, if NumEntries is 48, we need to return 128.
456 return NextPowerOf2(NumEntries * 4 / 3 + 1);
457 }
458
459 // Move key/value from Other to *this.
460 // Other is left in a valid but empty state.
461 void moveFrom(DerivedT &Other) {
462 // Insert all the old elements.
463 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
464 const KeyT TombstoneKey = KeyInfoT::getTombstoneKey();
465 for (BucketT &B : Other.buckets()) {
466 if (!KeyInfoT::isEqual(B.getFirst(), EmptyKey) &&
467 !KeyInfoT::isEqual(B.getFirst(), TombstoneKey)) {
468 // Insert the key/value into the new table.
469 BucketT *DestBucket;
470 bool FoundVal = LookupBucketFor(B.getFirst(), DestBucket);
471 (void)FoundVal; // silence warning.
472 assert(!FoundVal && "Key already in new map?");
473 DestBucket->getFirst() = std::move(B.getFirst());
474 ::new (&DestBucket->getSecond()) ValueT(std::move(B.getSecond()));
475 incrementNumEntries();
476
477 // Free the value.
478 B.getSecond().~ValueT();
479 }
480 B.getFirst().~KeyT();
481 }
482 Other.derived().kill();
483 }
484
485 void copyFrom(const DerivedT &other) {
486 this->destroyAll();
487 derived().deallocateBuckets();
488 setNumEntries(0);
489 setNumTombstones(0);
490 if (!derived().allocateBuckets(other.getNumBuckets())) {
491 // The bucket list is empty. No work to do.
492 return;
493 }
494
495 assert(&other != this);
496 assert(getNumBuckets() == other.getNumBuckets());
497
498 setNumEntries(other.getNumEntries());
499 setNumTombstones(other.getNumTombstones());
500
501 BucketT *Buckets = getBuckets();
502 const BucketT *OtherBuckets = other.getBuckets();
503 const size_t NumBuckets = getNumBuckets();
504 if constexpr (std::is_trivially_copyable_v<KeyT> &&
505 std::is_trivially_copyable_v<ValueT>) {
506 memcpy(reinterpret_cast<void *>(Buckets), OtherBuckets,
507 NumBuckets * sizeof(BucketT));
508 } else {
509 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
510 const KeyT TombstoneKey = KeyInfoT::getTombstoneKey();
511 for (size_t I = 0; I < NumBuckets; ++I) {
512 ::new (&Buckets[I].getFirst()) KeyT(OtherBuckets[I].getFirst());
513 if (!KeyInfoT::isEqual(Buckets[I].getFirst(), EmptyKey) &&
514 !KeyInfoT::isEqual(Buckets[I].getFirst(), TombstoneKey))
515 ::new (&Buckets[I].getSecond()) ValueT(OtherBuckets[I].getSecond());
516 }
517 }
518 }
519
520private:
521 DerivedT &derived() { return *static_cast<DerivedT *>(this); }
522 const DerivedT &derived() const {
523 return *static_cast<const DerivedT *>(this);
524 }
525
526 template <typename KeyArgT, typename... Ts>
527 std::pair<BucketT *, bool> lookupOrInsertIntoBucket(KeyArgT &&Key,
528 Ts &&...Args) {
529 BucketT *TheBucket = nullptr;
530 if (LookupBucketFor(Key, TheBucket))
531 return {TheBucket, false}; // Already in the map.
532
533 // Otherwise, insert the new element.
534 TheBucket = findBucketForInsertion(Key, TheBucket);
535 TheBucket->getFirst() = std::forward<KeyArgT>(Key);
536 ::new (&TheBucket->getSecond()) ValueT(std::forward<Ts>(Args)...);
537 return {TheBucket, true};
538 }
539
540 template <typename KeyArgT, typename... Ts>
541 std::pair<iterator, bool> try_emplace_impl(KeyArgT &&Key, Ts &&...Args) {
542 auto [Bucket, Inserted] = lookupOrInsertIntoBucket(
543 std::forward<KeyArgT>(Key), std::forward<Ts>(Args)...);
544 return {makeIterator(Bucket), Inserted};
545 }
546
547 iterator makeIterator(BucketT *TheBucket) {
548 return iterator::makeIterator(TheBucket, buckets(), *this);
549 }
550
551 const_iterator makeConstIterator(const BucketT *TheBucket) const {
552 return const_iterator::makeIterator(TheBucket, buckets(), *this);
553 }
554
555 unsigned getNumEntries() const { return derived().getNumEntries(); }
556
557 void setNumEntries(unsigned Num) { derived().setNumEntries(Num); }
558
559 void incrementNumEntries() { setNumEntries(getNumEntries() + 1); }
560
561 void decrementNumEntries() { setNumEntries(getNumEntries() - 1); }
562
563 unsigned getNumTombstones() const { return derived().getNumTombstones(); }
564
565 void setNumTombstones(unsigned Num) { derived().setNumTombstones(Num); }
566
567 void incrementNumTombstones() { setNumTombstones(getNumTombstones() + 1); }
568
569 void decrementNumTombstones() { setNumTombstones(getNumTombstones() - 1); }
570
571 const BucketT *getBuckets() const { return derived().getBuckets(); }
572
573 BucketT *getBuckets() { return derived().getBuckets(); }
574
575 unsigned getNumBuckets() const { return derived().getNumBuckets(); }
576
577 BucketT *getBucketsEnd() { return getBuckets() + getNumBuckets(); }
578
579 const BucketT *getBucketsEnd() const {
580 return getBuckets() + getNumBuckets();
581 }
582
583 iterator_range<BucketT *> buckets() {
584 return llvm::make_range(getBuckets(), getBucketsEnd());
585 }
586
587 iterator_range<const BucketT *> buckets() const {
588 return llvm::make_range(getBuckets(), getBucketsEnd());
589 }
590
591 void grow(unsigned MinNumBuckets) {
592 unsigned NumBuckets = DerivedT::roundUpNumBuckets(MinNumBuckets);
593 DerivedT Tmp(NumBuckets, ExactBucketCount{});
594 Tmp.moveFrom(derived());
595 if (derived().maybeMoveFast(std::move(Tmp)))
596 return;
597 initWithExactBucketCount(NumBuckets);
598 moveFrom(Tmp);
599 }
600
601 template <typename LookupKeyT>
602 BucketT *findBucketForInsertion(const LookupKeyT &Lookup,
603 BucketT *TheBucket) {
605
606 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
607 // the buckets are empty (meaning that many are filled with tombstones),
608 // grow the table.
609 //
610 // The later case is tricky. For example, if we had one empty bucket with
611 // tons of tombstones, failing lookups (e.g. for insertion) would have to
612 // probe almost the entire table until it found the empty bucket. If the
613 // table completely filled with tombstones, no lookup would ever succeed,
614 // causing infinite loops in lookup.
615 unsigned NewNumEntries = getNumEntries() + 1;
616 unsigned NumBuckets = getNumBuckets();
617 if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) {
618 this->grow(NumBuckets * 2);
619 LookupBucketFor(Lookup, TheBucket);
620 } else if (LLVM_UNLIKELY(NumBuckets -
621 (NewNumEntries + getNumTombstones()) <=
622 NumBuckets / 8)) {
623 this->grow(NumBuckets);
624 LookupBucketFor(Lookup, TheBucket);
625 }
626 assert(TheBucket);
627
628 // Only update the state after we've grown our bucket space appropriately
629 // so that when growing buckets we have self-consistent entry count.
630 incrementNumEntries();
631
632 // If we are writing over a tombstone, remember this.
633 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
634 if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey))
635 decrementNumTombstones();
636
637 return TheBucket;
638 }
639
640 template <typename LookupKeyT>
641 const BucketT *doFind(const LookupKeyT &Val) const {
642 const BucketT *BucketsPtr = getBuckets();
643 const unsigned NumBuckets = getNumBuckets();
644 if (NumBuckets == 0)
645 return nullptr;
646
647 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
648 unsigned BucketNo = KeyInfoT::getHashValue(Val) & (NumBuckets - 1);
649 unsigned ProbeAmt = 1;
650 while (true) {
651 const BucketT *Bucket = BucketsPtr + BucketNo;
652 if (LLVM_LIKELY(KeyInfoT::isEqual(Val, Bucket->getFirst())))
653 return Bucket;
654 if (LLVM_LIKELY(KeyInfoT::isEqual(Bucket->getFirst(), EmptyKey)))
655 return nullptr;
656
657 // Otherwise, it's a hash collision or a tombstone, continue quadratic
658 // probing.
659 BucketNo += ProbeAmt++;
660 BucketNo &= NumBuckets - 1;
661 }
662 }
663
664 template <typename LookupKeyT> BucketT *doFind(const LookupKeyT &Val) {
665 return const_cast<BucketT *>(
666 static_cast<const DenseMapBase *>(this)->doFind(Val));
667 }
668
669 /// Lookup the appropriate bucket for Val, returning it in FoundBucket. If the
670 /// bucket contains the key and a value, this returns true, otherwise it
671 /// returns a bucket with an empty marker or tombstone and returns false.
672 template <typename LookupKeyT>
673 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
674 BucketT *BucketsPtr = getBuckets();
675 const unsigned NumBuckets = getNumBuckets();
676
677 if (NumBuckets == 0) {
678 FoundBucket = nullptr;
679 return false;
680 }
681
682 // FoundTombstone - Keep track of whether we find a tombstone while probing.
683 BucketT *FoundTombstone = nullptr;
684 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
685 const KeyT TombstoneKey = KeyInfoT::getTombstoneKey();
686 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
687 !KeyInfoT::isEqual(Val, TombstoneKey) &&
688 "Empty/Tombstone value shouldn't be inserted into map!");
689
690 unsigned BucketNo = KeyInfoT::getHashValue(Val) & (NumBuckets - 1);
691 unsigned ProbeAmt = 1;
692 while (true) {
693 BucketT *ThisBucket = BucketsPtr + BucketNo;
694 // Found Val's bucket? If so, return it.
695 if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) {
696 FoundBucket = ThisBucket;
697 return true;
698 }
699
700 // If we found an empty bucket, the key doesn't exist in the set.
701 // Insert it and return the default value.
702 if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) {
703 // If we've already seen a tombstone while probing, fill it in instead
704 // of the empty bucket we eventually probed to.
705 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
706 return false;
707 }
708
709 // If this is a tombstone, remember it. If Val ends up not in the map, we
710 // prefer to return it than something that would require more probing.
711 if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
712 !FoundTombstone)
713 FoundTombstone = ThisBucket; // Remember the first tombstone found.
714
715 // Otherwise, it's a hash collision or a tombstone, continue quadratic
716 // probing.
717 BucketNo += ProbeAmt++;
718 BucketNo &= (NumBuckets - 1);
719 }
720 }
721
722public:
723 /// Return the approximate size (in bytes) of the actual map.
724 /// This is just the raw memory used by DenseMap.
725 /// If entries are pointers to objects, the size of the referenced objects
726 /// are not included.
727 [[nodiscard]] size_t getMemorySize() const {
728 return getNumBuckets() * sizeof(BucketT);
729 }
730};
731
732/// Equality comparison for DenseMap.
733///
734/// Iterates over elements of LHS confirming that each (key, value) pair in LHS
735/// is also in RHS, and that no additional pairs are in RHS.
736/// Equivalent to N calls to RHS.find and N value comparisons. Amortized
737/// complexity is linear, worst case is O(N^2) (if every hash collides).
738template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
739 typename BucketT>
740[[nodiscard]] bool
743 if (LHS.size() != RHS.size())
744 return false;
745
746 for (auto &KV : LHS) {
747 auto I = RHS.find(KV.first);
748 if (I == RHS.end() || I->second != KV.second)
749 return false;
750 }
751
752 return true;
753}
754
755/// Inequality comparison for DenseMap.
756///
757/// Equivalent to !(LHS == RHS). See operator== for performance notes.
758template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
759 typename BucketT>
760[[nodiscard]] bool
765
766template <typename KeyT, typename ValueT,
767 typename KeyInfoT = DenseMapInfo<KeyT>,
769class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
770 KeyT, ValueT, KeyInfoT, BucketT> {
771 friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
772
773 // Lift some types from the dependent base class into this class for
774 // simplicity of referring to them.
776
777 BucketT *Buckets = nullptr;
778 unsigned NumEntries = 0;
779 unsigned NumTombstones = 0;
780 unsigned NumBuckets = 0;
781
782 explicit DenseMap(unsigned NumBuckets, typename BaseT::ExactBucketCount) {
783 this->initWithExactBucketCount(NumBuckets);
784 }
785
786public:
787 /// Create a DenseMap with an optional \p NumElementsToReserve to guarantee
788 /// that this number of elements can be inserted in the map without grow().
789 explicit DenseMap(unsigned NumElementsToReserve = 0)
790 : DenseMap(BaseT::getMinBucketToReserveForEntries(NumElementsToReserve),
791 typename BaseT::ExactBucketCount{}) {}
792
793 DenseMap(const DenseMap &other) : DenseMap() { this->copyFrom(other); }
794
795 DenseMap(DenseMap &&other) : DenseMap() { this->swap(other); }
796
797 template <typename InputIt>
798 DenseMap(const InputIt &I, const InputIt &E) : DenseMap(std::distance(I, E)) {
799 this->insert(I, E);
800 }
801
802 template <typename RangeT>
804 : DenseMap(adl_begin(Range), adl_end(Range)) {}
805
806 DenseMap(std::initializer_list<typename BaseT::value_type> Vals)
807 : DenseMap(Vals.begin(), Vals.end()) {}
808
810 this->destroyAll();
811 deallocateBuckets();
812 }
813
814 DenseMap &operator=(const DenseMap &other) {
815 if (&other != this)
816 this->copyFrom(other);
817 return *this;
818 }
819
820 DenseMap &operator=(DenseMap &&other) {
821 this->destroyAll();
822 deallocateBuckets();
824 this->swap(other);
825 return *this;
826 }
827
828private:
829 void swapImpl(DenseMap &RHS) {
830 std::swap(Buckets, RHS.Buckets);
831 std::swap(NumEntries, RHS.NumEntries);
832 std::swap(NumTombstones, RHS.NumTombstones);
833 std::swap(NumBuckets, RHS.NumBuckets);
834 }
835
836 unsigned getNumEntries() const { return NumEntries; }
837
838 void setNumEntries(unsigned Num) { NumEntries = Num; }
839
840 unsigned getNumTombstones() const { return NumTombstones; }
841
842 void setNumTombstones(unsigned Num) { NumTombstones = Num; }
843
844 BucketT *getBuckets() const { return Buckets; }
845
846 unsigned getNumBuckets() const { return NumBuckets; }
847
848 void deallocateBuckets() {
849 deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
850 }
851
852 bool allocateBuckets(unsigned Num) {
853 NumBuckets = Num;
854 if (NumBuckets == 0) {
855 Buckets = nullptr;
856 return false;
857 }
858
859 Buckets = static_cast<BucketT *>(
860 allocate_buffer(sizeof(BucketT) * NumBuckets, alignof(BucketT)));
861 return true;
862 }
863
864 // Put the zombie instance in a known good state after a move.
865 void kill() {
866 deallocateBuckets();
867 Buckets = nullptr;
868 NumBuckets = 0;
869 }
870
871 static unsigned roundUpNumBuckets(unsigned MinNumBuckets) {
872 return std::max(64u,
873 static_cast<unsigned>(NextPowerOf2(MinNumBuckets - 1)));
874 }
875
876 bool maybeMoveFast(DenseMap &&Other) {
877 swapImpl(Other);
878 return true;
879 }
880
881 // Plan how to shrink the bucket table. Return:
882 // - {false, 0} to reuse the existing bucket table
883 // - {true, N} to reallocate a bucket table with N entries
884 std::pair<bool, unsigned> planShrinkAndClear() const {
885 unsigned NewNumBuckets = 0;
886 if (NumEntries)
887 NewNumBuckets = std::max(64u, 1u << (Log2_32_Ceil(NumEntries) + 1));
888 if (NewNumBuckets == NumBuckets)
889 return {false, 0}; // Reuse.
890 return {true, NewNumBuckets}; // Reallocate.
891 }
892};
893
894template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
895 typename KeyInfoT = DenseMapInfo<KeyT>,
897class SmallDenseMap
898 : public DenseMapBase<
899 SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT,
900 ValueT, KeyInfoT, BucketT> {
901 friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
902
903 // Lift some types from the dependent base class into this class for
904 // simplicity of referring to them.
906
907 static_assert(isPowerOf2_64(InlineBuckets),
908 "InlineBuckets must be a power of 2.");
909
910 unsigned Small : 1;
911 unsigned NumEntries : 31;
912 unsigned NumTombstones;
913
914 struct LargeRep {
915 BucketT *Buckets;
916 unsigned NumBuckets;
918 return llvm::make_range(Buckets, Buckets + NumBuckets);
919 }
920 };
921
922 /// A "union" of an inline bucket array and the struct representing
923 /// a large bucket. This union will be discriminated by the 'Small' bit.
924 AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
925
926 SmallDenseMap(unsigned NumBuckets, typename BaseT::ExactBucketCount) {
927 this->initWithExactBucketCount(NumBuckets);
928 }
929
930public:
931 explicit SmallDenseMap(unsigned NumElementsToReserve = 0)
932 : SmallDenseMap(
933 BaseT::getMinBucketToReserveForEntries(NumElementsToReserve),
934 typename BaseT::ExactBucketCount{}) {}
935
936 SmallDenseMap(const SmallDenseMap &other) : SmallDenseMap() {
937 this->copyFrom(other);
938 }
939
940 SmallDenseMap(SmallDenseMap &&other) : SmallDenseMap() { this->swap(other); }
941
942 template <typename InputIt>
943 SmallDenseMap(const InputIt &I, const InputIt &E)
944 : SmallDenseMap(std::distance(I, E)) {
945 this->insert(I, E);
946 }
947
948 template <typename RangeT>
950 : SmallDenseMap(adl_begin(Range), adl_end(Range)) {}
951
952 SmallDenseMap(std::initializer_list<typename BaseT::value_type> Vals)
953 : SmallDenseMap(Vals.begin(), Vals.end()) {}
954
956 this->destroyAll();
957 deallocateBuckets();
958 }
959
960 SmallDenseMap &operator=(const SmallDenseMap &other) {
961 if (&other != this)
962 this->copyFrom(other);
963 return *this;
964 }
965
966 SmallDenseMap &operator=(SmallDenseMap &&other) {
967 this->destroyAll();
968 deallocateBuckets();
970 this->swap(other);
971 return *this;
972 }
973
974private:
975 void swapImpl(SmallDenseMap &RHS) {
976 unsigned TmpNumEntries = RHS.NumEntries;
977 RHS.NumEntries = NumEntries;
978 NumEntries = TmpNumEntries;
979 std::swap(NumTombstones, RHS.NumTombstones);
980
981 const KeyT EmptyKey = KeyInfoT::getEmptyKey();
982 const KeyT TombstoneKey = KeyInfoT::getTombstoneKey();
983 if (Small && RHS.Small) {
984 // If we're swapping inline bucket arrays, we have to cope with some of
985 // the tricky bits of DenseMap's storage system: the buckets are not
986 // fully initialized. Thus we swap every key, but we may have
987 // a one-directional move of the value.
988 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
989 BucketT *LHSB = &getInlineBuckets()[i],
990 *RHSB = &RHS.getInlineBuckets()[i];
991 bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
992 !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
993 bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
994 !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
995 if (hasLHSValue && hasRHSValue) {
996 // Swap together if we can...
997 std::swap(*LHSB, *RHSB);
998 continue;
999 }
1000 // Swap separately and handle any asymmetry.
1001 std::swap(LHSB->getFirst(), RHSB->getFirst());
1002 if (hasLHSValue) {
1003 ::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
1004 LHSB->getSecond().~ValueT();
1005 } else if (hasRHSValue) {
1006 ::new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
1007 RHSB->getSecond().~ValueT();
1008 }
1009 }
1010 return;
1011 }
1012 if (!Small && !RHS.Small) {
1013 std::swap(*getLargeRep(), *RHS.getLargeRep());
1014 return;
1015 }
1016
1017 SmallDenseMap &SmallSide = Small ? *this : RHS;
1018 SmallDenseMap &LargeSide = Small ? RHS : *this;
1019
1020 // First stash the large side's rep and move the small side across.
1021 LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
1022 LargeSide.getLargeRep()->~LargeRep();
1023 LargeSide.Small = true;
1024 // This is similar to the standard move-from-old-buckets, but the bucket
1025 // count hasn't actually rotated in this case. So we have to carefully
1026 // move construct the keys and values into their new locations, but there
1027 // is no need to re-hash things.
1028 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
1029 BucketT *NewB = &LargeSide.getInlineBuckets()[i],
1030 *OldB = &SmallSide.getInlineBuckets()[i];
1031 ::new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
1032 OldB->getFirst().~KeyT();
1033 if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
1034 !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
1035 ::new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
1036 OldB->getSecond().~ValueT();
1037 }
1038 }
1039
1040 // The hard part of moving the small buckets across is done, just move
1041 // the TmpRep into its new home.
1042 SmallSide.Small = false;
1043 new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
1044 }
1045
1046 unsigned getNumEntries() const { return NumEntries; }
1047
1048 void setNumEntries(unsigned Num) {
1049 // NumEntries is hardcoded to be 31 bits wide.
1050 assert(Num < (1U << 31) && "Cannot support more than 1<<31 entries");
1051 NumEntries = Num;
1052 }
1053
1054 unsigned getNumTombstones() const { return NumTombstones; }
1055
1056 void setNumTombstones(unsigned Num) { NumTombstones = Num; }
1057
1058 const BucketT *getInlineBuckets() const {
1059 assert(Small);
1060 // Note that this cast does not violate aliasing rules as we assert that
1061 // the memory's dynamic type is the small, inline bucket buffer, and the
1062 // 'storage' is a POD containing a char buffer.
1063 return reinterpret_cast<const BucketT *>(&storage);
1064 }
1065
1066 BucketT *getInlineBuckets() {
1067 return const_cast<BucketT *>(
1068 const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
1069 }
1070
1071 const LargeRep *getLargeRep() const {
1072 assert(!Small);
1073 // Note, same rule about aliasing as with getInlineBuckets.
1074 return reinterpret_cast<const LargeRep *>(&storage);
1075 }
1076
1077 LargeRep *getLargeRep() {
1078 return const_cast<LargeRep *>(
1079 const_cast<const SmallDenseMap *>(this)->getLargeRep());
1080 }
1081
1082 const BucketT *getBuckets() const {
1083 return Small ? getInlineBuckets() : getLargeRep()->Buckets;
1084 }
1085
1086 BucketT *getBuckets() {
1087 return const_cast<BucketT *>(
1088 const_cast<const SmallDenseMap *>(this)->getBuckets());
1089 }
1090
1091 unsigned getNumBuckets() const {
1092 return Small ? InlineBuckets : getLargeRep()->NumBuckets;
1093 }
1094
1095 iterator_range<BucketT *> inlineBuckets() {
1096 BucketT *Begin = getInlineBuckets();
1097 return llvm::make_range(Begin, Begin + InlineBuckets);
1098 }
1099
1100 void deallocateBuckets() {
1101 // Fast path to deallocateBuckets in case getLargeRep()->NumBuckets == 0,
1102 // just like destroyAll. This path is used to destruct zombie instances
1103 // after moves.
1104 if (Small || getLargeRep()->NumBuckets == 0)
1105 return;
1106
1107 deallocate_buffer(getLargeRep()->Buckets,
1108 sizeof(BucketT) * getLargeRep()->NumBuckets,
1109 alignof(BucketT));
1110 getLargeRep()->~LargeRep();
1111 }
1112
1113 bool allocateBuckets(unsigned Num) {
1114 if (Num <= InlineBuckets) {
1115 Small = true;
1116 } else {
1117 Small = false;
1118 BucketT *NewBuckets = static_cast<BucketT *>(
1119 allocate_buffer(sizeof(BucketT) * Num, alignof(BucketT)));
1120 new (getLargeRep()) LargeRep{NewBuckets, Num};
1121 }
1122 return true;
1123 }
1124
1125 // Put the zombie instance in a known good state after a move.
1126 void kill() {
1127 deallocateBuckets();
1128 Small = false;
1129 new (getLargeRep()) LargeRep{nullptr, 0};
1130 }
1131
1132 static unsigned roundUpNumBuckets(unsigned MinNumBuckets) {
1133 if (MinNumBuckets <= InlineBuckets)
1134 return MinNumBuckets;
1135 return std::max(64u,
1136 static_cast<unsigned>(NextPowerOf2(MinNumBuckets - 1)));
1137 }
1138
1139 bool maybeMoveFast(SmallDenseMap &&Other) {
1140 if (Other.Small)
1141 return false;
1142
1143 Small = false;
1144 NumEntries = Other.NumEntries;
1145 NumTombstones = Other.NumTombstones;
1146 *getLargeRep() = std::move(*Other.getLargeRep());
1147 Other.getLargeRep()->NumBuckets = 0;
1148 return true;
1149 }
1150
1151 // Plan how to shrink the bucket table. Return:
1152 // - {false, 0} to reuse the existing bucket table
1153 // - {true, N} to reallocate a bucket table with N entries
1154 std::pair<bool, unsigned> planShrinkAndClear() const {
1155 unsigned NewNumBuckets = 0;
1156 if (!this->empty()) {
1157 NewNumBuckets = 1u << (Log2_32_Ceil(this->size()) + 1);
1158 if (NewNumBuckets > InlineBuckets)
1159 NewNumBuckets = std::max(64u, NewNumBuckets);
1160 }
1161 bool Reuse = Small ? NewNumBuckets <= InlineBuckets
1162 : NewNumBuckets == getLargeRep()->NumBuckets;
1163 if (Reuse)
1164 return {false, 0}; // Reuse.
1165 return {true, NewNumBuckets}; // Reallocate.
1166 }
1167};
1168
1169template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket,
1170 bool IsConst>
1171class DenseMapIterator : DebugEpochBase::HandleBase {
1172 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
1173 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;
1174
1175public:
1177 using value_type = std::conditional_t<IsConst, const Bucket, Bucket>;
1180 using iterator_category = std::forward_iterator_tag;
1181
1182private:
1183 using BucketItTy =
1184 std::conditional_t<shouldReverseIterate<KeyT>(),
1185 std::reverse_iterator<pointer>, pointer>;
1186
1187 BucketItTy Ptr = {};
1188 BucketItTy End = {};
1189
1190 DenseMapIterator(BucketItTy Pos, BucketItTy E, const DebugEpochBase &Epoch)
1191 : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) {
1192 assert(isHandleInSync() && "invalid construction!");
1193 }
1194
1195public:
1196 DenseMapIterator() = default;
1197
1198 static DenseMapIterator makeBegin(iterator_range<pointer> Buckets,
1199 bool IsEmpty, const DebugEpochBase &Epoch) {
1200 // When the map is empty, avoid the overhead of advancing/retreating past
1201 // empty buckets.
1202 if (IsEmpty)
1203 return makeEnd(Buckets, Epoch);
1204 auto R = maybeReverse(Buckets);
1205 DenseMapIterator Iter(R.begin(), R.end(), Epoch);
1206 Iter.AdvancePastEmptyBuckets();
1207 return Iter;
1208 }
1209
1210 static DenseMapIterator makeEnd(iterator_range<pointer> Buckets,
1211 const DebugEpochBase &Epoch) {
1212 auto R = maybeReverse(Buckets);
1213 return DenseMapIterator(R.end(), R.end(), Epoch);
1214 }
1215
1216 static DenseMapIterator makeIterator(pointer P,
1218 const DebugEpochBase &Epoch) {
1219 auto R = maybeReverse(Buckets);
1220 constexpr int Offset = shouldReverseIterate<KeyT>() ? 1 : 0;
1221 return DenseMapIterator(BucketItTy(P + Offset), R.end(), Epoch);
1222 }
1223
1224 // Converting ctor from non-const iterators to const iterators. SFINAE'd out
1225 // for const iterator destinations so it doesn't end up as a user defined copy
1226 // constructor.
1227 template <bool IsConstSrc,
1228 typename = std::enable_if_t<!IsConstSrc && IsConst>>
1230 const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I)
1231 : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {}
1232
1233 [[nodiscard]] reference operator*() const {
1234 assert(isHandleInSync() && "invalid iterator access!");
1235 assert(Ptr != End && "dereferencing end() iterator");
1236 return *Ptr;
1237 }
1238 [[nodiscard]] pointer operator->() const { return &operator*(); }
1239
1240 [[nodiscard]] friend bool operator==(const DenseMapIterator &LHS,
1241 const DenseMapIterator &RHS) {
1242 assert((!LHS.getEpochAddress() || LHS.isHandleInSync()) &&
1243 "handle not in sync!");
1244 assert((!RHS.getEpochAddress() || RHS.isHandleInSync()) &&
1245 "handle not in sync!");
1246 assert(LHS.getEpochAddress() == RHS.getEpochAddress() &&
1247 "comparing incomparable iterators!");
1248 return LHS.Ptr == RHS.Ptr;
1249 }
1250
1251 [[nodiscard]] friend bool operator!=(const DenseMapIterator &LHS,
1252 const DenseMapIterator &RHS) {
1253 return !(LHS == RHS);
1254 }
1255
1256 inline DenseMapIterator &operator++() { // Preincrement
1257 assert(isHandleInSync() && "invalid iterator access!");
1258 assert(Ptr != End && "incrementing end() iterator");
1259 ++Ptr;
1260 AdvancePastEmptyBuckets();
1261 return *this;
1262 }
1263 DenseMapIterator operator++(int) { // Postincrement
1264 assert(isHandleInSync() && "invalid iterator access!");
1265 DenseMapIterator tmp = *this;
1266 ++*this;
1267 return tmp;
1268 }
1269
1270private:
1271 void AdvancePastEmptyBuckets() {
1272 assert(Ptr <= End);
1273 const KeyT Empty = KeyInfoT::getEmptyKey();
1274 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1275
1276 while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
1277 KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
1278 ++Ptr;
1279 }
1280
1281 static auto maybeReverse(iterator_range<pointer> Range) {
1282 if constexpr (shouldReverseIterate<KeyT>())
1283 return reverse(Range);
1284 else
1285 return Range;
1286 }
1287};
1288
1289template <typename KeyT, typename ValueT, typename KeyInfoT>
1290[[nodiscard]] inline size_t
1292 return X.getMemorySize();
1293}
1294
1295} // end namespace llvm
1296
1297#endif // LLVM_ADT_DENSEMAP_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define X(NUM, ENUM, NAME)
Definition ELF.h:853
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:335
This file defines DenseMapInfo traits for DenseMap.
This file defines the DebugEpochBase and DebugEpochBase::HandleBase classes.
#define I(x, y, z)
Definition MD5.cpp:57
This file defines counterparts of C library allocation functions defined in the namespace 'std'.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file contains library features backported from future STL versions.
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
LocallyHashedType DenseMapInfo< LocallyHashedType >::Tombstone
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
Value * RHS
Value * LHS
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:223
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:205
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
void copyFrom(const DerivedT &other)
Definition DenseMap.h:485
unsigned size_type
Definition DenseMap.h:69
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:254
std::pair< iterator, bool > insert(std::pair< KeyT, ValueT > &&KV)
Definition DenseMap.h:246
bool erase(const KeyT &Val)
Definition DenseMap.h:328
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:74
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:272
void moveFrom(DerivedT &Other)
Definition DenseMap.h:461
DenseMapBase()=default
const_iterator find_as(const LookupKeyT &Val) const
Definition DenseMap.h:197
const_iterator end() const
Definition DenseMap.h:87
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:191
unsigned size() const
Definition DenseMap.h:110
const_iterator find(const_arg_type_t< KeyT > Val) const
Definition DenseMap.h:181
bool empty() const
Definition DenseMap.h:109
std::pair< iterator, bool > emplace_or_assign(const KeyT &Key, Ts &&...Args)
Definition DenseMap.h:313
void insert(InputIt I, InputIt E)
Range insertion of pairs.
Definition DenseMap.h:286
iterator begin()
Definition DenseMap.h:78
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:174
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:75
bool remove_if(Predicate Pred)
Remove entries that match the given predicate.
Definition DenseMap.h:353
iterator end()
Definition DenseMap.h:81
const ValueT & at(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or abort if no such entry exists.
Definition DenseMap.h:230
bool isPointerIntoBucketsArray(const void *Ptr) const
Return true if the specified pointer points somewhere into the DenseMap's array of buckets (i....
Definition DenseMap.h:384
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:169
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition DenseMap.h:262
const_iterator begin() const
Definition DenseMap.h:84
std::pair< iterator, bool > emplace_or_assign(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:321
void insert_range(Range &&R)
Inserts range of 'std::pair<KeyT, ValueT>' values into the map.
Definition DenseMap.h:292
const void * getPointerIntoBucketsArray() const
getPointerIntoBucketsArray() - Return an opaque pointer into the buckets array.
Definition DenseMap.h:391
std::pair< iterator, bool > insert_or_assign(KeyT &&Key, V &&Val)
Definition DenseMap.h:305
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Definition DenseMap.h:215
unsigned getMinBucketToReserveForEntries(unsigned NumEntries)
Returns the number of buckets to allocate to ensure that the DenseMap can accommodate NumEntries with...
Definition DenseMap.h:450
void swap(DerivedT &RHS)
Definition DenseMap.h:395
ValueT & operator[](const KeyT &Key)
Definition DenseMap.h:374
BucketT value_type
Definition DenseMap.h:72
auto keys() const
Definition DenseMap.h:101
void initWithExactBucketCount(unsigned NewNumBuckets)
Definition DenseMap.h:406
void shrink_and_clear()
Definition DenseMap.h:157
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:239
void erase(iterator I)
Definition DenseMap.h:339
std::pair< iterator, bool > insert_or_assign(const KeyT &Key, V &&Val)
Definition DenseMap.h:297
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:114
ValueT & operator[](KeyT &&Key)
Definition DenseMap.h:378
auto values() const
Definition DenseMap.h:105
size_t getMemorySize() const
Return the approximate size (in bytes) of the actual map.
Definition DenseMap.h:727
std::conditional_t< IsConst, const BucketT, BucketT > value_type
Definition DenseMap.h:1177
static DenseMapIterator makeIterator(pointer P, iterator_range< pointer > Buckets, const DebugEpochBase &Epoch)
Definition DenseMap.h:1216
friend bool operator!=(const DenseMapIterator &LHS, const DenseMapIterator &RHS)
Definition DenseMap.h:1251
DenseMapIterator & operator++()
Definition DenseMap.h:1256
pointer operator->() const
Definition DenseMap.h:1238
reference operator*() const
Definition DenseMap.h:1233
static DenseMapIterator makeBegin(iterator_range< pointer > Buckets, bool IsEmpty, const DebugEpochBase &Epoch)
Definition DenseMap.h:1198
DenseMapIterator operator++(int)
Definition DenseMap.h:1263
DenseMapIterator(const DenseMapIterator< KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc > &I)
Definition DenseMap.h:1229
friend bool operator==(const DenseMapIterator &LHS, const DenseMapIterator &RHS)
Definition DenseMap.h:1240
static DenseMapIterator makeEnd(iterator_range< pointer > Buckets, const DebugEpochBase &Epoch)
Definition DenseMap.h:1210
DenseMap(std::initializer_list< typename BaseT::value_type > Vals)
Definition DenseMap.h:806
DenseMap(unsigned NumElementsToReserve=0)
Create a DenseMap with an optional NumElementsToReserve to guarantee that this number of elements can...
Definition DenseMap.h:789
DenseMap & operator=(DenseMap &&other)
Definition DenseMap.h:820
DenseMap(llvm::from_range_t, const RangeT &Range)
Definition DenseMap.h:803
DenseMap(const DenseMap &other)
Definition DenseMap.h:793
DenseMap(const InputIt &I, const InputIt &E)
Definition DenseMap.h:798
DenseMap(DenseMap &&other)
Definition DenseMap.h:795
DenseMap & operator=(const DenseMap &other)
Definition DenseMap.h:814
SmallDenseMap(const InputIt &I, const InputIt &E)
Definition DenseMap.h:943
SmallDenseMap & operator=(SmallDenseMap &&other)
Definition DenseMap.h:966
SmallDenseMap & operator=(const SmallDenseMap &other)
Definition DenseMap.h:960
SmallDenseMap(unsigned NumElementsToReserve=0)
Definition DenseMap.h:931
SmallDenseMap(std::initializer_list< typename BaseT::value_type > Vals)
Definition DenseMap.h:952
SmallDenseMap(SmallDenseMap &&other)
Definition DenseMap.h:940
SmallDenseMap(const SmallDenseMap &other)
Definition DenseMap.h:936
SmallDenseMap(llvm::from_range_t, const RangeT &Range)
Definition DenseMap.h:949
A range adaptor for a pair of iterators.
constexpr char IsConst[]
Key for Kernel::Arg::Metadata::mIsConst.
A self-contained host- and target-independent arbitrary-precision floating-point software implementat...
Definition ADL.h:123
constexpr double e
This is an optimization pass for GlobalISel generic memory operations.
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:344
@ Offset
Definition DWP.cpp:558
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
constexpr auto adl_begin(RangeT &&range) -> decltype(adl_detail::begin_impl(std::forward< RangeT >(range)))
Returns the begin iterator to range using std::begin and function found through Argument-Dependent Lo...
Definition ADL.h:78
BitVector::size_type capacity_in_bytes(const BitVector &X)
Definition BitVector.h:851
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2142
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
constexpr auto adl_end(RangeT &&range) -> decltype(adl_detail::end_impl(std::forward< RangeT >(range)))
Returns the end iterator to range using std::end and functions found through Argument-Dependent Looku...
Definition ADL.h:86
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:365
LLVM_ABI 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.
Definition MemAlloc.cpp:15
LLVM_ABI void deallocate_buffer(void *Ptr, size_t Size, size_t Alignment)
Deallocate a buffer of memory with the given size and alignment.
Definition MemAlloc.cpp:27
constexpr bool shouldReverseIterate()
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
@ Other
Any other memory.
Definition ModRef.h:68
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1916
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
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:373
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:874
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:876
std::conditional_t< std::is_pointer_v< T >, typename add_const_past_pointer< T >::type, const T & > type
Definition type_traits.h:53
const ValueT & getSecond() const
Definition DenseMap.h:51
const KeyT & getFirst() const
Definition DenseMap.h:49