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/MathExtras.h"
18 #include "llvm/Support/PointerLikeTypeTraits.h"
19 #include "llvm/Support/type_traits.h"
20 #include "llvm/ADT/DenseMapInfo.h"
30 template<typename KeyT, typename ValueT,
31 typename KeyInfoT = DenseMapInfo<KeyT>,
32 typename ValueInfoT = DenseMapInfo<ValueT>, bool IsConst = false>
33 class DenseMapIterator;
35 template<typename KeyT, typename ValueT,
36 typename KeyInfoT = DenseMapInfo<KeyT>,
37 typename ValueInfoT = DenseMapInfo<ValueT> >
39 typedef std::pair<KeyT, ValueT> BucketT;
44 unsigned NumTombstones;
46 typedef KeyT key_type;
47 typedef ValueT mapped_type;
48 typedef BucketT value_type;
50 DenseMap(const DenseMap &other) {
55 explicit DenseMap(unsigned NumInitBuckets = 64) {
59 template<typename InputIt>
60 DenseMap(const InputIt &I, const InputIt &E) {
66 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
67 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
68 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
69 !KeyInfoT::isEqual(P->first, TombstoneKey))
74 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
76 operator delete(Buckets);
79 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
80 typedef DenseMapIterator<KeyT, ValueT,
81 KeyInfoT, ValueInfoT, true> const_iterator;
82 inline iterator begin() {
83 // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
84 return empty() ? end() : iterator(Buckets, Buckets+NumBuckets);
86 inline iterator end() {
87 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
89 inline const_iterator begin() const {
90 return empty() ? end() : const_iterator(Buckets, Buckets+NumBuckets);
92 inline const_iterator end() const {
93 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
96 bool empty() const { return NumEntries == 0; }
97 unsigned size() const { return NumEntries; }
99 /// Grow the densemap so that it has at least Size buckets. Does not shrink
100 void resize(size_t Size) { grow(Size); }
103 if (NumEntries == 0 && NumTombstones == 0) return;
105 // If the capacity of the array is huge, and the # elements used is small,
107 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
112 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
113 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
114 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
115 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
122 assert(NumEntries == 0 && "Node count imbalance!");
126 /// count - Return true if the specified key is in the map.
127 bool count(const KeyT &Val) const {
129 return LookupBucketFor(Val, TheBucket);
132 iterator find(const KeyT &Val) {
134 if (LookupBucketFor(Val, TheBucket))
135 return iterator(TheBucket, Buckets+NumBuckets);
138 const_iterator find(const KeyT &Val) const {
140 if (LookupBucketFor(Val, TheBucket))
141 return const_iterator(TheBucket, Buckets+NumBuckets);
145 /// lookup - Return the entry for the specified key, or a default
146 /// constructed value if no such entry exists.
147 ValueT lookup(const KeyT &Val) const {
149 if (LookupBucketFor(Val, TheBucket))
150 return TheBucket->second;
154 // Inserts key,value pair into the map if the key isn't already in the map.
155 // If the key is already in the map, it returns false and doesn't update the
157 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
159 if (LookupBucketFor(KV.first, TheBucket))
160 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
161 false); // Already in map.
163 // Otherwise, insert the new element.
164 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
165 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
169 /// insert - Range insertion of pairs.
170 template<typename InputIt>
171 void insert(InputIt I, InputIt E) {
177 bool erase(const KeyT &Val) {
179 if (!LookupBucketFor(Val, TheBucket))
180 return false; // not in map.
182 TheBucket->second.~ValueT();
183 TheBucket->first = getTombstoneKey();
188 void erase(iterator I) {
189 BucketT *TheBucket = &*I;
190 TheBucket->second.~ValueT();
191 TheBucket->first = getTombstoneKey();
196 void swap(DenseMap& RHS) {
197 std::swap(NumBuckets, RHS.NumBuckets);
198 std::swap(Buckets, RHS.Buckets);
199 std::swap(NumEntries, RHS.NumEntries);
200 std::swap(NumTombstones, RHS.NumTombstones);
203 value_type& FindAndConstruct(const KeyT &Key) {
205 if (LookupBucketFor(Key, TheBucket))
208 return *InsertIntoBucket(Key, ValueT(), TheBucket);
211 ValueT &operator[](const KeyT &Key) {
212 return FindAndConstruct(Key).second;
215 DenseMap& operator=(const DenseMap& other) {
220 /// isPointerIntoBucketsArray - Return true if the specified pointer points
221 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
222 /// value in the DenseMap).
223 bool isPointerIntoBucketsArray(const void *Ptr) const {
224 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
227 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
228 /// array. In conjunction with the previous method, this can be used to
229 /// determine whether an insertion caused the DenseMap to reallocate.
230 const void *getPointerIntoBucketsArray() const { return Buckets; }
233 void CopyFrom(const DenseMap& other) {
234 if (NumBuckets != 0 &&
235 (!isPodLike<KeyInfoT>::value || !isPodLike<ValueInfoT>::value)) {
236 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
237 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
238 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
239 !KeyInfoT::isEqual(P->first, TombstoneKey))
245 NumEntries = other.NumEntries;
246 NumTombstones = other.NumTombstones;
250 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
252 operator delete(Buckets);
254 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
257 if (isPodLike<KeyInfoT>::value && isPodLike<ValueInfoT>::value)
258 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
260 for (size_t i = 0; i < other.NumBuckets; ++i) {
261 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
262 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
263 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
264 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
266 NumBuckets = other.NumBuckets;
269 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
270 BucketT *TheBucket) {
271 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
272 // the buckets are empty (meaning that many are filled with tombstones),
275 // The later case is tricky. For example, if we had one empty bucket with
276 // tons of tombstones, failing lookups (e.g. for insertion) would have to
277 // probe almost the entire table until it found the empty bucket. If the
278 // table completely filled with tombstones, no lookup would ever succeed,
279 // causing infinite loops in lookup.
281 if (NumEntries*4 >= NumBuckets*3 ||
282 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
283 this->grow(NumBuckets * 2);
284 LookupBucketFor(Key, TheBucket);
287 // If we are writing over a tombstone, remember this.
288 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
291 TheBucket->first = Key;
292 new (&TheBucket->second) ValueT(Value);
296 static unsigned getHashValue(const KeyT &Val) {
297 return KeyInfoT::getHashValue(Val);
299 static const KeyT getEmptyKey() {
300 return KeyInfoT::getEmptyKey();
302 static const KeyT getTombstoneKey() {
303 return KeyInfoT::getTombstoneKey();
306 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
307 /// FoundBucket. If the bucket contains the key and a value, this returns
308 /// true, otherwise it returns a bucket with an empty marker or tombstone and
310 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
311 unsigned BucketNo = getHashValue(Val);
312 unsigned ProbeAmt = 1;
313 BucketT *BucketsPtr = Buckets;
315 // FoundTombstone - Keep track of whether we find a tombstone while probing.
316 BucketT *FoundTombstone = 0;
317 const KeyT EmptyKey = getEmptyKey();
318 const KeyT TombstoneKey = getTombstoneKey();
319 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
320 !KeyInfoT::isEqual(Val, TombstoneKey) &&
321 "Empty/Tombstone value shouldn't be inserted into map!");
324 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
325 // Found Val's bucket? If so, return it.
326 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
327 FoundBucket = ThisBucket;
331 // If we found an empty bucket, the key doesn't exist in the set.
332 // Insert it and return the default value.
333 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
334 // If we've already seen a tombstone while probing, fill it in instead
335 // of the empty bucket we eventually probed to.
336 if (FoundTombstone) ThisBucket = FoundTombstone;
337 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
341 // If this is a tombstone, remember it. If Val ends up not in the map, we
342 // prefer to return it than something that would require more probing.
343 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
344 FoundTombstone = ThisBucket; // Remember the first tombstone found.
346 // Otherwise, it's a hash collision or a tombstone, continue quadratic
348 BucketNo += ProbeAmt++;
352 void init(unsigned InitBuckets) {
355 NumBuckets = InitBuckets;
356 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
357 "# initial buckets must be a power of two!");
358 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
359 // Initialize all the keys to EmptyKey.
360 const KeyT EmptyKey = getEmptyKey();
361 for (unsigned i = 0; i != InitBuckets; ++i)
362 new (&Buckets[i].first) KeyT(EmptyKey);
365 void grow(unsigned AtLeast) {
366 unsigned OldNumBuckets = NumBuckets;
367 BucketT *OldBuckets = Buckets;
369 // Double the number of buckets.
370 while (NumBuckets < AtLeast)
373 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
375 // Initialize all the keys to EmptyKey.
376 const KeyT EmptyKey = getEmptyKey();
377 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
378 new (&Buckets[i].first) KeyT(EmptyKey);
380 // Insert all the old elements.
381 const KeyT TombstoneKey = getTombstoneKey();
382 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
383 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
384 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
385 // Insert the key/value into the new table.
387 bool FoundVal = LookupBucketFor(B->first, DestBucket);
388 FoundVal = FoundVal; // silence warning.
389 assert(!FoundVal && "Key already in new map?");
390 DestBucket->first = B->first;
391 new (&DestBucket->second) ValueT(B->second);
400 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
402 // Free the old table.
403 operator delete(OldBuckets);
406 void shrink_and_clear() {
407 unsigned OldNumBuckets = NumBuckets;
408 BucketT *OldBuckets = Buckets;
410 // Reduce the number of buckets.
411 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
414 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
416 // Initialize all the keys to EmptyKey.
417 const KeyT EmptyKey = getEmptyKey();
418 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
419 new (&Buckets[i].first) KeyT(EmptyKey);
421 // Free the old buckets.
422 const KeyT TombstoneKey = getTombstoneKey();
423 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
424 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
425 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
433 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
435 // Free the old table.
436 operator delete(OldBuckets);
442 template<typename KeyT, typename ValueT,
443 typename KeyInfoT, typename ValueInfoT, bool IsConst>
444 class DenseMapIterator {
445 typedef std::pair<KeyT, ValueT> Bucket;
446 typedef DenseMapIterator<KeyT, ValueT,
447 KeyInfoT, ValueInfoT, true> ConstIterator;
448 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, ValueInfoT, true>;
450 typedef ptrdiff_t difference_type;
451 typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
452 typedef value_type *pointer;
453 typedef value_type &reference;
454 typedef std::forward_iterator_tag iterator_category;
458 DenseMapIterator() : Ptr(0), End(0) {}
460 DenseMapIterator(pointer Pos, pointer E) : Ptr(Pos), End(E) {
461 AdvancePastEmptyBuckets();
464 // If IsConst is true this is a converting constructor from iterator to
465 // const_iterator and the default copy constructor is used.
466 // Otherwise this is a copy constructor for iterator.
467 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
468 KeyInfoT, ValueInfoT, false>& I)
469 : Ptr(I.Ptr), End(I.End) {}
471 reference operator*() const {
474 pointer operator->() const {
478 bool operator==(const ConstIterator &RHS) const {
479 return Ptr == RHS.operator->();
481 bool operator!=(const ConstIterator &RHS) const {
482 return Ptr != RHS.operator->();
485 inline DenseMapIterator& operator++() { // Preincrement
487 AdvancePastEmptyBuckets();
490 DenseMapIterator operator++(int) { // Postincrement
491 DenseMapIterator tmp = *this; ++*this; return tmp;
495 void AdvancePastEmptyBuckets() {
496 const KeyT Empty = KeyInfoT::getEmptyKey();
497 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
500 (KeyInfoT::isEqual(Ptr->first, Empty) ||
501 KeyInfoT::isEqual(Ptr->first, Tombstone)))
506 } // end namespace llvm