- do not clean up keep-alives here
[libfirm] / ir / ana / execfreq.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       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         query.idx  = -1;
116         return set_insert(set, &query, sizeof(query), HASH_PTR(irn));
117 }
118
119 double
120 get_block_execfreq(const ir_exec_freq *ef, const ir_node * irn)
121 {
122         if(!ef->infeasible) {
123                 set *freqs = ef->set;
124                 freq_t *freq;
125                 assert(is_Block(irn));
126                 freq = set_find_freq(freqs, irn);
127                 assert(freq);
128
129                 assert(freq->freq >= 0);
130                 return freq->freq;
131         }
132
133         return 1.0;
134 }
135
136 unsigned long
137 get_block_execfreq_ulong(const ir_exec_freq *ef, const ir_node *bb)
138 {
139         double f       = get_block_execfreq(ef, bb);
140         int res        = (int) (f > ef->min_non_zero ? ef->m * f + ef->b : 1.0);
141         return res;
142 }
143
144 static double *
145 solve_lgs(gs_matrix_t *mat, double *x, int size)
146 {
147         double init = 1.0 / size;
148         double dev;
149         int i, iter = 0;
150
151         /* better convergence. */
152         for (i = 0; i < size; ++i)
153                 x[i] = init;
154
155         stat_ev_dbl("execfreq_matrix_size", size);
156         stat_ev_tim_push();
157         do {
158                 ++iter;
159                 dev = gs_matrix_gauss_seidel(mat, x, size);
160         } while(fabs(dev) > SEIDEL_TOLERANCE);
161         stat_ev_tim_pop("execfreq_seidel_time");
162         stat_ev_dbl("execfreq_seidel_iter", iter);
163
164 #ifdef COMPARE_AGAINST_GAUSSJORDAN
165         {
166                 double *nw = XMALLOCN(double, size * size);
167                 double *nx = XMALLOCNZ(double, size);
168
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 = XMALLOCZ(ir_exec_freq);
216         execfreq->set = new_set(cmp_freq, 32);
217
218         memset(&execfreq->hook, 0, sizeof(execfreq->hook));
219         execfreq->hook.context = execfreq;
220         execfreq->hook.hook._hook_node_info = exec_freq_node_info;
221         register_hook(hook_node_info, &execfreq->hook);
222         (void) irg;
223
224         return execfreq;
225 }
226
227 void set_execfreq(ir_exec_freq *execfreq, const ir_node *block, double freq)
228 {
229         freq_t *f = set_insert_freq(execfreq->set, block);
230         f->freq = freq;
231 }
232
233 static void collect_blocks(ir_node *bl, void *data)
234 {
235         set *freqs = data;
236         set_insert_freq(freqs, bl);
237 }
238
239 ir_exec_freq *
240 compute_execfreq(ir_graph * irg, double loop_weight)
241 {
242         gs_matrix_t  *mat;
243         int           size;
244         int           idx;
245         freq_t       *freq, *s, *e;
246         ir_exec_freq *ef;
247         set          *freqs;
248         dfs_t        *dfs;
249         double       *x;
250         double        norm;
251
252         /*
253          * compute a DFS.
254          * using a toposort on the CFG (without back edges) will propagate
255          * the values better for the gauss/seidel iteration.
256          * => they can "flow" from start to end.
257          */
258         dfs = dfs_new(&absgraph_irg_cfg_succ, irg);
259         ef = XMALLOCZ(ir_exec_freq);
260         ef->min_non_zero = HUGE_VAL; /* initialize with a reasonable large number. */
261         freqs = ef->set = new_set(cmp_freq, dfs_get_n_nodes(dfs));
262
263         /*
264          * Populate the exec freq set.
265          * The DFS cannot be used alone, since the CFG might not be connected
266          * due to unreachable code.
267          */
268         irg_block_walk_graph(irg, collect_blocks, NULL, freqs);
269
270         construct_cf_backedges(irg);
271         edges_assure(irg);
272
273         size = dfs_get_n_nodes(dfs);
274         mat  = gs_new_matrix(size, size);
275         x    = XMALLOCN(double, size);
276
277         for (idx = dfs_get_n_nodes(dfs) - 1; idx >= 0; --idx) {
278                 ir_node *bb = (ir_node *) dfs_get_post_num_node(dfs, size - idx - 1);
279                 freq_t *freq;
280                 int i;
281
282                 freq = set_insert_freq(freqs, bb);
283                 freq->idx = idx;
284
285                 for(i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
286                         ir_node *pred = get_Block_cfgpred_block(bb, i);
287                         int pred_idx  = size - dfs_get_post_num(dfs, pred) - 1;
288
289                         gs_matrix_set(mat, idx, pred_idx, get_cf_probability(bb, i, loop_weight));
290                 }
291                 gs_matrix_set(mat, idx, idx, -1.0);
292         }
293
294         dfs_free(dfs);
295
296         /*
297          * Add a loop from end to start.
298          * The problem is then an eigenvalue problem:
299          * Solve A*x = 1*x => (A-I)x = 0
300          */
301         s = set_find_freq(freqs, get_irg_start_block(irg));
302         e = set_find_freq(freqs, get_irg_end_block(irg));
303         if (e->idx >= 0)
304                 gs_matrix_set(mat, s->idx, e->idx, 1.0);
305
306         /* solve the system and delete the matrix */
307         solve_lgs(mat, x, size);
308         gs_delete_matrix(mat);
309
310         /*
311          * compute the normalization factor.
312          * 1.0 / exec freq of start block.
313          */
314         norm = x[s->idx] != 0.0 ? 1.0 / x[s->idx] : 1.0;
315
316         ef->max = 0.0;
317         set_foreach(freqs, freq) {
318                 int idx = freq->idx;
319
320                 /* take abs because it sometimes can be -0 in case of endless loops */
321                 freq->freq = fabs(x[idx]) * norm;
322
323                 /* get the maximum exec freq */
324                 ef->max = MAX(ef->max, freq->freq);
325
326                 /* Get the minimum non-zero execution frequency. */
327                 if(freq->freq > 0.0)
328                         ef->min_non_zero = MIN(ef->min_non_zero, freq->freq);
329         }
330
331         /* compute m and b of the transformation used to convert the doubles into scaled ints */
332         {
333                 double smallest_diff = 1.0;
334
335                 double l2 = ef->min_non_zero;
336                 double h2 = ef->max;
337                 double l1 = 1.0;
338                 double h1 = MAX_INT_FREQ;
339
340                 double *fs = malloc(set_count(freqs) * sizeof(fs[0]));
341                 int i, j, n = 0;
342
343                 set_foreach(freqs, freq)
344                         fs[n++] = freq->freq;
345
346                 /*
347                  * find the smallest difference of the execution frequencies
348                  * we try to ressolve it with 1 integer.
349                  */
350                 for(i = 0; i < n; ++i) {
351                         if(fs[i] <= 0.0)
352                                 continue;
353
354                         for(j = i + 1; j < n; ++j) {
355                                 double diff = fabs(fs[i] - fs[j]);
356
357                                 if(!UNDEF(diff))
358                                         smallest_diff = MIN(diff, smallest_diff);
359                         }
360                 }
361
362                 /* according to that the slope of the translation function is 1.0 / smallest diff */
363                 ef->m = 1.0 / smallest_diff;
364
365                 /* the abscissa is then given by */
366                 ef->b = l1 - ef->m * l2;
367
368                 /*
369                  * if the slope is so high that the largest integer would be larger than MAX_INT_FREQ
370                  * set the largest int freq to that upper limit and recompute the translation function
371                  */
372                 if(ef->m * h2 + ef->b > MAX_INT_FREQ) {
373                         ef->m = (h1 - l1) / (h2 - l2);
374                         ef->b = l1 - ef->m * l2;
375                 }
376
377                 free(fs);
378         }
379
380         memset(&ef->hook, 0, sizeof(ef->hook));
381         ef->hook.context = ef;
382         ef->hook.hook._hook_node_info = exec_freq_node_info;
383         register_hook(hook_node_info, &ef->hook);
384
385         xfree(x);
386
387         return ef;
388 }
389
390 void
391 free_execfreq(ir_exec_freq *ef)
392 {
393         del_set(ef->set);
394         unregister_hook(hook_node_info, &ef->hook);
395         free(ef);
396 }