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