Add OALLOC*() to make allocating from obstacks a bit nicer.
[libfirm] / ir / stat / pattern.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   Statistics for Firm. Pattern history.
23  * @author  Michael Beck
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include <assert.h>
29 #include <stdlib.h>
30 #include <limits.h>
31
32 #include "ident.h"
33 #include "irnode_t.h"
34 #include "irgwalk.h"
35 #include "irprog.h"
36 #include "set.h"
37 #include "pset.h"
38 #include "counter.h"
39 #include "pattern_dmp.h"
40 #include "hashptr.h"
41
42 #ifdef FIRM_STATISTICS
43
44 /*
45  * just be make some things clear :-), the
46  * poor man "generics"
47  */
48 #define HASH_MAP(type) pset_##type
49
50 typedef pset pset_pattern_entry_t;
51
52 typedef unsigned char BYTE;
53
54 /** Maximum size of the pattern store. */
55 #define PATTERN_STORE_SIZE      2048
56
57
58 /**
59  * The code buffer.
60  */
61 typedef struct _code_buf_t {
62         BYTE     *next;    /**< Next byte address to be written. */
63         BYTE     *end;     /**< End address of the buffer. */
64         BYTE     *start;   /**< Start address of the buffer. */
65         unsigned hash;     /**< The hash value for the buffer content. */
66         unsigned overrun;  /**< flag set if the buffer was overrun */
67 } CODE_BUFFER;
68
69 /**
70  * Reserved VLC codes.
71  */
72 enum vlc_code_t {
73         VLC_7BIT       = 0x00,  /**< 8 bit code, carrying 7 bits payload */
74         VLC_14BIT      = 0x80,  /**< 16 bit code, carrying 14 bits payload */
75         VLC_21BIT      = 0xC0,  /**< 24 bit code, carrying 21 bits payload */
76         VLC_28BIT      = 0xE0,  /**< 32 bit code, carrying 28 bits payload */
77         VLC_32BIT      = 0xF0,  /**< 40 bit code, carrying 32 bits payload */
78
79         VLC_TAG_FIRST  = 0xF1,  /**< First possible tag value. */
80         VLC_TAG_ICONST = 0xFB,  /**< Encodes an integer constant. */
81         VLC_TAG_EMPTY  = 0xFC,  /**< Encodes an empty entity. */
82         VLC_TAG_OPTION = 0xFD,  /**< Options exists. */
83         VLC_TAG_REF    = 0xFE,  /**< Special tag, next code is an ID. */
84         VLC_TAG_END    = 0xFF,  /**< End tag. */
85 };
86
87 /*
88  * An entry for holding one pattern.
89  */
90 typedef struct _pattern_entry_t {
91         counter_t   count;        /**< Amount of pattern occurance. */
92         unsigned    len;          /**< The length of the VLC encoded buffer. */
93         BYTE        buf[1];       /**< The buffer containing the VLC encoded pattern. */
94 } pattern_entry_t;
95
96 /**
97  * Current options for the pattern matcher.
98  */
99 enum options_t {
100         OPT_WITH_MODE       = 0x00000001, /**< use modes */
101         OPT_ENC_DAG         = 0x00000002, /**< encode DAGs, not terms */
102         OPT_WITH_ICONST     = 0x00000004, /**< encode integer constants */
103         OPT_PERSIST_PATTERN = 0x00000008, /**< persistent pattern hash */
104 };
105
106
107 /**
108  * Pattern info.
109  */
110 typedef struct _pattern_info_t {
111         int                       enable;         /**< If non-zero, this module is enabled. */
112         struct obstack            obst;           /**< An obstack containing the counters. */
113         HASH_MAP(pattern_entry_t) *pattern_hash;  /**< A hash map containing the pattern. */
114         unsigned                  bound;          /**< Lowest value for pattern output. */
115         unsigned                  options;        /**< Current option mask. */
116         unsigned                  min_depth;      /**< Minimum pattern depth. */
117         unsigned                  max_depth;      /**< Maximum pattern depth. */
118 } pattern_info_t;
119
120 /*
121  * global status
122  */
123 static pattern_info_t _status, *status = &_status;
124
125 /**
126  * Compare two pattern for its occurance counter.
127  */
128 static int pattern_count_cmp(const void *elt, const void *key) {
129         int cmp;
130
131         pattern_entry_t **e1 = (pattern_entry_t **)elt;
132         pattern_entry_t **e2 = (pattern_entry_t **)key;
133
134         /* we want it sorted in descending order */
135         cmp = cnt_cmp(&(*e2)->count, &(*e1)->count);
136
137         return cmp;
138 }  /* pattern_count_cmp */
139
140 /**
141  * Compare two pattern for its pattern hash.
142  */
143 static int pattern_cmp(const void *elt, const void *key) {
144         const pattern_entry_t *e1 = elt;
145         const pattern_entry_t *e2 = key;
146         int diff = e1->len - e2->len;
147
148         if (diff)
149                 return diff;
150
151         return memcmp(e1->buf, e2->buf, e1->len);
152 }  /* pattern_cmp */
153
154 /**
155  * Initialize a code buffer.
156  *
157  * @param buf   the code buffer
158  * @param data  a buffer address
159  * @param len   the length of the data buffer
160  */
161 static void init_buf(CODE_BUFFER *buf, BYTE *data, unsigned len) {
162         buf->start   =
163         buf->next    = data;
164         buf->end     = data + len;
165         buf->hash    = 0x2BAD4;      /* An arbitrary seed. */
166         buf->overrun = 0;
167 }  /* init_buf */
168
169 /**
170  * Put a byte into the buffer.
171  *
172  * @param buf   the code buffer
173  * @param byte  the byte to write
174  *
175  * The hash value for the buffer content is updated.
176  */
177 static inline void put_byte(CODE_BUFFER *buf, BYTE byte) {
178         if (buf->next < buf->end) {
179                 *buf->next++ = byte;
180                 buf->hash = (buf->hash * 9) ^ byte;
181         } else {
182                 buf->overrun = 1;
183         }  /* if */
184 }  /* put_byte */
185
186 /**
187  * Returns the current length of a buffer.
188  *
189  * @param buf   the code buffer
190  *
191  * @return  the length of the buffer content
192  */
193 static unsigned buf_lenght(const CODE_BUFFER *buf) {
194         return buf->next - buf->start;
195 }  /* buf_lenght */
196
197 /**
198  * Returns the current content of a buffer.
199  *
200  * @param buf   the code buffer
201  *
202  * @return  the start address of the buffer content
203  */
204 static const BYTE *buf_content(const CODE_BUFFER *buf) {
205         return buf->start;
206 }  /* buf_content */
207
208 /**
209  * Returns the hash value of a buffer.
210  *
211  * @param buf   the code buffer
212  *
213  * @return  the hash value of the buffer content
214  */
215 static unsigned buf_hash(const CODE_BUFFER *buf) {
216         return buf->hash;
217 }  /* buf_hash */
218
219 /**
220  * Returns non-zero if a buffer overrun has occurred.
221  *
222  * @param buf   the code buffer
223  */
224 static unsigned buf_overrun(const CODE_BUFFER *buf) {
225         return buf->overrun;
226 }  /* buf_overrun */
227
228 /**
229  * Returns the next byte from the buffer WITHOUT dropping.
230  *
231  * @param buf   the code buffer
232  *
233  * @return  the next byte from the code buffer
234  */
235 static inline BYTE look_byte(CODE_BUFFER *buf) {
236         if (buf->next < buf->end)
237                 return *buf->next;
238         return VLC_TAG_END;
239 }  /* look_byte */
240
241 /**
242  * Returns the next byte from the buffer WITH dropping.
243  *
244  * @param buf   the code buffer
245  *
246  * @return  the next byte from the code buffer
247  */
248 static inline BYTE get_byte(CODE_BUFFER *buf) {
249         if (buf->next < buf->end)
250                 return *buf->next++;
251         return VLC_TAG_END;
252 }  /* get_byte */
253
254 #define BITS(n)   (1 << (n))
255
256 /**
257  * Put a 32bit value into the buffer.
258  *
259  * @param buf   the code buffer
260  * @param code  the code to be written into the buffer
261  */
262 static void put_code(CODE_BUFFER *buf, unsigned code) {
263         if (code < BITS(7)) {
264                 put_byte(buf, VLC_7BIT | code);
265         } else if (code < BITS(6 + 8)) {
266                 put_byte(buf, VLC_14BIT | (code >> 8));
267                 put_byte(buf, code);
268         } else if (code < BITS(5 + 8 + 8)) {
269                 put_byte(buf, VLC_21BIT | (code >> 16));
270                 put_byte(buf, code >> 8);
271                 put_byte(buf, code);
272         } else if (code < BITS(4 + 8 + 8 + 8)) {
273                 put_byte(buf, VLC_28BIT | (code >> 24));
274                 put_byte(buf, code >> 16);
275                 put_byte(buf, code >> 8);
276                 put_byte(buf, code);
277         } else {
278                 put_byte(buf, VLC_32BIT);
279                 put_byte(buf, code >> 24);
280                 put_byte(buf, code >> 16);
281                 put_byte(buf, code >> 8);
282                 put_byte(buf, code);
283         }  /* if */
284 }  /* put_code */
285
286 #define BIT_MASK(n) ((1 << (n)) - 1)
287
288 /**
289  * Get 32 bit from the buffer.
290  *
291  * @param buf   the code buffer
292  *
293  * @return  next 32bit value from the code buffer
294  */
295 static unsigned get_code(CODE_BUFFER *buf) {
296         unsigned code = get_byte(buf);
297
298         if (code < VLC_14BIT)
299                 return code;
300         if (code < VLC_21BIT)
301                 return ((code & BIT_MASK(6)) << 8) | get_byte(buf);
302         if (code < VLC_28BIT) {
303                 code  = ((code & BIT_MASK(5)) << 16) | (get_byte(buf) << 8);
304                 code |= get_byte(buf);
305                 return code;
306         }  /* if */
307         if (code < VLC_32BIT) {
308                 code  = ((code & BIT_MASK(4)) << 24) | (get_byte(buf) << 16);
309                 code |= get_byte(buf) <<  8;
310                 code |= get_byte(buf);
311                 return code;
312         }  /* if */
313         if (code == VLC_32BIT) {
314                 code  = get_byte(buf) << 24;
315                 code |= get_byte(buf) << 16;
316                 code |= get_byte(buf) <<  8;
317                 code |= get_byte(buf);
318                 return code;
319         }  /* if */
320         /* should not happen */
321         assert(0 && "Wrong code in buffer");
322
323         return 0;
324 }  /* get_code */
325
326 /**
327  * Put a tag into the buffer.
328  *
329  * @param buf   the code buffer
330  * @param tag   the tag to write to the code buffer
331  */
332 static void put_tag(CODE_BUFFER *buf, BYTE tag) {
333         assert(tag >= VLC_TAG_FIRST && "invalid tag");
334
335         put_byte(buf, tag);
336 }  /* put_tag */
337
338 /**
339  * Returns the next tag or zero if the next code isn't a tag.
340  *
341  * @param buf   the code buffer
342  *
343  * @return the next tag in the code buffer
344  */
345 static BYTE next_tag(CODE_BUFFER *buf) {
346         BYTE b = look_byte(buf);
347
348         if (b >= VLC_TAG_FIRST)
349                 return get_byte(buf);
350         return 0;
351 }  /* next_tag */
352
353 /**
354  * An Environment for the pattern encoder.
355  */
356 typedef struct _codec_enc_t {
357         CODE_BUFFER      *buf;      /**< The current code buffer. */
358         set              *id_set;   /**< A set containing all already seen Firm nodes. */
359         unsigned         curr_id;   /**< The current node id. */
360         unsigned         options;   /**< The encoding options. */
361         pattern_dumper_t *dmp;      /**< The dumper for the decoder. */
362 } codec_env_t;
363
364 /**
365  * An address entry.
366  */
367 typedef struct _addr_entry_t {
368         void *addr;     /**< the address */
369         unsigned id;    /**< associated ID */
370 } addr_entry_t;
371
372 /**
373  * Compare two addresses.
374  */
375 static int addr_cmp(const void *p1, const void *p2, size_t size) {
376         const addr_entry_t *e1 = p1;
377         const addr_entry_t *e2 = p2;
378         (void) size;
379
380         return e1->addr != e2->addr;
381 }  /* addr_cmp */
382
383 /**
384  * Encodes an IR-node, recursive worker.
385  *
386  * @return reached depth
387  */
388 static int _encode_node(ir_node *node, int max_depth, codec_env_t *env) {
389         addr_entry_t entry, *r_entry;
390         set_entry *s_entry;
391         int i, preds;
392         int res, depth;
393
394         ir_opcode code = get_irn_opcode(node);
395
396         /* insert the node into our ID map */
397         entry.addr = node;
398         entry.id   = env->curr_id;
399
400         s_entry = set_hinsert(env->id_set, &entry, sizeof(entry), HASH_PTR(node));
401         r_entry = (addr_entry_t *)s_entry->dptr;
402
403         if (r_entry->id != env->curr_id) {
404                 /* already in the map, add an REF */
405                 put_tag(env->buf, VLC_TAG_REF);
406                 put_code(env->buf, r_entry->id);
407
408                 return max_depth;
409         } else {
410                 /* a new entry, proceed */
411                 ++env->curr_id;
412         }  /* if */
413
414         put_code(env->buf, (unsigned)code);
415
416         /* do we need the mode ? */
417         if (env->options & OPT_WITH_MODE) {
418                 ir_mode *mode = get_irn_mode(node);
419
420                 if (mode)
421                         put_code(env->buf, stat_find_mode_index(mode));
422                 else
423                         put_tag(env->buf, VLC_TAG_EMPTY);
424         }  /* if */
425
426         /* do we need integer constants */
427         if (env->options & OPT_WITH_ICONST) {
428                 if (code == iro_Const) {
429                         tarval *tv = get_Const_tarval(node);
430
431                         if (tarval_is_long(tv)) {
432                                 long v = get_tarval_long(tv);
433
434                                 put_tag(env->buf, VLC_TAG_ICONST);
435                                 put_code(env->buf, v);
436                         }  /* if */
437                 }  /* if */
438         }  /* if */
439
440         --max_depth;
441
442         if (max_depth <= 0) {
443                 put_code(env->buf, 0);
444                 return max_depth;
445         } /* if */
446
447         preds = get_irn_arity(node);
448         put_code(env->buf, preds);
449
450         res = INT_MAX;
451         if (is_op_commutative(get_irn_op(node))) {
452                 ir_node *l = get_binop_left(node);
453                 ir_node *r = get_binop_right(node);
454                 int opcode_diff = (int)get_irn_opcode(l) - (int)get_irn_opcode(r);
455
456                 if (opcode_diff > 0) {
457                         ir_node *t = l;
458                         l = r;
459                         r = t;
460                 } else if (opcode_diff == 0 && l != r) {
461                         /* Both nodes have the same opcode, but are different.
462                            Need a better method here to decide which goes to the left side. */
463                 }  /* if */
464
465                 /* special handling for commutative operators */
466                 depth = _encode_node(l, max_depth, env);
467                 if (depth < res)
468                         res = depth;
469                 depth = _encode_node(r, max_depth, env);
470                 if (depth < res)
471                         res = depth;
472         } else {
473                 for (i = 0; i < preds; ++i) {
474                         ir_node *n = get_irn_n(node, i);
475
476                         depth = _encode_node(n, max_depth, env);
477                         if (depth < res)
478                                 res = depth;
479                 }  /* for */
480         }  /* if */
481         return res;
482 }  /* _encode_node */
483
484 /**
485  * Encode a DAG starting by the IR-node node.
486  *
487  * @param node       The root node of the graph
488  * @param buf        The code buffer to store the bitstring in
489  * @param max_depth  The maximum depth for descending
490  *
491  * @return The depth of the encoded graph (without cycles)
492  */
493 static int encode_node(ir_node *node, CODE_BUFFER *buf, int max_depth) {
494         codec_env_t env;
495         int         res;
496
497         /* initialize the encoder environment */
498         env.buf     = buf;
499         env.curr_id = 1;  /* 0 is used for special purpose */
500         env.options = status->options;
501         env.dmp     = NULL;
502
503         if (env.options & OPT_ENC_DAG)
504                 env.id_set = new_set(addr_cmp, 32);
505         else
506                 env.id_set = NULL;
507
508         /* encode options if any for the decoder */
509         if (env.options) {
510                 put_tag(buf, VLC_TAG_OPTION);
511                 put_code(buf, env.options);
512         }  /* if */
513
514         res = _encode_node(node, max_depth, &env);
515
516         if (env.id_set != NULL)
517                 del_set(env.id_set);
518
519         return max_depth - res;
520 }  /* encode_node */
521
522 /**
523  * Decode an IR-node, recursive walker.
524  */
525 static void _decode_node(unsigned parent, int position, codec_env_t *env) {
526         unsigned code;
527         unsigned op_code;
528         unsigned mode_code = 0;
529         long iconst;
530         void *attr = NULL;
531
532         code = next_tag(env->buf);
533         if (code == VLC_TAG_REF) { /* it's a REF */
534                 code = get_code(env->buf);
535
536                 /* dump the edge */
537                 if (parent) {
538                         int edge_mode = 0;
539                         /*
540                          * the mode of a Firm edge can be either computed from its target or
541                          * from its source and position. We must take the second approach because
542                          * we don't know the target here, it's a ref.
543                          */
544                         pattern_dump_edge(env->dmp, code, parent, position, edge_mode);
545                 }  /* if */
546
547                 /* dump the node ref */
548                 pattern_dump_ref(env->dmp, code);
549
550                 return;
551         }  /* if */
552
553         /* get the opcode */
554         op_code = get_code(env->buf);
555
556         /* get the mode if encoded */
557         if (env->options & OPT_WITH_MODE) {
558                 if (next_tag(env->buf) != VLC_TAG_EMPTY) {
559                         mode_code = get_code(env->buf);
560                 }  /* if */
561         }  /* if */
562
563         /* check, if a ICONST attribute is given */
564         if (next_tag(env->buf) == VLC_TAG_ICONST) {
565                 iconst = get_code(env->buf);
566                 attr   = &iconst;
567         }  /* if */
568
569         /* dump the edge */
570         if (parent) {
571                 int edge_mode = 0;
572
573                 /*
574                  * the mode of a Firm edge can be either computed from its target or
575                  * from its source and position. We take the second approach because
576                  * we need it anyway for ref's.
577                  */
578                 pattern_dump_edge(env->dmp, env->curr_id, parent, position, edge_mode);
579         }  /* if */
580
581         /* dump the node */
582         parent = env->curr_id;
583         pattern_dump_node(env->dmp, parent, op_code, mode_code, attr);
584
585         /* ok, we have a new ID */
586         ++env->curr_id;
587
588         code = next_tag(env->buf);
589         if (code != VLC_TAG_END) {
590                 /* more info, do recursion */
591                 int i, preds;
592
593                 preds = get_code(env->buf);
594                 if (preds > 0) {
595                         pattern_start_children(env->dmp, parent);
596                         for (i = 0; i < preds; ++i) {
597                                 _decode_node(parent, i, env);
598                         }  /* for */
599                         pattern_finish_children(env->dmp, parent);
600                 }  /* if */
601         }  /* if */
602 }  /* _decode_node */
603
604 /**
605  * Decode an IR-node.
606  */
607 static void decode_node(BYTE *b, unsigned len, pattern_dumper_t *dump) {
608         codec_env_t env;
609         CODE_BUFFER buf;
610         unsigned code, options = 0;
611
612         init_buf(&buf, b, len);
613
614         env.buf     = &buf;
615         env.curr_id = 1;  /* 0 is used for special purpose */
616         env.dmp     = dump;
617
618         /* decode options */
619         code = next_tag(&buf);
620         if (code == VLC_TAG_OPTION) {
621                 options = get_code(&buf);
622         }  /* if */
623         env.options = options;
624
625         _decode_node(0, 0, &env);
626 }  /* decode_node */
627
628 /**
629  * The environment for the pattern calculation.
630  */
631 typedef struct _pattern_env {
632         int max_depth;    /**< maximum depth for pattern generation. */
633 } pattern_env_t;
634
635 /**
636  * Returns the associates pattern_entry_t for a CODE_BUF.
637  *
638  * @param buf  the code buffer
639  * @param set  the hash table containing all pattern entries
640  *
641  * @return   the associated pattern_entry_t for the given code buffer
642  *
643  * If the code content was never seen before, a new pattern_entry is created
644  * and returned.
645  */
646 static pattern_entry_t *pattern_get_entry(CODE_BUFFER *buf, pset *set) {
647         pattern_entry_t *key, *elem;
648         unsigned len = buf_lenght(buf);
649         unsigned hash;
650
651         key = OALLOCF(&status->obst, pattern_entry_t, buf, len);
652         key->len = len;
653         memcpy(key->buf, buf_content(buf), len);
654
655         hash = buf_hash(buf);
656
657         elem = pset_find(set, key, hash);
658         if (elem != NULL) {
659                 obstack_free(&status->obst, key);
660                 return elem;
661         }  /* if */
662
663         cnt_clr(&key->count);
664         return pset_insert(set, key, hash);
665 }  /* pattern_get_entry */
666
667 /**
668  * Increase the count for a pattern.
669  *
670  * @param buf    the code buffer containing the pattern
671  * @param depth  the pattern depth
672  *
673  * @note Single node patterns are ignored
674  */
675 static void count_pattern(CODE_BUFFER *buf, int depth) {
676         pattern_entry_t *entry;
677
678         /* ignore single node pattern (i.e. constants) */
679         if (depth > 1) {
680                 entry = pattern_get_entry(buf, status->pattern_hash);
681
682                 /* increase count */
683                 cnt_inc(&entry->count);
684         }  /* if */
685 }  /* count_pattern */
686
687 /**
688  * Pre-walker for nodes pattern calculation.
689  */
690 static void calc_nodes_pattern(ir_node *node, void *ctx) {
691         pattern_env_t   *env = ctx;
692         BYTE            buffer[PATTERN_STORE_SIZE];
693         CODE_BUFFER     buf;
694         int             depth;
695
696         init_buf(&buf, buffer, sizeof(buffer));
697         depth = encode_node(node, &buf, env->max_depth);
698
699         if (buf_overrun(&buf)) {
700                 fprintf(stderr, "Pattern store: buffer overrun at size %u. Pattern ignored.\n", (unsigned) sizeof(buffer));
701         } else
702                 count_pattern(&buf, depth);
703 }  /* calc_nodes_pattern */
704
705 /**
706  * Store all collected patterns.
707  *
708  * @param fname  filename for storage
709  */
710 static void store_pattern(const char *fname) {
711         FILE *f;
712         pattern_entry_t *entry;
713         int i, count = pset_count(status->pattern_hash);
714
715         if (count <= 0)
716                 return;
717
718         f = fopen(fname, "wb");
719         if (! f) {
720                 perror(fname);
721                 return;
722         }  /* if */
723
724         fwrite("FPS1", 4, 1, f);
725         fwrite(&count, sizeof(count), 1, f);
726
727         for (i = 0, entry = pset_first(status->pattern_hash);
728              entry && i < count;
729              entry = pset_next(status->pattern_hash), ++i) {
730                 fwrite(entry, offsetof(pattern_entry_t, buf) + entry->len, 1, f);
731         }  /* for */
732         fclose(f);
733 }  /* store_pattern */
734
735 /**
736  * Read collected patterns from a file.
737  *
738  * @param fname  filename
739  */
740 static HASH_MAP(pattern_entry_t) *read_pattern(const char *fname) {
741         FILE *f;
742         pattern_entry_t *entry, tmp;
743         int i, count;
744         unsigned j;
745         char magic[4];
746         HASH_MAP(pattern_entry_t) *pattern_hash = new_pset(pattern_cmp, 8);
747         BYTE            buffer[PATTERN_STORE_SIZE];
748         CODE_BUFFER     buf;
749
750         f = fopen(fname, "rb");
751         if (! f) {
752                 perror(fname);
753                 return NULL;
754         }  /* if */
755
756         fread(magic, 4, 1, f);
757         count = 0;
758         fread(&count, sizeof(count), 1, f);
759         if (memcmp(magic, "FPS1", 4) != 0 || count <= 0) {
760                 fprintf(stderr, "Error: %s is not a Firm pattern store. Ignored.\n", fname);
761                 fclose(f);
762                 return NULL;
763         }  /* if */
764
765         /* read all pattern entries and put them into the hash table. */
766         for (i = 0; i < count; ++i) {
767                 init_buf(&buf, buffer, sizeof(buffer));
768                 fread(&tmp, offsetof(pattern_entry_t, buf), 1, f);
769                 for (j = 0; j < tmp.len; ++j)
770                         put_byte(&buf, fgetc(f));
771                 entry = pattern_get_entry(&buf, pattern_hash);
772                 memcpy(&entry->count, &tmp.count, sizeof(entry->count));
773         }  /* for */
774         fclose(f);
775
776         printf("Read %d pattern from %s\n", count, fname);
777         assert(pset_count(pattern_hash) == count);
778
779         return pattern_hash;
780 }  /* read_pattern */
781
782 /**
783  * Write the collected patterns to a VCG file for inspection.
784  *
785  * @param fname  name of the VCG file to create
786  */
787 static void pattern_output(const char *fname) {
788         pattern_entry_t  *entry;
789         pattern_entry_t  **pattern_arr;
790         pattern_dumper_t *dump;
791         int i, count = pset_count(status->pattern_hash);
792
793         printf("\n%d pattern detected\n", count);
794
795         if (count <= 0)
796                 return;
797
798         /* creates a dumper */
799         dump = new_vcg_dumper(fname, 100);
800
801         pattern_arr = XMALLOCN(pattern_entry_t*, count);
802         for (i = 0, entry = pset_first(status->pattern_hash);
803              entry && i < count;
804              entry = pset_next(status->pattern_hash), ++i) {
805                 pattern_arr[i] =  entry;
806         }  /* for */
807         assert(count == i);
808         count = i;
809
810         /* sort it */
811         qsort(pattern_arr, count, sizeof(*pattern_arr), pattern_count_cmp);
812
813         for (i = 0; i < count; ++i) {
814                 entry = pattern_arr[i];
815                 if (cnt_to_uint(&entry->count) < status->bound)
816                         continue;
817
818                 /* dump a pattern */
819                 pattern_dump_new_pattern(dump, &entry->count);
820                 decode_node(entry->buf, entry->len, dump);
821                 pattern_dump_finish_pattern(dump);
822         }  /* for */
823
824         /* destroy it */
825         pattern_end(dump);
826 }  /* pattern_output */
827
828 /*
829  * Calculates the pattern history.
830  */
831 void stat_calc_pattern_history(ir_graph *irg) {
832         pattern_env_t env;
833         unsigned      i;
834
835         if (! status->enable)
836                 return;
837
838         /* do NOT count the const code IRG */
839         if (irg == get_const_code_irg())
840                 return;
841
842         for (i = status->min_depth; i <= status->max_depth; ++i) {
843                 env.max_depth = i;
844                 irg_walk_graph(irg, calc_nodes_pattern, NULL, &env);
845         }  /* for */
846 }  /* stat_calc_pattern_history */
847
848 /*
849  * Initializes the pattern history.
850  */
851 void stat_init_pattern_history(int enable) {
852         HASH_MAP(pattern_entry_t) *pattern_hash = NULL;
853
854         status->enable = enable;
855         if (! enable)
856                 return;
857
858         status->bound     = 10;
859         status->options   = /* OPT_WITH_MODE | */ OPT_ENC_DAG | OPT_WITH_ICONST | OPT_PERSIST_PATTERN;
860         status->min_depth = 3;
861         status->max_depth = 5;
862
863         obstack_init(&status->obst);
864
865         /* create the hash-table */
866         if (status->options & OPT_PERSIST_PATTERN)
867                 pattern_hash = read_pattern("pattern.fps");
868         if (pattern_hash == NULL)
869                 pattern_hash = new_pset(pattern_cmp, 8);
870         status->pattern_hash = pattern_hash;
871 }  /* stat_init_pattern_history */
872
873 /*
874  * Finish the pattern history.
875  */
876 void stat_finish_pattern_history(const char *fname) {
877         (void) fname;
878         if (! status->enable)
879                 return;
880
881         store_pattern("pattern.fps");
882         pattern_output("pattern.vcg");
883
884         del_pset(status->pattern_hash);
885         obstack_free(&status->obst, NULL);
886
887         status->enable = 0;
888 }  /* stat_finish_pattern_history */
889
890 #endif /* FIRM_STATISTICS */