7f02dc92e21ef6b83bd99d36e87d957d1751ed18
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/DataTypes.h"
18 #include "llvm/Support/MathExtras.h"
19 #include <cassert>
20 #include <utility>
21
22 namespace llvm {
23   
24 template<typename T>
25 struct DenseMapInfo {
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);
30   //static bool isPod()
31 };
32
33 // Provide DenseMapInfo for all pointers.
34 template<typename T>
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);
41   }
42   static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
43   static bool isPod() { return true; }
44 };
45
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;
54
55 template<typename KeyT, typename ValueT,
56          typename KeyInfoT = DenseMapInfo<KeyT>,
57          typename ValueInfoT = DenseMapInfo<ValueT> >
58 class DenseMap {
59   typedef std::pair<KeyT, ValueT> BucketT;
60   unsigned NumBuckets;
61   BucketT *Buckets;
62   
63   unsigned NumEntries;
64   unsigned NumTombstones;
65 public:
66   typedef BucketT value_type;
67   
68   DenseMap(const DenseMap& other) {
69     NumBuckets = 0;
70     CopyFrom(other);
71   }
72   
73   explicit DenseMap(unsigned NumInitBuckets = 64) {
74     init(NumInitBuckets);
75   }
76   
77   ~DenseMap() {
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))
82         P->second.~ValueT();
83       P->first.~KeyT();
84     }
85     delete[] reinterpret_cast<char*>(Buckets);
86   }
87   
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);
92   }
93   inline iterator end() {
94     return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
95   }
96   inline const_iterator begin() const {
97     return const_iterator(Buckets, Buckets+NumBuckets);
98   }
99   inline const_iterator end() const {
100     return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
101   }
102   
103   bool empty() const { return NumEntries == 0; }
104   unsigned size() const { return NumEntries; }
105
106   /// Grow the densemap so that it has at least Size buckets. Does not shrink
107   void resize(size_t Size) { grow(Size); }
108   
109   void clear() {
110     // If the capacity of the array is huge, and the # elements used is small,
111     // shrink the array.
112     if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
113       shrink_and_clear();
114       return;
115     }
116     
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)) {
121           P->second.~ValueT();
122           --NumEntries;
123         }
124         P->first = EmptyKey;
125       }
126     }
127     assert(NumEntries == 0 && "Node count imbalance!");
128     NumTombstones = 0;
129   }
130
131   /// count - Return true if the specified key is in the map.
132   bool count(const KeyT &Val) const {
133     BucketT *TheBucket;
134     return LookupBucketFor(Val, TheBucket);
135   }
136   
137   iterator find(const KeyT &Val) {
138     BucketT *TheBucket;
139     if (LookupBucketFor(Val, TheBucket))
140       return iterator(TheBucket, Buckets+NumBuckets);
141     return end();
142   }
143   const_iterator find(const KeyT &Val) const {
144     BucketT *TheBucket;
145     if (LookupBucketFor(Val, TheBucket))
146       return const_iterator(TheBucket, Buckets+NumBuckets);
147     return end();
148   }
149   
150   bool insert(const std::pair<KeyT, ValueT> &KV) {
151     BucketT *TheBucket;
152     if (LookupBucketFor(KV.first, TheBucket))
153       return false; // Already in map.
154     
155     // Otherwise, insert the new element.
156     InsertIntoBucket(KV.first, KV.second, TheBucket);
157     return true;
158   }
159   
160   bool erase(const KeyT &Val) {
161     BucketT *TheBucket;
162     if (!LookupBucketFor(Val, TheBucket))
163       return false; // not in map.
164
165     TheBucket->second.~ValueT();
166     TheBucket->first = getTombstoneKey();
167     --NumEntries;
168     ++NumTombstones;
169     return true;
170   }
171   bool erase(iterator I) {
172     BucketT *TheBucket = &*I;
173     TheBucket->second.~ValueT();
174     TheBucket->first = getTombstoneKey();
175     --NumEntries;
176     ++NumTombstones;
177     return true;
178   }
179
180   value_type& FindAndConstruct(const KeyT &Key) {
181     BucketT *TheBucket;
182     if (LookupBucketFor(Key, TheBucket))
183       return *TheBucket;
184     
185     return *InsertIntoBucket(Key, ValueT(), TheBucket);
186   }
187   
188   ValueT &operator[](const KeyT &Key) {
189     return FindAndConstruct(Key).second;
190   }
191   
192   DenseMap& operator=(const DenseMap& other) {
193     CopyFrom(other);
194     return *this;
195   }
196   
197 private:
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))
204           P->second.~ValueT();
205         P->first.~KeyT();
206       }
207     }
208     
209     NumEntries = other.NumEntries;
210     NumTombstones = other.NumTombstones;
211     
212     if (NumBuckets)
213       delete[] reinterpret_cast<char*>(Buckets);
214     Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT) *
215                                                   other.NumBuckets]);
216     
217     if (KeyInfoT::isPod() && ValueInfoT::isPod())
218       memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
219     else
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);
225       }
226     NumBuckets = other.NumBuckets;
227   }
228   
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),
233     // grow the table.
234     //
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);
244     }
245     ++NumEntries;
246     
247     // If we are writing over a tombstone, remember this.
248     if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
249       --NumTombstones;
250     
251     TheBucket->first = Key;
252     new (&TheBucket->second) ValueT(Value);
253     return TheBucket;
254   }
255
256   static unsigned getHashValue(const KeyT &Val) {
257     return KeyInfoT::getHashValue(Val);
258   }
259   static const KeyT getEmptyKey() {
260     return KeyInfoT::getEmptyKey();
261   }
262   static const KeyT getTombstoneKey() {
263     return KeyInfoT::getTombstoneKey();
264   }
265   
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
269   /// returns false.
270   bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
271     unsigned BucketNo = getHashValue(Val);
272     unsigned ProbeAmt = 1;
273     BucketT *BucketsPtr = Buckets;
274     
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!");
282       
283     while (1) {
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;
288         return true;
289       }
290       
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;
298         return false;
299       }
300       
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.
305       
306       // Otherwise, it's a hash collision or a tombstone, continue quadratic
307       // probing.
308       BucketNo += ProbeAmt++;
309     }
310   }
311
312   void init(unsigned InitBuckets) {
313     NumEntries = 0;
314     NumTombstones = 0;
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);
323   }
324   
325   void grow(unsigned AtLeast) {
326     unsigned OldNumBuckets = NumBuckets;
327     BucketT *OldBuckets = Buckets;
328     
329     // Double the number of buckets.
330     while (NumBuckets <= AtLeast)
331       NumBuckets <<= 1;
332     NumTombstones = 0;
333     Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT)*NumBuckets]);
334
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);
339
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.
346         BucketT *DestBucket;
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);
352         
353         // Free the value.
354         B->second.~ValueT();
355       }
356       B->first.~KeyT();
357     }
358     
359     // Free the old table.
360     delete[] reinterpret_cast<char*>(OldBuckets);
361   }
362   
363   void shrink_and_clear() {
364     unsigned OldNumBuckets = NumBuckets;
365     BucketT *OldBuckets = Buckets;
366     
367     // Reduce the number of buckets.
368     NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
369                                  : 64;
370     NumTombstones = 0;
371     Buckets = reinterpret_cast<BucketT*>(new char[sizeof(BucketT)*NumBuckets]);
372
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);
377
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)) {
383         // Free the value.
384         B->second.~ValueT();
385       }
386       B->first.~KeyT();
387     }
388     
389     // Free the old table.
390     delete[] reinterpret_cast<char*>(OldBuckets);
391     
392     NumEntries = 0;
393   }
394 };
395
396 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
397 class DenseMapIterator {
398   typedef std::pair<KeyT, ValueT> BucketT;
399 protected:
400   const BucketT *Ptr, *End;
401 public:
402   DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
403     AdvancePastEmptyBuckets();
404   }
405   
406   std::pair<KeyT, ValueT> &operator*() const {
407     return *const_cast<BucketT*>(Ptr);
408   }
409   std::pair<KeyT, ValueT> *operator->() const {
410     return const_cast<BucketT*>(Ptr);
411   }
412   
413   bool operator==(const DenseMapIterator &RHS) const {
414     return Ptr == RHS.Ptr;
415   }
416   bool operator!=(const DenseMapIterator &RHS) const {
417     return Ptr != RHS.Ptr;
418   }
419   
420   inline DenseMapIterator& operator++() {          // Preincrement
421     ++Ptr;
422     AdvancePastEmptyBuckets();
423     return *this;
424   }
425   DenseMapIterator operator++(int) {        // Postincrement
426     DenseMapIterator tmp = *this; ++*this; return tmp;
427   }
428   
429 private:
430   void AdvancePastEmptyBuckets() {
431     const KeyT Empty = KeyInfoT::getEmptyKey();
432     const KeyT Tombstone = KeyInfoT::getTombstoneKey();
433
434     while (Ptr != End && 
435            (KeyInfoT::isEqual(Ptr->first, Empty) ||
436             KeyInfoT::isEqual(Ptr->first, Tombstone)))
437       ++Ptr;
438   }
439 };
440
441 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
442 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
443 public:
444   DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
445                         const std::pair<KeyT, ValueT> *E)
446     : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
447   }
448   const std::pair<KeyT, ValueT> &operator*() const {
449     return *this->Ptr;
450   }
451   const std::pair<KeyT, ValueT> *operator->() const {
452     return this->Ptr;
453   }
454 };
455
456 } // end namespace llvm
457
458 #endif