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) {
59 // Initialize the map with zero buckets to allocation.
65 StringMapImpl(unsigned InitSize, unsigned ItemSize);
68 /// ShouldRehash - Return true if the table should be rehashed after a new
69 /// element was recently inserted.
70 bool ShouldRehash() const {
71 // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
72 // the buckets are empty (meaning that many are filled with tombstones),
74 return NumItems*4 > NumBuckets*3 ||
75 NumBuckets-(NumItems+NumTombstones) < NumBuckets/8;
78 /// LookupBucketFor - Look up the bucket that the specified string should end
79 /// up in. If it already exists as a key in the map, the Item pointer for the
80 /// specified bucket will be non-null. Otherwise, it will be null. In either
81 /// case, the FullHashValue field of the bucket will be set to the hash value
83 unsigned LookupBucketFor(const char *KeyStart, const char *KeyEnd);
85 /// FindKey - Look up the bucket that contains the specified key. If it exists
86 /// in the map, return the bucket number of the key. Otherwise return -1.
87 /// This does not modify the map.
88 int FindKey(const char *KeyStart, const char *KeyEnd) const;
90 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
91 /// delete it. This aborts if the value isn't in the table.
92 void RemoveKey(StringMapEntryBase *V);
94 /// RemoveKey - Remove the StringMapEntry for the specified key from the
95 /// table, returning it. If the key is not in the table, this returns null.
96 StringMapEntryBase *RemoveKey(const char *KeyStart, const char *KeyEnd);
98 void init(unsigned Size);
100 static StringMapEntryBase *getTombstoneVal() {
101 return (StringMapEntryBase*)-1;
104 unsigned getNumBuckets() const { return NumBuckets; }
105 unsigned getNumItems() const { return NumItems; }
107 bool empty() const { return NumItems == 0; }
108 unsigned size() const { return NumItems; }
111 /// StringMapEntry - This is used to represent one value that is inserted into
112 /// a StringMap. It contains the Value itself and the key: the string length
114 template<typename ValueTy>
115 class StringMapEntry : public StringMapEntryBase {
118 StringMapEntry(unsigned StrLen)
119 : StringMapEntryBase(StrLen), Val() {}
120 StringMapEntry(unsigned StrLen, const ValueTy &V)
121 : StringMapEntryBase(StrLen), Val(V) {}
123 const ValueTy &getValue() const { return Val; }
124 ValueTy &getValue() { return Val; }
126 void setValue(const ValueTy &V) { Val = V; }
128 /// getKeyData - Return the start of the string data that is the key for this
129 /// value. The string data is always stored immediately after the
130 /// StringMapEntry object.
131 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
133 /// Create - Create a StringMapEntry for the specified key and default
134 /// construct the value.
135 template<typename AllocatorTy>
136 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
137 AllocatorTy &Allocator) {
138 unsigned KeyLength = KeyEnd-KeyStart;
140 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
141 // in. Allocate a new item with space for the string at the end and a null
143 unsigned AllocSize = sizeof(StringMapEntry)+KeyLength+1;
146 unsigned Alignment = __alignof__(StringMapEntry);
149 unsigned Alignment = 8;
151 StringMapEntry *NewItem =
152 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize, Alignment));
154 // Default construct the value.
155 new (NewItem) StringMapEntry(KeyLength);
157 // Copy the string information.
158 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
159 memcpy(StrBuffer, KeyStart, KeyLength);
160 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
164 /// Create - Create a StringMapEntry with normal malloc/free.
165 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
167 return Create(KeyStart, KeyEnd, A);
170 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
171 /// specified allocator.
172 template<typename AllocatorTy>
173 void Destroy(AllocatorTy &Allocator) {
174 // Free memory referenced by the item.
175 this->~StringMapEntry();
176 Allocator.Deallocate(this);
179 /// Destroy this object, releasing memory back to the malloc allocator.
187 /// StringMap - This is an unconventional map that is specialized for handling
188 /// keys that are "strings", which are basically ranges of bytes. This does some
189 /// funky memory allocation and hashing things to make it extremely efficient,
190 /// storing the string data *after* the value in the map.
191 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
192 class StringMap : public StringMapImpl {
193 AllocatorTy Allocator;
194 typedef StringMapEntry<ValueTy> MapEntryTy;
196 StringMap() : StringMapImpl(sizeof(MapEntryTy)) {}
197 StringMap(unsigned InitialSize)
198 : StringMapImpl(InitialSize, sizeof(MapEntryTy)) {}
200 AllocatorTy &getAllocator() { return Allocator; }
201 const AllocatorTy &getAllocator() const { return Allocator; }
203 typedef StringMapConstIterator<ValueTy> const_iterator;
204 typedef StringMapIterator<ValueTy> iterator;
207 return iterator(TheTable, NumBuckets == 0);
210 return iterator(TheTable+NumBuckets, true);
212 const_iterator begin() const {
213 return const_iterator(TheTable, NumBuckets == 0);
215 const_iterator end() const {
216 return const_iterator(TheTable+NumBuckets, true);
219 iterator find(const char *KeyStart, const char *KeyEnd) {
220 int Bucket = FindKey(KeyStart, KeyEnd);
221 if (Bucket == -1) return end();
222 return iterator(TheTable+Bucket);
225 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
226 int Bucket = FindKey(KeyStart, KeyEnd);
227 if (Bucket == -1) return end();
228 return const_iterator(TheTable+Bucket);
231 /// insert - Insert the specified key/value pair into the map. If the key
232 /// already exists in the map, return false and ignore the request, otherwise
233 /// insert it and return true.
234 bool insert(MapEntryTy *KeyValue) {
236 LookupBucketFor(KeyValue->getKeyData(),
237 KeyValue->getKeyData()+KeyValue->getKeyLength());
238 ItemBucket &Bucket = TheTable[BucketNo];
239 if (Bucket.Item && Bucket.Item != getTombstoneVal())
240 return false; // Already exists in map.
242 if (Bucket.Item == getTombstoneVal())
244 Bucket.Item = KeyValue;
252 /// GetOrCreateValue - Look up the specified key in the table. If a value
253 /// exists, return it. Otherwise, default construct a value, insert it, and
255 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
256 const char *KeyEnd) {
257 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
258 ItemBucket &Bucket = TheTable[BucketNo];
259 if (Bucket.Item && Bucket.Item != getTombstoneVal())
260 return *static_cast<MapEntryTy*>(Bucket.Item);
262 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator);
264 if (Bucket.Item == getTombstoneVal())
268 // Fill in the bucket for the hash table. The FullHashValue was already
269 // filled in by LookupBucketFor.
270 Bucket.Item = NewItem;
277 /// remove - Remove the specified key/value pair from the map, but do not
278 /// erase it. This aborts if the key is not in the map.
279 void remove(MapEntryTy *KeyValue) {
283 void erase(iterator I) {
286 V.Destroy(Allocator);
290 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
291 if (I->Item && I->Item != getTombstoneVal())
292 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
297 StringMap(const StringMap &); // FIXME: Implement.
298 void operator=(const StringMap &); // FIXME: Implement.
302 template<typename ValueTy>
303 class StringMapConstIterator {
305 StringMapImpl::ItemBucket *Ptr;
307 StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
308 bool NoAdvance = false)
310 if (!NoAdvance) AdvancePastEmptyBuckets();
313 const StringMapEntry<ValueTy> &operator*() const {
314 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
316 const StringMapEntry<ValueTy> *operator->() const {
317 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
320 bool operator==(const StringMapConstIterator &RHS) const {
321 return Ptr == RHS.Ptr;
323 bool operator!=(const StringMapConstIterator &RHS) const {
324 return Ptr != RHS.Ptr;
327 inline StringMapConstIterator& operator++() { // Preincrement
329 AdvancePastEmptyBuckets();
332 StringMapConstIterator operator++(int) { // Postincrement
333 StringMapConstIterator tmp = *this; ++*this; return tmp;
337 void AdvancePastEmptyBuckets() {
338 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
343 template<typename ValueTy>
344 class StringMapIterator : public StringMapConstIterator<ValueTy> {
346 StringMapIterator(StringMapImpl::ItemBucket *Bucket,
347 bool NoAdvance = false)
348 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
350 StringMapEntry<ValueTy> &operator*() const {
351 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
353 StringMapEntry<ValueTy> *operator->() const {
354 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);