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"
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;
36 template<typename KeyT, typename ValueT,
37 typename KeyInfoT = DenseMapInfo<KeyT>,
38 typename ValueInfoT = DenseMapInfo<ValueT> >
40 typedef std::pair<KeyT, ValueT> BucketT;
45 unsigned NumTombstones;
47 typedef KeyT key_type;
48 typedef ValueT mapped_type;
49 typedef BucketT value_type;
51 DenseMap(const DenseMap& other) {
56 explicit DenseMap(unsigned NumInitBuckets = 64) {
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))
69 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
71 operator delete(Buckets);
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);
79 inline iterator end() {
80 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
82 inline const_iterator begin() const {
83 return const_iterator(Buckets, Buckets+NumBuckets);
85 inline const_iterator end() const {
86 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
89 bool empty() const { return NumEntries == 0; }
90 unsigned size() const { return NumEntries; }
92 /// Grow the densemap so that it has at least Size buckets. Does not shrink
93 void resize(size_t Size) { grow(Size); }
96 // If the capacity of the array is huge, and the # elements used is small,
98 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
103 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
104 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
105 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
106 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
113 assert(NumEntries == 0 && "Node count imbalance!");
117 /// count - Return true if the specified key is in the map.
118 bool count(const KeyT &Val) const {
120 return LookupBucketFor(Val, TheBucket);
123 iterator find(const KeyT &Val) {
125 if (LookupBucketFor(Val, TheBucket))
126 return iterator(TheBucket, Buckets+NumBuckets);
129 const_iterator find(const KeyT &Val) const {
131 if (LookupBucketFor(Val, TheBucket))
132 return const_iterator(TheBucket, Buckets+NumBuckets);
136 /// lookup - Return the entry for the specified key, or a default
137 /// constructed value if no such entry exists.
138 ValueT lookup(const KeyT &Val) const {
140 if (LookupBucketFor(Val, TheBucket))
141 return TheBucket->second;
145 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
147 if (LookupBucketFor(KV.first, TheBucket))
148 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
149 false); // Already in map.
151 // Otherwise, insert the new element.
152 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
153 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
157 /// insert - Range insertion of pairs.
158 template<typename InputIt>
159 void insert(InputIt I, InputIt E) {
165 bool erase(const KeyT &Val) {
167 if (!LookupBucketFor(Val, TheBucket))
168 return false; // not in map.
170 TheBucket->second.~ValueT();
171 TheBucket->first = getTombstoneKey();
176 bool erase(iterator I) {
177 BucketT *TheBucket = &*I;
178 TheBucket->second.~ValueT();
179 TheBucket->first = getTombstoneKey();
185 value_type& FindAndConstruct(const KeyT &Key) {
187 if (LookupBucketFor(Key, TheBucket))
190 return *InsertIntoBucket(Key, ValueT(), TheBucket);
193 ValueT &operator[](const KeyT &Key) {
194 return FindAndConstruct(Key).second;
197 DenseMap& operator=(const DenseMap& other) {
202 /// isPointerIntoBucketsArray - Return true if the specified pointer points
203 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
204 /// value in the DenseMap).
205 bool isPointerIntoBucketsArray(const void *Ptr) const {
206 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
209 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
210 /// array. In conjunction with the previous method, this can be used to
211 /// determine whether an insertion caused the DenseMap to reallocate.
212 const void *getPointerIntoBucketsArray() const { return Buckets; }
215 void CopyFrom(const DenseMap& other) {
216 if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
217 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
218 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
219 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
220 !KeyInfoT::isEqual(P->first, TombstoneKey))
226 NumEntries = other.NumEntries;
227 NumTombstones = other.NumTombstones;
231 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
233 operator delete(Buckets);
235 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
238 if (KeyInfoT::isPod() && ValueInfoT::isPod())
239 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
241 for (size_t i = 0; i < other.NumBuckets; ++i) {
242 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
243 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
244 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
245 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
247 NumBuckets = other.NumBuckets;
250 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
251 BucketT *TheBucket) {
252 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
253 // the buckets are empty (meaning that many are filled with tombstones),
256 // The later case is tricky. For example, if we had one empty bucket with
257 // tons of tombstones, failing lookups (e.g. for insertion) would have to
258 // probe almost the entire table until it found the empty bucket. If the
259 // table completely filled with tombstones, no lookup would ever succeed,
260 // causing infinite loops in lookup.
262 if (NumEntries*4 >= NumBuckets*3 ||
263 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
264 this->grow(NumBuckets * 2);
265 LookupBucketFor(Key, TheBucket);
268 // If we are writing over a tombstone, remember this.
269 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
272 TheBucket->first = Key;
273 new (&TheBucket->second) ValueT(Value);
277 static unsigned getHashValue(const KeyT &Val) {
278 return KeyInfoT::getHashValue(Val);
280 static const KeyT getEmptyKey() {
281 return KeyInfoT::getEmptyKey();
283 static const KeyT getTombstoneKey() {
284 return KeyInfoT::getTombstoneKey();
287 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
288 /// FoundBucket. If the bucket contains the key and a value, this returns
289 /// true, otherwise it returns a bucket with an empty marker or tombstone and
291 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
292 unsigned BucketNo = getHashValue(Val);
293 unsigned ProbeAmt = 1;
294 BucketT *BucketsPtr = Buckets;
296 // FoundTombstone - Keep track of whether we find a tombstone while probing.
297 BucketT *FoundTombstone = 0;
298 const KeyT EmptyKey = getEmptyKey();
299 const KeyT TombstoneKey = getTombstoneKey();
300 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
301 !KeyInfoT::isEqual(Val, TombstoneKey) &&
302 "Empty/Tombstone value shouldn't be inserted into map!");
305 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
306 // Found Val's bucket? If so, return it.
307 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
308 FoundBucket = ThisBucket;
312 // If we found an empty bucket, the key doesn't exist in the set.
313 // Insert it and return the default value.
314 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
315 // If we've already seen a tombstone while probing, fill it in instead
316 // of the empty bucket we eventually probed to.
317 if (FoundTombstone) ThisBucket = FoundTombstone;
318 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
322 // If this is a tombstone, remember it. If Val ends up not in the map, we
323 // prefer to return it than something that would require more probing.
324 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
325 FoundTombstone = ThisBucket; // Remember the first tombstone found.
327 // Otherwise, it's a hash collision or a tombstone, continue quadratic
329 BucketNo += ProbeAmt++;
333 void init(unsigned InitBuckets) {
336 NumBuckets = InitBuckets;
337 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
338 "# initial buckets must be a power of two!");
339 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
340 // Initialize all the keys to EmptyKey.
341 const KeyT EmptyKey = getEmptyKey();
342 for (unsigned i = 0; i != InitBuckets; ++i)
343 new (&Buckets[i].first) KeyT(EmptyKey);
346 void grow(unsigned AtLeast) {
347 unsigned OldNumBuckets = NumBuckets;
348 BucketT *OldBuckets = Buckets;
350 // Double the number of buckets.
351 while (NumBuckets <= AtLeast)
354 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
356 // Initialize all the keys to EmptyKey.
357 const KeyT EmptyKey = getEmptyKey();
358 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
359 new (&Buckets[i].first) KeyT(EmptyKey);
361 // Insert all the old elements.
362 const KeyT TombstoneKey = getTombstoneKey();
363 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
364 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
365 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
366 // Insert the key/value into the new table.
368 bool FoundVal = LookupBucketFor(B->first, DestBucket);
369 FoundVal = FoundVal; // silence warning.
370 assert(!FoundVal && "Key already in new map?");
371 DestBucket->first = B->first;
372 new (&DestBucket->second) ValueT(B->second);
381 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
383 // Free the old table.
384 operator delete(OldBuckets);
387 void shrink_and_clear() {
388 unsigned OldNumBuckets = NumBuckets;
389 BucketT *OldBuckets = Buckets;
391 // Reduce the number of buckets.
392 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
395 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
397 // Initialize all the keys to EmptyKey.
398 const KeyT EmptyKey = getEmptyKey();
399 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
400 new (&Buckets[i].first) KeyT(EmptyKey);
402 // Free the old buckets.
403 const KeyT TombstoneKey = getTombstoneKey();
404 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
405 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
406 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
414 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
416 // Free the old table.
417 operator delete(OldBuckets);
423 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
424 class DenseMapIterator {
425 typedef std::pair<KeyT, ValueT> BucketT;
427 const BucketT *Ptr, *End;
429 DenseMapIterator(void) : Ptr(0), End(0) {}
431 DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
432 AdvancePastEmptyBuckets();
435 std::pair<KeyT, ValueT> &operator*() const {
436 return *const_cast<BucketT*>(Ptr);
438 std::pair<KeyT, ValueT> *operator->() const {
439 return const_cast<BucketT*>(Ptr);
442 bool operator==(const DenseMapIterator &RHS) const {
443 return Ptr == RHS.Ptr;
445 bool operator!=(const DenseMapIterator &RHS) const {
446 return Ptr != RHS.Ptr;
449 inline DenseMapIterator& operator++() { // Preincrement
451 AdvancePastEmptyBuckets();
454 DenseMapIterator operator++(int) { // Postincrement
455 DenseMapIterator tmp = *this; ++*this; return tmp;
459 void AdvancePastEmptyBuckets() {
460 const KeyT Empty = KeyInfoT::getEmptyKey();
461 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
464 (KeyInfoT::isEqual(Ptr->first, Empty) ||
465 KeyInfoT::isEqual(Ptr->first, Tombstone)))
470 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
471 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
473 DenseMapConstIterator(void) : DenseMapIterator<KeyT, ValueT, KeyInfoT>() {}
474 DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
475 const std::pair<KeyT, ValueT> *E)
476 : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
478 const std::pair<KeyT, ValueT> &operator*() const {
481 const std::pair<KeyT, ValueT> *operator->() const {
486 } // end namespace llvm