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/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 typedef BucketT value_type;
68 DenseMap(const DenseMap& other) {
73 explicit DenseMap(unsigned NumInitBuckets = 64) {
78 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
79 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
80 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
81 !KeyInfoT::isEqual(P->first, TombstoneKey))
85 delete[] reinterpret_cast<char*>(Buckets);
88 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
89 typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
90 inline iterator begin() {
91 return iterator(Buckets, Buckets+NumBuckets);
93 inline iterator end() {
94 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
96 inline const_iterator begin() const {
97 return const_iterator(Buckets, Buckets+NumBuckets);
99 inline const_iterator end() const {
100 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
103 bool empty() const { return NumEntries == 0; }
104 unsigned size() const { return NumEntries; }
106 /// Grow the densemap so that it has at least Size buckets. Does not shrink
107 void resize(size_t Size) { grow(Size); }
110 // If the capacity of the array is huge, and the # elements used is small,
112 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
117 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
118 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
119 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
120 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
127 assert(NumEntries == 0 && "Node count imbalance!");
131 /// count - Return true if the specified key is in the map.
132 bool count(const KeyT &Val) const {
134 return LookupBucketFor(Val, TheBucket);
137 iterator find(const KeyT &Val) {
139 if (LookupBucketFor(Val, TheBucket))
140 return iterator(TheBucket, Buckets+NumBuckets);
143 const_iterator find(const KeyT &Val) const {
145 if (LookupBucketFor(Val, TheBucket))
146 return const_iterator(TheBucket, Buckets+NumBuckets);
150 bool insert(const std::pair<KeyT, ValueT> &KV) {
152 if (LookupBucketFor(KV.first, TheBucket))
153 return false; // Already in map.
155 // Otherwise, insert the new element.
156 InsertIntoBucket(KV.first, KV.second, TheBucket);
160 bool erase(const KeyT &Val) {
162 if (!LookupBucketFor(Val, TheBucket))
163 return false; // not in map.
165 TheBucket->second.~ValueT();
166 TheBucket->first = getTombstoneKey();
171 bool erase(iterator I) {
172 BucketT *TheBucket = &*I;
173 TheBucket->second.~ValueT();
174 TheBucket->first = getTombstoneKey();
180 value_type& FindAndConstruct(const KeyT &Key) {
182 if (LookupBucketFor(Key, TheBucket))
185 return *InsertIntoBucket(Key, ValueT(), TheBucket);
188 ValueT &operator[](const KeyT &Key) {
189 return FindAndConstruct(Key).second;
192 DenseMap& operator=(const DenseMap& other) {
198 void CopyFrom(const DenseMap& other) {
199 if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
200 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
201 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
202 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
203 !KeyInfoT::isEqual(P->first, TombstoneKey))
209 NumEntries = other.NumEntries;
210 NumTombstones = other.NumTombstones;
213 delete[] reinterpret_cast<char*>(Buckets);
214 Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT) *
217 if (KeyInfoT::isPod() && ValueInfoT::isPod())
218 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
220 for (size_t i = 0; i < other.NumBuckets; ++i) {
221 new (Buckets[i].first) KeyT(other.Buckets[i].first);
222 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
223 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
224 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
226 NumBuckets = other.NumBuckets;
229 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
230 BucketT *TheBucket) {
231 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
232 // the buckets are empty (meaning that many are filled with tombstones),
235 // The later case is tricky. For example, if we had one empty bucket with
236 // tons of tombstones, failing lookups (e.g. for insertion) would have to
237 // probe almost the entire table until it found the empty bucket. If the
238 // table completely filled with tombstones, no lookup would ever succeed,
239 // causing infinite loops in lookup.
240 if (NumEntries*4 >= NumBuckets*3 ||
241 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
242 this->grow(NumBuckets * 2);
243 LookupBucketFor(Key, TheBucket);
247 // If we are writing over a tombstone, remember this.
248 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
251 TheBucket->first = Key;
252 new (&TheBucket->second) ValueT(Value);
256 static unsigned getHashValue(const KeyT &Val) {
257 return KeyInfoT::getHashValue(Val);
259 static const KeyT getEmptyKey() {
260 return KeyInfoT::getEmptyKey();
262 static const KeyT getTombstoneKey() {
263 return KeyInfoT::getTombstoneKey();
266 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
267 /// FoundBucket. If the bucket contains the key and a value, this returns
268 /// true, otherwise it returns a bucket with an empty marker or tombstone and
270 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
271 unsigned BucketNo = getHashValue(Val);
272 unsigned ProbeAmt = 1;
273 BucketT *BucketsPtr = Buckets;
275 // FoundTombstone - Keep track of whether we find a tombstone while probing.
276 BucketT *FoundTombstone = 0;
277 const KeyT EmptyKey = getEmptyKey();
278 const KeyT TombstoneKey = getTombstoneKey();
279 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
280 !KeyInfoT::isEqual(Val, TombstoneKey) &&
281 "Empty/Tombstone value shouldn't be inserted into map!");
284 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
285 // Found Val's bucket? If so, return it.
286 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
287 FoundBucket = ThisBucket;
291 // If we found an empty bucket, the key doesn't exist in the set.
292 // Insert it and return the default value.
293 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
294 // If we've already seen a tombstone while probing, fill it in instead
295 // of the empty bucket we eventually probed to.
296 if (FoundTombstone) ThisBucket = FoundTombstone;
297 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
301 // If this is a tombstone, remember it. If Val ends up not in the map, we
302 // prefer to return it than something that would require more probing.
303 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
304 FoundTombstone = ThisBucket; // Remember the first tombstone found.
306 // Otherwise, it's a hash collision or a tombstone, continue quadratic
308 BucketNo += ProbeAmt++;
312 void init(unsigned InitBuckets) {
315 NumBuckets = InitBuckets;
316 assert(InitBuckets && (InitBuckets & InitBuckets-1) == 0 &&
317 "# initial buckets must be a power of two!");
318 Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT)*InitBuckets]);
319 // Initialize all the keys to EmptyKey.
320 const KeyT EmptyKey = getEmptyKey();
321 for (unsigned i = 0; i != InitBuckets; ++i)
322 new (&Buckets[i].first) KeyT(EmptyKey);
325 void grow(unsigned AtLeast) {
326 unsigned OldNumBuckets = NumBuckets;
327 BucketT *OldBuckets = Buckets;
329 // Double the number of buckets.
330 while (NumBuckets <= AtLeast)
333 Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT)*NumBuckets]);
335 // Initialize all the keys to EmptyKey.
336 const KeyT EmptyKey = getEmptyKey();
337 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
338 new (&Buckets[i].first) KeyT(EmptyKey);
340 // Insert all the old elements.
341 const KeyT TombstoneKey = getTombstoneKey();
342 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
343 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
344 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
345 // Insert the key/value into the new table.
347 bool FoundVal = LookupBucketFor(B->first, DestBucket);
348 FoundVal = FoundVal; // silence warning.
349 assert(!FoundVal && "Key already in new map?");
350 DestBucket->first = B->first;
351 new (&DestBucket->second) ValueT(B->second);
359 // Free the old table.
360 delete[] reinterpret_cast<char*>(OldBuckets);
363 void shrink_and_clear() {
364 unsigned OldNumBuckets = NumBuckets;
365 BucketT *OldBuckets = Buckets;
367 // Reduce the number of buckets.
368 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
371 Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT)*NumBuckets]);
373 // Initialize all the keys to EmptyKey.
374 const KeyT EmptyKey = getEmptyKey();
375 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
376 new (&Buckets[i].first) KeyT(EmptyKey);
378 // Free the old buckets.
379 const KeyT TombstoneKey = getTombstoneKey();
380 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
381 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
382 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
389 // Free the old table.
390 delete[] reinterpret_cast<char*>(OldBuckets);
396 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
397 class DenseMapIterator {
398 typedef std::pair<KeyT, ValueT> BucketT;
400 const BucketT *Ptr, *End;
402 DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
403 AdvancePastEmptyBuckets();
406 std::pair<KeyT, ValueT> &operator*() const {
407 return *const_cast<BucketT*>(Ptr);
409 std::pair<KeyT, ValueT> *operator->() const {
410 return const_cast<BucketT*>(Ptr);
413 bool operator==(const DenseMapIterator &RHS) const {
414 return Ptr == RHS.Ptr;
416 bool operator!=(const DenseMapIterator &RHS) const {
417 return Ptr != RHS.Ptr;
420 inline DenseMapIterator& operator++() { // Preincrement
422 AdvancePastEmptyBuckets();
425 DenseMapIterator operator++(int) { // Postincrement
426 DenseMapIterator tmp = *this; ++*this; return tmp;
430 void AdvancePastEmptyBuckets() {
431 const KeyT Empty = KeyInfoT::getEmptyKey();
432 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
435 (KeyInfoT::isEqual(Ptr->first, Empty) ||
436 KeyInfoT::isEqual(Ptr->first, Tombstone)))
441 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
442 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
444 DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
445 const std::pair<KeyT, ValueT> *E)
446 : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
448 const std::pair<KeyT, ValueT> &operator*() const {
451 const std::pair<KeyT, ValueT> *operator->() const {
456 } // end namespace llvm