DenseMap.h revision 289148afcb68b28e155ee87aa5a9efcf75adb444
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/ADT/DenseMapInfo.h"
18#include "llvm/Support/AlignOf.h"
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/MathExtras.h"
21#include "llvm/Support/PointerLikeTypeTraits.h"
22#include "llvm/Support/type_traits.h"
23#include <algorithm>
24#include <cassert>
25#include <climits>
26#include <cstddef>
27#include <cstring>
28#include <iterator>
29#include <new>
30#include <utility>
31
32namespace llvm {
33
34template<typename KeyT, typename ValueT,
35         typename KeyInfoT = DenseMapInfo<KeyT>,
36         bool IsConst = false>
37class DenseMapIterator;
38
39template<typename DerivedT,
40         typename KeyT, typename ValueT, typename KeyInfoT>
41class DenseMapBase {
42protected:
43  typedef std::pair<KeyT, ValueT> BucketT;
44
45public:
46  typedef KeyT key_type;
47  typedef ValueT mapped_type;
48  typedef BucketT value_type;
49
50  typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
51  typedef DenseMapIterator<KeyT, ValueT,
52                           KeyInfoT, true> const_iterator;
53  inline iterator begin() {
54    // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
55    return empty() ? end() : iterator(getBuckets(), getBucketsEnd());
56  }
57  inline iterator end() {
58    return iterator(getBucketsEnd(), getBucketsEnd(), true);
59  }
60  inline const_iterator begin() const {
61    return empty() ? end() : const_iterator(getBuckets(), getBucketsEnd());
62  }
63  inline const_iterator end() const {
64    return const_iterator(getBucketsEnd(), getBucketsEnd(), true);
65  }
66
67  bool empty() const { return getNumEntries() == 0; }
68  unsigned size() const { return getNumEntries(); }
69
70  /// Grow the densemap so that it has at least Size buckets. Does not shrink
71  void resize(size_t Size) {
72    if (Size > getNumBuckets())
73      grow(Size);
74  }
75
76  void clear() {
77    if (getNumEntries() == 0 && getNumTombstones() == 0) return;
78
79    // If the capacity of the array is huge, and the # elements used is small,
80    // shrink the array.
81    if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
82      shrink_and_clear();
83      return;
84    }
85
86    const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
87    for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
88      if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
89        if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
90          P->second.~ValueT();
91          decrementNumEntries();
92        }
93        P->first = EmptyKey;
94      }
95    }
96    assert(getNumEntries() == 0 && "Node count imbalance!");
97    setNumTombstones(0);
98  }
99
100  /// count - Return true if the specified key is in the map.
101  bool count(const KeyT &Val) const {
102    const BucketT *TheBucket;
103    return LookupBucketFor(Val, TheBucket);
104  }
105
106  iterator find(const KeyT &Val) {
107    BucketT *TheBucket;
108    if (LookupBucketFor(Val, TheBucket))
109      return iterator(TheBucket, getBucketsEnd(), true);
110    return end();
111  }
112  const_iterator find(const KeyT &Val) const {
113    const BucketT *TheBucket;
114    if (LookupBucketFor(Val, TheBucket))
115      return const_iterator(TheBucket, getBucketsEnd(), true);
116    return end();
117  }
118
119  /// Alternate version of find() which allows a different, and possibly
120  /// less expensive, key type.
121  /// The DenseMapInfo is responsible for supplying methods
122  /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
123  /// type used.
124  template<class LookupKeyT>
125  iterator find_as(const LookupKeyT &Val) {
126    BucketT *TheBucket;
127    if (LookupBucketFor(Val, TheBucket))
128      return iterator(TheBucket, getBucketsEnd(), true);
129    return end();
130  }
131  template<class LookupKeyT>
132  const_iterator find_as(const LookupKeyT &Val) const {
133    const BucketT *TheBucket;
134    if (LookupBucketFor(Val, TheBucket))
135      return const_iterator(TheBucket, getBucketsEnd(), true);
136    return end();
137  }
138
139  /// lookup - Return the entry for the specified key, or a default
140  /// constructed value if no such entry exists.
141  ValueT lookup(const KeyT &Val) const {
142    const BucketT *TheBucket;
143    if (LookupBucketFor(Val, TheBucket))
144      return TheBucket->second;
145    return ValueT();
146  }
147
148  // Inserts key,value pair into the map if the key isn't already in the map.
149  // If the key is already in the map, it returns false and doesn't update the
150  // value.
151  std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
152    BucketT *TheBucket;
153    if (LookupBucketFor(KV.first, TheBucket))
154      return std::make_pair(iterator(TheBucket, getBucketsEnd(), true),
155                            false); // Already in map.
156
157    // Otherwise, insert the new element.
158    TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
159    return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true);
160  }
161
162#if LLVM_HAS_RVALUE_REFERENCES
163  // Inserts key,value pair into the map if the key isn't already in the map.
164  // If the key is already in the map, it returns false and doesn't update the
165  // value.
166  std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
167    BucketT *TheBucket;
168    if (LookupBucketFor(KV.first, TheBucket))
169      return std::make_pair(iterator(TheBucket, getBucketsEnd(), true),
170                            false); // Already in map.
171
172    // Otherwise, insert the new element.
173    TheBucket = InsertIntoBucket(std::move(KV.first),
174                                 std::move(KV.second),
175                                 TheBucket);
176    return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true);
177  }
178#endif
179
180  /// insert - Range insertion of pairs.
181  template<typename InputIt>
182  void insert(InputIt I, InputIt E) {
183    for (; I != E; ++I)
184      insert(*I);
185  }
186
187
188  bool erase(const KeyT &Val) {
189    BucketT *TheBucket;
190    if (!LookupBucketFor(Val, TheBucket))
191      return false; // not in map.
192
193    TheBucket->second.~ValueT();
194    TheBucket->first = getTombstoneKey();
195    decrementNumEntries();
196    incrementNumTombstones();
197    return true;
198  }
199  void erase(iterator I) {
200    BucketT *TheBucket = &*I;
201    TheBucket->second.~ValueT();
202    TheBucket->first = getTombstoneKey();
203    decrementNumEntries();
204    incrementNumTombstones();
205  }
206
207  value_type& FindAndConstruct(const KeyT &Key) {
208    BucketT *TheBucket;
209    if (LookupBucketFor(Key, TheBucket))
210      return *TheBucket;
211
212    return *InsertIntoBucket(Key, ValueT(), TheBucket);
213  }
214
215  ValueT &operator[](const KeyT &Key) {
216    return FindAndConstruct(Key).second;
217  }
218
219#if LLVM_HAS_RVALUE_REFERENCES
220  value_type& FindAndConstruct(KeyT &&Key) {
221    BucketT *TheBucket;
222    if (LookupBucketFor(Key, TheBucket))
223      return *TheBucket;
224
225    return *InsertIntoBucket(Key, ValueT(), TheBucket);
226  }
227
228  ValueT &operator[](KeyT &&Key) {
229    return FindAndConstruct(Key).second;
230  }
231#endif
232
233  /// isPointerIntoBucketsArray - Return true if the specified pointer points
234  /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
235  /// value in the DenseMap).
236  bool isPointerIntoBucketsArray(const void *Ptr) const {
237    return Ptr >= getBuckets() && Ptr < getBucketsEnd();
238  }
239
240  /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
241  /// array.  In conjunction with the previous method, this can be used to
242  /// determine whether an insertion caused the DenseMap to reallocate.
243  const void *getPointerIntoBucketsArray() const { return getBuckets(); }
244
245protected:
246  DenseMapBase() {}
247
248  void destroyAll() {
249    if (getNumBuckets() == 0) // Nothing to do.
250      return;
251
252    const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
253    for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
254      if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
255          !KeyInfoT::isEqual(P->first, TombstoneKey))
256        P->second.~ValueT();
257      P->first.~KeyT();
258    }
259
260#ifndef NDEBUG
261    memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
262#endif
263  }
264
265  void initEmpty() {
266    setNumEntries(0);
267    setNumTombstones(0);
268
269    assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
270           "# initial buckets must be a power of two!");
271    const KeyT EmptyKey = getEmptyKey();
272    for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
273      new (&B->first) KeyT(EmptyKey);
274  }
275
276  void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
277    initEmpty();
278
279    // Insert all the old elements.
280    const KeyT EmptyKey = getEmptyKey();
281    const KeyT TombstoneKey = getTombstoneKey();
282    for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
283      if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
284          !KeyInfoT::isEqual(B->first, TombstoneKey)) {
285        // Insert the key/value into the new table.
286        BucketT *DestBucket;
287        bool FoundVal = LookupBucketFor(B->first, DestBucket);
288        (void)FoundVal; // silence warning.
289        assert(!FoundVal && "Key already in new map?");
290        DestBucket->first = llvm_move(B->first);
291        new (&DestBucket->second) ValueT(llvm_move(B->second));
292        incrementNumEntries();
293
294        // Free the value.
295        B->second.~ValueT();
296      }
297      B->first.~KeyT();
298    }
299
300#ifndef NDEBUG
301    if (OldBucketsBegin != OldBucketsEnd)
302      memset((void*)OldBucketsBegin, 0x5a,
303             sizeof(BucketT) * (OldBucketsEnd - OldBucketsBegin));
304#endif
305  }
306
307  template <typename OtherBaseT>
308  void copyFrom(const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT>& other) {
309    assert(getNumBuckets() == other.getNumBuckets());
310
311    setNumEntries(other.getNumEntries());
312    setNumTombstones(other.getNumTombstones());
313
314    if (isPodLike<KeyT>::value && isPodLike<ValueT>::value)
315      memcpy(getBuckets(), other.getBuckets(),
316             getNumBuckets() * sizeof(BucketT));
317    else
318      for (size_t i = 0; i < getNumBuckets(); ++i) {
319        new (&getBuckets()[i].first) KeyT(other.getBuckets()[i].first);
320        if (!KeyInfoT::isEqual(getBuckets()[i].first, getEmptyKey()) &&
321            !KeyInfoT::isEqual(getBuckets()[i].first, getTombstoneKey()))
322          new (&getBuckets()[i].second) ValueT(other.getBuckets()[i].second);
323      }
324  }
325
326  void swap(DenseMapBase& RHS) {
327    std::swap(getNumEntries(), RHS.getNumEntries());
328    std::swap(getNumTombstones(), RHS.getNumTombstones());
329  }
330
331  static unsigned getHashValue(const KeyT &Val) {
332    return KeyInfoT::getHashValue(Val);
333  }
334  template<typename LookupKeyT>
335  static unsigned getHashValue(const LookupKeyT &Val) {
336    return KeyInfoT::getHashValue(Val);
337  }
338  static const KeyT getEmptyKey() {
339    return KeyInfoT::getEmptyKey();
340  }
341  static const KeyT getTombstoneKey() {
342    return KeyInfoT::getTombstoneKey();
343  }
344
345private:
346  unsigned getNumEntries() const {
347    return static_cast<const DerivedT *>(this)->getNumEntries();
348  }
349  void setNumEntries(unsigned Num) {
350    static_cast<DerivedT *>(this)->setNumEntries(Num);
351  }
352  void incrementNumEntries() {
353    setNumEntries(getNumEntries() + 1);
354  }
355  void decrementNumEntries() {
356    setNumEntries(getNumEntries() - 1);
357  }
358  unsigned getNumTombstones() const {
359    return static_cast<const DerivedT *>(this)->getNumTombstones();
360  }
361  void setNumTombstones(unsigned Num) {
362    static_cast<DerivedT *>(this)->setNumTombstones(Num);
363  }
364  void incrementNumTombstones() {
365    setNumTombstones(getNumTombstones() + 1);
366  }
367  void decrementNumTombstones() {
368    setNumTombstones(getNumTombstones() - 1);
369  }
370  const BucketT *getBuckets() const {
371    return static_cast<const DerivedT *>(this)->getBuckets();
372  }
373  BucketT *getBuckets() {
374    return static_cast<DerivedT *>(this)->getBuckets();
375  }
376  unsigned getNumBuckets() const {
377    return static_cast<const DerivedT *>(this)->getNumBuckets();
378  }
379  BucketT *getBucketsEnd() {
380    return getBuckets() + getNumBuckets();
381  }
382  const BucketT *getBucketsEnd() const {
383    return getBuckets() + getNumBuckets();
384  }
385
386  void grow(unsigned AtLeast) {
387    static_cast<DerivedT *>(this)->grow(AtLeast);
388  }
389
390  void shrink_and_clear() {
391    static_cast<DerivedT *>(this)->shrink_and_clear();
392  }
393
394
395  BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
396                            BucketT *TheBucket) {
397    TheBucket = InsertIntoBucketImpl(Key, TheBucket);
398
399    TheBucket->first = Key;
400    new (&TheBucket->second) ValueT(Value);
401    return TheBucket;
402  }
403
404#if LLVM_HAS_RVALUE_REFERENCES
405  BucketT *InsertIntoBucket(const KeyT &Key, ValueT &&Value,
406                            BucketT *TheBucket) {
407    TheBucket = InsertIntoBucketImpl(Key, TheBucket);
408
409    TheBucket->first = Key;
410    new (&TheBucket->second) ValueT(std::move(Value));
411    return TheBucket;
412  }
413
414  BucketT *InsertIntoBucket(KeyT &&Key, ValueT &&Value, BucketT *TheBucket) {
415    TheBucket = InsertIntoBucketImpl(Key, TheBucket);
416
417    TheBucket->first = std::move(Key);
418    new (&TheBucket->second) ValueT(std::move(Value));
419    return TheBucket;
420  }
421#endif
422
423  BucketT *InsertIntoBucketImpl(const KeyT &Key, BucketT *TheBucket) {
424    // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
425    // the buckets are empty (meaning that many are filled with tombstones),
426    // grow the table.
427    //
428    // The later case is tricky.  For example, if we had one empty bucket with
429    // tons of tombstones, failing lookups (e.g. for insertion) would have to
430    // probe almost the entire table until it found the empty bucket.  If the
431    // table completely filled with tombstones, no lookup would ever succeed,
432    // causing infinite loops in lookup.
433    unsigned NewNumEntries = getNumEntries() + 1;
434    unsigned NumBuckets = getNumBuckets();
435    if (NewNumEntries*4 >= NumBuckets*3) {
436      this->grow(NumBuckets * 2);
437      LookupBucketFor(Key, TheBucket);
438      NumBuckets = getNumBuckets();
439    }
440    if (NumBuckets-(NewNumEntries+getNumTombstones()) <= NumBuckets/8) {
441      this->grow(NumBuckets * 2);
442      LookupBucketFor(Key, TheBucket);
443    }
444    assert(TheBucket);
445
446    // Only update the state after we've grown our bucket space appropriately
447    // so that when growing buckets we have self-consistent entry count.
448    incrementNumEntries();
449
450    // If we are writing over a tombstone, remember this.
451    const KeyT EmptyKey = getEmptyKey();
452    if (!KeyInfoT::isEqual(TheBucket->first, EmptyKey))
453      decrementNumTombstones();
454
455    return TheBucket;
456  }
457
458  /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
459  /// FoundBucket.  If the bucket contains the key and a value, this returns
460  /// true, otherwise it returns a bucket with an empty marker or tombstone and
461  /// returns false.
462  template<typename LookupKeyT>
463  bool LookupBucketFor(const LookupKeyT &Val,
464                       const BucketT *&FoundBucket) const {
465    const BucketT *BucketsPtr = getBuckets();
466    const unsigned NumBuckets = getNumBuckets();
467
468    if (NumBuckets == 0) {
469      FoundBucket = 0;
470      return false;
471    }
472
473    // FoundTombstone - Keep track of whether we find a tombstone while probing.
474    const BucketT *FoundTombstone = 0;
475    const KeyT EmptyKey = getEmptyKey();
476    const KeyT TombstoneKey = getTombstoneKey();
477    assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
478           !KeyInfoT::isEqual(Val, TombstoneKey) &&
479           "Empty/Tombstone value shouldn't be inserted into map!");
480
481    unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
482    unsigned ProbeAmt = 1;
483    while (1) {
484      const BucketT *ThisBucket = BucketsPtr + BucketNo;
485      // Found Val's bucket?  If so, return it.
486      if (KeyInfoT::isEqual(Val, ThisBucket->first)) {
487        FoundBucket = ThisBucket;
488        return true;
489      }
490
491      // If we found an empty bucket, the key doesn't exist in the set.
492      // Insert it and return the default value.
493      if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
494        // If we've already seen a tombstone while probing, fill it in instead
495        // of the empty bucket we eventually probed to.
496        if (FoundTombstone) ThisBucket = FoundTombstone;
497        FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
498        return false;
499      }
500
501      // If this is a tombstone, remember it.  If Val ends up not in the map, we
502      // prefer to return it than something that would require more probing.
503      if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
504        FoundTombstone = ThisBucket;  // Remember the first tombstone found.
505
506      // Otherwise, it's a hash collision or a tombstone, continue quadratic
507      // probing.
508      BucketNo += ProbeAmt++;
509      BucketNo &= (NumBuckets-1);
510    }
511  }
512
513  template <typename LookupKeyT>
514  bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
515    const BucketT *ConstFoundBucket;
516    bool Result = const_cast<const DenseMapBase *>(this)
517      ->LookupBucketFor(Val, ConstFoundBucket);
518    FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
519    return Result;
520  }
521
522public:
523  /// Return the approximate size (in bytes) of the actual map.
524  /// This is just the raw memory used by DenseMap.
525  /// If entries are pointers to objects, the size of the referenced objects
526  /// are not included.
527  size_t getMemorySize() const {
528    return getNumBuckets() * sizeof(BucketT);
529  }
530};
531
532template<typename KeyT, typename ValueT,
533         typename KeyInfoT = DenseMapInfo<KeyT> >
534class DenseMap
535    : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT>,
536                          KeyT, ValueT, KeyInfoT> {
537  // Lift some types from the dependent base class into this class for
538  // simplicity of referring to them.
539  typedef DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT> BaseT;
540  typedef typename BaseT::BucketT BucketT;
541  friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT>;
542
543  BucketT *Buckets;
544  unsigned NumEntries;
545  unsigned NumTombstones;
546  unsigned NumBuckets;
547
548public:
549  explicit DenseMap(unsigned NumInitBuckets = 0) {
550    init(NumInitBuckets);
551  }
552
553  DenseMap(const DenseMap &other) : BaseT() {
554    init(0);
555    copyFrom(other);
556  }
557
558#if LLVM_HAS_RVALUE_REFERENCES
559  DenseMap(DenseMap &&other) : BaseT() {
560    init(0);
561    swap(other);
562  }
563#endif
564
565  template<typename InputIt>
566  DenseMap(const InputIt &I, const InputIt &E) {
567    init(NextPowerOf2(std::distance(I, E)));
568    this->insert(I, E);
569  }
570
571  ~DenseMap() {
572    this->destroyAll();
573    operator delete(Buckets);
574  }
575
576  void swap(DenseMap& RHS) {
577    std::swap(Buckets, RHS.Buckets);
578    std::swap(NumEntries, RHS.NumEntries);
579    std::swap(NumTombstones, RHS.NumTombstones);
580    std::swap(NumBuckets, RHS.NumBuckets);
581  }
582
583  DenseMap& operator=(const DenseMap& other) {
584    copyFrom(other);
585    return *this;
586  }
587
588#if LLVM_HAS_RVALUE_REFERENCES
589  DenseMap& operator=(DenseMap &&other) {
590    this->destroyAll();
591    operator delete(Buckets);
592    init(0);
593    swap(other);
594    return *this;
595  }
596#endif
597
598  void copyFrom(const DenseMap& other) {
599    this->destroyAll();
600    operator delete(Buckets);
601    if (allocateBuckets(other.NumBuckets)) {
602      this->BaseT::copyFrom(other);
603    } else {
604      NumEntries = 0;
605      NumTombstones = 0;
606    }
607  }
608
609  void init(unsigned InitBuckets) {
610    if (allocateBuckets(InitBuckets)) {
611      this->BaseT::initEmpty();
612    } else {
613      NumEntries = 0;
614      NumTombstones = 0;
615    }
616  }
617
618  void grow(unsigned AtLeast) {
619    unsigned OldNumBuckets = NumBuckets;
620    BucketT *OldBuckets = Buckets;
621
622    allocateBuckets(std::max<unsigned>(64, NextPowerOf2(AtLeast-1)));
623    assert(Buckets);
624    if (!OldBuckets) {
625      this->BaseT::initEmpty();
626      return;
627    }
628
629    this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
630
631    // Free the old table.
632    operator delete(OldBuckets);
633  }
634
635  void shrink_and_clear() {
636    unsigned OldNumEntries = NumEntries;
637    this->destroyAll();
638
639    // Reduce the number of buckets.
640    unsigned NewNumBuckets = 0;
641    if (OldNumEntries)
642      NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
643    if (NewNumBuckets == NumBuckets) {
644      this->BaseT::initEmpty();
645      return;
646    }
647
648    operator delete(Buckets);
649    init(NewNumBuckets);
650  }
651
652private:
653  unsigned getNumEntries() const {
654    return NumEntries;
655  }
656  void setNumEntries(unsigned Num) {
657    NumEntries = Num;
658  }
659
660  unsigned getNumTombstones() const {
661    return NumTombstones;
662  }
663  void setNumTombstones(unsigned Num) {
664    NumTombstones = Num;
665  }
666
667  BucketT *getBuckets() const {
668    return Buckets;
669  }
670
671  unsigned getNumBuckets() const {
672    return NumBuckets;
673  }
674
675  bool allocateBuckets(unsigned Num) {
676    NumBuckets = Num;
677    if (NumBuckets == 0) {
678      Buckets = 0;
679      return false;
680    }
681
682    Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
683    return true;
684  }
685};
686
687template<typename KeyT, typename ValueT,
688         unsigned InlineBuckets = 4,
689         typename KeyInfoT = DenseMapInfo<KeyT> >
690class SmallDenseMap
691    : public DenseMapBase<SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT>,
692                          KeyT, ValueT, KeyInfoT> {
693  // Lift some types from the dependent base class into this class for
694  // simplicity of referring to them.
695  typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT> BaseT;
696  typedef typename BaseT::BucketT BucketT;
697  friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT>;
698
699  unsigned Small : 1;
700  unsigned NumEntries : 31;
701  unsigned NumTombstones;
702
703  struct LargeRep {
704    BucketT *Buckets;
705    unsigned NumBuckets;
706  };
707
708  /// A "union" of an inline bucket array and the struct representing
709  /// a large bucket. This union will be discriminated by the 'Small' bit.
710  AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
711
712public:
713  explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
714    init(NumInitBuckets);
715  }
716
717  SmallDenseMap(const SmallDenseMap &other) {
718    init(0);
719    copyFrom(other);
720  }
721
722#if LLVM_HAS_RVALUE_REFERENCES
723  SmallDenseMap(SmallDenseMap &&other) {
724    init(0);
725    swap(other);
726  }
727#endif
728
729  template<typename InputIt>
730  SmallDenseMap(const InputIt &I, const InputIt &E) {
731    init(NextPowerOf2(std::distance(I, E)));
732    this->insert(I, E);
733  }
734
735  ~SmallDenseMap() {
736    this->destroyAll();
737    deallocateBuckets();
738  }
739
740  void swap(SmallDenseMap& RHS) {
741    unsigned TmpNumEntries = RHS.NumEntries;
742    RHS.NumEntries = NumEntries;
743    NumEntries = TmpNumEntries;
744    std::swap(NumTombstones, RHS.NumTombstones);
745
746    const KeyT EmptyKey = this->getEmptyKey();
747    const KeyT TombstoneKey = this->getTombstoneKey();
748    if (Small && RHS.Small) {
749      // If we're swapping inline bucket arrays, we have to cope with some of
750      // the tricky bits of DenseMap's storage system: the buckets are not
751      // fully initialized. Thus we swap every key, but we may have
752      // a one-directional move of the value.
753      for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
754        BucketT *LHSB = &getInlineBuckets()[i],
755                *RHSB = &RHS.getInlineBuckets()[i];
756        bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->first, EmptyKey) &&
757                            !KeyInfoT::isEqual(LHSB->first, TombstoneKey));
758        bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->first, EmptyKey) &&
759                            !KeyInfoT::isEqual(RHSB->first, TombstoneKey));
760        if (hasLHSValue && hasRHSValue) {
761          // Swap together if we can...
762          std::swap(*LHSB, *RHSB);
763          continue;
764        }
765        // Swap separately and handle any assymetry.
766        std::swap(LHSB->first, RHSB->first);
767        if (hasLHSValue) {
768          new (&RHSB->second) ValueT(llvm_move(LHSB->second));
769          LHSB->second.~ValueT();
770        } else if (hasRHSValue) {
771          new (&LHSB->second) ValueT(llvm_move(RHSB->second));
772          RHSB->second.~ValueT();
773        }
774      }
775      return;
776    }
777    if (!Small && !RHS.Small) {
778      std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
779      std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
780      return;
781    }
782
783    SmallDenseMap &SmallSide = Small ? *this : RHS;
784    SmallDenseMap &LargeSide = Small ? RHS : *this;
785
786    // First stash the large side's rep and move the small side across.
787    LargeRep TmpRep = llvm_move(*LargeSide.getLargeRep());
788    LargeSide.getLargeRep()->~LargeRep();
789    LargeSide.Small = true;
790    // This is similar to the standard move-from-old-buckets, but the bucket
791    // count hasn't actually rotated in this case. So we have to carefully
792    // move construct the keys and values into their new locations, but there
793    // is no need to re-hash things.
794    for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
795      BucketT *NewB = &LargeSide.getInlineBuckets()[i],
796              *OldB = &SmallSide.getInlineBuckets()[i];
797      new (&NewB->first) KeyT(llvm_move(OldB->first));
798      OldB->first.~KeyT();
799      if (!KeyInfoT::isEqual(NewB->first, EmptyKey) &&
800          !KeyInfoT::isEqual(NewB->first, TombstoneKey)) {
801        new (&NewB->second) ValueT(llvm_move(OldB->second));
802        OldB->second.~ValueT();
803      }
804    }
805
806    // The hard part of moving the small buckets across is done, just move
807    // the TmpRep into its new home.
808    SmallSide.Small = false;
809    new (SmallSide.getLargeRep()) LargeRep(llvm_move(TmpRep));
810  }
811
812  SmallDenseMap& operator=(const SmallDenseMap& other) {
813    copyFrom(other);
814    return *this;
815  }
816
817#if LLVM_HAS_RVALUE_REFERENCES
818  SmallDenseMap& operator=(SmallDenseMap &&other) {
819    this->destroyAll();
820    deallocateBuckets();
821    init(0);
822    swap(other);
823    return *this;
824  }
825#endif
826
827  void copyFrom(const SmallDenseMap& other) {
828    this->destroyAll();
829    deallocateBuckets();
830    Small = true;
831    if (other.getNumBuckets() > InlineBuckets) {
832      Small = false;
833      allocateBuckets(other.getNumBuckets());
834    }
835    this->BaseT::copyFrom(other);
836  }
837
838  void init(unsigned InitBuckets) {
839    Small = true;
840    if (InitBuckets > InlineBuckets) {
841      Small = false;
842      new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
843    }
844    this->BaseT::initEmpty();
845  }
846
847  void grow(unsigned AtLeast) {
848    if (AtLeast >= InlineBuckets)
849      AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
850
851    if (Small) {
852      if (AtLeast < InlineBuckets)
853        return; // Nothing to do.
854
855      // First move the inline buckets into a temporary storage.
856      AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
857      BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
858      BucketT *TmpEnd = TmpBegin;
859
860      // Loop over the buckets, moving non-empty, non-tombstones into the
861      // temporary storage. Have the loop move the TmpEnd forward as it goes.
862      const KeyT EmptyKey = this->getEmptyKey();
863      const KeyT TombstoneKey = this->getTombstoneKey();
864      for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
865        if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
866            !KeyInfoT::isEqual(P->first, TombstoneKey)) {
867          assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
868                 "Too many inline buckets!");
869          new (&TmpEnd->first) KeyT(llvm_move(P->first));
870          new (&TmpEnd->second) ValueT(llvm_move(P->second));
871          ++TmpEnd;
872          P->second.~ValueT();
873        }
874        P->first.~KeyT();
875      }
876
877      // Now make this map use the large rep, and move all the entries back
878      // into it.
879      Small = false;
880      new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
881      this->moveFromOldBuckets(TmpBegin, TmpEnd);
882      return;
883    }
884
885    LargeRep OldRep = llvm_move(*getLargeRep());
886    getLargeRep()->~LargeRep();
887    if (AtLeast <= InlineBuckets) {
888      Small = true;
889    } else {
890      new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
891    }
892
893    this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
894
895    // Free the old table.
896    operator delete(OldRep.Buckets);
897  }
898
899  void shrink_and_clear() {
900    unsigned OldSize = this->size();
901    this->destroyAll();
902
903    // Reduce the number of buckets.
904    unsigned NewNumBuckets = 0;
905    if (OldSize) {
906      NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
907      if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
908        NewNumBuckets = 64;
909    }
910    if ((Small && NewNumBuckets <= InlineBuckets) ||
911        (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
912      this->BaseT::initEmpty();
913      return;
914    }
915
916    deallocateBuckets();
917    init(NewNumBuckets);
918  }
919
920private:
921  unsigned getNumEntries() const {
922    return NumEntries;
923  }
924  void setNumEntries(unsigned Num) {
925    assert(Num < INT_MAX && "Cannot support more than INT_MAX entries");
926    NumEntries = Num;
927  }
928
929  unsigned getNumTombstones() const {
930    return NumTombstones;
931  }
932  void setNumTombstones(unsigned Num) {
933    NumTombstones = Num;
934  }
935
936  const BucketT *getInlineBuckets() const {
937    assert(Small);
938    // Note that this cast does not violate aliasing rules as we assert that
939    // the memory's dynamic type is the small, inline bucket buffer, and the
940    // 'storage.buffer' static type is 'char *'.
941    return reinterpret_cast<const BucketT *>(storage.buffer);
942  }
943  BucketT *getInlineBuckets() {
944    return const_cast<BucketT *>(
945      const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
946  }
947  const LargeRep *getLargeRep() const {
948    assert(!Small);
949    // Note, same rule about aliasing as with getInlineBuckets.
950    return reinterpret_cast<const LargeRep *>(storage.buffer);
951  }
952  LargeRep *getLargeRep() {
953    return const_cast<LargeRep *>(
954      const_cast<const SmallDenseMap *>(this)->getLargeRep());
955  }
956
957  const BucketT *getBuckets() const {
958    return Small ? getInlineBuckets() : getLargeRep()->Buckets;
959  }
960  BucketT *getBuckets() {
961    return const_cast<BucketT *>(
962      const_cast<const SmallDenseMap *>(this)->getBuckets());
963  }
964  unsigned getNumBuckets() const {
965    return Small ? InlineBuckets : getLargeRep()->NumBuckets;
966  }
967
968  void deallocateBuckets() {
969    if (Small)
970      return;
971
972    operator delete(getLargeRep()->Buckets);
973    getLargeRep()->~LargeRep();
974  }
975
976  LargeRep allocateBuckets(unsigned Num) {
977    assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
978    LargeRep Rep = {
979      static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
980    };
981    return Rep;
982  }
983};
984
985template<typename KeyT, typename ValueT,
986         typename KeyInfoT, bool IsConst>
987class DenseMapIterator {
988  typedef std::pair<KeyT, ValueT> Bucket;
989  typedef DenseMapIterator<KeyT, ValueT,
990                           KeyInfoT, true> ConstIterator;
991  friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, true>;
992public:
993  typedef ptrdiff_t difference_type;
994  typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
995  typedef value_type *pointer;
996  typedef value_type &reference;
997  typedef std::forward_iterator_tag iterator_category;
998private:
999  pointer Ptr, End;
1000public:
1001  DenseMapIterator() : Ptr(0), End(0) {}
1002
1003  DenseMapIterator(pointer Pos, pointer E, bool NoAdvance = false)
1004    : Ptr(Pos), End(E) {
1005    if (!NoAdvance) AdvancePastEmptyBuckets();
1006  }
1007
1008  // If IsConst is true this is a converting constructor from iterator to
1009  // const_iterator and the default copy constructor is used.
1010  // Otherwise this is a copy constructor for iterator.
1011  DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
1012                                          KeyInfoT, false>& I)
1013    : Ptr(I.Ptr), End(I.End) {}
1014
1015  reference operator*() const {
1016    return *Ptr;
1017  }
1018  pointer operator->() const {
1019    return Ptr;
1020  }
1021
1022  bool operator==(const ConstIterator &RHS) const {
1023    return Ptr == RHS.operator->();
1024  }
1025  bool operator!=(const ConstIterator &RHS) const {
1026    return Ptr != RHS.operator->();
1027  }
1028
1029  inline DenseMapIterator& operator++() {  // Preincrement
1030    ++Ptr;
1031    AdvancePastEmptyBuckets();
1032    return *this;
1033  }
1034  DenseMapIterator operator++(int) {  // Postincrement
1035    DenseMapIterator tmp = *this; ++*this; return tmp;
1036  }
1037
1038private:
1039  void AdvancePastEmptyBuckets() {
1040    const KeyT Empty = KeyInfoT::getEmptyKey();
1041    const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1042
1043    while (Ptr != End &&
1044           (KeyInfoT::isEqual(Ptr->first, Empty) ||
1045            KeyInfoT::isEqual(Ptr->first, Tombstone)))
1046      ++Ptr;
1047  }
1048};
1049
1050template<typename KeyT, typename ValueT, typename KeyInfoT>
1051static inline size_t
1052capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
1053  return X.getMemorySize();
1054}
1055
1056} // end namespace llvm
1057
1058#endif
1059