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 InitSize, unsigned ItemSize);
61 /// ShouldRehash - Return true if the table should be rehashed after a new
62 /// element was recently inserted.
63 bool ShouldRehash() const {
64 // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
65 // the buckets are empty (meaning that many are filled with tombstones),
67 return NumItems*4 > NumBuckets*3 ||
68 NumBuckets-(NumItems+NumTombstones) < NumBuckets/8;
71 /// LookupBucketFor - Look up the bucket that the specified string should end
72 /// up in. If it already exists as a key in the map, the Item pointer for the
73 /// specified bucket will be non-null. Otherwise, it will be null. In either
74 /// case, the FullHashValue field of the bucket will be set to the hash value
76 unsigned LookupBucketFor(const char *KeyStart, const char *KeyEnd);
78 /// FindKey - Look up the bucket that contains the specified key. If it exists
79 /// in the map, return the bucket number of the key. Otherwise return -1.
80 /// This does not modify the map.
81 int FindKey(const char *KeyStart, const char *KeyEnd) const;
83 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
84 /// delete it. This aborts if the value isn't in the table.
85 void RemoveKey(StringMapEntryBase *V);
87 /// RemoveKey - Remove the StringMapEntry for the specified key from the
88 /// table, returning it. If the key is not in the table, this returns null.
89 StringMapEntryBase *RemoveKey(const char *KeyStart, const char *KeyEnd);
92 static StringMapEntryBase *getTombstoneVal() {
93 return (StringMapEntryBase*)-1;
96 unsigned getNumBuckets() const { return NumBuckets; }
97 unsigned getNumItems() const { return NumItems; }
99 bool empty() const { return NumItems == 0; }
100 unsigned size() const { return NumItems; }
103 /// StringMapEntry - This is used to represent one value that is inserted into
104 /// a StringMap. It contains the Value itself and the key: the string length
106 template<typename ValueTy>
107 class StringMapEntry : public StringMapEntryBase {
110 StringMapEntry(unsigned StrLen)
111 : StringMapEntryBase(StrLen), Val() {}
112 StringMapEntry(unsigned StrLen, const ValueTy &V)
113 : StringMapEntryBase(StrLen), Val(V) {}
115 const ValueTy &getValue() const { return Val; }
116 ValueTy &getValue() { return Val; }
118 void setValue(const ValueTy &V) { Val = V; }
120 /// getKeyData - Return the start of the string data that is the key for this
121 /// value. The string data is always stored immediately after the
122 /// StringMapEntry object.
123 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
125 /// Create - Create a StringMapEntry for the specified key and default
126 /// construct the value.
127 template<typename AllocatorTy>
128 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
129 AllocatorTy &Allocator) {
130 unsigned KeyLength = KeyEnd-KeyStart;
132 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
133 // in. Allocate a new item with space for the string at the end and a null
135 unsigned AllocSize = sizeof(StringMapEntry)+KeyLength+1;
138 unsigned Alignment = __alignof__(StringMapEntry);
141 unsigned Alignment = 8;
143 StringMapEntry *NewItem =
144 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize, Alignment));
146 // Default construct the value.
147 new (NewItem) StringMapEntry(KeyLength);
149 // Copy the string information.
150 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
151 memcpy(StrBuffer, KeyStart, KeyLength);
152 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
156 /// Create - Create a StringMapEntry with normal malloc/free.
157 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
159 return Create(KeyStart, KeyEnd, A);
162 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
163 /// specified allocator.
164 template<typename AllocatorTy>
165 void Destroy(AllocatorTy &Allocator) {
166 // Free memory referenced by the item.
167 this->~StringMapEntry();
168 Allocator.Deallocate(this);
171 /// Destroy this object, releasing memory back to the malloc allocator.
179 /// StringMap - This is an unconventional map that is specialized for handling
180 /// keys that are "strings", which are basically ranges of bytes. This does some
181 /// funky memory allocation and hashing things to make it extremely efficient,
182 /// storing the string data *after* the value in the map.
183 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
184 class StringMap : public StringMapImpl {
185 AllocatorTy Allocator;
186 typedef StringMapEntry<ValueTy> MapEntryTy;
188 StringMap(unsigned InitialSize = 0)
189 : StringMapImpl(InitialSize, sizeof(MapEntryTy)) {}
191 AllocatorTy &getAllocator() { return Allocator; }
192 const AllocatorTy &getAllocator() const { return Allocator; }
194 typedef StringMapConstIterator<ValueTy> const_iterator;
195 typedef StringMapIterator<ValueTy> iterator;
197 iterator begin() { return iterator(TheTable); }
198 iterator end() { return iterator(TheTable+NumBuckets); }
199 const_iterator begin() const { return const_iterator(TheTable); }
200 const_iterator end() const { return const_iterator(TheTable+NumBuckets); }
203 iterator find(const char *KeyStart, const char *KeyEnd) {
204 int Bucket = FindKey(KeyStart, KeyEnd);
205 if (Bucket == -1) return end();
206 return iterator(TheTable+Bucket);
209 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
210 int Bucket = FindKey(KeyStart, KeyEnd);
211 if (Bucket == -1) return end();
212 return const_iterator(TheTable+Bucket);
215 /// insert - Insert the specified key/value pair into the map. If the key
216 /// already exists in the map, return false and ignore the request, otherwise
217 /// insert it and return true.
218 bool insert(MapEntryTy *KeyValue) {
220 LookupBucketFor(KeyValue->getKeyData(),
221 KeyValue->getKeyData()+KeyValue->getKeyLength());
222 ItemBucket &Bucket = TheTable[BucketNo];
223 if (Bucket.Item && Bucket.Item != getTombstoneVal())
224 return false; // Already exists in map.
226 if (Bucket.Item == getTombstoneVal())
228 Bucket.Item = KeyValue;
236 /// GetOrCreateValue - Look up the specified key in the table. If a value
237 /// exists, return it. Otherwise, default construct a value, insert it, and
239 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
240 const char *KeyEnd) {
241 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
242 ItemBucket &Bucket = TheTable[BucketNo];
243 if (Bucket.Item && Bucket.Item != getTombstoneVal())
244 return *static_cast<MapEntryTy*>(Bucket.Item);
246 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator);
248 if (Bucket.Item == getTombstoneVal())
252 // Fill in the bucket for the hash table. The FullHashValue was already
253 // filled in by LookupBucketFor.
254 Bucket.Item = NewItem;
261 /// remove - Remove the specified key/value pair from the map, but do not
262 /// erase it. This aborts if the key is not in the map.
263 void remove(MapEntryTy *KeyValue) {
268 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
269 if (I->Item && I->Item != getTombstoneVal())
270 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
277 template<typename ValueTy>
278 class StringMapConstIterator {
280 StringMapImpl::ItemBucket *Ptr;
282 StringMapConstIterator(StringMapImpl::ItemBucket *Bucket) : Ptr(Bucket) {
283 AdvancePastEmptyBuckets();
286 const StringMapEntry<ValueTy> &operator*() const {
287 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
289 const StringMapEntry<ValueTy> *operator->() const {
290 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
293 bool operator==(const StringMapConstIterator &RHS) const {
294 return Ptr == RHS.Ptr;
296 bool operator!=(const StringMapConstIterator &RHS) const {
297 return Ptr != RHS.Ptr;
300 inline StringMapConstIterator& operator++() { // Preincrement
302 AdvancePastEmptyBuckets();
305 StringMapConstIterator operator++(int) { // Postincrement
306 StringMapConstIterator tmp = *this; ++*this; return tmp;
310 void AdvancePastEmptyBuckets() {
311 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
316 template<typename ValueTy>
317 class StringMapIterator : public StringMapConstIterator<ValueTy> {
319 StringMapIterator(StringMapImpl::ItemBucket *Bucket)
320 : StringMapConstIterator<ValueTy>(Bucket) {
322 StringMapEntry<ValueTy> &operator*() const {
323 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
325 StringMapEntry<ValueTy> *operator->() const {
326 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);