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/PointerLikeTypeTraits.h"
18 #include "llvm/Support/MathExtras.h"
26 //static inline T getEmptyKey();
27 //static inline T getTombstoneKey();
28 //static unsigned getHashValue(const T &Val);
29 //static bool isEqual(const T &LHS, const T &RHS);
33 // Provide DenseMapInfo for all pointers.
35 struct DenseMapInfo<T*> {
36 static inline T* getEmptyKey() {
38 Val <<= PointerLikeTypeTraits<T*>::NumLowBitsAvailable;
39 return reinterpret_cast<T*>(Val);
41 static inline T* getTombstoneKey() {
43 Val <<= PointerLikeTypeTraits<T*>::NumLowBitsAvailable;
44 return reinterpret_cast<T*>(Val);
46 static unsigned getHashValue(const T *PtrVal) {
47 return (unsigned((uintptr_t)PtrVal) >> 4) ^
48 (unsigned((uintptr_t)PtrVal) >> 9);
50 static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
51 static bool isPod() { return true; }
54 // Provide DenseMapInfo for chars.
55 template<> struct DenseMapInfo<char> {
56 static inline char getEmptyKey() { return ~0; }
57 static inline char getTombstoneKey() { return ~0 - 1; }
58 static unsigned getHashValue(const char& Val) { return Val * 37; }
59 static bool isPod() { return true; }
60 static bool isEqual(const char &LHS, const char &RHS) {
65 // Provide DenseMapInfo for unsigned ints.
66 template<> struct DenseMapInfo<unsigned> {
67 static inline unsigned getEmptyKey() { return ~0; }
68 static inline unsigned getTombstoneKey() { return ~0 - 1; }
69 static unsigned getHashValue(const unsigned& Val) { return Val * 37; }
70 static bool isPod() { return true; }
71 static bool isEqual(const unsigned& LHS, const unsigned& RHS) {
76 // Provide DenseMapInfo for unsigned longs.
77 template<> struct DenseMapInfo<unsigned long> {
78 static inline unsigned long getEmptyKey() { return ~0L; }
79 static inline unsigned long getTombstoneKey() { return ~0L - 1L; }
80 static unsigned getHashValue(const unsigned long& Val) {
81 return (unsigned)(Val * 37L);
83 static bool isPod() { return true; }
84 static bool isEqual(const unsigned long& LHS, const unsigned long& RHS) {
89 // Provide DenseMapInfo for all pairs whose members have info.
90 template<typename T, typename U>
91 struct DenseMapInfo<std::pair<T, U> > {
92 typedef std::pair<T, U> Pair;
93 typedef DenseMapInfo<T> FirstInfo;
94 typedef DenseMapInfo<U> SecondInfo;
96 static inline Pair getEmptyKey() {
97 return std::make_pair(FirstInfo::getEmptyKey(),
98 SecondInfo::getEmptyKey());
100 static inline Pair getTombstoneKey() {
101 return std::make_pair(FirstInfo::getTombstoneKey(),
102 SecondInfo::getEmptyKey());
104 static unsigned getHashValue(const Pair& PairVal) {
105 uint64_t key = (uint64_t)FirstInfo::getHashValue(PairVal.first) << 32
106 | (uint64_t)SecondInfo::getHashValue(PairVal.second);
115 return (unsigned)key;
117 static bool isEqual(const Pair& LHS, const Pair& RHS) { return LHS == RHS; }
118 static bool isPod() { return FirstInfo::isPod() && SecondInfo::isPod(); }
121 template<typename KeyT, typename ValueT,
122 typename KeyInfoT = DenseMapInfo<KeyT>,
123 typename ValueInfoT = DenseMapInfo<ValueT> >
124 class DenseMapIterator;
125 template<typename KeyT, typename ValueT,
126 typename KeyInfoT = DenseMapInfo<KeyT>,
127 typename ValueInfoT = DenseMapInfo<ValueT> >
128 class DenseMapConstIterator;
130 template<typename KeyT, typename ValueT,
131 typename KeyInfoT = DenseMapInfo<KeyT>,
132 typename ValueInfoT = DenseMapInfo<ValueT> >
134 typedef std::pair<KeyT, ValueT> BucketT;
139 unsigned NumTombstones;
141 typedef KeyT key_type;
142 typedef ValueT mapped_type;
143 typedef BucketT value_type;
145 DenseMap(const DenseMap& other) {
150 explicit DenseMap(unsigned NumInitBuckets = 64) {
151 init(NumInitBuckets);
155 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
156 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
157 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
158 !KeyInfoT::isEqual(P->first, TombstoneKey))
162 operator delete(Buckets);
165 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
166 typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
167 inline iterator begin() {
168 return iterator(Buckets, Buckets+NumBuckets);
170 inline iterator end() {
171 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
173 inline const_iterator begin() const {
174 return const_iterator(Buckets, Buckets+NumBuckets);
176 inline const_iterator end() const {
177 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
180 bool empty() const { return NumEntries == 0; }
181 unsigned size() const { return NumEntries; }
183 /// Grow the densemap so that it has at least Size buckets. Does not shrink
184 void resize(size_t Size) { grow(Size); }
187 // If the capacity of the array is huge, and the # elements used is small,
189 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
194 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
195 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
196 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
197 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
204 assert(NumEntries == 0 && "Node count imbalance!");
208 /// count - Return true if the specified key is in the map.
209 bool count(const KeyT &Val) const {
211 return LookupBucketFor(Val, TheBucket);
214 iterator find(const KeyT &Val) {
216 if (LookupBucketFor(Val, TheBucket))
217 return iterator(TheBucket, Buckets+NumBuckets);
220 const_iterator find(const KeyT &Val) const {
222 if (LookupBucketFor(Val, TheBucket))
223 return const_iterator(TheBucket, Buckets+NumBuckets);
227 /// lookup - Return the entry for the specified key, or a default
228 /// constructed value if no such entry exists.
229 ValueT lookup(const KeyT &Val) const {
231 if (LookupBucketFor(Val, TheBucket))
232 return TheBucket->second;
236 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
238 if (LookupBucketFor(KV.first, TheBucket))
239 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
240 false); // Already in map.
242 // Otherwise, insert the new element.
243 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
244 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
248 /// insert - Range insertion of pairs.
249 template<typename InputIt>
250 void insert(InputIt I, InputIt E) {
256 bool erase(const KeyT &Val) {
258 if (!LookupBucketFor(Val, TheBucket))
259 return false; // not in map.
261 TheBucket->second.~ValueT();
262 TheBucket->first = getTombstoneKey();
267 bool erase(iterator I) {
268 BucketT *TheBucket = &*I;
269 TheBucket->second.~ValueT();
270 TheBucket->first = getTombstoneKey();
276 value_type& FindAndConstruct(const KeyT &Key) {
278 if (LookupBucketFor(Key, TheBucket))
281 return *InsertIntoBucket(Key, ValueT(), TheBucket);
284 ValueT &operator[](const KeyT &Key) {
285 return FindAndConstruct(Key).second;
288 DenseMap& operator=(const DenseMap& other) {
293 /// isPointerIntoBucketsArray - Return true if the specified pointer points
294 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
295 /// value in the DenseMap).
296 bool isPointerIntoBucketsArray(const void *Ptr) const {
297 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
300 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
301 /// array. In conjunction with the previous method, this can be used to
302 /// determine whether an insertion caused the DenseMap to reallocate.
303 const void *getPointerIntoBucketsArray() const { return Buckets; }
306 void CopyFrom(const DenseMap& other) {
307 if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
308 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
309 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
310 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
311 !KeyInfoT::isEqual(P->first, TombstoneKey))
317 NumEntries = other.NumEntries;
318 NumTombstones = other.NumTombstones;
321 operator delete(Buckets);
322 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
325 if (KeyInfoT::isPod() && ValueInfoT::isPod())
326 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
328 for (size_t i = 0; i < other.NumBuckets; ++i) {
329 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
330 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
331 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
332 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
334 NumBuckets = other.NumBuckets;
337 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
338 BucketT *TheBucket) {
339 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
340 // the buckets are empty (meaning that many are filled with tombstones),
343 // The later case is tricky. For example, if we had one empty bucket with
344 // tons of tombstones, failing lookups (e.g. for insertion) would have to
345 // probe almost the entire table until it found the empty bucket. If the
346 // table completely filled with tombstones, no lookup would ever succeed,
347 // causing infinite loops in lookup.
348 if (NumEntries*4 >= NumBuckets*3 ||
349 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
350 this->grow(NumBuckets * 2);
351 LookupBucketFor(Key, TheBucket);
355 // If we are writing over a tombstone, remember this.
356 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
359 TheBucket->first = Key;
360 new (&TheBucket->second) ValueT(Value);
364 static unsigned getHashValue(const KeyT &Val) {
365 return KeyInfoT::getHashValue(Val);
367 static const KeyT getEmptyKey() {
368 return KeyInfoT::getEmptyKey();
370 static const KeyT getTombstoneKey() {
371 return KeyInfoT::getTombstoneKey();
374 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
375 /// FoundBucket. If the bucket contains the key and a value, this returns
376 /// true, otherwise it returns a bucket with an empty marker or tombstone and
378 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
379 unsigned BucketNo = getHashValue(Val);
380 unsigned ProbeAmt = 1;
381 BucketT *BucketsPtr = Buckets;
383 // FoundTombstone - Keep track of whether we find a tombstone while probing.
384 BucketT *FoundTombstone = 0;
385 const KeyT EmptyKey = getEmptyKey();
386 const KeyT TombstoneKey = getTombstoneKey();
387 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
388 !KeyInfoT::isEqual(Val, TombstoneKey) &&
389 "Empty/Tombstone value shouldn't be inserted into map!");
392 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
393 // Found Val's bucket? If so, return it.
394 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
395 FoundBucket = ThisBucket;
399 // If we found an empty bucket, the key doesn't exist in the set.
400 // Insert it and return the default value.
401 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
402 // If we've already seen a tombstone while probing, fill it in instead
403 // of the empty bucket we eventually probed to.
404 if (FoundTombstone) ThisBucket = FoundTombstone;
405 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
409 // If this is a tombstone, remember it. If Val ends up not in the map, we
410 // prefer to return it than something that would require more probing.
411 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
412 FoundTombstone = ThisBucket; // Remember the first tombstone found.
414 // Otherwise, it's a hash collision or a tombstone, continue quadratic
416 BucketNo += ProbeAmt++;
420 void init(unsigned InitBuckets) {
423 NumBuckets = InitBuckets;
424 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
425 "# initial buckets must be a power of two!");
426 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
427 // Initialize all the keys to EmptyKey.
428 const KeyT EmptyKey = getEmptyKey();
429 for (unsigned i = 0; i != InitBuckets; ++i)
430 new (&Buckets[i].first) KeyT(EmptyKey);
433 void grow(unsigned AtLeast) {
434 unsigned OldNumBuckets = NumBuckets;
435 BucketT *OldBuckets = Buckets;
437 // Double the number of buckets.
438 while (NumBuckets <= AtLeast)
441 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
443 // Initialize all the keys to EmptyKey.
444 const KeyT EmptyKey = getEmptyKey();
445 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
446 new (&Buckets[i].first) KeyT(EmptyKey);
448 // Insert all the old elements.
449 const KeyT TombstoneKey = getTombstoneKey();
450 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
451 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
452 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
453 // Insert the key/value into the new table.
455 bool FoundVal = LookupBucketFor(B->first, DestBucket);
456 FoundVal = FoundVal; // silence warning.
457 assert(!FoundVal && "Key already in new map?");
458 DestBucket->first = B->first;
459 new (&DestBucket->second) ValueT(B->second);
467 // Free the old table.
468 operator delete(OldBuckets);
471 void shrink_and_clear() {
472 unsigned OldNumBuckets = NumBuckets;
473 BucketT *OldBuckets = Buckets;
475 // Reduce the number of buckets.
476 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
479 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
481 // Initialize all the keys to EmptyKey.
482 const KeyT EmptyKey = getEmptyKey();
483 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
484 new (&Buckets[i].first) KeyT(EmptyKey);
486 // Free the old buckets.
487 const KeyT TombstoneKey = getTombstoneKey();
488 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
489 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
490 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
497 // Free the old table.
498 operator delete(OldBuckets);
504 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
505 class DenseMapIterator {
506 typedef std::pair<KeyT, ValueT> BucketT;
508 const BucketT *Ptr, *End;
510 DenseMapIterator(void) : Ptr(0), End(0) {}
512 DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
513 AdvancePastEmptyBuckets();
516 std::pair<KeyT, ValueT> &operator*() const {
517 return *const_cast<BucketT*>(Ptr);
519 std::pair<KeyT, ValueT> *operator->() const {
520 return const_cast<BucketT*>(Ptr);
523 bool operator==(const DenseMapIterator &RHS) const {
524 return Ptr == RHS.Ptr;
526 bool operator!=(const DenseMapIterator &RHS) const {
527 return Ptr != RHS.Ptr;
530 inline DenseMapIterator& operator++() { // Preincrement
532 AdvancePastEmptyBuckets();
535 DenseMapIterator operator++(int) { // Postincrement
536 DenseMapIterator tmp = *this; ++*this; return tmp;
540 void AdvancePastEmptyBuckets() {
541 const KeyT Empty = KeyInfoT::getEmptyKey();
542 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
545 (KeyInfoT::isEqual(Ptr->first, Empty) ||
546 KeyInfoT::isEqual(Ptr->first, Tombstone)))
551 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
552 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
554 DenseMapConstIterator(void) : DenseMapIterator<KeyT, ValueT, KeyInfoT>() {}
555 DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
556 const std::pair<KeyT, ValueT> *E)
557 : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
559 const std::pair<KeyT, ValueT> &operator*() const {
562 const std::pair<KeyT, ValueT> *operator->() const {
567 } // end namespace llvm