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