1 //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the DenseMap class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_DENSEMAP_H
15 #define LLVM_ADT_DENSEMAP_H
17 #include "llvm/Support/MathExtras.h"
18 #include "llvm/Support/PointerLikeTypeTraits.h"
19 #include "llvm/Support/type_traits.h"
20 #include "llvm/ADT/DenseMapInfo.h"
31 template<typename KeyT, typename ValueT,
32 typename KeyInfoT = DenseMapInfo<KeyT>,
33 typename ValueInfoT = DenseMapInfo<ValueT>, bool IsConst = false>
34 class DenseMapIterator;
36 template<typename KeyT, typename ValueT,
37 typename KeyInfoT = DenseMapInfo<KeyT>,
38 typename ValueInfoT = DenseMapInfo<ValueT> >
40 typedef std::pair<KeyT, ValueT> BucketT;
45 unsigned NumTombstones;
47 typedef KeyT key_type;
48 typedef ValueT mapped_type;
49 typedef BucketT value_type;
51 DenseMap(const DenseMap &other) {
56 explicit DenseMap(unsigned NumInitBuckets = 0) {
60 template<typename InputIt>
61 DenseMap(const InputIt &I, const InputIt &E) {
62 init(NextPowerOf2(std::distance(I, E)));
67 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
68 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
69 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
70 !KeyInfoT::isEqual(P->first, TombstoneKey))
75 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
77 operator delete(Buckets);
80 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
81 typedef DenseMapIterator<KeyT, ValueT,
82 KeyInfoT, ValueInfoT, true> const_iterator;
83 inline iterator begin() {
84 // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
85 return empty() ? end() : iterator(Buckets, Buckets+NumBuckets);
87 inline iterator end() {
88 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
90 inline const_iterator begin() const {
91 return empty() ? end() : const_iterator(Buckets, Buckets+NumBuckets);
93 inline const_iterator end() const {
94 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
97 bool empty() const { return NumEntries == 0; }
98 unsigned size() const { return NumEntries; }
100 /// Grow the densemap so that it has at least Size buckets. Does not shrink
101 void resize(size_t Size) {
102 if (Size > NumBuckets)
107 if (NumEntries == 0 && NumTombstones == 0) return;
109 // If the capacity of the array is huge, and the # elements used is small,
111 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
116 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
117 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
118 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
119 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
126 assert(NumEntries == 0 && "Node count imbalance!");
130 /// count - Return true if the specified key is in the map.
131 bool count(const KeyT &Val) const {
133 return LookupBucketFor(Val, TheBucket);
136 iterator find(const KeyT &Val) {
138 if (LookupBucketFor(Val, TheBucket))
139 return iterator(TheBucket, Buckets+NumBuckets);
142 const_iterator find(const KeyT &Val) const {
144 if (LookupBucketFor(Val, TheBucket))
145 return const_iterator(TheBucket, Buckets+NumBuckets);
149 /// lookup - Return the entry for the specified key, or a default
150 /// constructed value if no such entry exists.
151 ValueT lookup(const KeyT &Val) const {
153 if (LookupBucketFor(Val, TheBucket))
154 return TheBucket->second;
158 // Inserts key,value pair into the map if the key isn't already in the map.
159 // If the key is already in the map, it returns false and doesn't update the
161 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
163 if (LookupBucketFor(KV.first, TheBucket))
164 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
165 false); // Already in map.
167 // Otherwise, insert the new element.
168 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
169 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
173 /// insert - Range insertion of pairs.
174 template<typename InputIt>
175 void insert(InputIt I, InputIt E) {
181 bool erase(const KeyT &Val) {
183 if (!LookupBucketFor(Val, TheBucket))
184 return false; // not in map.
186 TheBucket->second.~ValueT();
187 TheBucket->first = getTombstoneKey();
192 void erase(iterator I) {
193 BucketT *TheBucket = &*I;
194 TheBucket->second.~ValueT();
195 TheBucket->first = getTombstoneKey();
200 void swap(DenseMap& RHS) {
201 std::swap(NumBuckets, RHS.NumBuckets);
202 std::swap(Buckets, RHS.Buckets);
203 std::swap(NumEntries, RHS.NumEntries);
204 std::swap(NumTombstones, RHS.NumTombstones);
207 value_type& FindAndConstruct(const KeyT &Key) {
209 if (LookupBucketFor(Key, TheBucket))
212 return *InsertIntoBucket(Key, ValueT(), TheBucket);
215 ValueT &operator[](const KeyT &Key) {
216 return FindAndConstruct(Key).second;
219 DenseMap& operator=(const DenseMap& other) {
224 /// isPointerIntoBucketsArray - Return true if the specified pointer points
225 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
226 /// value in the DenseMap).
227 bool isPointerIntoBucketsArray(const void *Ptr) const {
228 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
231 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
232 /// array. In conjunction with the previous method, this can be used to
233 /// determine whether an insertion caused the DenseMap to reallocate.
234 const void *getPointerIntoBucketsArray() const { return Buckets; }
237 void CopyFrom(const DenseMap& other) {
238 if (NumBuckets != 0 &&
239 (!isPodLike<KeyInfoT>::value || !isPodLike<ValueInfoT>::value)) {
240 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
241 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
242 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
243 !KeyInfoT::isEqual(P->first, TombstoneKey))
249 NumEntries = other.NumEntries;
250 NumTombstones = other.NumTombstones;
254 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
256 operator delete(Buckets);
258 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
261 if (isPodLike<KeyInfoT>::value && isPodLike<ValueInfoT>::value)
262 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
264 for (size_t i = 0; i < other.NumBuckets; ++i) {
265 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
266 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
267 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
268 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
270 NumBuckets = other.NumBuckets;
273 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
274 BucketT *TheBucket) {
275 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
276 // the buckets are empty (meaning that many are filled with tombstones),
279 // The later case is tricky. For example, if we had one empty bucket with
280 // tons of tombstones, failing lookups (e.g. for insertion) would have to
281 // probe almost the entire table until it found the empty bucket. If the
282 // table completely filled with tombstones, no lookup would ever succeed,
283 // causing infinite loops in lookup.
285 if (NumEntries*4 >= NumBuckets*3 ||
286 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
287 this->grow(NumBuckets * 2);
288 LookupBucketFor(Key, TheBucket);
291 // If we are writing over a tombstone, remember this.
292 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
295 TheBucket->first = Key;
296 new (&TheBucket->second) ValueT(Value);
300 static unsigned getHashValue(const KeyT &Val) {
301 return KeyInfoT::getHashValue(Val);
303 static const KeyT getEmptyKey() {
304 return KeyInfoT::getEmptyKey();
306 static const KeyT getTombstoneKey() {
307 return KeyInfoT::getTombstoneKey();
310 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
311 /// FoundBucket. If the bucket contains the key and a value, this returns
312 /// true, otherwise it returns a bucket with an empty marker or tombstone and
314 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
315 unsigned BucketNo = getHashValue(Val);
316 unsigned ProbeAmt = 1;
317 BucketT *BucketsPtr = Buckets;
319 if (NumBuckets == 0) {
324 // FoundTombstone - Keep track of whether we find a tombstone while probing.
325 BucketT *FoundTombstone = 0;
326 const KeyT EmptyKey = getEmptyKey();
327 const KeyT TombstoneKey = getTombstoneKey();
328 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
329 !KeyInfoT::isEqual(Val, TombstoneKey) &&
330 "Empty/Tombstone value shouldn't be inserted into map!");
333 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
334 // Found Val's bucket? If so, return it.
335 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
336 FoundBucket = ThisBucket;
340 // If we found an empty bucket, the key doesn't exist in the set.
341 // Insert it and return the default value.
342 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
343 // If we've already seen a tombstone while probing, fill it in instead
344 // of the empty bucket we eventually probed to.
345 if (FoundTombstone) ThisBucket = FoundTombstone;
346 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
350 // If this is a tombstone, remember it. If Val ends up not in the map, we
351 // prefer to return it than something that would require more probing.
352 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
353 FoundTombstone = ThisBucket; // Remember the first tombstone found.
355 // Otherwise, it's a hash collision or a tombstone, continue quadratic
357 BucketNo += ProbeAmt++;
361 void init(unsigned InitBuckets) {
364 NumBuckets = InitBuckets;
366 if (InitBuckets == 0) {
371 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
372 "# initial buckets must be a power of two!");
373 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
374 // Initialize all the keys to EmptyKey.
375 const KeyT EmptyKey = getEmptyKey();
376 for (unsigned i = 0; i != InitBuckets; ++i)
377 new (&Buckets[i].first) KeyT(EmptyKey);
380 void grow(unsigned AtLeast) {
381 unsigned OldNumBuckets = NumBuckets;
382 BucketT *OldBuckets = Buckets;
387 // Double the number of buckets.
388 while (NumBuckets < AtLeast)
391 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
393 // Initialize all the keys to EmptyKey.
394 const KeyT EmptyKey = getEmptyKey();
395 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
396 new (&Buckets[i].first) KeyT(EmptyKey);
398 // Insert all the old elements.
399 const KeyT TombstoneKey = getTombstoneKey();
400 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
401 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
402 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
403 // Insert the key/value into the new table.
405 bool FoundVal = LookupBucketFor(B->first, DestBucket);
406 (void)FoundVal; // silence warning.
407 assert(!FoundVal && "Key already in new map?");
408 DestBucket->first = B->first;
409 new (&DestBucket->second) ValueT(B->second);
418 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
420 // Free the old table.
421 operator delete(OldBuckets);
424 void shrink_and_clear() {
425 unsigned OldNumBuckets = NumBuckets;
426 BucketT *OldBuckets = Buckets;
428 // Reduce the number of buckets.
429 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
432 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
434 // Initialize all the keys to EmptyKey.
435 const KeyT EmptyKey = getEmptyKey();
436 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
437 new (&Buckets[i].first) KeyT(EmptyKey);
439 // Free the old buckets.
440 const KeyT TombstoneKey = getTombstoneKey();
441 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
442 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
443 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
451 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
453 // Free the old table.
454 operator delete(OldBuckets);
460 template<typename KeyT, typename ValueT,
461 typename KeyInfoT, typename ValueInfoT, bool IsConst>
462 class DenseMapIterator {
463 typedef std::pair<KeyT, ValueT> Bucket;
464 typedef DenseMapIterator<KeyT, ValueT,
465 KeyInfoT, ValueInfoT, true> ConstIterator;
466 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, ValueInfoT, true>;
468 typedef ptrdiff_t difference_type;
469 typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
470 typedef value_type *pointer;
471 typedef value_type &reference;
472 typedef std::forward_iterator_tag iterator_category;
476 DenseMapIterator() : Ptr(0), End(0) {}
478 DenseMapIterator(pointer Pos, pointer E) : Ptr(Pos), End(E) {
479 AdvancePastEmptyBuckets();
482 // If IsConst is true this is a converting constructor from iterator to
483 // const_iterator and the default copy constructor is used.
484 // Otherwise this is a copy constructor for iterator.
485 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
486 KeyInfoT, ValueInfoT, false>& I)
487 : Ptr(I.Ptr), End(I.End) {}
489 reference operator*() const {
492 pointer operator->() const {
496 bool operator==(const ConstIterator &RHS) const {
497 return Ptr == RHS.operator->();
499 bool operator!=(const ConstIterator &RHS) const {
500 return Ptr != RHS.operator->();
503 inline DenseMapIterator& operator++() { // Preincrement
505 AdvancePastEmptyBuckets();
508 DenseMapIterator operator++(int) { // Postincrement
509 DenseMapIterator tmp = *this; ++*this; return tmp;
513 void AdvancePastEmptyBuckets() {
514 const KeyT Empty = KeyInfoT::getEmptyKey();
515 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
518 (KeyInfoT::isEqual(Ptr->first, Empty) ||
519 KeyInfoT::isEqual(Ptr->first, Tombstone)))
524 } // end namespace llvm