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 explicit 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 explicit 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 explicit 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
144 unsigned AllocSize = sizeof(StringMapEntry)+KeyLength+1;
145 unsigned Alignment = alignof<StringMapEntry>();
147 StringMapEntry *NewItem =
148 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
150 // Default construct the value.
151 new (NewItem) StringMapEntry(KeyLength);
153 // Copy the string information.
154 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
155 memcpy(StrBuffer, KeyStart, KeyLength);
156 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
160 /// Create - Create a StringMapEntry with normal malloc/free.
161 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
163 return Create(KeyStart, KeyEnd, A);
167 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
168 /// into a StringMapEntry, return the StringMapEntry itself.
169 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
170 StringMapEntry *EPtr = 0;
171 char *Ptr = reinterpret_cast<char*>(&V) -
172 (reinterpret_cast<char*>(&EPtr->Val) -
173 reinterpret_cast<char*>(EPtr));
174 return *reinterpret_cast<StringMapEntry*>(Ptr);
176 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
177 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
180 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
181 /// specified allocator.
182 template<typename AllocatorTy>
183 void Destroy(AllocatorTy &Allocator) {
184 // Free memory referenced by the item.
185 this->~StringMapEntry();
186 Allocator.Deallocate(this);
189 /// Destroy this object, releasing memory back to the malloc allocator.
197 /// StringMap - This is an unconventional map that is specialized for handling
198 /// keys that are "strings", which are basically ranges of bytes. This does some
199 /// funky memory allocation and hashing things to make it extremely efficient,
200 /// storing the string data *after* the value in the map.
201 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
202 class StringMap : public StringMapImpl {
203 AllocatorTy Allocator;
204 typedef StringMapEntry<ValueTy> MapEntryTy;
206 StringMap() : StringMapImpl(sizeof(MapEntryTy)) {}
207 explicit StringMap(unsigned InitialSize)
208 : StringMapImpl(InitialSize, sizeof(MapEntryTy)) {}
210 AllocatorTy &getAllocator() { return Allocator; }
211 const AllocatorTy &getAllocator() const { return Allocator; }
213 typedef StringMapConstIterator<ValueTy> const_iterator;
214 typedef StringMapIterator<ValueTy> iterator;
217 return iterator(TheTable, NumBuckets == 0);
220 return iterator(TheTable+NumBuckets, true);
222 const_iterator begin() const {
223 return const_iterator(TheTable, NumBuckets == 0);
225 const_iterator end() const {
226 return const_iterator(TheTable+NumBuckets, true);
229 iterator find(const char *KeyStart, const char *KeyEnd) {
230 int Bucket = FindKey(KeyStart, KeyEnd);
231 if (Bucket == -1) return end();
232 return iterator(TheTable+Bucket);
235 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
236 int Bucket = FindKey(KeyStart, KeyEnd);
237 if (Bucket == -1) return end();
238 return const_iterator(TheTable+Bucket);
241 /// insert - Insert the specified key/value pair into the map. If the key
242 /// already exists in the map, return false and ignore the request, otherwise
243 /// insert it and return true.
244 bool insert(MapEntryTy *KeyValue) {
246 LookupBucketFor(KeyValue->getKeyData(),
247 KeyValue->getKeyData()+KeyValue->getKeyLength());
248 ItemBucket &Bucket = TheTable[BucketNo];
249 if (Bucket.Item && Bucket.Item != getTombstoneVal())
250 return false; // Already exists in map.
252 if (Bucket.Item == getTombstoneVal())
254 Bucket.Item = KeyValue;
262 /// GetOrCreateValue - Look up the specified key in the table. If a value
263 /// exists, return it. Otherwise, default construct a value, insert it, and
265 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
266 const char *KeyEnd) {
267 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
268 ItemBucket &Bucket = TheTable[BucketNo];
269 if (Bucket.Item && Bucket.Item != getTombstoneVal())
270 return *static_cast<MapEntryTy*>(Bucket.Item);
272 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator);
274 if (Bucket.Item == getTombstoneVal())
278 // Fill in the bucket for the hash table. The FullHashValue was already
279 // filled in by LookupBucketFor.
280 Bucket.Item = NewItem;
287 /// remove - Remove the specified key/value pair from the map, but do not
288 /// erase it. This aborts if the key is not in the map.
289 void remove(MapEntryTy *KeyValue) {
293 void erase(iterator I) {
296 V.Destroy(Allocator);
300 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
301 if (I->Item && I->Item != getTombstoneVal())
302 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
307 StringMap(const StringMap &); // FIXME: Implement.
308 void operator=(const StringMap &); // FIXME: Implement.
312 template<typename ValueTy>
313 class StringMapConstIterator {
315 StringMapImpl::ItemBucket *Ptr;
317 explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
318 bool NoAdvance = false)
320 if (!NoAdvance) AdvancePastEmptyBuckets();
323 const StringMapEntry<ValueTy> &operator*() const {
324 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
326 const StringMapEntry<ValueTy> *operator->() const {
327 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
330 bool operator==(const StringMapConstIterator &RHS) const {
331 return Ptr == RHS.Ptr;
333 bool operator!=(const StringMapConstIterator &RHS) const {
334 return Ptr != RHS.Ptr;
337 inline StringMapConstIterator& operator++() { // Preincrement
339 AdvancePastEmptyBuckets();
342 StringMapConstIterator operator++(int) { // Postincrement
343 StringMapConstIterator tmp = *this; ++*this; return tmp;
347 void AdvancePastEmptyBuckets() {
348 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
353 template<typename ValueTy>
354 class StringMapIterator : public StringMapConstIterator<ValueTy> {
356 StringMapIterator(StringMapImpl::ItemBucket *Bucket,
357 bool NoAdvance = false)
358 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
360 StringMapEntry<ValueTy> &operator*() const {
361 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
363 StringMapEntry<ValueTy> *operator->() const {
364 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);