1 //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/DataTypes.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() { return reinterpret_cast<T*>(-1); }
37 static inline T* getTombstoneKey() { return reinterpret_cast<T*>(-2); }
38 static unsigned getHashValue(const T *PtrVal) {
39 return (unsigned(uintptr_t(PtrVal)) >> 4) ^
40 (unsigned(uintptr_t(PtrVal)) >> 9);
42 static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
43 static bool isPod() { return true; }
46 template<typename KeyT, typename ValueT,
47 typename KeyInfoT = DenseMapInfo<KeyT>,
48 typename ValueInfoT = DenseMapInfo<ValueT> >
49 class DenseMapIterator;
50 template<typename KeyT, typename ValueT,
51 typename KeyInfoT = DenseMapInfo<KeyT>,
52 typename ValueInfoT = DenseMapInfo<ValueT> >
53 class DenseMapConstIterator;
55 template<typename KeyT, typename ValueT,
56 typename KeyInfoT = DenseMapInfo<KeyT>,
57 typename ValueInfoT = DenseMapInfo<ValueT> >
59 typedef std::pair<KeyT, ValueT> BucketT;
64 unsigned NumTombstones;
66 DenseMap(const DenseMap& other) {
71 explicit DenseMap(unsigned NumInitBuckets = 64) {
76 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
77 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
78 if (P->first != EmptyKey && P->first != TombstoneKey)
82 delete[] reinterpret_cast<char*>(Buckets);
85 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
86 typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
87 inline iterator begin() {
88 return iterator(Buckets, Buckets+NumBuckets);
90 inline iterator end() {
91 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
93 inline const_iterator begin() const {
94 return const_iterator(Buckets, Buckets+NumBuckets);
96 inline const_iterator end() const {
97 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
100 bool empty() const { return NumEntries == 0; }
101 unsigned size() const { return NumEntries; }
103 /// Grow the densemap so that it has at least Size buckets. Does not shrink
104 void resize(size_t Size) { grow(Size); }
107 // If the capacity of the array is huge, and the # elements used is small,
109 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
114 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
115 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
116 if (P->first != EmptyKey) {
117 if (P->first != TombstoneKey) {
124 assert(NumEntries == 0 && "Node count imbalance!");
128 /// count - Return true if the specified key is in the map.
129 bool count(const KeyT &Val) const {
131 return LookupBucketFor(Val, TheBucket);
134 iterator find(const KeyT &Val) {
136 if (LookupBucketFor(Val, TheBucket))
137 return iterator(TheBucket, Buckets+NumBuckets);
140 const_iterator find(const KeyT &Val) const {
142 if (LookupBucketFor(Val, TheBucket))
143 return const_iterator(TheBucket, Buckets+NumBuckets);
147 bool insert(const std::pair<KeyT, ValueT> &KV) {
149 if (LookupBucketFor(KV.first, TheBucket))
150 return false; // Already in map.
152 // Otherwise, insert the new element.
153 InsertIntoBucket(KV.first, KV.second, TheBucket);
157 bool erase(const KeyT &Val) {
159 if (!LookupBucketFor(Val, TheBucket))
160 return false; // not in map.
162 TheBucket->second.~ValueT();
163 TheBucket->first = getTombstoneKey();
168 bool erase(iterator I) {
169 BucketT *TheBucket = &*I;
170 TheBucket->second.~ValueT();
171 TheBucket->first = getTombstoneKey();
177 ValueT &operator[](const KeyT &Key) {
179 if (LookupBucketFor(Key, TheBucket))
180 return TheBucket->second;
182 return InsertIntoBucket(Key, ValueT(), TheBucket)->second;
185 DenseMap& operator=(const DenseMap& other) {
191 void CopyFrom(const DenseMap& other) {
192 if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
193 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
194 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
195 if (P->first != EmptyKey && P->first != TombstoneKey)
201 NumEntries = other.NumEntries;
202 NumTombstones = other.NumTombstones;
205 delete[] reinterpret_cast<char*>(Buckets);
206 Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT) *
209 if (KeyInfoT::isPod() && ValueInfoT::isPod())
210 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
212 for (size_t i = 0; i < other.NumBuckets; ++i) {
213 new (Buckets[i].first) KeyT(other.Buckets[i].first);
214 if (Buckets[i].first != getEmptyKey() &&
215 Buckets[i].first != getTombstoneKey())
216 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
218 NumBuckets = other.NumBuckets;
221 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
222 BucketT *TheBucket) {
223 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
224 // the buckets are empty (meaning that many are filled with tombstones),
227 // The later case is tricky. For example, if we had one empty bucket with
228 // tons of tombstones, failing lookups (e.g. for insertion) would have to
229 // probe almost the entire table until it found the empty bucket. If the
230 // table completely filled with tombstones, no lookup would ever succeed,
231 // causing infinite loops in lookup.
232 if (NumEntries*4 >= NumBuckets*3 ||
233 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
234 this->grow(NumBuckets * 2);
235 LookupBucketFor(Key, TheBucket);
239 // If we are writing over a tombstone, remember this.
240 if (TheBucket->first != getEmptyKey())
243 TheBucket->first = Key;
244 new (&TheBucket->second) ValueT(Value);
248 static unsigned getHashValue(const KeyT &Val) {
249 return KeyInfoT::getHashValue(Val);
251 static const KeyT getEmptyKey() {
252 return KeyInfoT::getEmptyKey();
254 static const KeyT getTombstoneKey() {
255 return KeyInfoT::getTombstoneKey();
258 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
259 /// FoundBucket. If the bucket contains the key and a value, this returns
260 /// true, otherwise it returns a bucket with an empty marker or tombstone and
262 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
263 unsigned BucketNo = getHashValue(Val);
264 unsigned ProbeAmt = 1;
265 BucketT *BucketsPtr = Buckets;
267 // FoundTombstone - Keep track of whether we find a tombstone while probing.
268 BucketT *FoundTombstone = 0;
269 const KeyT EmptyKey = getEmptyKey();
270 const KeyT TombstoneKey = getTombstoneKey();
271 assert(Val != EmptyKey && Val != TombstoneKey &&
272 "Empty/Tombstone value shouldn't be inserted into map!");
275 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
276 // Found Val's bucket? If so, return it.
277 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
278 FoundBucket = ThisBucket;
282 // If we found an empty bucket, the key doesn't exist in the set.
283 // Insert it and return the default value.
284 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
285 // If we've already seen a tombstone while probing, fill it in instead
286 // of the empty bucket we eventually probed to.
287 if (FoundTombstone) ThisBucket = FoundTombstone;
288 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
292 // If this is a tombstone, remember it. If Val ends up not in the map, we
293 // prefer to return it than something that would require more probing.
294 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
295 FoundTombstone = ThisBucket; // Remember the first tombstone found.
297 // Otherwise, it's a hash collision or a tombstone, continue quadratic
299 BucketNo += ProbeAmt++;
303 void init(unsigned InitBuckets) {
306 NumBuckets = InitBuckets;
307 assert(InitBuckets && (InitBuckets & InitBuckets-1) == 0 &&
308 "# initial buckets must be a power of two!");
309 Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT)*InitBuckets]);
310 // Initialize all the keys to EmptyKey.
311 const KeyT EmptyKey = getEmptyKey();
312 for (unsigned i = 0; i != InitBuckets; ++i)
313 new (&Buckets[i].first) KeyT(EmptyKey);
316 void grow(unsigned AtLeast) {
317 unsigned OldNumBuckets = NumBuckets;
318 BucketT *OldBuckets = Buckets;
320 // Double the number of buckets.
321 while (NumBuckets <= AtLeast)
324 Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT)*NumBuckets]);
326 // Initialize all the keys to EmptyKey.
327 const KeyT EmptyKey = getEmptyKey();
328 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
329 new (&Buckets[i].first) KeyT(EmptyKey);
331 // Insert all the old elements.
332 const KeyT TombstoneKey = getTombstoneKey();
333 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
334 if (B->first != EmptyKey && B->first != TombstoneKey) {
335 // Insert the key/value into the new table.
337 bool FoundVal = LookupBucketFor(B->first, DestBucket);
338 FoundVal = FoundVal; // silence warning.
339 assert(!FoundVal && "Key already in new map?");
340 DestBucket->first = B->first;
341 new (&DestBucket->second) ValueT(B->second);
349 // Free the old table.
350 delete[] reinterpret_cast<char*>(OldBuckets);
353 void shrink_and_clear() {
354 unsigned OldNumBuckets = NumBuckets;
355 BucketT *OldBuckets = Buckets;
357 // Reduce the number of buckets.
358 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
361 Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT)*NumBuckets]);
363 // Initialize all the keys to EmptyKey.
364 const KeyT EmptyKey = getEmptyKey();
365 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
366 new (&Buckets[i].first) KeyT(EmptyKey);
368 // Free the old buckets.
369 const KeyT TombstoneKey = getTombstoneKey();
370 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
371 if (B->first != EmptyKey && B->first != TombstoneKey) {
378 // Free the old table.
379 delete[] reinterpret_cast<char*>(OldBuckets);
385 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
386 class DenseMapIterator {
387 typedef std::pair<KeyT, ValueT> BucketT;
389 const BucketT *Ptr, *End;
391 DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
392 AdvancePastEmptyBuckets();
395 std::pair<KeyT, ValueT> &operator*() const {
396 return *const_cast<BucketT*>(Ptr);
398 std::pair<KeyT, ValueT> *operator->() const {
399 return const_cast<BucketT*>(Ptr);
402 bool operator==(const DenseMapIterator &RHS) const {
403 return Ptr == RHS.Ptr;
405 bool operator!=(const DenseMapIterator &RHS) const {
406 return Ptr != RHS.Ptr;
409 inline DenseMapIterator& operator++() { // Preincrement
411 AdvancePastEmptyBuckets();
414 DenseMapIterator operator++(int) { // Postincrement
415 DenseMapIterator tmp = *this; ++*this; return tmp;
419 void AdvancePastEmptyBuckets() {
420 const KeyT Empty = KeyInfoT::getEmptyKey();
421 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
424 (KeyInfoT::isEqual(Ptr->first, Empty) ||
425 KeyInfoT::isEqual(Ptr->first, Tombstone)))
430 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
431 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
433 DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
434 const std::pair<KeyT, ValueT> *E)
435 : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
437 const std::pair<KeyT, ValueT> &operator*() const {
440 const std::pair<KeyT, ValueT> *operator->() const {
445 } // end namespace llvm