b220714b36cabb7cc5a73dc9f040f974f4a47073
[oota-llvm.git] / include / llvm / ADT / DenseMap.h
1 //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/Support/PointerLikeTypeTraits.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/ADT/DenseMapInfo.h"
20 #include <cassert>
21 #include <cstring>
22 #include <utility>
23 #include <new>
24
25 namespace llvm {
26
27 template<typename KeyT, typename ValueT,
28          typename KeyInfoT = DenseMapInfo<KeyT>,
29          typename ValueInfoT = DenseMapInfo<ValueT> >
30 class DenseMapIterator;
31 template<typename KeyT, typename ValueT,
32          typename KeyInfoT = DenseMapInfo<KeyT>,
33          typename ValueInfoT = DenseMapInfo<ValueT> >
34 class DenseMapConstIterator;
35
36 template<typename KeyT, typename ValueT,
37          typename KeyInfoT = DenseMapInfo<KeyT>,
38          typename ValueInfoT = DenseMapInfo<ValueT> >
39 class DenseMap {
40   typedef std::pair<KeyT, ValueT> BucketT;
41   unsigned NumBuckets;
42   BucketT *Buckets;
43
44   unsigned NumEntries;
45   unsigned NumTombstones;
46 public:
47   typedef KeyT key_type;
48   typedef ValueT mapped_type;
49   typedef BucketT value_type;
50
51   DenseMap(const DenseMap& other) {
52     NumBuckets = 0;
53     CopyFrom(other);
54   }
55
56   explicit DenseMap(unsigned NumInitBuckets = 64) {
57     init(NumInitBuckets);
58   }
59
60   ~DenseMap() {
61     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
62     for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
63       if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
64           !KeyInfoT::isEqual(P->first, TombstoneKey))
65         P->second.~ValueT();
66       P->first.~KeyT();
67     }
68 #ifndef NDEBUG
69     memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
70 #endif
71     operator delete(Buckets);
72   }
73
74   typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
75   typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
76   inline iterator begin() {
77      return iterator(Buckets, Buckets+NumBuckets);
78   }
79   inline iterator end() {
80     return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
81   }
82   inline const_iterator begin() const {
83     return const_iterator(Buckets, Buckets+NumBuckets);
84   }
85   inline const_iterator end() const {
86     return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
87   }
88
89   bool empty() const { return NumEntries == 0; }
90   unsigned size() const { return NumEntries; }
91
92   /// Grow the densemap so that it has at least Size buckets. Does not shrink
93   void resize(size_t Size) { grow(Size); }
94
95   void clear() {
96     if (NumEntries == 0 && NumTombstones == 0) return;
97     
98     // If the capacity of the array is huge, and the # elements used is small,
99     // shrink the array.
100     if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
101       shrink_and_clear();
102       return;
103     }
104
105     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
106     for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
107       if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
108         if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
109           P->second.~ValueT();
110           --NumEntries;
111         }
112         P->first = EmptyKey;
113       }
114     }
115     assert(NumEntries == 0 && "Node count imbalance!");
116     NumTombstones = 0;
117   }
118
119   /// count - Return true if the specified key is in the map.
120   bool count(const KeyT &Val) const {
121     BucketT *TheBucket;
122     return LookupBucketFor(Val, TheBucket);
123   }
124
125   iterator find(const KeyT &Val) {
126     BucketT *TheBucket;
127     if (LookupBucketFor(Val, TheBucket))
128       return iterator(TheBucket, Buckets+NumBuckets);
129     return end();
130   }
131   const_iterator find(const KeyT &Val) const {
132     BucketT *TheBucket;
133     if (LookupBucketFor(Val, TheBucket))
134       return const_iterator(TheBucket, Buckets+NumBuckets);
135     return end();
136   }
137
138   /// lookup - Return the entry for the specified key, or a default
139   /// constructed value if no such entry exists.
140   ValueT lookup(const KeyT &Val) const {
141     BucketT *TheBucket;
142     if (LookupBucketFor(Val, TheBucket))
143       return TheBucket->second;
144     return ValueT();
145   }
146
147   std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
148     BucketT *TheBucket;
149     if (LookupBucketFor(KV.first, TheBucket))
150       return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
151                             false); // Already in map.
152
153     // Otherwise, insert the new element.
154     TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
155     return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
156                           true);
157   }
158
159   /// insert - Range insertion of pairs.
160   template<typename InputIt>
161   void insert(InputIt I, InputIt E) {
162     for (; I != E; ++I)
163       insert(*I);
164   }
165
166
167   bool erase(const KeyT &Val) {
168     BucketT *TheBucket;
169     if (!LookupBucketFor(Val, TheBucket))
170       return false; // not in map.
171
172     TheBucket->second.~ValueT();
173     TheBucket->first = getTombstoneKey();
174     --NumEntries;
175     ++NumTombstones;
176     return true;
177   }
178   bool erase(iterator I) {
179     BucketT *TheBucket = &*I;
180     TheBucket->second.~ValueT();
181     TheBucket->first = getTombstoneKey();
182     --NumEntries;
183     ++NumTombstones;
184     return true;
185   }
186
187   value_type& FindAndConstruct(const KeyT &Key) {
188     BucketT *TheBucket;
189     if (LookupBucketFor(Key, TheBucket))
190       return *TheBucket;
191
192     return *InsertIntoBucket(Key, ValueT(), TheBucket);
193   }
194
195   ValueT &operator[](const KeyT &Key) {
196     return FindAndConstruct(Key).second;
197   }
198
199   DenseMap& operator=(const DenseMap& other) {
200     CopyFrom(other);
201     return *this;
202   }
203
204   /// isPointerIntoBucketsArray - Return true if the specified pointer points
205   /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
206   /// value in the DenseMap).
207   bool isPointerIntoBucketsArray(const void *Ptr) const {
208     return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
209   }
210
211   /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
212   /// array.  In conjunction with the previous method, this can be used to
213   /// determine whether an insertion caused the DenseMap to reallocate.
214   const void *getPointerIntoBucketsArray() const { return Buckets; }
215
216 private:
217   void CopyFrom(const DenseMap& other) {
218     if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
219       const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
220       for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
221         if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
222             !KeyInfoT::isEqual(P->first, TombstoneKey))
223           P->second.~ValueT();
224         P->first.~KeyT();
225       }
226     }
227
228     NumEntries = other.NumEntries;
229     NumTombstones = other.NumTombstones;
230
231     if (NumBuckets) {
232 #ifndef NDEBUG
233       memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
234 #endif
235       operator delete(Buckets);
236     }
237     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
238                                                  other.NumBuckets));
239
240     if (KeyInfoT::isPod() && ValueInfoT::isPod())
241       memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
242     else
243       for (size_t i = 0; i < other.NumBuckets; ++i) {
244         new (&Buckets[i].first) KeyT(other.Buckets[i].first);
245         if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
246             !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
247           new (&Buckets[i].second) ValueT(other.Buckets[i].second);
248       }
249     NumBuckets = other.NumBuckets;
250   }
251
252   BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
253                             BucketT *TheBucket) {
254     // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
255     // the buckets are empty (meaning that many are filled with tombstones),
256     // grow the table.
257     //
258     // The later case is tricky.  For example, if we had one empty bucket with
259     // tons of tombstones, failing lookups (e.g. for insertion) would have to
260     // probe almost the entire table until it found the empty bucket.  If the
261     // table completely filled with tombstones, no lookup would ever succeed,
262     // causing infinite loops in lookup.
263     ++NumEntries;
264     if (NumEntries*4 >= NumBuckets*3 ||
265         NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
266       this->grow(NumBuckets * 2);
267       LookupBucketFor(Key, TheBucket);
268     }
269
270     // If we are writing over a tombstone, remember this.
271     if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
272       --NumTombstones;
273
274     TheBucket->first = Key;
275     new (&TheBucket->second) ValueT(Value);
276     return TheBucket;
277   }
278
279   static unsigned getHashValue(const KeyT &Val) {
280     return KeyInfoT::getHashValue(Val);
281   }
282   static const KeyT getEmptyKey() {
283     return KeyInfoT::getEmptyKey();
284   }
285   static const KeyT getTombstoneKey() {
286     return KeyInfoT::getTombstoneKey();
287   }
288
289   /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
290   /// FoundBucket.  If the bucket contains the key and a value, this returns
291   /// true, otherwise it returns a bucket with an empty marker or tombstone and
292   /// returns false.
293   bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
294     unsigned BucketNo = getHashValue(Val);
295     unsigned ProbeAmt = 1;
296     BucketT *BucketsPtr = Buckets;
297
298     // FoundTombstone - Keep track of whether we find a tombstone while probing.
299     BucketT *FoundTombstone = 0;
300     const KeyT EmptyKey = getEmptyKey();
301     const KeyT TombstoneKey = getTombstoneKey();
302     assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
303            !KeyInfoT::isEqual(Val, TombstoneKey) &&
304            "Empty/Tombstone value shouldn't be inserted into map!");
305
306     while (1) {
307       BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
308       // Found Val's bucket?  If so, return it.
309       if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
310         FoundBucket = ThisBucket;
311         return true;
312       }
313
314       // If we found an empty bucket, the key doesn't exist in the set.
315       // Insert it and return the default value.
316       if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
317         // If we've already seen a tombstone while probing, fill it in instead
318         // of the empty bucket we eventually probed to.
319         if (FoundTombstone) ThisBucket = FoundTombstone;
320         FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
321         return false;
322       }
323
324       // If this is a tombstone, remember it.  If Val ends up not in the map, we
325       // prefer to return it than something that would require more probing.
326       if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
327         FoundTombstone = ThisBucket;  // Remember the first tombstone found.
328
329       // Otherwise, it's a hash collision or a tombstone, continue quadratic
330       // probing.
331       BucketNo += ProbeAmt++;
332     }
333   }
334
335   void init(unsigned InitBuckets) {
336     NumEntries = 0;
337     NumTombstones = 0;
338     NumBuckets = InitBuckets;
339     assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
340            "# initial buckets must be a power of two!");
341     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
342     // Initialize all the keys to EmptyKey.
343     const KeyT EmptyKey = getEmptyKey();
344     for (unsigned i = 0; i != InitBuckets; ++i)
345       new (&Buckets[i].first) KeyT(EmptyKey);
346   }
347
348   void grow(unsigned AtLeast) {
349     unsigned OldNumBuckets = NumBuckets;
350     BucketT *OldBuckets = Buckets;
351
352     // Double the number of buckets.
353     while (NumBuckets <= AtLeast)
354       NumBuckets <<= 1;
355     NumTombstones = 0;
356     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
357
358     // Initialize all the keys to EmptyKey.
359     const KeyT EmptyKey = getEmptyKey();
360     for (unsigned i = 0, e = NumBuckets; i != e; ++i)
361       new (&Buckets[i].first) KeyT(EmptyKey);
362
363     // Insert all the old elements.
364     const KeyT TombstoneKey = getTombstoneKey();
365     for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
366       if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
367           !KeyInfoT::isEqual(B->first, TombstoneKey)) {
368         // Insert the key/value into the new table.
369         BucketT *DestBucket;
370         bool FoundVal = LookupBucketFor(B->first, DestBucket);
371         FoundVal = FoundVal; // silence warning.
372         assert(!FoundVal && "Key already in new map?");
373         DestBucket->first = B->first;
374         new (&DestBucket->second) ValueT(B->second);
375
376         // Free the value.
377         B->second.~ValueT();
378       }
379       B->first.~KeyT();
380     }
381
382 #ifndef NDEBUG
383     memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
384 #endif
385     // Free the old table.
386     operator delete(OldBuckets);
387   }
388
389   void shrink_and_clear() {
390     unsigned OldNumBuckets = NumBuckets;
391     BucketT *OldBuckets = Buckets;
392
393     // Reduce the number of buckets.
394     NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
395                                  : 64;
396     NumTombstones = 0;
397     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
398
399     // Initialize all the keys to EmptyKey.
400     const KeyT EmptyKey = getEmptyKey();
401     for (unsigned i = 0, e = NumBuckets; i != e; ++i)
402       new (&Buckets[i].first) KeyT(EmptyKey);
403
404     // Free the old buckets.
405     const KeyT TombstoneKey = getTombstoneKey();
406     for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
407       if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
408           !KeyInfoT::isEqual(B->first, TombstoneKey)) {
409         // Free the value.
410         B->second.~ValueT();
411       }
412       B->first.~KeyT();
413     }
414
415 #ifndef NDEBUG
416     memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
417 #endif
418     // Free the old table.
419     operator delete(OldBuckets);
420
421     NumEntries = 0;
422   }
423 };
424
425 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
426 class DenseMapIterator {
427   typedef std::pair<KeyT, ValueT> BucketT;
428 protected:
429   const BucketT *Ptr, *End;
430 public:
431   DenseMapIterator() : Ptr(0), End(0) {}
432
433   DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
434     AdvancePastEmptyBuckets();
435   }
436
437   std::pair<KeyT, ValueT> &operator*() const {
438     return *const_cast<BucketT*>(Ptr);
439   }
440   std::pair<KeyT, ValueT> *operator->() const {
441     return const_cast<BucketT*>(Ptr);
442   }
443
444   bool operator==(const DenseMapIterator &RHS) const {
445     return Ptr == RHS.Ptr;
446   }
447   bool operator!=(const DenseMapIterator &RHS) const {
448     return Ptr != RHS.Ptr;
449   }
450
451   inline DenseMapIterator& operator++() {          // Preincrement
452     ++Ptr;
453     AdvancePastEmptyBuckets();
454     return *this;
455   }
456   DenseMapIterator operator++(int) {        // Postincrement
457     DenseMapIterator tmp = *this; ++*this; return tmp;
458   }
459
460 private:
461   void AdvancePastEmptyBuckets() {
462     const KeyT Empty = KeyInfoT::getEmptyKey();
463     const KeyT Tombstone = KeyInfoT::getTombstoneKey();
464
465     while (Ptr != End &&
466            (KeyInfoT::isEqual(Ptr->first, Empty) ||
467             KeyInfoT::isEqual(Ptr->first, Tombstone)))
468       ++Ptr;
469   }
470 };
471
472 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
473 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
474 public:
475   DenseMapConstIterator() : DenseMapIterator<KeyT, ValueT, KeyInfoT>() {}
476   DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
477                         const std::pair<KeyT, ValueT> *E)
478     : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
479   }
480   const std::pair<KeyT, ValueT> &operator*() const {
481     return *this->Ptr;
482   }
483   const std::pair<KeyT, ValueT> *operator->() const {
484     return this->Ptr;
485   }
486 };
487
488 } // end namespace llvm
489
490 #endif