1 //===--- StringMap.h - String Hash table map interface ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the StringMap class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_STRINGMAP_H
15 #define LLVM_ADT_STRINGMAP_H
17 #include "llvm/Support/Allocator.h"
21 template<typename ValueT>
22 class StringMapConstIterator;
23 template<typename ValueT>
24 class StringMapIterator;
27 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
28 class StringMapEntryBase {
31 StringMapEntryBase(unsigned Len) : StrLen(Len) {}
33 unsigned getKeyLength() const { return StrLen; }
36 /// StringMapImpl - This is the base class of StringMap that is shared among
37 /// all of its instantiations.
40 /// ItemBucket - The hash table consists of an array of these. If Item is
41 /// non-null, this is an extant entry, otherwise, it is a hole.
43 /// FullHashValue - This remembers the full hash value of the key for
45 unsigned FullHashValue;
47 /// Item - This is a pointer to the actual item object.
48 StringMapEntryBase *Item;
55 unsigned NumTombstones;
58 StringMapImpl(unsigned itemSize) : ItemSize(itemSize) { init(16); }
59 StringMapImpl(unsigned InitSize, unsigned ItemSize);
62 /// ShouldRehash - Return true if the table should be rehashed after a new
63 /// element was recently inserted.
64 bool ShouldRehash() const {
65 // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
66 // the buckets are empty (meaning that many are filled with tombstones),
68 return NumItems*4 > NumBuckets*3 ||
69 NumBuckets-(NumItems+NumTombstones) < NumBuckets/8;
72 /// LookupBucketFor - Look up the bucket that the specified string should end
73 /// up in. If it already exists as a key in the map, the Item pointer for the
74 /// specified bucket will be non-null. Otherwise, it will be null. In either
75 /// case, the FullHashValue field of the bucket will be set to the hash value
77 unsigned LookupBucketFor(const char *KeyStart, const char *KeyEnd);
79 /// FindKey - Look up the bucket that contains the specified key. If it exists
80 /// in the map, return the bucket number of the key. Otherwise return -1.
81 /// This does not modify the map.
82 int FindKey(const char *KeyStart, const char *KeyEnd) const;
84 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
85 /// delete it. This aborts if the value isn't in the table.
86 void RemoveKey(StringMapEntryBase *V);
88 /// RemoveKey - Remove the StringMapEntry for the specified key from the
89 /// table, returning it. If the key is not in the table, this returns null.
90 StringMapEntryBase *RemoveKey(const char *KeyStart, const char *KeyEnd);
92 void init(unsigned Size);
94 static StringMapEntryBase *getTombstoneVal() {
95 return (StringMapEntryBase*)-1;
98 unsigned getNumBuckets() const { return NumBuckets; }
99 unsigned getNumItems() const { return NumItems; }
101 bool empty() const { return NumItems == 0; }
102 unsigned size() const { return NumItems; }
105 /// StringMapEntry - This is used to represent one value that is inserted into
106 /// a StringMap. It contains the Value itself and the key: the string length
108 template<typename ValueTy>
109 class StringMapEntry : public StringMapEntryBase {
112 StringMapEntry(unsigned StrLen)
113 : StringMapEntryBase(StrLen), Val() {}
114 StringMapEntry(unsigned StrLen, const ValueTy &V)
115 : StringMapEntryBase(StrLen), Val(V) {}
117 const ValueTy &getValue() const { return Val; }
118 ValueTy &getValue() { return Val; }
120 void setValue(const ValueTy &V) { Val = V; }
122 /// getKeyData - Return the start of the string data that is the key for this
123 /// value. The string data is always stored immediately after the
124 /// StringMapEntry object.
125 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
127 /// Create - Create a StringMapEntry for the specified key and default
128 /// construct the value.
129 template<typename AllocatorTy>
130 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
131 AllocatorTy &Allocator) {
132 unsigned KeyLength = KeyEnd-KeyStart;
134 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
135 // in. Allocate a new item with space for the string at the end and a null
137 unsigned AllocSize = sizeof(StringMapEntry)+KeyLength+1;
140 unsigned Alignment = __alignof__(StringMapEntry);
143 unsigned Alignment = 8;
145 StringMapEntry *NewItem =
146 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize, Alignment));
148 // Default construct the value.
149 new (NewItem) StringMapEntry(KeyLength);
151 // Copy the string information.
152 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
153 memcpy(StrBuffer, KeyStart, KeyLength);
154 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
158 /// Create - Create a StringMapEntry with normal malloc/free.
159 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
161 return Create(KeyStart, KeyEnd, A);
164 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
165 /// specified allocator.
166 template<typename AllocatorTy>
167 void Destroy(AllocatorTy &Allocator) {
168 // Free memory referenced by the item.
169 this->~StringMapEntry();
170 Allocator.Deallocate(this);
173 /// Destroy this object, releasing memory back to the malloc allocator.
181 /// StringMap - This is an unconventional map that is specialized for handling
182 /// keys that are "strings", which are basically ranges of bytes. This does some
183 /// funky memory allocation and hashing things to make it extremely efficient,
184 /// storing the string data *after* the value in the map.
185 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
186 class StringMap : public StringMapImpl {
187 AllocatorTy Allocator;
188 typedef StringMapEntry<ValueTy> MapEntryTy;
190 StringMap() : StringMapImpl(sizeof(MapEntryTy)) {}
191 StringMap(unsigned InitialSize)
192 : StringMapImpl(InitialSize, sizeof(MapEntryTy)) {}
194 AllocatorTy &getAllocator() { return Allocator; }
195 const AllocatorTy &getAllocator() const { return Allocator; }
197 typedef StringMapConstIterator<ValueTy> const_iterator;
198 typedef StringMapIterator<ValueTy> iterator;
201 return iterator(TheTable, NumBuckets == 0);
204 return iterator(TheTable+NumBuckets, true);
206 const_iterator begin() const {
207 return const_iterator(TheTable, NumBuckets == 0);
209 const_iterator end() const {
210 return const_iterator(TheTable+NumBuckets, true);
213 iterator find(const char *KeyStart, const char *KeyEnd) {
214 int Bucket = FindKey(KeyStart, KeyEnd);
215 if (Bucket == -1) return end();
216 return iterator(TheTable+Bucket);
219 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
220 int Bucket = FindKey(KeyStart, KeyEnd);
221 if (Bucket == -1) return end();
222 return const_iterator(TheTable+Bucket);
225 /// insert - Insert the specified key/value pair into the map. If the key
226 /// already exists in the map, return false and ignore the request, otherwise
227 /// insert it and return true.
228 bool insert(MapEntryTy *KeyValue) {
230 LookupBucketFor(KeyValue->getKeyData(),
231 KeyValue->getKeyData()+KeyValue->getKeyLength());
232 ItemBucket &Bucket = TheTable[BucketNo];
233 if (Bucket.Item && Bucket.Item != getTombstoneVal())
234 return false; // Already exists in map.
236 if (Bucket.Item == getTombstoneVal())
238 Bucket.Item = KeyValue;
246 /// GetOrCreateValue - Look up the specified key in the table. If a value
247 /// exists, return it. Otherwise, default construct a value, insert it, and
249 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
250 const char *KeyEnd) {
251 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
252 ItemBucket &Bucket = TheTable[BucketNo];
253 if (Bucket.Item && Bucket.Item != getTombstoneVal())
254 return *static_cast<MapEntryTy*>(Bucket.Item);
256 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator);
258 if (Bucket.Item == getTombstoneVal())
262 // Fill in the bucket for the hash table. The FullHashValue was already
263 // filled in by LookupBucketFor.
264 Bucket.Item = NewItem;
271 /// remove - Remove the specified key/value pair from the map, but do not
272 /// erase it. This aborts if the key is not in the map.
273 void remove(MapEntryTy *KeyValue) {
278 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
279 if (I->Item && I->Item != getTombstoneVal())
280 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
287 template<typename ValueTy>
288 class StringMapConstIterator {
290 StringMapImpl::ItemBucket *Ptr;
292 StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
293 bool NoAdvance = false)
295 if (!NoAdvance) AdvancePastEmptyBuckets();
298 const StringMapEntry<ValueTy> &operator*() const {
299 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
301 const StringMapEntry<ValueTy> *operator->() const {
302 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
305 bool operator==(const StringMapConstIterator &RHS) const {
306 return Ptr == RHS.Ptr;
308 bool operator!=(const StringMapConstIterator &RHS) const {
309 return Ptr != RHS.Ptr;
312 inline StringMapConstIterator& operator++() { // Preincrement
314 AdvancePastEmptyBuckets();
317 StringMapConstIterator operator++(int) { // Postincrement
318 StringMapConstIterator tmp = *this; ++*this; return tmp;
322 void AdvancePastEmptyBuckets() {
323 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
328 template<typename ValueTy>
329 class StringMapIterator : public StringMapConstIterator<ValueTy> {
331 StringMapIterator(StringMapImpl::ItemBucket *Bucket,
332 bool NoAdvance = false)
333 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
335 StringMapEntry<ValueTy> &operator*() const {
336 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
338 StringMapEntry<ValueTy> *operator->() const {
339 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);