allow derived hashsets to have an own resize
[libfirm] / ir / adt / hashset.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Generic hashset implementation
23  * @author  Matthias Braun, inspiration from densehash from google sparsehash
24  *          package
25  * @date    17.03.2007
26  * @version $Id$
27  *
28  *
29  * You have to specialize this file by defining:
30  *
31  * <ul>
32  *  <li><b>HashSet</b>         The name of the hashset type</li>
33  *  <li><b>HashSetIterator</b> The name of the hashset iterator type</li>
34  *  <li><b>ValueType</b>       The type of the stored data values</li>
35  *  <li><b>NullValue</b>       A special value representing no values</li>
36  *  <li><b>DeletedValue</b>    A special value representing deleted entries</li>
37  *  <li><b>Hash(hashset,key)</b> calculates the hash value for a given key</li>
38  * </ul>
39  *
40  * Note that by default it is assumed that the data values themselfes are used
41  * as keys. However you can change that with additional defines:
42  *
43  * <ul>
44  *  <li><b>KeyType</b>         The type of the keys identifying data values.
45  *                             Defining this implies, that a data value contains
46  *                             more than just the key.</li>
47  *  <li><b>GetKey(value)</b>   Extracts the key from a data value</li>
48  *  <li><b>KeysEqual(hashset,key1,key2)</b>  Tests wether 2 keys are equal</li>
49  *  <li><b>DO_REHASH</b>       Instead of storing the hash-values, recalculate
50  *                             them on demand from the datavalues. (usefull if
51  *                             calculating the hash-values takes less time than
52  *                             a memory access)</li>
53  * </ul>
54  *
55  * You can further fine tune your hashset by defining the following:
56  *
57  * <ul>
58  *  <li><b>JUMP(num_probes)</b> The probing method</li>
59  *  <li><b>Alloc(count)</b>     Allocates count hashset entries (NOT bytes)</li>
60  *  <li><b>Free(ptr)</b>        Frees a block of memory allocated by Alloc</li>
61  *  <li><b>SetRangeEmpty(ptr,count)</b> Efficiently sets a range of elements to
62  *                                      the Null value</li>
63  *  <li><b>ADDITIONAL_DATA<b>   Additional fields appended to the hashset struct</li>
64  * </ul>
65  */
66 #ifdef HashSet
67
68 #include <stdlib.h>
69 #include <string.h>
70 #include <assert.h>
71
72 #include "bitfiddle.h"
73 #include "util.h"
74
75 /* quadratic probing */
76 #ifndef JUMP
77 #define JUMP(num_probes)      (num_probes)
78 #endif /* JUMP */
79
80 #ifndef Hash
81 #define ID_HASH
82 #define Hash(self,key)        ((unsigned)(((char *)key) - (char *)0))
83 #endif /* Hash */
84
85 #ifdef DO_REHASH
86 #define HashSetEntry                   ValueType
87 #define EntrySetHash(entry,new_hash)
88 #define EntryGetHash(self,entry)       Hash(self, GetKey(entry))
89 #define EntryGetValue(entry)           (entry)
90 #else /* ! DO_REHASH */
91 #define EntryGetHash(self,entry)       (entry).hash
92 #define EntrySetHash(entry,new_hash)   (entry).hash = (new_hash)
93 #define EntryGetValue(entry)           (entry).data
94 #endif /* DO_REHASH */
95
96 #ifndef Alloc
97 #include "xmalloc.h"
98 #define Alloc(size)    (HashSetEntry*) xmalloc((size) * sizeof(HashSetEntry))
99 #define Free(ptr)      free(ptr)
100 #endif /* Alloc */
101
102 #ifdef ID_HASH
103 #define InsertReturnValue                 int
104 #define GetInsertReturnValue(entry,found) (found)
105 #define NullReturnValue                   0
106 #else /* ! ID_HASH */
107 #ifdef SCALAR_RETURN
108 #define InsertReturnValue                 ValueType
109 #define GetInsertReturnValue(entry,found) EntryGetValue(entry)
110 #define NullReturnValue                   NullValue
111 #else
112 #define InsertReturnValue                 ValueType*
113 #define GetInsertReturnValue(entry,found) & EntryGetValue(entry)
114 #define NullReturnValue                   & NullValue
115 #endif
116 #endif /* ID_HASH */
117
118 #ifndef KeyType
119 #define KeyType                  ValueType
120 #define GetKey(value)            (value)
121 #define InitData(self,value,key) (value) = (key)
122 #endif /* KeyType */
123
124 #ifndef ConstKeyType
125 #define ConstKeyType             const KeyType
126 #endif /* ConstKeyType */
127
128 #ifndef EntrySetEmpty
129 #define EntrySetEmpty(entry)    EntryGetValue(entry) = NullValue
130 #endif /* EntrySetEmpty */
131 #ifndef EntrySetDeleted
132 #define EntrySetDeleted(entry)  EntryGetValue(entry) = DeletedValue
133 #endif /* EntrySetDeleted */
134 #ifndef EntryIsEmpty
135 #define EntryIsEmpty(entry)     (EntryGetValue(entry) == NullValue)
136 #endif /* EntryIsEmpty */
137 #ifndef EntryIsDeleted
138 #define EntryIsDeleted(entry)   (EntryGetValue(entry) == DeletedValue)
139 #endif /* EntryIsDeleted */
140 #ifndef SetRangeEmpty
141 #define SetRangeEmpty(ptr,size)                \
142 {                                              \
143         size_t _i;                                 \
144         size_t _size = (size);                     \
145         HashSetEntry *entries = (ptr);             \
146         for(_i = 0; _i < _size; ++_i) {            \
147                 HashSetEntry *entry = & entries[_i];   \
148                 EntrySetEmpty(*entry);                 \
149         }                                          \
150 }
151 #endif /* SetRangeEmpty */
152
153 #ifndef HT_OCCUPANCY_FLT
154 /** how full before we double size */
155 #define HT_OCCUPANCY_FLT(x) ((x)/2)
156 #endif /* HT_OCCUPANCY_FLT */
157 #ifndef HT_1_DIV_OCCUPANCY_FLT
158 #define HT_1_DIV_OCCUPANCY_FLT 2
159 #endif
160
161 #ifndef HT_EMPTY_FLT
162 /** how empty before we half size */
163 #define HT_EMPTY_FLT(x)     ((x)/5)
164 #endif /* HT_EMPTY_FLT */
165
166 #ifndef HT_MIN_BUCKETS
167 /** default smallest bucket size */
168 #define HT_MIN_BUCKETS    32
169 #endif /* HT_MIN_BUCKETS */
170
171 #define ILLEGAL_POS       ((size_t)-1)
172
173 /* check that all needed functions are defined */
174 #ifndef hashset_init
175 #error You have to redefine hashset_init
176 #endif
177 #ifndef hashset_init_size
178 #error You have to redefine hashset_init_size
179 #endif
180 #ifndef hashset_destroy
181 #error You have to redefine hashset_destroy
182 #endif
183 #ifndef hashset_insert
184 #error You have to redefine hashset_insert
185 #endif
186 #ifndef hashset_remove
187 #error You have to redefine hashset_remove
188 #endif
189 #ifndef hashset_find
190 #error You have to redefine hashset_find
191 #endif
192 #ifndef hashset_size
193 #error You have to redefine hashset_size
194 #endif
195
196 #ifndef NO_ITERATOR
197 #ifndef hashset_iterator_init
198 #error You have to redefine hashset_iterator_init
199 #endif
200 #ifndef hashset_iterator_next
201 #error You have to redefine hashset_iterator_next
202 #endif
203 #ifndef hashset_remove_iterator
204 #error You have to redefine hashset_remove_iterator
205 #endif
206 #endif
207
208 /**
209  * Returns the number of elements in the hashset
210  */
211 size_t hashset_size(const HashSet *self)
212 {
213         return self->num_elements - self->num_deleted;
214 }
215
216 /**
217  * Inserts an element into a hashset without growing the set (you have to make
218  * sure there's enough room for that.
219  * @note also see comments for hashset_insert()
220  * @internal
221  */
222 static INLINE
223 InsertReturnValue insert_nogrow(HashSet *self, KeyType key)
224 {
225         size_t   num_probes  = 0;
226         size_t   num_buckets = self->num_buckets;
227         size_t   hashmask    = num_buckets - 1;
228         unsigned hash        = Hash(self, key);
229         size_t   bucknum     = hash & hashmask;
230         size_t   insert_pos  = ILLEGAL_POS;
231
232         assert((num_buckets & (num_buckets - 1)) == 0);
233
234         while(1) {
235                 HashSetEntry *entry = & self->entries[bucknum];
236
237                 if(EntryIsEmpty(*entry)) {
238                         size_t p;
239                         HashSetEntry *nentry;
240
241                         if(insert_pos != ILLEGAL_POS) {
242                                 p = insert_pos;
243                         } else {
244                                 p = bucknum;
245                         }
246
247                         nentry = &self->entries[p];
248                         InitData(self, EntryGetValue(*nentry), key);
249                         EntrySetHash(*nentry, hash);
250                         self->num_elements++;
251                         return GetInsertReturnValue(*nentry, 0);
252                 }
253                 if(EntryIsDeleted(*entry)) {
254                         if(insert_pos == ILLEGAL_POS)
255                                 insert_pos = bucknum;
256                 } else if(EntryGetHash(self, *entry) == hash) {
257                         if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
258                                 // Value already in the set, return it
259                                 return GetInsertReturnValue(*entry, 1);
260                         }
261                 }
262
263                 ++num_probes;
264                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
265                 assert(num_probes < num_buckets);
266         }
267 }
268
269 /**
270  * Inserts an element into a hashset under the assumption that the hashset
271  * contains no deleted entries and the element doesn't exist in the hashset yet.
272  * @internal
273  */
274 static
275 void insert_new(HashSet *self, unsigned hash, ValueType value)
276 {
277         size_t num_probes  = 0;
278         size_t num_buckets = self->num_buckets;
279         size_t hashmask    = num_buckets - 1;
280         size_t bucknum     = hash & hashmask;
281         size_t insert_pos  = ILLEGAL_POS;
282
283         //assert(value != NullValue);
284
285         while(1) {
286                 HashSetEntry *entry = & self->entries[bucknum];
287
288                 if(EntryIsEmpty(*entry)) {
289                         size_t        p;
290                         HashSetEntry *nentry;
291
292                         if(insert_pos != ILLEGAL_POS) {
293                                 p = insert_pos;
294                         } else {
295                                 p = bucknum;
296                         }
297                         nentry = &self->entries[p];
298
299                         EntryGetValue(*nentry) = value;
300                         EntrySetHash(*nentry, hash);
301                         self->num_elements++;
302                         return;
303                 }
304                 assert(!EntryIsDeleted(*entry));
305
306                 ++num_probes;
307                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
308                 assert(num_probes < num_buckets);
309         }
310 }
311
312 /**
313  * calculate shrink and enlarge limits
314  * @internal
315  */
316 static INLINE
317 void reset_thresholds(HashSet *self)
318 {
319         self->enlarge_threshold = (size_t) HT_OCCUPANCY_FLT(self->num_buckets);
320         self->shrink_threshold  = (size_t) HT_EMPTY_FLT(self->num_buckets);
321         self->consider_shrink   = 0;
322 }
323
324 #ifndef HAVE_OWN_RESIZE
325 /**
326  * Resize the hashset
327  * @internal
328  */
329 static INLINE
330 void resize(HashSet *self, size_t new_size)
331 {
332         size_t num_buckets = self->num_buckets;
333         size_t i;
334         HashSetEntry *old_entries = self->entries;
335         HashSetEntry *new_entries;
336
337         /* allocate a new array with double size */
338         new_entries = Alloc(new_size);
339         SetRangeEmpty(new_entries, new_size);
340
341         /* use the new array */
342         self->entries      = new_entries;
343         self->num_buckets  = new_size;
344         self->num_elements = 0;
345         self->num_deleted  = 0;
346 #ifndef NDEBUG
347         self->entries_version++;
348 #endif
349         reset_thresholds(self);
350
351         /* reinsert all elements */
352         for(i = 0; i < num_buckets; ++i) {
353                 HashSetEntry *entry = & old_entries[i];
354                 if(EntryIsEmpty(*entry) || EntryIsDeleted(*entry))
355                         continue;
356
357                 insert_new(self, EntryGetHash(self, *entry), EntryGetValue(*entry));
358         }
359
360         /* now we can free the old array */
361         Free(old_entries);
362 }
363 #else
364
365 /* resize must be defined outside */
366 static void resize(HashSet *self, size_t new_size);
367
368 #endif
369
370 /**
371  * grow the hashset if adding 1 more elements would make it too crowded
372  * @internal
373  */
374 static INLINE
375 void maybe_grow(HashSet *self)
376 {
377         size_t resize_to;
378
379         if(LIKELY(self->num_elements + 1 <= self->enlarge_threshold))
380                 return;
381
382         /* double table size */
383         resize_to = self->num_buckets * 2;
384         resize(self, resize_to);
385 }
386
387 /**
388  * shrink the hashset if it is only sparsely filled
389  * @internal
390  */
391 static INLINE
392 void maybe_shrink(HashSet *self)
393 {
394         size_t size;
395         size_t resize_to;
396
397         if(!self->consider_shrink)
398                 return;
399
400         self->consider_shrink = 0;
401         size                  = hashset_size(self);
402         if(size <= HT_MIN_BUCKETS)
403                 return;
404
405         if(LIKELY(size > self->shrink_threshold))
406                 return;
407
408         resize_to = ceil_po2(size);
409
410         if(resize_to < 4)
411                 resize_to = 4;
412
413         resize(self, resize_to);
414 }
415
416 /**
417  * Insert an element into the hashset. If no element with the given key exists yet,
418  * then a new one is created and initialized with the InitData function.
419  * Otherwise the existing element is returned (for hashs where key is equal to
420  * value, nothing is returned.)
421  *
422  * @param self   the hashset
423  * @param key    the key that identifies the data
424  * @returns      the existing or newly created data element (or nothing in case of hashs where keys are the while value)
425  */
426 InsertReturnValue hashset_insert(HashSet *self, KeyType key)
427 {
428 #ifndef NDEBUG
429         self->entries_version++;
430 #endif
431
432         maybe_shrink(self);
433         maybe_grow(self);
434         return insert_nogrow(self, key);
435 }
436
437 /**
438  * Searches for an element with key @p key.
439  *
440  * @param self      the hashset
441  * @param key       the key to search for
442  * @returns         the found value or NullValue if nothing was found
443  */
444 InsertReturnValue hashset_find(const HashSet *self, ConstKeyType key)
445 {
446         size_t   num_probes  = 0;
447         size_t   num_buckets = self->num_buckets;
448         size_t   hashmask    = num_buckets - 1;
449         unsigned hash        = Hash(self, key);
450         size_t   bucknum     = hash & hashmask;
451
452         while(1) {
453                 HashSetEntry *entry = & self->entries[bucknum];
454
455                 if(EntryIsEmpty(*entry)) {
456                         return NullReturnValue;
457                 }
458                 if(EntryIsDeleted(*entry)) {
459                         // value is deleted
460                 } else if(EntryGetHash(self, *entry) == hash) {
461                         if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
462                                 // found the value
463                                 return GetInsertReturnValue(*entry, 1);
464                         }
465                 }
466
467                 ++num_probes;
468                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
469                 assert(num_probes < num_buckets);
470         }
471 }
472
473 /**
474  * Removes an element from a hashset. Does nothing if the set doesn't contain
475  * the element.
476  *
477  * @param self    the hashset
478  * @param key     key that identifies the data to remove
479  */
480 void hashset_remove(HashSet *self, ConstKeyType key)
481 {
482         size_t   num_probes  = 0;
483         size_t   num_buckets = self->num_buckets;
484         size_t   hashmask    = num_buckets - 1;
485         unsigned hash        = Hash(self, key);
486         size_t   bucknum     = hash & hashmask;
487
488 #ifndef NDEBUG
489         self->entries_version++;
490 #endif
491
492         while(1) {
493                 HashSetEntry *entry = & self->entries[bucknum];
494
495                 if(EntryIsEmpty(*entry)) {
496                         return;
497                 }
498                 if(EntryIsDeleted(*entry)) {
499                         // entry is deleted
500                 } else if(EntryGetHash(self, *entry) == hash) {
501                         if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
502                                 EntrySetDeleted(*entry);
503                                 self->num_deleted++;
504                                 self->consider_shrink = 1;
505                                 return;
506                         }
507                 }
508
509                 ++num_probes;
510                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
511                 assert(num_probes < num_buckets);
512         }
513 }
514
515 /**
516  * Initializes hashset with a specific size
517  * @internal
518  */
519 static INLINE
520 void init_size(HashSet *self, size_t initial_size)
521 {
522         if(initial_size < 4)
523                 initial_size = 4;
524
525         self->entries         = Alloc(initial_size);
526         SetRangeEmpty(self->entries, initial_size);
527         self->num_buckets     = initial_size;
528         self->consider_shrink = 0;
529         self->num_elements    = 0;
530         self->num_deleted     = 0;
531 #ifndef NDEBUG
532         self->entries_version = 0;
533 #endif
534 #ifdef ADDITIONAL_INIT
535         ADDITIONAL_INIT
536 #endif
537
538         reset_thresholds(self);
539 }
540
541 /**
542  * Initializes a hashset with the default size. The memory for the set has to
543  * already allocated.
544  */
545 void hashset_init(HashSet *self)
546 {
547         init_size(self, HT_MIN_BUCKETS);
548 }
549
550 /**
551  * Destroys a hashset, freeing all used memory (except the memory for the
552  * HashSet struct itself).
553  */
554 void hashset_destroy(HashSet *self)
555 {
556 #ifdef ADDITIONAL_TERM
557         ADDITIONAL_TERM
558 #endif
559         Free(self->entries);
560 #ifndef NDEBUG
561         self->entries = NULL;
562 #endif
563 }
564
565 /**
566  * Initializes a hashset expecting expected_element size.
567  */
568 void hashset_init_size(HashSet *self, size_t expected_elements)
569 {
570         size_t needed_size;
571         size_t po2size;
572
573         if(expected_elements >= UINT_MAX/2) {
574                 abort();
575         }
576
577         needed_size = expected_elements * HT_1_DIV_OCCUPANCY_FLT;
578         po2size     = ceil_po2(needed_size);
579         init_size(self, po2size);
580 }
581
582 #ifndef NO_ITERATOR
583 /**
584  * Initializes a hashset iterator. The memory for the allocator has to be
585  * already allocated.
586  * @note it is not allowed to remove or insert elements while iterating
587  */
588 void hashset_iterator_init(HashSetIterator *self, const HashSet *hashset)
589 {
590         self->current_bucket = hashset->entries - 1;
591         self->end            = hashset->entries + hashset->num_buckets;
592 #ifndef NDEBUG
593         self->set             = hashset;
594         self->entries_version = hashset->entries_version;
595 #endif
596 }
597
598 /**
599  * Returns the next value in the iterator or NULL if no value is left
600  * in the hashset.
601  * @note it is not allowed to remove or insert elements while iterating
602  */
603 ValueType hashset_iterator_next(HashSetIterator *self)
604 {
605         HashSetEntry *current_bucket = self->current_bucket;
606         HashSetEntry *end            = self->end;
607
608         /* using hashset_insert or hashset_remove is not allowed while iterating */
609         assert(self->entries_version == self->set->entries_version);
610
611         do {
612                 current_bucket++;
613                 if(current_bucket >= end)
614                         return NullValue;
615         } while(EntryIsEmpty(*current_bucket) || EntryIsDeleted(*current_bucket));
616
617         self->current_bucket = current_bucket;
618         return EntryGetValue(*current_bucket);
619 }
620
621 /**
622  * Removes the element the iterator points to. Removing an element a second time
623  * has no result.
624  */
625 void hashset_remove_iterator(HashSet *self, const HashSetIterator *iter)
626 {
627         HashSetEntry *entry = iter->current_bucket;
628
629         /* iterator_next needs to have been called at least once */
630         assert(entry >= self->entries);
631         /* needs to be on a valid element */
632         assert(entry < self->entries + self->num_buckets);
633
634         if(EntryIsDeleted(*entry))
635                 return;
636
637         EntrySetDeleted(*entry);
638         self->num_deleted++;
639         self->consider_shrink = 1;
640 }
641 #endif /* NO_ITERATOR */
642
643 #endif /* HashSet */