fixed warnings
[libfirm] / ir / stat / pattern.c
1 /*
2  * Copyright (C) 1995-2007 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 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <assert.h>
31 #include <stdlib.h>
32 #include <limits.h>
33
34 #include "ident.h"
35 #include "irnode_t.h"
36 #include "irgwalk.h"
37 #include "irprog.h"
38 #include "set.h"
39 #include "pset.h"
40 #include "counter.h"
41 #include "pattern_dmp.h"
42 #include "hashptr.h"
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                         /* FIXME: not 64bit save */
422                         put_code(env->buf, (unsigned)mode);
423                 else
424                         put_tag(env->buf, VLC_TAG_EMPTY);
425         }  /* if */
426
427         /* do we need integer constants */
428         if (env->options & OPT_WITH_ICONST) {
429                 if (code == iro_Const) {
430                         tarval *tv = get_Const_tarval(node);
431
432                         if (tarval_is_long(tv)) {
433                                 long v = get_tarval_long(tv);
434
435                                 put_tag(env->buf, VLC_TAG_ICONST);
436                                 put_code(env->buf, v);
437                         }  /* if */
438                 }  /* if */
439         }  /* if */
440
441         --max_depth;
442
443         if (max_depth <= 0) {
444                 put_code(env->buf, 0);
445                 return max_depth;
446         } /* if */
447
448         preds = get_irn_arity(node);
449         put_code(env->buf, preds);
450
451         res = INT_MAX;
452         if (is_op_commutative(get_irn_op(node))) {
453                 ir_node *l = get_binop_left(node);
454                 ir_node *r = get_binop_right(node);
455                 int opcode_diff = (int)get_irn_opcode(l) - (int)get_irn_opcode(r);
456
457                 if (opcode_diff > 0) {
458                         ir_node *t = l;
459                         l = r;
460                         r = t;
461                 } else if (opcode_diff == 0 && l != r) {
462                         /* Both nodes have the same opcode, but are different.
463                            Need a better method here to decide which goes to the left side. */
464                 }  /* if */
465
466                 /* special handling for commutative operators */
467                 depth = _encode_node(l, max_depth, env);
468                 if (depth < res)
469                         res = depth;
470                 depth = _encode_node(r, max_depth, env);
471                 if (depth < res)
472                         res = depth;
473         } else {
474                 for (i = 0; i < preds; ++i) {
475                         ir_node *n = get_irn_n(node, i);
476
477                         depth = _encode_node(n, max_depth, env);
478                         if (depth < res)
479                                 res = depth;
480                 }  /* for */
481         }  /* if */
482         return res;
483 }  /* _encode_node */
484
485 /**
486  * Encode a DAG starting by the IR-node node.
487  *
488  * @param node       The root node of the graph
489  * @param buf        The code buffer to store the bitstring in
490  * @param max_depth  The maximum depth for descending
491  *
492  * @return The depth of the encoded graph (without cycles)
493  */
494 static int encode_node(ir_node *node, CODE_BUFFER *buf, int max_depth) {
495         codec_env_t env;
496         int         res;
497
498         /* initialize the encoder environment */
499         env.buf     = buf;
500         env.curr_id = 1;  /* 0 is used for special purpose */
501         env.options = status->options;
502         env.dmp     = NULL;
503
504         if (env.options & OPT_ENC_DAG)
505                 env.id_set = new_set(addr_cmp, 32);
506         else
507                 env.id_set = NULL;
508
509         /* encode options if any for the decoder */
510         if (env.options) {
511                 put_tag(buf, VLC_TAG_OPTION);
512                 put_code(buf, env.options);
513         }  /* if */
514
515         res = _encode_node(node, max_depth, &env);
516
517         if (env.id_set != NULL)
518                 del_set(env.id_set);
519
520         return max_depth - res;
521 }  /* encode_node */
522
523 /**
524  * Decode an IR-node, recursive walker.
525  */
526 static void _decode_node(unsigned parent, int position, codec_env_t *env) {
527         unsigned code;
528         unsigned op_code;
529         unsigned mode_code = 0;
530         long iconst;
531         void *attr = NULL;
532
533         code = next_tag(env->buf);
534         if (code == VLC_TAG_REF) { /* it's a REF */
535                 code = get_code(env->buf);
536
537                 /* dump the edge */
538                 if (parent) {
539                         int edge_mode = 0;
540                         /*
541                          * the mode of a Firm edge can be either computed from its target or
542                          * from its source and position. We must take the second approach because
543                          * we don't know the target here, it's a ref.
544                          */
545                         pattern_dump_edge(env->dmp, code, parent, position, edge_mode);
546                 }  /* if */
547
548                 /* dump the node ref */
549                 pattern_dump_ref(env->dmp, code);
550
551                 return;
552         }  /* if */
553
554         /* get the opcode */
555         op_code = get_code(env->buf);
556
557         /* get the mode if encoded */
558         if (env->options & OPT_WITH_MODE) {
559                 if (next_tag(env->buf) != VLC_TAG_EMPTY) {
560                         mode_code = get_code(env->buf);
561                 }  /* if */
562         }  /* if */
563
564         /* check, if a ICONST attribute is given */
565         if (next_tag(env->buf) == VLC_TAG_ICONST) {
566                 iconst = get_code(env->buf);
567                 attr   = &iconst;
568         }  /* if */
569
570         /* dump the edge */
571         if (parent) {
572                 int edge_mode = 0;
573
574                 /*
575                  * the mode of a Firm edge can be either computed from its target or
576                  * from its source and position. We take the second approach because
577                  * we need it anyway for ref's.
578                  */
579                 pattern_dump_edge(env->dmp, env->curr_id, parent, position, edge_mode);
580         }  /* if */
581
582         /* dump the node */
583         parent = env->curr_id;
584         pattern_dump_node(env->dmp, parent, op_code, mode_code, attr);
585
586         /* ok, we have a new ID */
587         ++env->curr_id;
588
589         code = next_tag(env->buf);
590         if (code != VLC_TAG_END) {
591                 /* more info, do recursion */
592                 int i, preds;
593
594                 preds = get_code(env->buf);
595                 if (preds > 0) {
596                         pattern_start_children(env->dmp, parent);
597                         for (i = 0; i < preds; ++i) {
598                                 _decode_node(parent, i, env);
599                         }  /* for */
600                         pattern_finish_children(env->dmp, parent);
601                 }  /* if */
602         }  /* if */
603 }  /* _decode_node */
604
605 /**
606  * Decode an IR-node.
607  */
608 static void decode_node(BYTE *b, unsigned len, pattern_dumper_t *dump) {
609         codec_env_t env;
610         CODE_BUFFER buf;
611         unsigned code, options = 0;
612
613         init_buf(&buf, b, len);
614
615         env.buf     = &buf;
616         env.curr_id = 1;  /* 0 is used for special purpose */
617         env.dmp     = dump;
618
619         /* decode options */
620         code = next_tag(&buf);
621         if (code == VLC_TAG_OPTION) {
622                 options = get_code(&buf);
623         }  /* if */
624         env.options = options;
625
626         _decode_node(0, 0, &env);
627 }  /* decode_node */
628
629 /**
630  * The environment for the pattern calculation.
631  */
632 typedef struct _pattern_env {
633         int max_depth;    /**< maximum depth for pattern generation. */
634 } pattern_env_t;
635
636 /**
637  * Returns the associates pattern_entry_t for a CODE_BUF.
638  *
639  * @param buf  the code buffer
640  * @param set  the hash table containing all pattern entries
641  *
642  * @return   the associated pattern_entry_t for the given code buffer
643  *
644  * If the code content was never seen before, a new pattern_entry is created
645  * and returned.
646  */
647 static pattern_entry_t *pattern_get_entry(CODE_BUFFER *buf, pset *set) {
648         pattern_entry_t *key, *elem;
649         unsigned len = buf_lenght(buf);
650         unsigned hash;
651
652         key = obstack_alloc(&status->obst, offsetof(pattern_entry_t, buf) + len);
653         assert(key);
654
655         key->len = len;
656         memcpy(key->buf, buf_content(buf), len);
657
658         hash = buf_hash(buf);
659
660         elem = pset_find(set, key, hash);
661         if (elem != NULL) {
662                 obstack_free(&status->obst, key);
663                 return elem;
664         }  /* if */
665
666         cnt_clr(&key->count);
667         return pset_insert(set, key, hash);
668 }  /* pattern_get_entry */
669
670 /**
671  * Increase the count for a pattern.
672  *
673  * @param buf    the code buffer containing the pattern
674  * @param depth  the pattern depth
675  *
676  * @note Single node patterns are ignored
677  */
678 static void count_pattern(CODE_BUFFER *buf, int depth) {
679         pattern_entry_t *entry;
680
681         /* ignore single node pattern (i.e. constants) */
682         if (depth > 1) {
683                 entry = pattern_get_entry(buf, status->pattern_hash);
684
685                 /* increase count */
686                 cnt_inc(&entry->count);
687         }  /* if */
688 }  /* count_pattern */
689
690 /**
691  * Pre-walker for nodes pattern calculation.
692  */
693 static void calc_nodes_pattern(ir_node *node, void *ctx) {
694         pattern_env_t   *env = ctx;
695         BYTE            buffer[PATTERN_STORE_SIZE];
696         CODE_BUFFER     buf;
697         int             depth;
698
699         init_buf(&buf, buffer, sizeof(buffer));
700         depth = encode_node(node, &buf, env->max_depth);
701
702         if (buf_overrun(&buf)) {
703                 fprintf(stderr, "Pattern store: buffer overrun at size %d. Pattern ignored.\n", sizeof(buffer));
704         } else
705                 count_pattern(&buf, depth);
706 }  /* calc_nodes_pattern */
707
708 /**
709  * Store all collected patterns.
710  *
711  * @param fname  filename for storage
712  */
713 static void store_pattern(const char *fname) {
714         FILE *f;
715         pattern_entry_t *entry;
716         int i, count = pset_count(status->pattern_hash);
717
718         if (count <= 0)
719                 return;
720
721         f = fopen(fname, "wb");
722         if (! f) {
723                 perror(fname);
724                 return;
725         }  /* if */
726
727         fwrite("FPS1", 4, 1, f);
728         fwrite(&count, sizeof(count), 1, f);
729
730         for (i = 0, entry = pset_first(status->pattern_hash);
731              entry && i < count;
732              entry = pset_next(status->pattern_hash), ++i) {
733                 fwrite(entry, offsetof(pattern_entry_t, buf) + entry->len, 1, f);
734         }  /* for */
735         fclose(f);
736 }  /* store_pattern */
737
738 /**
739  * Read collected patterns from a file.
740  *
741  * @param fname  filename
742  */
743 static HASH_MAP(pattern_entry_t) *read_pattern(const char *fname) {
744         FILE *f;
745         pattern_entry_t *entry, tmp;
746         int i, count;
747         unsigned j;
748         char magic[4];
749         HASH_MAP(pattern_entry_t) *pattern_hash = new_pset(pattern_cmp, 8);
750         BYTE            buffer[PATTERN_STORE_SIZE];
751         CODE_BUFFER     buf;
752
753         f = fopen(fname, "rb");
754         if (! f) {
755                 perror(fname);
756                 return NULL;
757         }  /* if */
758
759         fread(magic, 4, 1, f);
760         count = 0;
761         fread(&count, sizeof(count), 1, f);
762         if (memcmp(magic, "FPS1", 4) != 0 || count <= 0) {
763                 fprintf(stderr, "Error: %s is not a Firm pattern store. Ignored.\n", fname);
764                 fclose(f);
765                 return NULL;
766         }  /* if */
767
768         /* read all pattern entries and put them into the hash table. */
769         for (i = 0; i < count; ++i) {
770                 init_buf(&buf, buffer, sizeof(buffer));
771                 fread(&tmp, offsetof(pattern_entry_t, buf), 1, f);
772                 for (j = 0; j < tmp.len; ++j)
773                         put_byte(&buf, fgetc(f));
774                 entry = pattern_get_entry(&buf, pattern_hash);
775                 memcpy(&entry->count, &tmp.count, sizeof(entry->count));
776         }  /* for */
777         fclose(f);
778
779         printf("Read %d pattern from %s\n", count, fname);
780         assert(pset_count(pattern_hash) == count);
781
782         return pattern_hash;
783 }  /* read_pattern */
784
785 /**
786  * Write the collected patterns to a VCG file for inspection.
787  *
788  * @param fname  name of the VCG file to create
789  */
790 static void pattern_output(const char *fname) {
791         pattern_entry_t  *entry;
792         pattern_entry_t  **pattern_arr;
793         pattern_dumper_t *dump;
794         int i, count = pset_count(status->pattern_hash);
795
796         printf("\n%d pattern detected\n", count);
797
798         if (count <= 0)
799                 return;
800
801         /* creates a dumper */
802         dump = new_vcg_dumper(fname, 100);
803
804         pattern_arr = xmalloc(sizeof(*pattern_arr) * count);
805         for (i = 0, entry = pset_first(status->pattern_hash);
806              entry && i < count;
807              entry = pset_next(status->pattern_hash), ++i) {
808                 pattern_arr[i] =  entry;
809         }  /* for */
810         assert(count == i);
811         count = i;
812
813         /* sort it */
814         qsort(pattern_arr, count, sizeof(*pattern_arr), pattern_count_cmp);
815
816         for (i = 0; i < count; ++i) {
817                 entry = pattern_arr[i];
818                 if (cnt_to_uint(&entry->count) < status->bound)
819                         continue;
820
821                 /* dump a pattern */
822                 pattern_dump_new_pattern(dump, &entry->count);
823                 decode_node(entry->buf, entry->len, dump);
824                 pattern_dump_finish_pattern(dump);
825         }  /* for */
826
827         /* destroy it */
828         pattern_end(dump);
829 }  /* pattern_output */
830
831 /*
832  * Calculates the pattern history.
833  */
834 void stat_calc_pattern_history(ir_graph *irg) {
835         pattern_env_t env;
836         unsigned      i;
837
838         if (! status->enable)
839                 return;
840
841         /* do NOT count the const code IRG */
842         if (irg == get_const_code_irg())
843                 return;
844
845         for (i = status->min_depth; i <= status->max_depth; ++i) {
846                 env.max_depth = i;
847                 irg_walk_graph(irg, calc_nodes_pattern, NULL, &env);
848         }  /* for */
849 }  /* stat_calc_pattern_history */
850
851 /*
852  * Initializes the pattern history.
853  */
854 void stat_init_pattern_history(int enable) {
855         HASH_MAP(pattern_entry_t) *pattern_hash = NULL;
856
857         status->enable = enable;
858         if (! enable)
859                 return;
860
861         status->bound     = 10;
862         status->options   = /* OPT_WITH_MODE | */ OPT_ENC_DAG | OPT_WITH_ICONST | OPT_PERSIST_PATTERN;
863         status->min_depth = 3;
864         status->max_depth = 5;
865
866         obstack_init(&status->obst);
867
868         /* create the hash-table */
869         if (status->options & OPT_PERSIST_PATTERN)
870                 pattern_hash = read_pattern("pattern.fps");
871         if (pattern_hash == NULL)
872                 pattern_hash = new_pset(pattern_cmp, 8);
873         status->pattern_hash = pattern_hash;
874 }  /* stat_init_pattern_history */
875
876 /*
877  * Finish the pattern history.
878  */
879 void stat_finish_pattern_history(const char *fname) {
880         (void) fname;
881         if (! status->enable)
882                 return;
883
884         store_pattern("pattern.fps");
885         pattern_output("pattern.vcg");
886
887         del_pset(status->pattern_hash);
888         obstack_free(&status->obst, NULL);
889
890         status->enable = 0;
891 }  /* stat_finish_pattern_history */