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/PointerLikeTypeTraits.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/ADT/DenseMapInfo.h"
28 template<typename KeyT, typename ValueT,
29 typename KeyInfoT = DenseMapInfo<KeyT>,
30 typename ValueInfoT = DenseMapInfo<ValueT> >
31 class DenseMapIterator;
32 template<typename KeyT, typename ValueT,
33 typename KeyInfoT = DenseMapInfo<KeyT>,
34 typename ValueInfoT = DenseMapInfo<ValueT> >
35 class DenseMapConstIterator;
37 template<typename KeyT, typename ValueT,
38 typename KeyInfoT = DenseMapInfo<KeyT>,
39 typename ValueInfoT = DenseMapInfo<ValueT> >
41 typedef std::pair<KeyT, ValueT> BucketT;
46 unsigned NumTombstones;
48 typedef KeyT key_type;
49 typedef ValueT mapped_type;
50 typedef BucketT value_type;
52 DenseMap(const DenseMap& other) {
57 explicit DenseMap(unsigned NumInitBuckets = 64) {
62 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
63 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
64 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
65 !KeyInfoT::isEqual(P->first, TombstoneKey))
70 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
72 operator delete(Buckets);
75 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
76 typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
77 inline iterator begin() {
78 return iterator(Buckets, Buckets+NumBuckets);
80 inline iterator end() {
81 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
83 inline const_iterator begin() const {
84 return const_iterator(Buckets, Buckets+NumBuckets);
86 inline const_iterator end() const {
87 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
90 bool empty() const { return NumEntries == 0; }
91 unsigned size() const { return NumEntries; }
93 /// Grow the densemap so that it has at least Size buckets. Does not shrink
94 void resize(size_t Size) { grow(Size); }
97 if (NumEntries == 0 && NumTombstones == 0) return;
99 // If the capacity of the array is huge, and the # elements used is small,
101 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
106 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
107 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
108 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
109 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
116 assert(NumEntries == 0 && "Node count imbalance!");
120 /// count - Return true if the specified key is in the map.
121 bool count(const KeyT &Val) const {
123 return LookupBucketFor(Val, TheBucket);
126 iterator find(const KeyT &Val) {
128 if (LookupBucketFor(Val, TheBucket))
129 return iterator(TheBucket, Buckets+NumBuckets);
132 const_iterator find(const KeyT &Val) const {
134 if (LookupBucketFor(Val, TheBucket))
135 return const_iterator(TheBucket, Buckets+NumBuckets);
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 {
143 if (LookupBucketFor(Val, TheBucket))
144 return TheBucket->second;
148 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
150 if (LookupBucketFor(KV.first, TheBucket))
151 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
152 false); // Already in map.
154 // Otherwise, insert the new element.
155 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
156 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
160 /// insert - Range insertion of pairs.
161 template<typename InputIt>
162 void insert(InputIt I, InputIt E) {
168 bool erase(const KeyT &Val) {
170 if (!LookupBucketFor(Val, TheBucket))
171 return false; // not in map.
173 TheBucket->second.~ValueT();
174 TheBucket->first = getTombstoneKey();
179 bool erase(iterator I) {
180 BucketT *TheBucket = &*I;
181 TheBucket->second.~ValueT();
182 TheBucket->first = getTombstoneKey();
188 value_type& FindAndConstruct(const KeyT &Key) {
190 if (LookupBucketFor(Key, TheBucket))
193 return *InsertIntoBucket(Key, ValueT(), TheBucket);
196 ValueT &operator[](const KeyT &Key) {
197 return FindAndConstruct(Key).second;
200 DenseMap& operator=(const DenseMap& other) {
205 /// isPointerIntoBucketsArray - Return true if the specified pointer points
206 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
207 /// value in the DenseMap).
208 bool isPointerIntoBucketsArray(const void *Ptr) const {
209 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
212 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
213 /// array. In conjunction with the previous method, this can be used to
214 /// determine whether an insertion caused the DenseMap to reallocate.
215 const void *getPointerIntoBucketsArray() const { return Buckets; }
218 void CopyFrom(const DenseMap& other) {
219 if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
220 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
221 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
222 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
223 !KeyInfoT::isEqual(P->first, TombstoneKey))
229 NumEntries = other.NumEntries;
230 NumTombstones = other.NumTombstones;
234 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
236 operator delete(Buckets);
238 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
241 if (KeyInfoT::isPod() && ValueInfoT::isPod())
242 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
244 for (size_t i = 0; i < other.NumBuckets; ++i) {
245 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
246 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
247 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
248 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
250 NumBuckets = other.NumBuckets;
253 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
254 BucketT *TheBucket) {
255 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
256 // the buckets are empty (meaning that many are filled with tombstones),
259 // The later case is tricky. For example, if we had one empty bucket with
260 // tons of tombstones, failing lookups (e.g. for insertion) would have to
261 // probe almost the entire table until it found the empty bucket. If the
262 // table completely filled with tombstones, no lookup would ever succeed,
263 // causing infinite loops in lookup.
265 if (NumEntries*4 >= NumBuckets*3 ||
266 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
267 this->grow(NumBuckets * 2);
268 LookupBucketFor(Key, TheBucket);
271 // If we are writing over a tombstone, remember this.
272 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
275 TheBucket->first = Key;
276 new (&TheBucket->second) ValueT(Value);
280 static unsigned getHashValue(const KeyT &Val) {
281 return KeyInfoT::getHashValue(Val);
283 static const KeyT getEmptyKey() {
284 return KeyInfoT::getEmptyKey();
286 static const KeyT getTombstoneKey() {
287 return KeyInfoT::getTombstoneKey();
290 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
291 /// FoundBucket. If the bucket contains the key and a value, this returns
292 /// true, otherwise it returns a bucket with an empty marker or tombstone and
294 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
295 unsigned BucketNo = getHashValue(Val);
296 unsigned ProbeAmt = 1;
297 BucketT *BucketsPtr = Buckets;
299 // FoundTombstone - Keep track of whether we find a tombstone while probing.
300 BucketT *FoundTombstone = 0;
301 const KeyT EmptyKey = getEmptyKey();
302 const KeyT TombstoneKey = getTombstoneKey();
303 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
304 !KeyInfoT::isEqual(Val, TombstoneKey) &&
305 "Empty/Tombstone value shouldn't be inserted into map!");
308 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
309 // Found Val's bucket? If so, return it.
310 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
311 FoundBucket = ThisBucket;
315 // If we found an empty bucket, the key doesn't exist in the set.
316 // Insert it and return the default value.
317 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
318 // If we've already seen a tombstone while probing, fill it in instead
319 // of the empty bucket we eventually probed to.
320 if (FoundTombstone) ThisBucket = FoundTombstone;
321 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
325 // If this is a tombstone, remember it. If Val ends up not in the map, we
326 // prefer to return it than something that would require more probing.
327 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
328 FoundTombstone = ThisBucket; // Remember the first tombstone found.
330 // Otherwise, it's a hash collision or a tombstone, continue quadratic
332 BucketNo += ProbeAmt++;
336 void init(unsigned InitBuckets) {
339 NumBuckets = InitBuckets;
340 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
341 "# initial buckets must be a power of two!");
342 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
343 // Initialize all the keys to EmptyKey.
344 const KeyT EmptyKey = getEmptyKey();
345 for (unsigned i = 0; i != InitBuckets; ++i)
346 new (&Buckets[i].first) KeyT(EmptyKey);
349 void grow(unsigned AtLeast) {
350 unsigned OldNumBuckets = NumBuckets;
351 BucketT *OldBuckets = Buckets;
353 // Double the number of buckets.
354 while (NumBuckets <= AtLeast)
357 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
359 // Initialize all the keys to EmptyKey.
360 const KeyT EmptyKey = getEmptyKey();
361 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
362 new (&Buckets[i].first) KeyT(EmptyKey);
364 // Insert all the old elements.
365 const KeyT TombstoneKey = getTombstoneKey();
366 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
367 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
368 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
369 // Insert the key/value into the new table.
371 bool FoundVal = LookupBucketFor(B->first, DestBucket);
372 FoundVal = FoundVal; // silence warning.
373 assert(!FoundVal && "Key already in new map?");
374 DestBucket->first = B->first;
375 new (&DestBucket->second) ValueT(B->second);
384 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
386 // Free the old table.
387 operator delete(OldBuckets);
390 void shrink_and_clear() {
391 unsigned OldNumBuckets = NumBuckets;
392 BucketT *OldBuckets = Buckets;
394 // Reduce the number of buckets.
395 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
398 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
400 // Initialize all the keys to EmptyKey.
401 const KeyT EmptyKey = getEmptyKey();
402 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
403 new (&Buckets[i].first) KeyT(EmptyKey);
405 // Free the old buckets.
406 const KeyT TombstoneKey = getTombstoneKey();
407 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
408 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
409 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
417 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
419 // Free the old table.
420 operator delete(OldBuckets);
426 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
427 class DenseMapIterator :
428 public std::iterator<std::forward_iterator_tag, std::pair<KeyT, ValueT>,
430 typedef std::pair<KeyT, ValueT> BucketT;
432 const BucketT *Ptr, *End;
434 DenseMapIterator() : Ptr(0), End(0) {}
436 DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
437 AdvancePastEmptyBuckets();
440 std::pair<KeyT, ValueT> &operator*() const {
441 return *const_cast<BucketT*>(Ptr);
443 std::pair<KeyT, ValueT> *operator->() const {
444 return const_cast<BucketT*>(Ptr);
447 bool operator==(const DenseMapIterator &RHS) const {
448 return Ptr == RHS.Ptr;
450 bool operator!=(const DenseMapIterator &RHS) const {
451 return Ptr != RHS.Ptr;
454 inline DenseMapIterator& operator++() { // Preincrement
456 AdvancePastEmptyBuckets();
459 DenseMapIterator operator++(int) { // Postincrement
460 DenseMapIterator tmp = *this; ++*this; return tmp;
464 void AdvancePastEmptyBuckets() {
465 const KeyT Empty = KeyInfoT::getEmptyKey();
466 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
469 (KeyInfoT::isEqual(Ptr->first, Empty) ||
470 KeyInfoT::isEqual(Ptr->first, Tombstone)))
475 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
476 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
478 DenseMapConstIterator() : DenseMapIterator<KeyT, ValueT, KeyInfoT>() {}
479 DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
480 const std::pair<KeyT, ValueT> *E)
481 : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
483 const std::pair<KeyT, ValueT> &operator*() const {
486 const std::pair<KeyT, ValueT> *operator->() const {
491 } // end namespace llvm