set.c 12.8 KB
Newer Older
Götz Lindenmaier's avatar
Götz Lindenmaier committed
1
2
3
4
5
6
7
8
9
10
11
/*
 * Project:     libFIRM
 * File name:   ir/adt/set.c
 * Purpose:     Set --- collection of entries that are unique wrt to a key.
 * Author:      Markus Armbruster
 * Modified by:
 * Created:     1999 by getting from fiasco
 * CVS-ID:      $Id$
 * Copyright:   (c) 1995, 1996 Markus Armbruster
 * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
 */
Christian Schäfer's avatar
Christian Schäfer committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25

/*  This code is derived from:

    From: ejp@ausmelb.oz.AU (Esmond Pitt)
    Date: Tue, 7 Mar 1989 22:06:26 GMT
    Subject: v06i042: dynamic hashing version of hsearch(3)
    Message-ID: <1821@basser.oz>
    Newsgroups: comp.sources.misc
    Sender: msgs@basser.oz

    Posting-number: Volume 6, Issue 42
    Submitted-By: Esmond Pitt <ejp@ausmelb.oz.AU>
    Archive-name: dynamic-hash

Sebastian Felis's avatar
Sebastian Felis committed
26
27
28
    * Dynamic hashing, after CACM April 1988 pp 446-457, by Per-Ake Larson.
    * Coded into C, with minor code improvements, and with hsearch(3) interface,
    * by ejp@ausmelb.oz, Jul 26, 1988: 13:16;
Christian Schäfer's avatar
Christian Schäfer committed
29
30
31
32

    TODO: Fix Esmond's ugly MixedCapsIdentifiers ;->
 */

Boris Boesler's avatar
Boris Boesler committed
33
34
/* $Id$ */

Christian Schäfer's avatar
Christian Schäfer committed
35
#ifdef HAVE_CONFIG_H
Michael Beck's avatar
Michael Beck committed
36
# include "config.h"
Christian Schäfer's avatar
Christian Schäfer committed
37
38
#endif

Götz Lindenmaier's avatar
Götz Lindenmaier committed
39
/* bcopy is not ISO C *
40
#define bcopy(X, Y, Z) memcpy((Y), (X), (Z))
Götz Lindenmaier's avatar
Götz Lindenmaier committed
41
*/
42

Christian Schäfer's avatar
Christian Schäfer committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#ifdef PSET
# define SET pset
# define PMANGLE(pre) pre##_pset
# define MANGLEP(post) pset_##post
# define MANGLE(pre, post) pre##pset##post
# define EQUAL(cmp, elt, key, siz) (!(cmp) ((elt)->entry.dptr, (key)))
#else
# define SET set
# define PMANGLE(pre) pre##_set
# define MANGLEP(post) set_##post
# define MANGLE(pre, post) pre##set##post
# define EQUAL(cmp, elt, key, siz) \
    (((elt)->entry.size == (siz)) && !(cmp) ((elt)->entry.dptr, (key), (siz)))
#endif

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
62
#include "xmalloc.h"
Christian Schäfer's avatar
Christian Schäfer committed
63
64
65
66
67
68
#ifdef PSET
# include "pset.h"
#else
# include "set.h"
#endif

69

Christian Schäfer's avatar
Christian Schäfer committed
70
71
72
73
74
75
76
77
#define TOBSTACK_ID MANGLEP(tag)
#include "obst.h"


#define SEGMENT_SIZE_SHIFT	8
#define SEGMENT_SIZE		(1 << SEGMENT_SIZE_SHIFT)
#define DIRECTORY_SIZE_SHIFT	8
#define DIRECTORY_SIZE		(1 << DIRECTORY_SIZE_SHIFT)
78
#define MAX_LOAD_FACTOR		4
Christian Schäfer's avatar
Christian Schäfer committed
79
80
81


typedef struct element {
Michael Beck's avatar
Michael Beck committed
82
  struct element *chain;	/**< for chaining Elements */
Christian Schäfer's avatar
Christian Schäfer committed
83
84
85
86
87
  MANGLEP (entry) entry;
} Element, *Segment;


struct SET {
Michael Beck's avatar
Michael Beck committed
88
89
90
91
  unsigned p;			/**< Next bucket to be split	*/
  unsigned maxp;		/**< upper bound on p during expansion	*/
  unsigned nkey;		/**< current # keys	*/
  unsigned nseg;		/**< current # segments	*/
Christian Schäfer's avatar
Christian Schäfer committed
92
  Segment *dir[DIRECTORY_SIZE];
Michael Beck's avatar
Michael Beck committed
93
  MANGLEP(cmp_fun) cmp;		/**< function comparing entries */
94
  unsigned iter_i, iter_j;
Michael Beck's avatar
Michael Beck committed
95
  Element *iter_tail;		/**< non-NULL while iterating over elts */
Christian Schäfer's avatar
Christian Schäfer committed
96
#ifdef PSET
Michael Beck's avatar
Michael Beck committed
97
  Element *free_list;		/**< list of free Elements */
Christian Schäfer's avatar
Christian Schäfer committed
98
#endif
Michael Beck's avatar
Michael Beck committed
99
  struct obstack obst;		/**< obstack for allocation all data */
Christian Schäfer's avatar
Christian Schäfer committed
100
101
102
103
104
#ifdef STATS
  int naccess, ncollision, ndups;
  int max_chain_len;
#endif
#ifdef DEBUG
Michael Beck's avatar
Michael Beck committed
105
  const char *tag;              /**< an optionally tag for distinguishing sets */
Christian Schäfer's avatar
Christian Schäfer committed
106
107
108
109
110
111
#endif
};


#ifdef STATS

112
void
Christian Schäfer's avatar
Christian Schäfer committed
113
114
115
116
117
118
119
120
121
122
123
MANGLEP(stats) (SET *table)
{
  int nfree = 0;
#ifdef PSET
  Element *q = table->free_list;
  while (q) { q = q->chain; ++nfree; }
#endif
  printf ("     accesses  collisions        keys  duplicates     longest      wasted\n%12d%12d%12d%12d%12d%12d\n",
	  table->naccess, table->ncollision, table->nkey, table->ndups, table->max_chain_len, nfree);
}

124
static INLINE void
Christian Schäfer's avatar
Christian Schäfer committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
stat_chain_len (SET *table, int chain_len)
{
  table->ncollision += chain_len;
  if (table->max_chain_len < chain_len) table->max_chain_len = chain_len;
}

# define stat_access(table) (++(table)->naccess)
# define stat_dup(table) (++(table)->ndups)

#else /* !STATS */

# define stat_chain_len(table, chain_len) ((void)0)
# define stat_access(table) ((void)0)
# define stat_dup(table) ((void)0)

#endif /* !STATS */

#ifdef DEBUG

const char *MANGLEP(tag);


Götz Lindenmaier's avatar
fix    
Götz Lindenmaier committed
147
void
Christian Schäfer's avatar
Christian Schäfer committed
148
149
MANGLEP(describe) (SET *table)
{
150
  unsigned i, j, collide;
Christian Schäfer's avatar
Christian Schäfer committed
151
152
153
  Element *ptr;
  Segment *seg;

154
  printf ("p=%u maxp=%u nkey=%u nseg=%u\n",
Christian Schäfer's avatar
Christian Schäfer committed
155
156
157
158
159
160
161
162
163
	  table->p, table->maxp, table->nkey, table->nseg);
  for (i = 0;  i < table->nseg;  i++) {
    seg = table->dir[i];
    for (j = 0;  j < SEGMENT_SIZE;  j++) {
      collide = 0;
      ptr = seg[j];
      while (ptr) {
	if (collide) printf ("<%3d>", collide);
	else printf ("table");
Götz Lindenmaier's avatar
fix    
Götz Lindenmaier committed
164
	printf ("[%d][%3d]: %u %p\n", i, j, ptr->entry.hash, (void *)ptr->entry.dptr);
Christian Schäfer's avatar
Christian Schäfer committed
165
166
167
168
169
	ptr = ptr->chain;
	collide++;
      }
    }
  }
170
171
172
#ifdef STATS
  MANGLEP(stats)(table);
#endif
Christian Schäfer's avatar
Christian Schäfer committed
173
174
175
176
177
178
179
180
181
182
183
}

#endif /* !DEBUG */


SET *
(PMANGLE(new)) (MANGLEP(cmp_fun) cmp, int nslots)
{
  int i;
  SET *table = xmalloc (sizeof (SET));

184
  if (nslots > SEGMENT_SIZE * DIRECTORY_SIZE)
Götz Lindenmaier's avatar
Götz Lindenmaier committed
185
    nslots = DIRECTORY_SIZE;
186
187
188
189
  else {
    assert (nslots >= 0);
    /* Adjust nslots up to next power of 2, minimum SEGMENT_SIZE */
    for (i = SEGMENT_SIZE;  i < nslots;  i <<= 1);
Götz Lindenmaier's avatar
fix    
Götz Lindenmaier committed
190
    nslots = i >> SEGMENT_SIZE_SHIFT;
191
  }
Christian Schäfer's avatar
Christian Schäfer committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

  table->nseg = table->p = table->nkey = 0;
  table->maxp = nslots << SEGMENT_SIZE_SHIFT;
  table->cmp = cmp;
  table->iter_tail = NULL;
#ifdef PSET
  table->free_list = NULL;
#endif
  obstack_init (&table->obst);

  /* Make segments */
  for (i = 0;  i < nslots;  ++i) {
    table->dir[i] = (Segment *)obstack_alloc (&table->obst,
					      sizeof (Segment) * SEGMENT_SIZE);

Michael Beck's avatar
Michael Beck committed
207
    memset(table->dir[i], 0, sizeof (Segment) * SEGMENT_SIZE);
Christian Schäfer's avatar
Christian Schäfer committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    table->nseg++;
  }

#ifdef STATS
  table->naccess = table->ncollision = table->ndups = 0;
  table->max_chain_len = 0;
#endif
#ifdef DEBUG
  table->tag = MANGLEP(tag);
#endif
  return table;
}


222
void
Christian Schäfer's avatar
Christian Schäfer committed
223
224
225
226
227
228
229
230
231
PMANGLE(del) (SET *table)
{
#ifdef DEBUG
  MANGLEP(tag) = table->tag;
#endif
  obstack_free (&table->obst, NULL);
  xfree (table);
}

Michael Beck's avatar
Michael Beck committed
232
233
234
235
236
237
int
MANGLEP(count) (SET *table)
{
  return table->nkey;
}

238
239
240
241
/*
 * do one iteration step, return 1
 * if still data in the set, 0 else
 */
242
static INLINE int
Christian Schäfer's avatar
Christian Schäfer committed
243
244
245
246
247
248
249
250
251
252
253
254
iter_step (SET *table)
{
  if (++table->iter_j >= SEGMENT_SIZE) {
    table->iter_j = 0;
    if (++table->iter_i >= table->nseg) {
      table->iter_i = 0;
      return 0;
    }
  }
  return 1;
}

255
256
257
/*
 * finds the first entry in the table
 */
258
void *
Christian Schäfer's avatar
Christian Schäfer committed
259
260
261
262
263
264
265
266
267
268
269
270
271
MANGLEP(first) (SET *table)
{
  assert (!table->iter_tail);
  table->iter_i = 0;
  table->iter_j = 0;
  while (!table->dir[table->iter_i][table->iter_j]) {
    if (!iter_step (table)) return NULL;
  }
  table->iter_tail = table->dir[table->iter_i][table->iter_j];
  assert (table->iter_tail->entry.dptr);
  return table->iter_tail->entry.dptr;
}

272
273
274
/*
 * returns next entry in the table
 */
275
void *
Christian Schäfer's avatar
Christian Schäfer committed
276
277
MANGLEP(next) (SET *table)
{
Michael Beck's avatar
Michael Beck committed
278
279
  if (!table->iter_tail)
    return NULL;
280
281

  /* follow collision chain */
Christian Schäfer's avatar
Christian Schäfer committed
282
283
  table->iter_tail = table->iter_tail->chain;
  if (!table->iter_tail) {
284
    /* go to next segment */
Christian Schäfer's avatar
Christian Schäfer committed
285
286
287
288
289
290
291
292
293
    do {
      if (!iter_step (table)) return NULL;
    } while (!table->dir[table->iter_i][table->iter_j]);
    table->iter_tail = table->dir[table->iter_i][table->iter_j];
  }
  assert (table->iter_tail->entry.dptr);
  return table->iter_tail->entry.dptr;
}

294
void
Christian Schäfer's avatar
Christian Schäfer committed
295
296
297
298
299
MANGLEP(break) (SET *table)
{
  table->iter_tail = NULL;
}

300
301
302
/*
 * limit the hash value
 */
303
static INLINE unsigned
Christian Schäfer's avatar
Christian Schäfer committed
304
305
306
307
Hash (SET *table, unsigned h)
{
  unsigned address;

308
  address = h & (table->maxp - 1);          /* h % table->maxp */
Christian Schäfer's avatar
Christian Schäfer committed
309
310
311
312
313
  if (address < (unsigned)table->p)
    address = h & ((table->maxp << 1) - 1); /* h % (2*table->maxp) */
  return address;
}

314
315
316
317
/*
 * returns non-zero if the number of elements in
 * the set is greater then number of segments * MAX_LOAD_FACTOR
 */
318
static INLINE int
Christian Schäfer's avatar
Christian Schäfer committed
319
320
321
322
323
324
loaded (SET *table)
{
  return (  ++table->nkey
	  > (table->nseg << SEGMENT_SIZE_SHIFT) * MAX_LOAD_FACTOR);
}

325
326
327
328
329
330
331
332
/*
 * expand the hash-table: the algorithm is split, so on every
 * insert, only ONE segment is rehashed!
 *
 * table->p contains the current segment to split
 * after all segments were split, table->p is set to zero and
 * table->maxp is duplicated.
 */
Christian Schäfer's avatar
Christian Schäfer committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
static void
expand_table (SET *table)
{
  unsigned NewAddress;
  int OldSegmentIndex, NewSegmentIndex;
  int OldSegmentDir, NewSegmentDir;
  Segment *OldSegment;
  Segment *NewSegment;
  Element *Current;
  Element **Previous;
  Element **LastOfNew;

  if (table->maxp + table->p < (DIRECTORY_SIZE << SEGMENT_SIZE_SHIFT)) {
    /* Locate the bucket to be split */
347
348
    OldSegmentDir   = table->p >> SEGMENT_SIZE_SHIFT;
    OldSegment      = table->dir[OldSegmentDir];
Christian Schäfer's avatar
Christian Schäfer committed
349
350
351
    OldSegmentIndex = table->p & (SEGMENT_SIZE-1);

    /* Expand address space; if necessary create a new segment */
352
353
    NewAddress      = table->maxp + table->p;
    NewSegmentDir   = NewAddress >> SEGMENT_SIZE_SHIFT;
Christian Schäfer's avatar
Christian Schäfer committed
354
355
356
357
358
    NewSegmentIndex = NewAddress & (SEGMENT_SIZE-1);
    if (NewSegmentIndex == 0) {
      table->dir[NewSegmentDir] =
	(Segment *)obstack_alloc (&table->obst,
				  sizeof(Segment) * SEGMENT_SIZE);
359
      memset(table->dir[NewSegmentDir], 0, sizeof(Segment) * SEGMENT_SIZE);
360
      table->nseg++;
Christian Schäfer's avatar
Christian Schäfer committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
    }
    NewSegment = table->dir[NewSegmentDir];

    /* Adjust state variables */
    table->p++;
    if (table->p == table->maxp) {
      table->maxp <<= 1;	/* table->maxp *= 2	*/
      table->p = 0;
    }

    /* Relocate records to the new bucket */
    Previous = &OldSegment[OldSegmentIndex];
    Current = *Previous;
    LastOfNew = &NewSegment[NewSegmentIndex];
    *LastOfNew = NULL;
    while (Current != NULL) {
      if (Hash (table, Current->entry.hash) == NewAddress) {
	/* move to new chain */
	*LastOfNew = Current;
380
381
382
	*Previous  = Current->chain;
	LastOfNew  = &Current->chain;
	Current    = Current->chain;
Christian Schäfer's avatar
Christian Schäfer committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
	*LastOfNew = NULL;
      } else {
	/* leave on old chain */
	Previous = &Current->chain;
	Current = Current->chain;
      }
    }
  }
}


void *
MANGLE(_,_search) (SET *table,
		   const void *key,
#ifndef PSET
		   size_t size,
#endif
		   unsigned hash,
		   MANGLE(_,_action) action)
{
  unsigned h;
  Segment *CurrentSegment;
  int SegmentIndex;
  MANGLEP(cmp_fun) cmp = table->cmp;
  Segment q;
  int chain_len = 0;

  assert (table);
  assert (key);
#ifdef DEBUG
  MANGLEP(tag) = table->tag;
#endif
  stat_access (table);

  /* Find collision chain */
  h = Hash (table, hash);
419
  SegmentIndex   = h & (SEGMENT_SIZE-1);
Christian Schäfer's avatar
Christian Schäfer committed
420
421
422
423
424
425
426
427
428
429
430
431
432
  CurrentSegment = table->dir[h >> SEGMENT_SIZE_SHIFT];
  assert (CurrentSegment != NULL);
  q = CurrentSegment[SegmentIndex];

  /* Follow collision chain */
  while (q && !EQUAL (cmp, q, key, size)) {
    q = q->chain;
    ++chain_len;
  }

  stat_chain_len (table, chain_len);

  if (!q && (action != MANGLE(_,_find))) { /* not found, insert */
433
434
    assert (!table->iter_tail && "insert an element into a set that is iterated");

Christian Schäfer's avatar
Christian Schäfer committed
435
436
437
438
439
440
441
442
443
444
445
446
    if (CurrentSegment[SegmentIndex]) stat_dup (table);

#ifdef PSET
    if (table->free_list) {
      q = table->free_list;
      table->free_list = table->free_list->chain;
    } else {
      q = obstack_alloc (&table->obst, sizeof (Element));
    }
    q->entry.dptr = (void *)key;
#else
    obstack_blank (&table->obst, offsetof (Element, entry.dptr));
447
448
449
450
    if (action == _set_hinsert0)
      obstack_grow0 (&table->obst, key, size);
    else
      obstack_grow (&table->obst, key, size);
Christian Schäfer's avatar
Christian Schäfer committed
451
452
453
454
455
456
457
458
459
460
461
462
463
    q = obstack_finish (&table->obst);
    q->entry.size = size;
#endif
    q->chain = CurrentSegment[SegmentIndex];
    q->entry.hash = hash;
    CurrentSegment[SegmentIndex] = q;

    if (loaded (table)) {
      expand_table(table);	/* doesn't affect q */
    }
  }

  if (!q) return NULL;
464
465
466
467
468
#ifdef PSET
  if (action == _pset_hinsert) return &q->entry;
#else
  if (action == _set_hinsert || action == _set_hinsert0) return &q->entry;
#endif
Christian Schäfer's avatar
Christian Schäfer committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
  return q->entry.dptr;
}


#ifdef PSET

void *
pset_remove (SET *table, const void *key, unsigned hash)
{
  unsigned h;
  Segment *CurrentSegment;
  int SegmentIndex;
  pset_cmp_fun cmp = table->cmp;
  Segment *p;
  Segment q;
  int chain_len = 0;

  assert (table && !table->iter_tail);
  stat_access (table);

  /* Find collision chain */
  h = Hash (table, hash);
  SegmentIndex = h & (SEGMENT_SIZE-1);
  CurrentSegment = table->dir[h >> SEGMENT_SIZE_SHIFT];
  assert (CurrentSegment != NULL);
  p = &CurrentSegment[SegmentIndex];

  /* Follow collision chain */
  while (!EQUAL (cmp, *p, key, size)) {
    p = &(*p)->chain;
    assert (*p);
    ++chain_len;
  }

  stat_chain_len (table, chain_len);

  q = *p;
Michael Beck's avatar
Michael Beck committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519

  if (q == table->iter_tail) {
    /* removing current element */
    table->iter_tail = q->chain;
    if (!table->iter_tail) {
      /* go to next segment */
      do {
	if (!iter_step (table))
	  break;
      } while (!table->dir[table->iter_i][table->iter_j]);
      table->iter_tail = table->dir[table->iter_i][table->iter_j];
    }
  }

Christian Schäfer's avatar
Christian Schäfer committed
520
521
522
  *p = (*p)->chain;
  q->chain = table->free_list;
  table->free_list = q;
Michael Beck's avatar
Michael Beck committed
523
  --table->nkey;
Christian Schäfer's avatar
Christian Schäfer committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571

  return q->entry.dptr;
}


void *
(pset_find) (SET *se, const void *key, unsigned hash)
{
  return pset_find (se, key, hash);
}


void *
(pset_insert) (SET *se, const void *key, unsigned hash)
{
  return pset_insert (se, key, hash);
}


MANGLEP(entry) *
(pset_hinsert) (SET *se, const void *key, unsigned hash)
{
  return pset_hinsert (se, key, hash);
}

#else /* !PSET */

void *
(set_find) (set *se, const void *key, size_t size, unsigned hash)
{
  return set_find (se, key, size, hash);
}


void *
(set_insert) (set *se, const void *key, size_t size, unsigned hash)
{
  return set_insert (se, key, size, hash);
}


set_entry *
(set_hinsert) (set *se, const void *key, size_t size, unsigned hash)
{
  return set_hinsert (se, key, size, hash);
}

#endif /* !PSET */