Cmp(Conv(x), 0) -> Cmp(x, 0) if dest mode ist wider than source mode.
[libfirm] / ir / ana / execfreq.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       Compute an estimate of basic block executions.
23  * @author      Adam M. Szalkowski
24  * @date        28.05.2006
25  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <limits.h>
34 #include <math.h>
35
36 #include "gaussseidel.h"
37
38 #include "firm_common_t.h"
39 #include "set.h"
40 #include "hashptr.h"
41 #include "debug.h"
42 #include "statev.h"
43 #include "dfs_t.h"
44 #include "absgraph.h"
45
46 #include "irprog_t.h"
47 #include "irgraph_t.h"
48 #include "irnode_t.h"
49 #include "irloop.h"
50 #include "irgwalk.h"
51 #include "iredges.h"
52 #include "irprintf.h"
53 #include "irtools.h"
54 #include "irhooks.h"
55
56 #include "execfreq.h"
57
58 /* enable to also solve the equations with Gauss-Jordan */
59 #undef COMPARE_AGAINST_GAUSSJORDAN
60
61 #ifdef COMPARE_AGAINST_GAUSSJORDAN
62 #include "gaussjordan.h"
63 #endif
64
65
66 #define EPSILON              1e-5
67 #define UNDEF(x)         (fabs(x) < EPSILON)
68 #define SEIDEL_TOLERANCE 1e-7
69
70 #define MAX_INT_FREQ 1000000
71
72 #define set_foreach(s,i) for((i)=set_first((s)); (i); (i)=set_next((s)))
73
74 typedef struct _freq_t {
75         const ir_node    *irn;
76         int               idx;
77         double            freq;
78 } freq_t;
79
80 struct ir_exec_freq {
81         set *set;
82         hook_entry_t hook;
83         double max;
84         double min_non_zero;
85         double m, b;
86         unsigned infeasible : 1;
87 };
88
89 static int
90 cmp_freq(const void *a, const void *b, size_t size)
91 {
92         const freq_t *p = a;
93         const freq_t *q = b;
94         (void) size;
95
96         return !(p->irn == q->irn);
97 }
98
99 static freq_t *
100 set_find_freq(set * set, const ir_node * irn)
101 {
102         freq_t     query;
103
104         query.irn = irn;
105         return set_find(set, &query, sizeof(query), HASH_PTR(irn));
106 }
107
108 static freq_t *
109 set_insert_freq(set * set, const ir_node * irn)
110 {
111         freq_t query;
112
113         query.irn = irn;
114         query.freq = 0.0;
115         return set_insert(set, &query, sizeof(query), HASH_PTR(irn));
116 }
117
118 double
119 get_block_execfreq(const ir_exec_freq *ef, const ir_node * irn)
120 {
121         if(!ef->infeasible) {
122                 set *freqs = ef->set;
123                 freq_t *freq;
124                 assert(is_Block(irn));
125                 freq = set_find_freq(freqs, irn);
126                 assert(freq);
127
128                 assert(freq->freq >= 0);
129                 return freq->freq;
130         }
131
132         return 1.0;
133 }
134
135 unsigned long
136 get_block_execfreq_ulong(const ir_exec_freq *ef, const ir_node *bb)
137 {
138         double f       = get_block_execfreq(ef, bb);
139         int res        = (int) (f > ef->min_non_zero ? ef->m * f + ef->b : 1.0);
140         return res;
141 }
142
143 static double *
144 solve_lgs(gs_matrix_t *mat, double *x, int size)
145 {
146         double init = 1.0 / size;
147         double dev;
148         int i, iter = 0;
149
150         /* better convergence. */
151         for (i = 0; i < size; ++i)
152                 x[i] = init;
153
154         stat_ev_dbl("execfreq_matrix_size", size);
155         stat_ev_tim_push();
156         do {
157                 ++iter;
158                 dev = gs_matrix_gauss_seidel(mat, x, size);
159         } while(fabs(dev) > SEIDEL_TOLERANCE);
160         stat_ev_tim_pop("execfreq_seidel_time");
161         stat_ev_dbl("execfreq_seidel_iter", iter);
162
163 #ifdef COMPARE_AGAINST_GAUSSJORDAN
164         {
165                 double *nw = xmalloc(size * size * sizeof(*nw));
166                 double *nx = xmalloc(size * sizeof(*nx));
167
168                 memset(nx, 0, size * sizeof(*nx));
169                 gs_matrix_export(mat, nw, size);
170
171                 stat_ev_tim_push();
172                 firm_gaussjordansolve(nw, nx, size);
173                 stat_ev_tim_pop("execfreq_jordan_time");
174
175                 xfree(nw);
176                 xfree(nx);
177         }
178 #endif
179
180         return x;
181 }
182
183 static double
184 get_cf_probability(ir_node *bb, int pos, double loop_weight)
185 {
186         double  sum = 0.0;
187         double  cur = 0.0;
188         const ir_node *pred = get_Block_cfgpred_block(bb, pos);
189         const ir_loop *pred_loop = get_irn_loop(pred);
190         int pred_depth = get_loop_depth(pred_loop);
191         const ir_edge_t *edge;
192
193         cur = get_loop_depth(get_irn_loop(bb)) < get_loop_depth(get_irn_loop(pred)) ? 1.0 : loop_weight;
194
195         foreach_block_succ(pred, edge) {
196                 const ir_node *block = get_edge_src_irn(edge);
197                 const ir_loop *loop = get_irn_loop(block);
198                 int depth = get_loop_depth(loop);
199                 sum += depth < pred_depth ? 1.0 : loop_weight;
200         }
201
202         return cur/sum;
203 }
204
205 static void exec_freq_node_info(void *ctx, FILE *f, const ir_node *irn)
206 {
207         if(is_Block(irn)) {
208                 ir_exec_freq *ef = ctx;
209                 fprintf(f, "execution frequency: %g/%lu\n", get_block_execfreq(ef, irn), get_block_execfreq_ulong(ef, irn));
210         }
211 }
212
213 ir_exec_freq *create_execfreq(ir_graph *irg)
214 {
215         ir_exec_freq *execfreq = xmalloc(sizeof(execfreq[0]));
216         memset(execfreq, 0, sizeof(execfreq[0]));
217         execfreq->set = new_set(cmp_freq, 32);
218
219         memset(&execfreq->hook, 0, sizeof(execfreq->hook));
220         execfreq->hook.context = execfreq;
221         execfreq->hook.hook._hook_node_info = exec_freq_node_info;
222         register_hook(hook_node_info, &execfreq->hook);
223         (void) irg;
224
225         return execfreq;
226 }
227
228 void set_execfreq(ir_exec_freq *execfreq, const ir_node *block, double freq)
229 {
230         freq_t *f = set_insert_freq(execfreq->set, block);
231         f->freq = freq;
232 }
233
234 ir_exec_freq *
235 compute_execfreq(ir_graph * irg, double loop_weight)
236 {
237         gs_matrix_t  *mat;
238         int           size;
239         int           idx;
240         freq_t       *freq, *s, *e;
241         ir_exec_freq *ef;
242         set          *freqs;
243         dfs_t        *dfs;
244         double       *x;
245         double        norm;
246
247         /*
248          * compute a DFS.
249          * using a toposort on the CFG (without back edges) will propagate
250          * the values better for the gauss/seidel iteration.
251          * => they can "flow" from start to end.
252          */
253         dfs = dfs_new(&absgraph_irg_cfg_succ, irg);
254         ef = xmalloc(sizeof(ef[0]));
255         memset(ef, 0, sizeof(ef[0]));
256         ef->min_non_zero = HUGE_VAL; /* initialize with a reasonable large number. */
257         freqs = ef->set = new_set(cmp_freq, 32);
258
259         construct_cf_backedges(irg);
260         /* TODO: edges are corrupt for EDGE_KIND_BLOCK after the local optimize
261                  graph phase merges blocks in the x86 backend */
262         edges_deactivate(irg);
263         edges_activate(irg);
264         /* edges_assure(irg); */
265
266         size = dfs_get_n_nodes(dfs);
267         mat  = gs_new_matrix(size, size);
268         x    = xmalloc(size*sizeof(*x));
269
270         for (idx = dfs_get_n_nodes(dfs) - 1; idx >= 0; --idx) {
271                 ir_node *bb = (ir_node *) dfs_get_post_num_node(dfs, size - idx - 1);
272                 freq_t *freq;
273                 int i;
274
275                 freq = set_insert_freq(freqs, bb);
276                 freq->idx = idx;
277
278                 gs_matrix_set(mat, idx, idx, -1.0);
279                 for(i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
280                         ir_node *pred = get_Block_cfgpred_block(bb, i);
281                         int pred_idx  = size - dfs_get_post_num(dfs, pred) - 1;
282
283                         gs_matrix_set(mat, idx, pred_idx, get_cf_probability(bb, i, loop_weight));
284                 }
285         }
286
287         /*
288          * Add a loop from end to start.
289          * The problem is then an eigenvalue problem:
290          * Solve A*x = 1*x => (A-I)x = 0
291          */
292         s = set_find_freq(freqs, get_irg_start_block(irg));
293         e = set_find_freq(freqs, get_irg_end_block(irg));
294         gs_matrix_set(mat, s->idx, e->idx, 1.0);
295
296         /* solve the system and delete the matrix */
297         solve_lgs(mat, x, size);
298         gs_delete_matrix(mat);
299
300         /*
301          * compute the normalization factor.
302          * 1.0 / exec freq of start block.
303          */
304         assert(x[s->idx] > 0.0);
305         norm = 1.0 / x[s->idx];
306
307         ef->max = 0.0;
308         set_foreach(freqs, freq) {
309                 int idx = freq->idx;
310
311                 /* freq->freq = UNDEF(x[idx]) ? EPSILON : x[idx]; */
312                 /* TODO: Do we need the check for zero? */
313                 freq->freq = x[idx] * norm;
314
315                 /* get the maximum exec freq */
316                 ef->max = MAX(ef->max, freq->freq);
317
318                 /* Get the minimum non-zero execution frequency. */
319                 if(freq->freq > 0.0)
320                         ef->min_non_zero = MIN(ef->min_non_zero, freq->freq);
321         }
322
323         /* compute m and b of the transformation used to convert the doubles into scaled ints */
324         {
325                 double smallest_diff = 1.0;
326
327                 double l2 = ef->min_non_zero;
328                 double h2 = ef->max;
329                 double l1 = 1.0;
330                 double h1 = MAX_INT_FREQ;
331
332                 double *fs = malloc(set_count(freqs) * sizeof(fs[0]));
333                 int i, j, n = 0;
334
335                 set_foreach(freqs, freq)
336                         fs[n++] = freq->freq;
337
338                 /*
339                  * find the smallest difference of the execution frequencies
340                  * we try to ressolve it with 1 integer.
341                  */
342                 for(i = 0; i < n; ++i) {
343                         if(fs[i] <= 0.0)
344                                 continue;
345
346                         for(j = i + 1; j < n; ++j) {
347                                 double diff = fabs(fs[i] - fs[j]);
348
349                                 if(!UNDEF(diff))
350                                         smallest_diff = MIN(diff, smallest_diff);
351                         }
352                 }
353
354                 /* according to that the slope of the translation function is 1.0 / smallest diff */
355                 ef->m = 1.0 / smallest_diff;
356
357                 /* the abscissa is then given by */
358                 ef->b = l1 - ef->m * l2;
359
360                 /*
361                  * if the slope is so high that the largest integer would be larger than MAX_INT_FREQ
362                  * set the largest int freq to that upper limit and recompute the translation function
363                  */
364                 if(ef->m * h2 + ef->b > MAX_INT_FREQ) {
365                         ef->m = (h1 - l1) / (h2 - l2);
366                         ef->b = l1 - ef->m * l2;
367                 }
368
369                 free(fs);
370         }
371
372         memset(&ef->hook, 0, sizeof(ef->hook));
373         ef->hook.context = ef;
374         ef->hook.hook._hook_node_info = exec_freq_node_info;
375         register_hook(hook_node_info, &ef->hook);
376
377         xfree(x);
378
379         return ef;
380 }
381
382 void
383 free_execfreq(ir_exec_freq *ef)
384 {
385         del_set(ef->set);
386         unregister_hook(hook_node_info, &ef->hook);
387         free(ef);
388 }