Include gdb_assert.h in common-defs.h
[binutils-gdb.git] / gdb / bcache.c
1 /* Implement a cached obstack.
2 Written by Fred Fish <fnf@cygnus.com>
3 Rewritten by Jim Blandy <jimb@cygnus.com>
4
5 Copyright (C) 1999-2014 Free Software Foundation, Inc.
6
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21
22 #include "defs.h"
23 #include "gdb_obstack.h"
24 #include "bcache.h"
25 #include <string.h> /* For memcpy declaration */
26
27 /* The type used to hold a single bcache string. The user data is
28 stored in d.data. Since it can be any type, it needs to have the
29 same alignment as the most strict alignment of any type on the host
30 machine. I don't know of any really correct way to do this in
31 stock ANSI C, so just do it the same way obstack.h does. */
32
33 struct bstring
34 {
35 /* Hash chain. */
36 struct bstring *next;
37 /* Assume the data length is no more than 64k. */
38 unsigned short length;
39 /* The half hash hack. This contains the upper 16 bits of the hash
40 value and is used as a pre-check when comparing two strings and
41 avoids the need to do length or memcmp calls. It proves to be
42 roughly 100% effective. */
43 unsigned short half_hash;
44
45 union
46 {
47 char data[1];
48 double dummy;
49 }
50 d;
51 };
52
53
54 /* The structure for a bcache itself. The bcache is initialized, in
55 bcache_xmalloc(), by filling it with zeros and then setting the
56 corresponding obstack's malloc() and free() methods. */
57
58 struct bcache
59 {
60 /* All the bstrings are allocated here. */
61 struct obstack cache;
62
63 /* How many hash buckets we're using. */
64 unsigned int num_buckets;
65
66 /* Hash buckets. This table is allocated using malloc, so when we
67 grow the table we can return the old table to the system. */
68 struct bstring **bucket;
69
70 /* Statistics. */
71 unsigned long unique_count; /* number of unique strings */
72 long total_count; /* total number of strings cached, including dups */
73 long unique_size; /* size of unique strings, in bytes */
74 long total_size; /* total number of bytes cached, including dups */
75 long structure_size; /* total size of bcache, including infrastructure */
76 /* Number of times that the hash table is expanded and hence
77 re-built, and the corresponding number of times that a string is
78 [re]hashed as part of entering it into the expanded table. The
79 total number of hashes can be computed by adding TOTAL_COUNT to
80 expand_hash_count. */
81 unsigned long expand_count;
82 unsigned long expand_hash_count;
83 /* Number of times that the half-hash compare hit (compare the upper
84 16 bits of hash values) hit, but the corresponding combined
85 length/data compare missed. */
86 unsigned long half_hash_miss_count;
87
88 /* Hash function to be used for this bcache object. */
89 unsigned long (*hash_function)(const void *addr, int length);
90
91 /* Compare function to be used for this bcache object. */
92 int (*compare_function)(const void *, const void *, int length);
93 };
94
95 /* The old hash function was stolen from SDBM. This is what DB 3.0
96 uses now, and is better than the old one. */
97 \f
98 unsigned long
99 hash(const void *addr, int length)
100 {
101 return hash_continue (addr, length, 0);
102 }
103
104 /* Continue the calculation of the hash H at the given address. */
105
106 unsigned long
107 hash_continue (const void *addr, int length, unsigned long h)
108 {
109 const unsigned char *k, *e;
110
111 k = (const unsigned char *)addr;
112 e = k+length;
113 for (; k< e;++k)
114 {
115 h *=16777619;
116 h ^= *k;
117 }
118 return (h);
119 }
120 \f
121 /* Growing the bcache's hash table. */
122
123 /* If the average chain length grows beyond this, then we want to
124 resize our hash table. */
125 #define CHAIN_LENGTH_THRESHOLD (5)
126
127 static void
128 expand_hash_table (struct bcache *bcache)
129 {
130 /* A table of good hash table sizes. Whenever we grow, we pick the
131 next larger size from this table. sizes[i] is close to 1 << (i+10),
132 so we roughly double the table size each time. After we fall off
133 the end of this table, we just double. Don't laugh --- there have
134 been executables sighted with a gigabyte of debug info. */
135 static unsigned long sizes[] = {
136 1021, 2053, 4099, 8191, 16381, 32771,
137 65537, 131071, 262144, 524287, 1048573, 2097143,
138 4194301, 8388617, 16777213, 33554467, 67108859, 134217757,
139 268435459, 536870923, 1073741827, 2147483659UL
140 };
141 unsigned int new_num_buckets;
142 struct bstring **new_buckets;
143 unsigned int i;
144
145 /* Count the stats. Every unique item needs to be re-hashed and
146 re-entered. */
147 bcache->expand_count++;
148 bcache->expand_hash_count += bcache->unique_count;
149
150 /* Find the next size. */
151 new_num_buckets = bcache->num_buckets * 2;
152 for (i = 0; i < (sizeof (sizes) / sizeof (sizes[0])); i++)
153 if (sizes[i] > bcache->num_buckets)
154 {
155 new_num_buckets = sizes[i];
156 break;
157 }
158
159 /* Allocate the new table. */
160 {
161 size_t new_size = new_num_buckets * sizeof (new_buckets[0]);
162
163 new_buckets = (struct bstring **) xmalloc (new_size);
164 memset (new_buckets, 0, new_size);
165
166 bcache->structure_size -= (bcache->num_buckets
167 * sizeof (bcache->bucket[0]));
168 bcache->structure_size += new_size;
169 }
170
171 /* Rehash all existing strings. */
172 for (i = 0; i < bcache->num_buckets; i++)
173 {
174 struct bstring *s, *next;
175
176 for (s = bcache->bucket[i]; s; s = next)
177 {
178 struct bstring **new_bucket;
179 next = s->next;
180
181 new_bucket = &new_buckets[(bcache->hash_function (&s->d.data,
182 s->length)
183 % new_num_buckets)];
184 s->next = *new_bucket;
185 *new_bucket = s;
186 }
187 }
188
189 /* Plug in the new table. */
190 if (bcache->bucket)
191 xfree (bcache->bucket);
192 bcache->bucket = new_buckets;
193 bcache->num_buckets = new_num_buckets;
194 }
195
196 \f
197 /* Looking up things in the bcache. */
198
199 /* The number of bytes needed to allocate a struct bstring whose data
200 is N bytes long. */
201 #define BSTRING_SIZE(n) (offsetof (struct bstring, d.data) + (n))
202
203 /* Find a copy of the LENGTH bytes at ADDR in BCACHE. If BCACHE has
204 never seen those bytes before, add a copy of them to BCACHE. In
205 either case, return a pointer to BCACHE's copy of that string. */
206 const void *
207 bcache (const void *addr, int length, struct bcache *cache)
208 {
209 return bcache_full (addr, length, cache, NULL);
210 }
211
212 /* Find a copy of the LENGTH bytes at ADDR in BCACHE. If BCACHE has
213 never seen those bytes before, add a copy of them to BCACHE. In
214 either case, return a pointer to BCACHE's copy of that string. If
215 optional ADDED is not NULL, return 1 in case of new entry or 0 if
216 returning an old entry. */
217
218 const void *
219 bcache_full (const void *addr, int length, struct bcache *bcache, int *added)
220 {
221 unsigned long full_hash;
222 unsigned short half_hash;
223 int hash_index;
224 struct bstring *s;
225
226 if (added)
227 *added = 0;
228
229 /* Lazily initialize the obstack. This can save quite a bit of
230 memory in some cases. */
231 if (bcache->total_count == 0)
232 {
233 /* We could use obstack_specify_allocation here instead, but
234 gdb_obstack.h specifies the allocation/deallocation
235 functions. */
236 obstack_init (&bcache->cache);
237 }
238
239 /* If our average chain length is too high, expand the hash table. */
240 if (bcache->unique_count >= bcache->num_buckets * CHAIN_LENGTH_THRESHOLD)
241 expand_hash_table (bcache);
242
243 bcache->total_count++;
244 bcache->total_size += length;
245
246 full_hash = bcache->hash_function (addr, length);
247
248 half_hash = (full_hash >> 16);
249 hash_index = full_hash % bcache->num_buckets;
250
251 /* Search the hash bucket for a string identical to the caller's.
252 As a short-circuit first compare the upper part of each hash
253 values. */
254 for (s = bcache->bucket[hash_index]; s; s = s->next)
255 {
256 if (s->half_hash == half_hash)
257 {
258 if (s->length == length
259 && bcache->compare_function (&s->d.data, addr, length))
260 return &s->d.data;
261 else
262 bcache->half_hash_miss_count++;
263 }
264 }
265
266 /* The user's string isn't in the list. Insert it after *ps. */
267 {
268 struct bstring *new
269 = obstack_alloc (&bcache->cache, BSTRING_SIZE (length));
270
271 memcpy (&new->d.data, addr, length);
272 new->length = length;
273 new->next = bcache->bucket[hash_index];
274 new->half_hash = half_hash;
275 bcache->bucket[hash_index] = new;
276
277 bcache->unique_count++;
278 bcache->unique_size += length;
279 bcache->structure_size += BSTRING_SIZE (length);
280
281 if (added)
282 *added = 1;
283
284 return &new->d.data;
285 }
286 }
287 \f
288
289 /* Compare the byte string at ADDR1 of lenght LENGHT to the
290 string at ADDR2. Return 1 if they are equal. */
291
292 static int
293 bcache_compare (const void *addr1, const void *addr2, int length)
294 {
295 return memcmp (addr1, addr2, length) == 0;
296 }
297
298 /* Allocating and freeing bcaches. */
299
300 /* Allocated a bcache. HASH_FUNCTION and COMPARE_FUNCTION can be used
301 to pass in custom hash, and compare functions to be used by this
302 bcache. If HASH_FUNCTION is NULL hash() is used and if
303 COMPARE_FUNCTION is NULL memcmp() is used. */
304
305 struct bcache *
306 bcache_xmalloc (unsigned long (*hash_function)(const void *, int length),
307 int (*compare_function)(const void *,
308 const void *,
309 int length))
310 {
311 /* Allocate the bcache pre-zeroed. */
312 struct bcache *b = XCNEW (struct bcache);
313
314 if (hash_function)
315 b->hash_function = hash_function;
316 else
317 b->hash_function = hash;
318
319 if (compare_function)
320 b->compare_function = compare_function;
321 else
322 b->compare_function = bcache_compare;
323 return b;
324 }
325
326 /* Free all the storage associated with BCACHE. */
327 void
328 bcache_xfree (struct bcache *bcache)
329 {
330 if (bcache == NULL)
331 return;
332 /* Only free the obstack if we actually initialized it. */
333 if (bcache->total_count > 0)
334 obstack_free (&bcache->cache, 0);
335 xfree (bcache->bucket);
336 xfree (bcache);
337 }
338
339
340 \f
341 /* Printing statistics. */
342
343 static void
344 print_percentage (int portion, int total)
345 {
346 if (total == 0)
347 /* i18n: Like "Percentage of duplicates, by count: (not applicable)". */
348 printf_filtered (_("(not applicable)\n"));
349 else
350 printf_filtered ("%3d%%\n", (int) (portion * 100.0 / total));
351 }
352
353
354 /* Print statistics on BCACHE's memory usage and efficacity at
355 eliminating duplication. NAME should describe the kind of data
356 BCACHE holds. Statistics are printed using `printf_filtered' and
357 its ilk. */
358 void
359 print_bcache_statistics (struct bcache *c, char *type)
360 {
361 int occupied_buckets;
362 int max_chain_length;
363 int median_chain_length;
364 int max_entry_size;
365 int median_entry_size;
366
367 /* Count the number of occupied buckets, tally the various string
368 lengths, and measure chain lengths. */
369 {
370 unsigned int b;
371 int *chain_length = XCNEWVEC (int, c->num_buckets + 1);
372 int *entry_size = XCNEWVEC (int, c->unique_count + 1);
373 int stringi = 0;
374
375 occupied_buckets = 0;
376
377 for (b = 0; b < c->num_buckets; b++)
378 {
379 struct bstring *s = c->bucket[b];
380
381 chain_length[b] = 0;
382
383 if (s)
384 {
385 occupied_buckets++;
386
387 while (s)
388 {
389 gdb_assert (b < c->num_buckets);
390 chain_length[b]++;
391 gdb_assert (stringi < c->unique_count);
392 entry_size[stringi++] = s->length;
393 s = s->next;
394 }
395 }
396 }
397
398 /* To compute the median, we need the set of chain lengths
399 sorted. */
400 qsort (chain_length, c->num_buckets, sizeof (chain_length[0]),
401 compare_positive_ints);
402 qsort (entry_size, c->unique_count, sizeof (entry_size[0]),
403 compare_positive_ints);
404
405 if (c->num_buckets > 0)
406 {
407 max_chain_length = chain_length[c->num_buckets - 1];
408 median_chain_length = chain_length[c->num_buckets / 2];
409 }
410 else
411 {
412 max_chain_length = 0;
413 median_chain_length = 0;
414 }
415 if (c->unique_count > 0)
416 {
417 max_entry_size = entry_size[c->unique_count - 1];
418 median_entry_size = entry_size[c->unique_count / 2];
419 }
420 else
421 {
422 max_entry_size = 0;
423 median_entry_size = 0;
424 }
425
426 xfree (chain_length);
427 xfree (entry_size);
428 }
429
430 printf_filtered (_(" Cached '%s' statistics:\n"), type);
431 printf_filtered (_(" Total object count: %ld\n"), c->total_count);
432 printf_filtered (_(" Unique object count: %lu\n"), c->unique_count);
433 printf_filtered (_(" Percentage of duplicates, by count: "));
434 print_percentage (c->total_count - c->unique_count, c->total_count);
435 printf_filtered ("\n");
436
437 printf_filtered (_(" Total object size: %ld\n"), c->total_size);
438 printf_filtered (_(" Unique object size: %ld\n"), c->unique_size);
439 printf_filtered (_(" Percentage of duplicates, by size: "));
440 print_percentage (c->total_size - c->unique_size, c->total_size);
441 printf_filtered ("\n");
442
443 printf_filtered (_(" Max entry size: %d\n"), max_entry_size);
444 printf_filtered (_(" Average entry size: "));
445 if (c->unique_count > 0)
446 printf_filtered ("%ld\n", c->unique_size / c->unique_count);
447 else
448 /* i18n: "Average entry size: (not applicable)". */
449 printf_filtered (_("(not applicable)\n"));
450 printf_filtered (_(" Median entry size: %d\n"), median_entry_size);
451 printf_filtered ("\n");
452
453 printf_filtered (_(" \
454 Total memory used by bcache, including overhead: %ld\n"),
455 c->structure_size);
456 printf_filtered (_(" Percentage memory overhead: "));
457 print_percentage (c->structure_size - c->unique_size, c->unique_size);
458 printf_filtered (_(" Net memory savings: "));
459 print_percentage (c->total_size - c->structure_size, c->total_size);
460 printf_filtered ("\n");
461
462 printf_filtered (_(" Hash table size: %3d\n"),
463 c->num_buckets);
464 printf_filtered (_(" Hash table expands: %lu\n"),
465 c->expand_count);
466 printf_filtered (_(" Hash table hashes: %lu\n"),
467 c->total_count + c->expand_hash_count);
468 printf_filtered (_(" Half hash misses: %lu\n"),
469 c->half_hash_miss_count);
470 printf_filtered (_(" Hash table population: "));
471 print_percentage (occupied_buckets, c->num_buckets);
472 printf_filtered (_(" Median hash chain length: %3d\n"),
473 median_chain_length);
474 printf_filtered (_(" Average hash chain length: "));
475 if (c->num_buckets > 0)
476 printf_filtered ("%3lu\n", c->unique_count / c->num_buckets);
477 else
478 /* i18n: "Average hash chain length: (not applicable)". */
479 printf_filtered (_("(not applicable)\n"));
480 printf_filtered (_(" Maximum hash chain length: %3d\n"),
481 max_chain_length);
482 printf_filtered ("\n");
483 }
484
485 int
486 bcache_memory_used (struct bcache *bcache)
487 {
488 if (bcache->total_count == 0)
489 return 0;
490 return obstack_memory_used (&bcache->cache);
491 }