Fixed inconsistent uses of DEBUG_ONLY.
[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. (useful 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)   (void)0
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) XMALLOCN(HashSetEntry, (size))
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 InsertReturnValue insert_nogrow(HashSet *self, KeyType key)
223 {
224         size_t   num_probes  = 0;
225         size_t   num_buckets = self->num_buckets;
226         size_t   hashmask    = num_buckets - 1;
227         unsigned hash        = Hash(self, key);
228         size_t   bucknum     = hash & hashmask;
229         size_t   insert_pos  = ILLEGAL_POS;
230
231         assert((num_buckets & (num_buckets - 1)) == 0);
232
233         for (;;) {
234                 HashSetEntry *entry = & self->entries[bucknum];
235
236                 if (EntryIsEmpty(*entry)) {
237                         size_t p;
238                         HashSetEntry *nentry;
239
240                         if (insert_pos != ILLEGAL_POS) {
241                                 p = insert_pos;
242                         } else {
243                                 p = bucknum;
244                         }
245
246                         nentry = &self->entries[p];
247                         InitData(self, EntryGetValue(*nentry), key);
248                         EntrySetHash(*nentry, hash);
249                         self->num_elements++;
250                         return GetInsertReturnValue(*nentry, 0);
251                 }
252                 if (EntryIsDeleted(*entry)) {
253                         if (insert_pos == ILLEGAL_POS)
254                                 insert_pos = bucknum;
255                 } else if (EntryGetHash(self, *entry) == hash) {
256                         if (KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
257                                 // Value already in the set, return it
258                                 return GetInsertReturnValue(*entry, 1);
259                         }
260                 }
261
262                 ++num_probes;
263                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
264                 assert(num_probes < num_buckets);
265         }
266 }
267
268 /**
269  * calculate shrink and enlarge limits
270  * @internal
271  */
272 static inline void reset_thresholds(HashSet *self)
273 {
274         self->enlarge_threshold = (size_t) HT_OCCUPANCY_FLT(self->num_buckets);
275         self->shrink_threshold  = (size_t) HT_EMPTY_FLT(self->num_buckets);
276         self->consider_shrink   = 0;
277 }
278
279 #ifndef HAVE_OWN_RESIZE
280 /**
281  * Inserts an element into a hashset under the assumption that the hashset
282  * contains no deleted entries and the element doesn't exist in the hashset yet.
283  * @internal
284  */
285 static void insert_new(HashSet *self, unsigned hash, ValueType value)
286 {
287         size_t num_probes  = 0;
288         size_t num_buckets = self->num_buckets;
289         size_t hashmask    = num_buckets - 1;
290         size_t bucknum     = hash & hashmask;
291         size_t insert_pos  = ILLEGAL_POS;
292
293         //assert(value != NullValue);
294
295         for (;;) {
296                 HashSetEntry *entry = & self->entries[bucknum];
297
298                 if (EntryIsEmpty(*entry)) {
299                         size_t        p;
300                         HashSetEntry *nentry;
301
302                         if (insert_pos != ILLEGAL_POS) {
303                                 p = insert_pos;
304                         } else {
305                                 p = bucknum;
306                         }
307                         nentry = &self->entries[p];
308
309                         EntryGetValue(*nentry) = value;
310                         EntrySetHash(*nentry, hash);
311                         self->num_elements++;
312                         return;
313                 }
314                 assert(!EntryIsDeleted(*entry));
315
316                 ++num_probes;
317                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
318                 assert(num_probes < num_buckets);
319         }
320 }
321
322 /**
323  * Resize the hashset
324  * @internal
325  */
326 static inline void resize(HashSet *self, size_t new_size)
327 {
328         size_t num_buckets = self->num_buckets;
329         size_t i;
330         HashSetEntry *old_entries = self->entries;
331         HashSetEntry *new_entries;
332
333         /* allocate a new array with double size */
334         new_entries = Alloc(new_size);
335         SetRangeEmpty(new_entries, new_size);
336
337         /* use the new array */
338         self->entries      = new_entries;
339         self->num_buckets  = new_size;
340         self->num_elements = 0;
341         self->num_deleted  = 0;
342 #ifndef NDEBUG
343         self->entries_version++;
344 #endif
345         reset_thresholds(self);
346
347         /* reinsert all elements */
348         for (i = 0; i < num_buckets; ++i) {
349                 HashSetEntry *entry = & old_entries[i];
350                 if (EntryIsEmpty(*entry) || EntryIsDeleted(*entry))
351                         continue;
352
353                 insert_new(self, EntryGetHash(self, *entry), EntryGetValue(*entry));
354         }
355
356         /* now we can free the old array */
357         Free(old_entries);
358 }
359 #else
360
361 /* resize must be defined outside */
362 static inline void resize(HashSet *self, size_t new_size);
363
364 #endif
365
366 /**
367  * grow the hashset if adding 1 more elements would make it too crowded
368  * @internal
369  */
370 static inline void maybe_grow(HashSet *self)
371 {
372         size_t resize_to;
373
374         if (LIKELY(self->num_elements + 1 <= self->enlarge_threshold))
375                 return;
376
377         /* double table size */
378         resize_to = self->num_buckets * 2;
379         resize(self, resize_to);
380 }
381
382 /**
383  * shrink the hashset if it is only sparsely filled
384  * @internal
385  */
386 static inline void maybe_shrink(HashSet *self)
387 {
388         size_t size;
389         size_t resize_to;
390
391         if (!self->consider_shrink)
392                 return;
393
394         self->consider_shrink = 0;
395         size                  = hashset_size(self);
396         if (size <= HT_MIN_BUCKETS)
397                 return;
398
399         if (LIKELY(size > self->shrink_threshold))
400                 return;
401
402         resize_to = ceil_po2(size);
403
404         if (resize_to < 4)
405                 resize_to = 4;
406
407         resize(self, resize_to);
408 }
409
410 /**
411  * Insert an element into the hashset. If no element with the given key exists yet,
412  * then a new one is created and initialized with the InitData function.
413  * Otherwise the existing element is returned (for hashs where key is equal to
414  * value, nothing is returned.)
415  *
416  * @param self   the hashset
417  * @param key    the key that identifies the data
418  * @returns      the existing or newly created data element (or nothing in case of hashs where keys are the while value)
419  */
420 InsertReturnValue hashset_insert(HashSet *self, KeyType key)
421 {
422 #ifndef NDEBUG
423         self->entries_version++;
424 #endif
425
426         maybe_shrink(self);
427         maybe_grow(self);
428         return insert_nogrow(self, key);
429 }
430
431 /**
432  * Searches for an element with key @p key.
433  *
434  * @param self      the hashset
435  * @param key       the key to search for
436  * @returns         the found value or NullValue if nothing was found
437  */
438 InsertReturnValue hashset_find(const HashSet *self, ConstKeyType key)
439 {
440         size_t   num_probes  = 0;
441         size_t   num_buckets = self->num_buckets;
442         size_t   hashmask    = num_buckets - 1;
443         unsigned hash        = Hash(self, key);
444         size_t   bucknum     = hash & hashmask;
445
446         for (;;) {
447                 HashSetEntry *entry = & self->entries[bucknum];
448
449                 if (EntryIsEmpty(*entry)) {
450                         return NullReturnValue;
451                 }
452                 if (EntryIsDeleted(*entry)) {
453                         // value is deleted
454                 } else if (EntryGetHash(self, *entry) == hash) {
455                         if (KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
456                                 // found the value
457                                 return GetInsertReturnValue(*entry, 1);
458                         }
459                 }
460
461                 ++num_probes;
462                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
463                 assert(num_probes < num_buckets);
464         }
465 }
466
467 /**
468  * Removes an element from a hashset. Does nothing if the set doesn't contain
469  * the element.
470  *
471  * @param self    the hashset
472  * @param key     key that identifies the data to remove
473  */
474 void hashset_remove(HashSet *self, ConstKeyType key)
475 {
476         size_t   num_probes  = 0;
477         size_t   num_buckets = self->num_buckets;
478         size_t   hashmask    = num_buckets - 1;
479         unsigned hash        = Hash(self, key);
480         size_t   bucknum     = hash & hashmask;
481
482 #ifndef NDEBUG
483         self->entries_version++;
484 #endif
485
486         for (;;) {
487                 HashSetEntry *entry = & self->entries[bucknum];
488
489                 if (EntryIsEmpty(*entry)) {
490                         return;
491                 }
492                 if (EntryIsDeleted(*entry)) {
493                         // entry is deleted
494                 } else if (EntryGetHash(self, *entry) == hash) {
495                         if (KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
496                                 EntrySetDeleted(*entry);
497                                 self->num_deleted++;
498                                 self->consider_shrink = 1;
499                                 return;
500                         }
501                 }
502
503                 ++num_probes;
504                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
505                 assert(num_probes < num_buckets);
506         }
507 }
508
509 /**
510  * Initializes hashset with a specific size
511  * @internal
512  */
513 static inline void init_size(HashSet *self, size_t initial_size)
514 {
515         if (initial_size < 4)
516                 initial_size = 4;
517
518         self->entries         = Alloc(initial_size);
519         SetRangeEmpty(self->entries, initial_size);
520         self->num_buckets     = initial_size;
521         self->consider_shrink = 0;
522         self->num_elements    = 0;
523         self->num_deleted     = 0;
524 #ifndef NDEBUG
525         self->entries_version = 0;
526 #endif
527 #ifdef ADDITIONAL_INIT
528         ADDITIONAL_INIT
529 #endif
530
531         reset_thresholds(self);
532 }
533
534 /**
535  * Initializes a hashset with the default size. The memory for the set has to
536  * already allocated.
537  */
538 void hashset_init(HashSet *self)
539 {
540         init_size(self, HT_MIN_BUCKETS);
541 }
542
543 /**
544  * Destroys a hashset, freeing all used memory (except the memory for the
545  * HashSet struct itself).
546  */
547 void hashset_destroy(HashSet *self)
548 {
549 #ifdef ADDITIONAL_TERM
550         ADDITIONAL_TERM
551 #endif
552         Free(self->entries);
553 #ifndef NDEBUG
554         self->entries = NULL;
555 #endif
556 }
557
558 /**
559  * Initializes a hashset expecting expected_element size.
560  */
561 void hashset_init_size(HashSet *self, size_t expected_elements)
562 {
563         size_t needed_size;
564         size_t po2size;
565
566         if (expected_elements >= UINT_MAX/2) {
567                 abort();
568         }
569
570         needed_size = expected_elements * HT_1_DIV_OCCUPANCY_FLT;
571         po2size     = ceil_po2(needed_size);
572         init_size(self, po2size);
573 }
574
575 #ifndef NO_ITERATOR
576 /**
577  * Initializes a hashset iterator. The memory for the allocator has to be
578  * already allocated.
579  * @note it is not allowed to remove or insert elements while iterating
580  */
581 void hashset_iterator_init(HashSetIterator *self, const HashSet *hashset)
582 {
583         self->current_bucket = hashset->entries - 1;
584         self->end            = hashset->entries + hashset->num_buckets;
585 #ifndef NDEBUG
586         self->set             = hashset;
587         self->entries_version = hashset->entries_version;
588 #endif
589 }
590
591 /**
592  * Returns the next value in the iterator or NULL if no value is left
593  * in the hashset.
594  * @note it is not allowed to remove or insert elements while iterating
595  */
596 ValueType hashset_iterator_next(HashSetIterator *self)
597 {
598         HashSetEntry *current_bucket = self->current_bucket;
599         HashSetEntry *end            = self->end;
600
601         /* using hashset_insert or hashset_remove is not allowed while iterating */
602         assert(self->entries_version == self->set->entries_version);
603
604         do {
605                 current_bucket++;
606                 if (current_bucket >= end)
607                         return NullValue;
608         } while (EntryIsEmpty(*current_bucket) || EntryIsDeleted(*current_bucket));
609
610         self->current_bucket = current_bucket;
611         return EntryGetValue(*current_bucket);
612 }
613
614 /**
615  * Removes the element the iterator points to. Removing an element a second time
616  * has no result.
617  */
618 void hashset_remove_iterator(HashSet *self, const HashSetIterator *iter)
619 {
620         HashSetEntry *entry = iter->current_bucket;
621
622         /* iterator_next needs to have been called at least once */
623         assert(entry >= self->entries);
624         /* needs to be on a valid element */
625         assert(entry < self->entries + self->num_buckets);
626
627         if (EntryIsDeleted(*entry))
628                 return;
629
630         EntrySetDeleted(*entry);
631         self->num_deleted++;
632         self->consider_shrink = 1;
633 }
634 #endif /* NO_ITERATOR */
635
636 #endif /* HashSet */