1 //===--- StringMap.h - String Hash table map interface ----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the StringMap class.
11 //
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_STRINGMAP_H
15 #define LLVM_ADT_STRINGMAP_H
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/Allocator.h"
19 #include <cstring>
21 namespace llvm {
22 template<typename ValueT>
23 class StringMapConstIterator;
24 template<typename ValueT>
25 class StringMapIterator;
26 template<typename ValueTy>
27 class StringMapEntry;
29 /// StringMapEntryInitializer - This datatype can be partially specialized for
30 /// various datatypes in a stringmap to allow them to be initialized when an
31 /// entry is default constructed for the map.
32 template<typename ValueTy>
33 class StringMapEntryInitializer {
34 public:
35 template <typename InitTy>
36 static void Initialize(StringMapEntry<ValueTy> &T, InitTy InitVal) {
37 T.second = InitVal;
38 }
39 };
42 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
43 class StringMapEntryBase {
44 unsigned StrLen;
45 public:
46 explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
48 unsigned getKeyLength() const { return StrLen; }
49 };
51 /// StringMapImpl - This is the base class of StringMap that is shared among
52 /// all of its instantiations.
53 class StringMapImpl {
54 protected:
55 // Array of NumBuckets pointers to entries, null pointers are holes.
56 // TheTable[NumBuckets] contains a sentinel value for easy iteration. Follwed
57 // by an array of the actual hash values as unsigned integers.
58 StringMapEntryBase **TheTable;
59 unsigned NumBuckets;
60 unsigned NumItems;
61 unsigned NumTombstones;
62 unsigned ItemSize;
63 protected:
64 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
65 // Initialize the map with zero buckets to allocation.
66 TheTable = 0;
67 NumBuckets = 0;
68 NumItems = 0;
69 NumTombstones = 0;
70 }
71 StringMapImpl(unsigned InitSize, unsigned ItemSize);
72 void RehashTable();
74 /// LookupBucketFor - Look up the bucket that the specified string should end
75 /// up in. If it already exists as a key in the map, the Item pointer for the
76 /// specified bucket will be non-null. Otherwise, it will be null. In either
77 /// case, the FullHashValue field of the bucket will be set to the hash value
78 /// of the string.
79 unsigned LookupBucketFor(StringRef Key);
81 /// FindKey - Look up the bucket that contains the specified key. If it exists
82 /// in the map, return the bucket number of the key. Otherwise return -1.
83 /// This does not modify the map.
84 int FindKey(StringRef Key) const;
86 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
87 /// delete it. This aborts if the value isn't in the table.
88 void RemoveKey(StringMapEntryBase *V);
90 /// RemoveKey - Remove the StringMapEntry for the specified key from the
91 /// table, returning it. If the key is not in the table, this returns null.
92 StringMapEntryBase *RemoveKey(StringRef Key);
93 private:
94 void init(unsigned Size);
95 public:
96 static StringMapEntryBase *getTombstoneVal() {
97 return (StringMapEntryBase*)-1;
98 }
100 unsigned getNumBuckets() const { return NumBuckets; }
101 unsigned getNumItems() const { return NumItems; }
103 bool empty() const { return NumItems == 0; }
104 unsigned size() const { return NumItems; }
105 };
107 /// StringMapEntry - This is used to represent one value that is inserted into
108 /// a StringMap. It contains the Value itself and the key: the string length
109 /// and data.
110 template<typename ValueTy>
111 class StringMapEntry : public StringMapEntryBase {
112 public:
113 ValueTy second;
115 explicit StringMapEntry(unsigned strLen)
116 : StringMapEntryBase(strLen), second() {}
117 StringMapEntry(unsigned strLen, const ValueTy &V)
118 : StringMapEntryBase(strLen), second(V) {}
120 StringRef getKey() const {
121 return StringRef(getKeyData(), getKeyLength());
122 }
124 const ValueTy &getValue() const { return second; }
125 ValueTy &getValue() { return second; }
127 void setValue(const ValueTy &V) { second = V; }
129 /// getKeyData - Return the start of the string data that is the key for this
130 /// value. The string data is always stored immediately after the
131 /// StringMapEntry object.
132 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
134 StringRef first() const { return StringRef(getKeyData(), getKeyLength()); }
136 /// Create - Create a StringMapEntry for the specified key and default
137 /// construct the value.
138 template<typename AllocatorTy, typename InitType>
139 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
140 AllocatorTy &Allocator,
141 InitType InitVal) {
142 unsigned KeyLength = static_cast<unsigned>(KeyEnd-KeyStart);
144 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
145 // in. Allocate a new item with space for the string at the end and a null
146 // terminator.
148 unsigned AllocSize = static_cast<unsigned>(sizeof(StringMapEntry))+
149 KeyLength+1;
150 unsigned Alignment = alignOf<StringMapEntry>();
152 StringMapEntry *NewItem =
153 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
155 // Default construct the value.
156 new (NewItem) StringMapEntry(KeyLength);
158 // Copy the string information.
159 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
160 memcpy(StrBuffer, KeyStart, KeyLength);
161 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
163 // Initialize the value if the client wants to.
164 StringMapEntryInitializer<ValueTy>::Initialize(*NewItem, InitVal);
165 return NewItem;
166 }
168 template<typename AllocatorTy>
169 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
170 AllocatorTy &Allocator) {
171 return Create(KeyStart, KeyEnd, Allocator, 0);
172 }
175 /// Create - Create a StringMapEntry with normal malloc/free.
176 template<typename InitType>
177 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
178 InitType InitVal) {
179 MallocAllocator A;
180 return Create(KeyStart, KeyEnd, A, InitVal);
181 }
183 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
184 return Create(KeyStart, KeyEnd, ValueTy());
185 }
187 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
188 /// into a StringMapEntry, return the StringMapEntry itself.
189 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
190 StringMapEntry *EPtr = 0;
191 char *Ptr = reinterpret_cast<char*>(&V) -
192 (reinterpret_cast<char*>(&EPtr->second) -
193 reinterpret_cast<char*>(EPtr));
194 return *reinterpret_cast<StringMapEntry*>(Ptr);
195 }
196 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
197 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
198 }
200 /// GetStringMapEntryFromKeyData - Given key data that is known to be embedded
201 /// into a StringMapEntry, return the StringMapEntry itself.
202 static StringMapEntry &GetStringMapEntryFromKeyData(const char *KeyData) {
203 char *Ptr = const_cast<char*>(KeyData) - sizeof(StringMapEntry<ValueTy>);
204 return *reinterpret_cast<StringMapEntry*>(Ptr);
205 }
208 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
209 /// specified allocator.
210 template<typename AllocatorTy>
211 void Destroy(AllocatorTy &Allocator) {
212 // Free memory referenced by the item.
213 this->~StringMapEntry();
214 Allocator.Deallocate(this);
215 }
217 /// Destroy this object, releasing memory back to the malloc allocator.
218 void Destroy() {
219 MallocAllocator A;
220 Destroy(A);
221 }
222 };
225 /// StringMap - This is an unconventional map that is specialized for handling
226 /// keys that are "strings", which are basically ranges of bytes. This does some
227 /// funky memory allocation and hashing things to make it extremely efficient,
228 /// storing the string data *after* the value in the map.
229 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
230 class StringMap : public StringMapImpl {
231 AllocatorTy Allocator;
232 typedef StringMapEntry<ValueTy> MapEntryTy;
233 public:
234 StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
235 explicit StringMap(unsigned InitialSize)
236 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
238 explicit StringMap(AllocatorTy A)
239 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))), Allocator(A) {}
241 explicit StringMap(const StringMap &RHS)
242 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
243 assert(RHS.empty() &&
244 "Copy ctor from non-empty stringmap not implemented yet!");
245 (void)RHS;
246 }
247 void operator=(const StringMap &RHS) {
248 assert(RHS.empty() &&
249 "assignment from non-empty stringmap not implemented yet!");
250 (void)RHS;
251 clear();
252 }
254 typedef typename ReferenceAdder<AllocatorTy>::result AllocatorRefTy;
255 typedef typename ReferenceAdder<const AllocatorTy>::result AllocatorCRefTy;
256 AllocatorRefTy getAllocator() { return Allocator; }
257 AllocatorCRefTy getAllocator() const { return Allocator; }
259 typedef const char* key_type;
260 typedef ValueTy mapped_type;
261 typedef StringMapEntry<ValueTy> value_type;
262 typedef size_t size_type;
264 typedef StringMapConstIterator<ValueTy> const_iterator;
265 typedef StringMapIterator<ValueTy> iterator;
267 iterator begin() {
268 return iterator(TheTable, NumBuckets == 0);
269 }
270 iterator end() {
271 return iterator(TheTable+NumBuckets, true);
272 }
273 const_iterator begin() const {
274 return const_iterator(TheTable, NumBuckets == 0);
275 }
276 const_iterator end() const {
277 return const_iterator(TheTable+NumBuckets, true);
278 }
280 iterator find(StringRef Key) {
281 int Bucket = FindKey(Key);
282 if (Bucket == -1) return end();
283 return iterator(TheTable+Bucket);
284 }
286 const_iterator find(StringRef Key) const {
287 int Bucket = FindKey(Key);
288 if (Bucket == -1) return end();
289 return const_iterator(TheTable+Bucket);
290 }
292 /// lookup - Return the entry for the specified key, or a default
293 /// constructed value if no such entry exists.
294 ValueTy lookup(StringRef Key) const {
295 const_iterator it = find(Key);
296 if (it != end())
297 return it->second;
298 return ValueTy();
299 }
301 ValueTy &operator[](StringRef Key) {
302 return GetOrCreateValue(Key).getValue();
303 }
305 size_type count(StringRef Key) const {
306 return find(Key) == end() ? 0 : 1;
307 }
309 /// insert - Insert the specified key/value pair into the map. If the key
310 /// already exists in the map, return false and ignore the request, otherwise
311 /// insert it and return true.
312 bool insert(MapEntryTy *KeyValue) {
313 unsigned BucketNo = LookupBucketFor(KeyValue->getKey());
314 StringMapEntryBase *&Bucket = TheTable[BucketNo];
315 if (Bucket && Bucket != getTombstoneVal())
316 return false; // Already exists in map.
318 if (Bucket == getTombstoneVal())
319 --NumTombstones;
320 Bucket = KeyValue;
321 ++NumItems;
322 assert(NumItems + NumTombstones <= NumBuckets);
324 RehashTable();
325 return true;
326 }
328 // clear - Empties out the StringMap
329 void clear() {
330 if (empty()) return;
332 // Zap all values, resetting the keys back to non-present (not tombstone),
333 // which is safe because we're removing all elements.
334 for (unsigned I = 0, E = NumBuckets; I != E; ++I) {
335 StringMapEntryBase *&Bucket = TheTable[I];
336 if (Bucket && Bucket != getTombstoneVal()) {
337 static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
338 Bucket = 0;
339 }
340 }
342 NumItems = 0;
343 NumTombstones = 0;
344 }
346 /// GetOrCreateValue - Look up the specified key in the table. If a value
347 /// exists, return it. Otherwise, default construct a value, insert it, and
348 /// return.
349 template <typename InitTy>
350 MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
351 unsigned BucketNo = LookupBucketFor(Key);
352 StringMapEntryBase *&Bucket = TheTable[BucketNo];
353 if (Bucket && Bucket != getTombstoneVal())
354 return *static_cast<MapEntryTy*>(Bucket);
356 MapEntryTy *NewItem =
357 MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
359 if (Bucket == getTombstoneVal())
360 --NumTombstones;
361 ++NumItems;
362 assert(NumItems + NumTombstones <= NumBuckets);
364 // Fill in the bucket for the hash table. The FullHashValue was already
365 // filled in by LookupBucketFor.
366 Bucket = NewItem;
368 RehashTable();
369 return *NewItem;
370 }
372 MapEntryTy &GetOrCreateValue(StringRef Key) {
373 return GetOrCreateValue(Key, ValueTy());
374 }
376 /// remove - Remove the specified key/value pair from the map, but do not
377 /// erase it. This aborts if the key is not in the map.
378 void remove(MapEntryTy *KeyValue) {
379 RemoveKey(KeyValue);
380 }
382 void erase(iterator I) {
383 MapEntryTy &V = *I;
384 remove(&V);
385 V.Destroy(Allocator);
386 }
388 bool erase(StringRef Key) {
389 iterator I = find(Key);
390 if (I == end()) return false;
391 erase(I);
392 return true;
393 }
395 ~StringMap() {
396 clear();
397 free(TheTable);
398 }
399 };
402 template<typename ValueTy>
403 class StringMapConstIterator {
404 protected:
405 StringMapEntryBase **Ptr;
406 public:
407 typedef StringMapEntry<ValueTy> value_type;
409 explicit StringMapConstIterator(StringMapEntryBase **Bucket,
410 bool NoAdvance = false)
411 : Ptr(Bucket) {
412 if (!NoAdvance) AdvancePastEmptyBuckets();
413 }
415 const value_type &operator*() const {
416 return *static_cast<StringMapEntry<ValueTy>*>(*Ptr);
417 }
418 const value_type *operator->() const {
419 return static_cast<StringMapEntry<ValueTy>*>(*Ptr);
420 }
422 bool operator==(const StringMapConstIterator &RHS) const {
423 return Ptr == RHS.Ptr;
424 }
425 bool operator!=(const StringMapConstIterator &RHS) const {
426 return Ptr != RHS.Ptr;
427 }
429 inline StringMapConstIterator& operator++() { // Preincrement
430 ++Ptr;
431 AdvancePastEmptyBuckets();
432 return *this;
433 }
434 StringMapConstIterator operator++(int) { // Postincrement
435 StringMapConstIterator tmp = *this; ++*this; return tmp;
436 }
438 private:
439 void AdvancePastEmptyBuckets() {
440 while (*Ptr == 0 || *Ptr == StringMapImpl::getTombstoneVal())
441 ++Ptr;
442 }
443 };
445 template<typename ValueTy>
446 class StringMapIterator : public StringMapConstIterator<ValueTy> {
447 public:
448 explicit StringMapIterator(StringMapEntryBase **Bucket,
449 bool NoAdvance = false)
450 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
451 }
452 StringMapEntry<ValueTy> &operator*() const {
453 return *static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
454 }
455 StringMapEntry<ValueTy> *operator->() const {
456 return static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
457 }
458 };
460 }
462 #endif