]> git.xonotic.org Git - xonotic/gmqcc.git/blob - stat.c
Holy mexicans 15% better hashing == 5% faster compiles.
[xonotic/gmqcc.git] / stat.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Dale Weiler
4  *     Wolfgang Bumiller
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24
25 #include <string.h>
26 #include <stdlib.h>
27 #include <ctype.h>
28
29 #include "gmqcc.h"
30
31 /*
32  * GMQCC performs tons of allocations, constructions, and crazyness
33  * all around. When trying to optimizes systems, or just get fancy
34  * statistics out of the compiler, it's often printf mess. This file
35  * implements the statistics system of the compiler. I.E the allocator
36  * we use to track allocations, and other systems of interest.
37  */
38 #define ST_SIZE 1024
39
40 typedef struct stat_mem_block_s {
41     const char              *file;
42     size_t                   line;
43     size_t                   size;
44     struct stat_mem_block_s *next;
45     struct stat_mem_block_s *prev;
46 } stat_mem_block_t;
47
48 typedef struct {
49     size_t key;
50     size_t value;
51 } stat_size_entry_t, **stat_size_table_t;
52
53 static uint64_t          stat_mem_allocated         = 0;
54 static uint64_t          stat_mem_deallocated       = 0;
55 static uint64_t          stat_mem_allocated_total   = 0;
56 static uint64_t          stat_mem_deallocated_total = 0;
57 static uint64_t          stat_mem_high              = 0;
58 static uint64_t          stat_mem_peak              = 0;
59 static uint64_t          stat_used_strdups          = 0;
60 static uint64_t          stat_used_vectors          = 0;
61 static uint64_t          stat_used_hashtables       = 0;
62 static uint64_t          stat_type_vectors          = 0;
63 static uint64_t          stat_type_hashtables       = 0;
64 static stat_size_table_t stat_size_vectors          = NULL;
65 static stat_size_table_t stat_size_hashtables       = NULL;
66 static stat_mem_block_t *stat_mem_block_root        = NULL;
67
68 /*
69  * A tiny size_t key-value hashtbale for tracking vector and hashtable
70  * sizes. We can use it for other things too, if we need to. This is
71  * very TIGHT, and efficent in terms of space though.
72  */
73 static stat_size_table_t stat_size_new(void) {
74     return (stat_size_table_t)memset(
75         mem_a(sizeof(stat_size_entry_t) * ST_SIZE),
76         0, ST_SIZE * sizeof(stat_size_entry_t)
77     );
78 }
79
80 static void stat_size_del(stat_size_table_t table) {
81     size_t i = 0;
82     for (; i < ST_SIZE; i++) if(table[i]) mem_d(table[i]);
83     mem_d(table);
84 }
85
86 static stat_size_entry_t *stat_size_get(stat_size_table_t table, size_t key) {
87     size_t hash = (key % ST_SIZE);
88     while (table[hash] && table[hash]->key != key)
89         hash = (hash + 1) % ST_SIZE;
90     return table[hash];
91 }
92 static void stat_size_put(stat_size_table_t table, size_t key, size_t value) {
93     size_t hash = (key % ST_SIZE);
94     while (table[hash] && table[hash]->key != key)
95         hash = (hash + 1) % ST_SIZE;
96     table[hash]        = (stat_size_entry_t*)mem_a(sizeof(stat_size_entry_t));
97     table[hash]->key   = key;
98     table[hash]->value = value;
99 }
100
101 /*
102  * A basic header of information wrapper allocator. Simply stores
103  * information as a header, returns the memory + 1 past it, can be
104  * retrieved again with - 1. Where type is stat_mem_block_t*.
105  */
106 void *stat_mem_allocate(size_t size, size_t line, const char *file) {
107     stat_mem_block_t *info = (stat_mem_block_t*)malloc(sizeof(stat_mem_block_t) + size);
108     void             *data = (void*)(info + 1);
109
110     if(!info)
111         return NULL;
112
113     info->line = line;
114     info->size = size;
115     info->file = file;
116     info->prev = NULL;
117     info->next = stat_mem_block_root;
118
119     if (stat_mem_block_root)
120         stat_mem_block_root->prev = info;
121
122     stat_mem_block_root       = info;
123     stat_mem_allocated       += size;
124     stat_mem_high            += size;
125     stat_mem_allocated_total ++;
126
127     if (stat_mem_high > stat_mem_peak)
128         stat_mem_peak = stat_mem_high;
129
130     return data;
131 }
132
133 void stat_mem_deallocate(void *ptr) {
134     stat_mem_block_t *info = NULL;
135
136     if (!ptr)
137         return;
138
139     info = ((stat_mem_block_t*)ptr - 1);
140
141     stat_mem_deallocated       += info->size;
142     stat_mem_high              -= info->size;
143     stat_mem_deallocated_total ++;
144
145     if (info->prev) info->prev->next = info->next;
146     if (info->next) info->next->prev = info->prev;
147
148     /* move ahead */
149     if (info == stat_mem_block_root)
150         stat_mem_block_root = info->next;
151
152     free(info);
153 }
154
155 void *stat_mem_reallocate(void *ptr, size_t size, size_t line, const char *file) {
156     stat_mem_block_t *oldinfo = NULL;
157     stat_mem_block_t *newinfo;
158
159     if (!ptr)
160         return stat_mem_allocate(size, line, file);
161
162     /* stay consistent with glic */
163     if (!size) {
164         stat_mem_deallocate(ptr);
165         return NULL;
166     }
167
168     oldinfo = ((stat_mem_block_t*)ptr - 1);
169     newinfo = ((stat_mem_block_t*)malloc(sizeof(stat_mem_block_t) + size));
170
171     if (!newinfo) {
172         stat_mem_deallocate(ptr);
173         return NULL;
174     }
175
176     memcpy(newinfo+1, oldinfo+1, oldinfo->size);
177
178     if (oldinfo->prev) oldinfo->prev->next = oldinfo->next;
179     if (oldinfo->next) oldinfo->next->prev = oldinfo->prev;
180
181     /* move ahead */
182     if (oldinfo == stat_mem_block_root)
183         stat_mem_block_root = oldinfo->next;
184
185     newinfo->line = line;
186     newinfo->size = size;
187     newinfo->file = file;
188     newinfo->prev = NULL;
189     newinfo->next = stat_mem_block_root;
190
191     if (stat_mem_block_root)
192         stat_mem_block_root->prev = newinfo;
193
194     stat_mem_block_root = newinfo;
195     stat_mem_allocated -= oldinfo->size;
196     stat_mem_high      -= oldinfo->size;
197     stat_mem_allocated += newinfo->size;
198     stat_mem_high      += newinfo->size;
199
200     if (stat_mem_high > stat_mem_peak)
201         stat_mem_peak = stat_mem_high;
202
203     free(oldinfo);
204
205     return newinfo + 1;
206 }
207
208 /*
209  * strdup does it's own malloc, we need to track malloc. We don't want
210  * to overwrite malloc though, infact, we can't really hook it at all
211  * without library specific assumptions. So we re implement strdup.
212  */
213 char *stat_mem_strdup(const char *src, size_t line, const char *file, bool empty) {
214     size_t len = 0;
215     char  *ptr = NULL;
216
217     if (!src)
218         return NULL;
219
220     len = strlen(src);
221     if (((!empty) ? len : true) && (ptr = (char*)stat_mem_allocate(len + 1, line, file))) {
222         memcpy(ptr, src, len);
223         ptr[len] = '\0';
224     }
225
226     stat_used_strdups ++;
227     return ptr;
228 }
229
230 /*
231  * The reallocate function for resizing vectors.
232  */
233 void _util_vec_grow(void **a, size_t i, size_t s) {
234     vector_t          *d = vec_meta(*a);
235     size_t             m = 0;
236     stat_size_entry_t *e = NULL;
237     void              *p = NULL;
238
239     if (*a) {
240         m = 2 * d->allocated + i;
241         p = mem_r(d, s * m + sizeof(vector_t));
242     } else {
243         m = i + 1;
244         p = mem_a(s * m + sizeof(vector_t));
245         ((vector_t*)p)->used = 0;
246         stat_used_vectors++;
247     }
248
249     if (!stat_size_vectors)
250         stat_size_vectors = stat_size_new();
251
252     if ((e = stat_size_get(stat_size_vectors, s))) {
253         e->value ++;
254     } else {
255         stat_size_put(stat_size_vectors, s, 1); /* start off with 1 */
256         stat_type_vectors++;
257     }
258
259     *a = (vector_t*)p + 1;
260     vec_meta(*a)->allocated = m;
261 }
262
263 /*
264  * Hash table for generic data, based on dynamic memory allocations
265  * all around.  This is the internal interface, please look for
266  * EXPOSED INTERFACE comment below
267  */
268 typedef struct hash_node_t {
269     char               *key;   /* the key for this node in table */
270     void               *value; /* pointer to the data as void*   */
271     struct hash_node_t *next;  /* next node (linked list)        */
272 } hash_node_t;
273
274 /*
275  * This is a patched version of the Murmur2 hashing function to use
276  * a proper pre-mix and post-mix setup. Infact this is Murmur3 for
277  * the most part just reinvented.
278  * 
279  * Murmur 2 contains an inner loop such as:
280  * while (l >= 4) {
281  *      u32 k = *(u32*)d;
282  *      k *= m;
283  *      k ^= k >> r;
284  *      k *= m;
285  * 
286  *      h *= m;
287  *      h ^= k;
288  *      d += 4;
289  *      l -= 4;
290  * }
291  * 
292  * The two u32s that form the key are the same value x (pulled from data)
293  * this premix stage will be perform the same results for both. Unrolled
294  * this produces just:
295  *  x *= m;
296  *  x ^= x >> r;
297  *  x *= m;
298  *
299  *  h *= m;
300  *  h ^= x;
301  *  h *= m;
302  *  h ^= x;
303  * 
304  * This appears to be fine, except what happens when m == 1, well x
305  * cancels out entierly, leaving just:
306  *  x ^= x >> r;
307  *  h ^= x;
308  *  h ^= x;
309  * 
310  * So all keys hash to the same value, but how often does m == 1?
311  * well, it turns out testing x for all possible values yeilds only
312  * 172,013,942 unique results instead of 2^32. So nearly ~4.6 bits
313  * are cancelled out on average!
314  * 
315  * This means we have a 14.5% (rounded) chance of colliding more, which
316  * results in another bucket/chain for the hashtable.
317  *
318  * We fix it buy upgrading the pre and post mix ssystems to align with murmur
319  * hash 3.
320  */
321 #if 1
322 #define GMQCC_ROTL32(X, R) (((X) << (R)) | ((X) >> (32 - (R))))
323 GMQCC_INLINE size_t util_hthash(hash_table_t *ht, const char *key) {
324     const unsigned char *data   = (const unsigned char *)key;
325     const size_t         len    = strlen(key);
326     const size_t         block  = len / 4;
327     const uint32_t       mask1  = 0xCC9E2D51;
328     const uint32_t       mask2  = 0x1B873593;
329     const uint32_t      *blocks = (const uint32_t*)(data + block * 4);
330     const unsigned char *tail   = (const unsigned char *)(data + block * 4);
331
332     size_t   i;
333     uint32_t k;
334     uint32_t h = 0x1EF0 ^ len;
335
336     for (i = -block; i; i++) {
337         k  = blocks[i];
338         k *= mask1;
339         k  = GMQCC_ROTL32(k, 15);
340         k *= mask2;
341         h ^= k;
342         h  = GMQCC_ROTL32(h, 13);
343         h  = h * 5 + 0xE6546B64;
344     }
345
346     k = 0;
347     switch (len & 3) {
348         case 3:
349             k ^= tail[2] << 16;
350         case 2:
351             k ^= tail[1] << 8;
352         case 1:
353             k ^= tail[0];
354             k *= mask1;
355             k  = GMQCC_ROTL32(k, 15);
356             k *= mask2;
357             h ^= k;
358     }
359
360     h ^= len;
361     h ^= h >> 16;
362     h *= 0x85EBCA6B;
363     h ^= h >> 13;
364     h *= 0xC2B2AE35;
365     h ^= h >> 16;
366
367     return (size_t) (h % ht->size);
368 }
369 #undef GMQCC_ROTL32
370 #else
371 /* We keep the old for reference */
372 GMQCC_INLINE size_t util_hthash(hash_table_t *ht, const char *key) {
373     const uint32_t       mix   = 0x5BD1E995;
374     const uint32_t       rot   = 24;
375     size_t               size  = strlen(key);
376     uint32_t             hash  = 0x1EF0 /* LICRC TAB */  ^ size;
377     uint32_t             alias = 0;
378     const unsigned char *data  = (const unsigned char*)key;
379
380     while (size >= 4) {
381         alias  = (data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24));
382         alias *= mix;
383         alias ^= alias >> rot;
384         alias *= mix;
385
386         hash  *= mix;
387         hash  ^= alias;
388
389         data += 4;
390         size -= 4;
391     }
392
393     switch (size) {
394         case 3: hash ^= data[2] << 16;
395         case 2: hash ^= data[1] << 8;
396         case 1: hash ^= data[0];
397                 hash *= mix;
398     }
399
400     hash ^= hash >> 13;
401     hash *= mix;
402     hash ^= hash >> 15;
403
404     return (size_t) (hash % ht->size);
405 }
406 #endif
407
408 static hash_node_t *_util_htnewpair(const char *key, void *value) {
409     hash_node_t *node;
410     if (!(node = (hash_node_t*)mem_a(sizeof(hash_node_t))))
411         return NULL;
412
413     if (!(node->key = util_strdupe(key))) {
414         mem_d(node);
415         return NULL;
416     }
417
418     node->value = value;
419     node->next  = NULL;
420
421     return node;
422 }
423
424 /*
425  * EXPOSED INTERFACE for the hashtable implementation
426  * util_htnew(size)                             -- to make a new hashtable
427  * util_htset(table, key, value, sizeof(value)) -- to set something in the table
428  * util_htget(table, key)                       -- to get something from the table
429  * util_htdel(table)                            -- to delete the table
430  */
431 hash_table_t *util_htnew(size_t size) {
432     hash_table_t      *hashtable = NULL;
433     stat_size_entry_t *find      = NULL;
434
435     if (size < 1)
436         return NULL;
437
438     if (!stat_size_hashtables)
439         stat_size_hashtables = stat_size_new();
440
441     if (!(hashtable = (hash_table_t*)mem_a(sizeof(hash_table_t))))
442         return NULL;
443
444     if (!(hashtable->table = (hash_node_t**)mem_a(sizeof(hash_node_t*) * size))) {
445         mem_d(hashtable);
446         return NULL;
447     }
448
449     if ((find = stat_size_get(stat_size_hashtables, size)))
450         find->value++;
451     else {
452         stat_type_hashtables++;
453         stat_size_put(stat_size_hashtables, size, 1);
454     }
455
456     hashtable->size = size;
457     memset(hashtable->table, 0, sizeof(hash_node_t*) * size);
458
459     stat_used_hashtables++;
460     return hashtable;
461 }
462
463 void util_htseth(hash_table_t *ht, const char *key, size_t bin, void *value) {
464     hash_node_t *newnode = NULL;
465     hash_node_t *next    = NULL;
466     hash_node_t *last    = NULL;
467
468     next = ht->table[bin];
469
470     while (next && next->key && strcmp(key, next->key) > 0)
471         last = next, next = next->next;
472
473     /* already in table, do a replace */
474     if (next && next->key && strcmp(key, next->key) == 0) {
475         next->value = value;
476     } else {
477         /* not found, grow a pair man :P */
478         newnode = _util_htnewpair(key, value);
479         if (next == ht->table[bin]) {
480             newnode->next  = next;
481             ht->table[bin] = newnode;
482         } else if (!next) {
483             last->next = newnode;
484         } else {
485             newnode->next = next;
486             last->next = newnode;
487         }
488     }
489 }
490
491 void util_htset(hash_table_t *ht, const char *key, void *value) {
492     util_htseth(ht, key, util_hthash(ht, key), value);
493 }
494
495 void *util_htgeth(hash_table_t *ht, const char *key, size_t bin) {
496     hash_node_t *pair = ht->table[bin];
497
498     while (pair && pair->key && strcmp(key, pair->key) > 0)
499         pair = pair->next;
500
501     if (!pair || !pair->key || strcmp(key, pair->key) != 0)
502         return NULL;
503
504     return pair->value;
505 }
506
507 void *util_htget(hash_table_t *ht, const char *key) {
508     return util_htgeth(ht, key, util_hthash(ht, key));
509 }
510
511 void *code_util_str_htgeth(hash_table_t *ht, const char *key, size_t bin) {
512     hash_node_t *pair;
513     size_t len, keylen;
514     int cmp;
515
516     keylen = strlen(key);
517
518     pair = ht->table[bin];
519     while (pair && pair->key) {
520         len = strlen(pair->key);
521         if (len < keylen) {
522             pair = pair->next;
523             continue;
524         }
525         if (keylen == len) {
526             cmp = strcmp(key, pair->key);
527             if (cmp == 0)
528                 return pair->value;
529             if (cmp < 0)
530                 return NULL;
531             pair = pair->next;
532             continue;
533         }
534         cmp = strcmp(key, pair->key + len - keylen);
535         if (cmp == 0) {
536             uintptr_t up = (uintptr_t)pair->value;
537             up += len - keylen;
538             return (void*)up;
539         }
540         pair = pair->next;
541     }
542     return NULL;
543 }
544
545 /*
546  * Free all allocated data in a hashtable, this is quite the amount
547  * of work.
548  */
549 void util_htrem(hash_table_t *ht, void (*callback)(void *data)) {
550     size_t i = 0;
551
552     for (; i < ht->size; ++i) {
553         hash_node_t *n = ht->table[i];
554         hash_node_t *p;
555
556         /* free in list */
557         while (n) {
558             if (n->key)
559                 mem_d(n->key);
560             if (callback)
561                 callback(n->value);
562             p = n;
563             n = p->next;
564             mem_d(p);
565         }
566
567     }
568     /* free table */
569     mem_d(ht->table);
570     mem_d(ht);
571 }
572
573 void util_htrmh(hash_table_t *ht, const char *key, size_t bin, void (*cb)(void*)) {
574     hash_node_t **pair = &ht->table[bin];
575     hash_node_t *tmp;
576
577     while (*pair && (*pair)->key && strcmp(key, (*pair)->key) > 0)
578         pair = &(*pair)->next;
579
580     tmp = *pair;
581     if (!tmp || !tmp->key || strcmp(key, tmp->key) != 0)
582         return;
583
584     if (cb)
585         (*cb)(tmp->value);
586
587     *pair = tmp->next;
588     mem_d(tmp->key);
589     mem_d(tmp);
590 }
591
592 void util_htrm(hash_table_t *ht, const char *key, void (*cb)(void*)) {
593     util_htrmh(ht, key, util_hthash(ht, key), cb);
594 }
595
596 void util_htdel(hash_table_t *ht) {
597     util_htrem(ht, NULL);
598 }
599
600 /*
601  * The following functions below implement printing / dumping of statistical
602  * information.
603  */
604 static void stat_dump_mem_contents(stat_mem_block_t *memory, uint16_t cols) {
605     uint32_t i, j;
606     for (i = 0; i < memory->size + ((memory->size % cols) ? (cols - memory->size % cols) : 0); i++) {
607         if (i % cols == 0)    con_out(" 0x%06X: ", i);
608         if (i < memory->size) con_out("%02X " , 0xFF & ((unsigned char*)(memory + 1))[i]);
609         else                  con_out(" ");
610
611         if ((uint16_t)(i % cols) == (cols - 1)) {
612             for (j = i - (cols - 1); j <= i; j++) {
613                 con_out("%c",
614                     (j >= memory->size)
615                         ? ' '
616                         : (isprint(((unsigned char*)(memory + 1))[j]))
617                             ? 0xFF & ((unsigned char*)(memory + 1)) [j]
618                             : '.'
619                 );
620             }
621             con_out("\n");
622         }
623     }
624 }
625
626 static void stat_dump_mem_leaks(void) {
627     stat_mem_block_t *info;
628     for (info = stat_mem_block_root; info; info = info->next) {
629         con_out("lost: %u (bytes) at %s:%u\n",
630             info->size,
631             info->file,
632             info->line
633         );
634
635         stat_dump_mem_contents(info, OPTS_OPTION_U16(OPTION_MEMDUMPCOLS));
636     }
637 }
638
639 static void stat_dump_mem_info(void) {
640     con_out("Memory Information:\n\
641     Total allocations:   %llu\n\
642     Total deallocations: %llu\n\
643     Total allocated:     %f (MB)\n\
644     Total deallocated:   %f (MB)\n\
645     Total peak memory:   %f (MB)\n\
646     Total leaked memory: %f (MB) in %llu allocations\n",
647         stat_mem_allocated_total,
648         stat_mem_deallocated_total,
649         (float)(stat_mem_allocated)                        / 1048576.0f,
650         (float)(stat_mem_deallocated)                      / 1048576.0f,
651         (float)(stat_mem_peak)                             / 1048576.0f,
652         (float)(stat_mem_allocated - stat_mem_deallocated) / 1048576.0f,
653         stat_mem_allocated_total - stat_mem_deallocated_total
654     );
655 }
656
657 static void stat_dump_stats_table(stat_size_table_t table, const char *string, uint64_t *size) {
658     size_t i,j;
659
660     if (!table)
661         return;
662
663     for (i = 0, j = 1; i < ST_SIZE; i++) {
664         stat_size_entry_t *entry;
665
666         if (!(entry = table[i]))
667             continue;
668
669         con_out(string, (unsigned)j, (unsigned)entry->key, (unsigned)entry->value);
670         j++;
671
672         if (size)
673             *size += entry->key * entry->value;
674     }
675 }
676
677 void stat_info() {
678     if (OPTS_OPTION_BOOL(OPTION_MEMCHK) ||
679         OPTS_OPTION_BOOL(OPTION_STATISTICS)) {
680         uint64_t mem = 0;
681
682         con_out("Memory Statistics:\n\
683     Total vectors allocated:    %llu\n\
684     Total string duplicates:    %llu\n\
685     Total hashtables allocated: %llu\n\
686     Total unique vector sizes:  %llu\n",
687             stat_used_vectors,
688             stat_used_strdups,
689             stat_used_hashtables,
690             stat_type_vectors
691         );
692
693         stat_dump_stats_table (
694             stat_size_vectors,
695             "        %2u| # of %5u byte vectors: %u\n",
696             &mem
697         );
698
699         con_out (
700             "    Total unique hashtable sizes: %llu\n",
701             stat_type_hashtables
702         );
703
704         stat_dump_stats_table (
705             stat_size_hashtables,
706             "        %2u| # of %5u element hashtables: %u\n",
707             NULL
708         );
709
710         con_out (
711             "    Total vector memory:          %f (MB)\n\n",
712             (float)(mem) / 1048576.0f
713         );
714     }
715
716     if (stat_size_vectors)
717         stat_size_del(stat_size_vectors);
718     if (stat_size_hashtables)
719         stat_size_del(stat_size_hashtables);
720
721     if (OPTS_OPTION_BOOL(OPTION_DEBUG) ||
722         OPTS_OPTION_BOOL(OPTION_MEMCHK))
723         stat_dump_mem_info();
724
725     if (OPTS_OPTION_BOOL(OPTION_DEBUG))
726         stat_dump_mem_leaks();
727 }
728 #undef ST_SIZE