Use foreach_out_edge_safe() instead of reimplementing it.
[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  */
26 #include "config.h"
27
28 #include <stdio.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <math.h>
32
33 #include "gaussseidel.h"
34
35 #include "set.h"
36 #include "hashptr.h"
37 #include "debug.h"
38 #include "statev.h"
39 #include "dfs_t.h"
40 #include "absgraph.h"
41
42 #include "irprog_t.h"
43 #include "irgraph_t.h"
44 #include "irnode_t.h"
45 #include "irloop.h"
46 #include "irgwalk.h"
47 #include "iredges.h"
48 #include "irouts.h"
49 #include "irprintf.h"
50 #include "util.h"
51 #include "irhooks.h"
52
53 #include "execfreq.h"
54
55 /* enable to also solve the equations with Gauss-Jordan */
56 #undef COMPARE_AGAINST_GAUSSJORDAN
57
58 #ifdef COMPARE_AGAINST_GAUSSJORDAN
59 #include "gaussjordan.h"
60 #endif
61
62
63 #define EPSILON          1e-5
64 #define UNDEF(x)         (fabs(x) < EPSILON)
65 #define SEIDEL_TOLERANCE 1e-7
66
67 #define MAX_INT_FREQ 1000000
68
69 typedef struct freq_t {
70         const ir_node    *irn;
71         int               idx;
72         double            freq;
73 } freq_t;
74
75 struct ir_exec_freq {
76         set *freqs;
77         hook_entry_t hook;
78         double max;
79         double min_non_zero;
80         double m, b;
81         unsigned infeasible : 1;
82 };
83
84 static int cmp_freq(const void *a, const void *b, size_t size)
85 {
86         const freq_t *p = (const freq_t*) a;
87         const freq_t *q = (const freq_t*) b;
88         (void) size;
89
90         return !(p->irn == q->irn);
91 }
92
93 static freq_t *set_find_freq(set *freqs, const ir_node *irn)
94 {
95         freq_t query;
96         query.irn = irn;
97         return set_find(freq_t, freqs, &query, sizeof(query), hash_ptr(irn));
98 }
99
100 static freq_t *set_insert_freq(set *freqs, const ir_node *irn)
101 {
102         freq_t query;
103
104         query.irn = irn;
105         query.freq = 0.0;
106         query.idx  = -1;
107         return set_insert(freq_t, freqs, &query, sizeof(query), hash_ptr(irn));
108 }
109
110 double get_block_execfreq(const ir_exec_freq *ef, const ir_node *irn)
111 {
112         if (!ef->infeasible) {
113                 set *freqs = ef->freqs;
114                 freq_t *freq;
115                 assert(is_Block(irn));
116                 freq = set_find_freq(freqs, irn);
117                 assert(freq);
118
119                 assert(freq->freq >= 0);
120                 return freq->freq;
121         }
122
123         return 1.0;
124 }
125
126 unsigned long
127 get_block_execfreq_ulong(const ir_exec_freq *ef, const ir_node *bb)
128 {
129         double f       = get_block_execfreq(ef, bb);
130         int res        = (int) (f > ef->min_non_zero ? ef->m * f + ef->b : 1.0);
131         return res;
132 }
133
134 static double *solve_lgs(gs_matrix_t *mat, double *x, int size)
135 {
136         double init = 1.0 / size;
137         double dev;
138         int i, iter = 0;
139
140         /* better convergence. */
141         for (i = 0; i < size; ++i)
142                 x[i] = init;
143
144         stat_ev_dbl("execfreq_matrix_size", size);
145         stat_ev_tim_push();
146         do {
147                 ++iter;
148                 dev = gs_matrix_gauss_seidel(mat, x, size);
149         } while (fabs(dev) > SEIDEL_TOLERANCE);
150         stat_ev_tim_pop("execfreq_seidel_time");
151         stat_ev_dbl("execfreq_seidel_iter", iter);
152
153 #ifdef COMPARE_AGAINST_GAUSSJORDAN
154         {
155                 double *nw = XMALLOCN(double, size * size);
156                 double *nx = XMALLOCNZ(double, size);
157
158                 gs_matrix_export(mat, nw, size);
159
160                 stat_ev_tim_push();
161                 firm_gaussjordansolve(nw, nx, size);
162                 stat_ev_tim_pop("execfreq_jordan_time");
163
164                 xfree(nw);
165                 xfree(nx);
166         }
167 #endif
168
169         return x;
170 }
171
172 /*
173  * Determine probability that predecessor pos takes this cf edge.
174  */
175 static double get_cf_probability(ir_node *bb, int pos, double loop_weight)
176 {
177         double           sum = 0.0;
178         double           cur = 1.0;
179         double           inv_loop_weight = 1./loop_weight;
180         const ir_node   *pred = get_Block_cfgpred_block(bb, pos);
181         const ir_loop   *pred_loop;
182         int              pred_depth;
183         const ir_edge_t *edge;
184         const ir_loop   *loop;
185         int              depth;
186         int              d;
187
188         if (is_Bad(pred))
189                 return 0;
190
191         loop       = get_irn_loop(bb);
192         depth      = get_loop_depth(loop);
193         pred_loop  = get_irn_loop(pred);
194         pred_depth = get_loop_depth(pred_loop);
195
196         for (d = depth; d < pred_depth; ++d) {
197                 cur *= inv_loop_weight;
198         }
199
200         foreach_block_succ(pred, edge) {
201                 const ir_node *succ       = get_edge_src_irn(edge);
202                 const ir_loop *succ_loop  = get_irn_loop(succ);
203                 int            succ_depth = get_loop_depth(succ_loop);
204
205                 double         fac = 1.0;
206                 for (d = succ_depth; d < pred_depth; ++d) {
207                         fac *= inv_loop_weight;
208                 }
209                 sum += fac;
210         }
211
212         return cur/sum;
213 }
214
215 static void exec_freq_node_info(void *ctx, FILE *f, const ir_node *irn)
216 {
217         ir_exec_freq *ef = (ir_exec_freq*) ctx;
218         if (!is_Block(irn))
219                 return;
220
221         fprintf(f, "execution frequency: %g/%lu\n", get_block_execfreq(ef, irn), get_block_execfreq_ulong(ef, irn));
222 }
223
224 ir_exec_freq *create_execfreq(ir_graph *irg)
225 {
226         ir_exec_freq *execfreq = XMALLOCZ(ir_exec_freq);
227         execfreq->freqs = new_set(cmp_freq, 32);
228
229         memset(&execfreq->hook, 0, sizeof(execfreq->hook));
230
231         // set reasonable values to convert double execfreq to ulong execfreq
232         execfreq->m = 1.0;
233
234         execfreq->hook.context = execfreq;
235         execfreq->hook.hook._hook_node_info = exec_freq_node_info;
236         register_hook(hook_node_info, &execfreq->hook);
237         (void) irg;
238
239         return execfreq;
240 }
241
242 void set_execfreq(ir_exec_freq *execfreq, const ir_node *block, double freq)
243 {
244         freq_t *f = set_insert_freq(execfreq->freqs, block);
245         f->freq = freq;
246 }
247
248 static void collect_blocks(ir_node *bl, void *data)
249 {
250         set *freqs = (set*) data;
251         set_insert_freq(freqs, bl);
252 }
253
254 ir_exec_freq *compute_execfreq(ir_graph *irg, double loop_weight)
255 {
256         gs_matrix_t  *mat;
257         int           size;
258         int           n_keepalives;
259         int           idx;
260         freq_t       *freq, *s, *e;
261         ir_exec_freq *ef;
262         ir_node      *end = get_irg_end(irg);
263         set          *freqs;
264         dfs_t        *dfs;
265         double       *x;
266         double        norm;
267
268         /*
269          * compute a DFS.
270          * using a toposort on the CFG (without back edges) will propagate
271          * the values better for the gauss/seidel iteration.
272          * => they can "flow" from start to end.
273          */
274         dfs = dfs_new(&absgraph_irg_cfg_succ, irg);
275         ef = XMALLOCZ(ir_exec_freq);
276         ef->min_non_zero = HUGE_VAL; /* initialize with a reasonable large number. */
277         freqs = ef->freqs = new_set(cmp_freq, dfs_get_n_nodes(dfs));
278
279         /*
280          * Populate the exec freq set.
281          * The DFS cannot be used alone, since the CFG might not be connected
282          * due to unreachable code.
283          */
284         irg_block_walk_graph(irg, collect_blocks, NULL, freqs);
285
286         construct_cf_backedges(irg);
287         assure_edges(irg);
288
289         size = dfs_get_n_nodes(dfs);
290         mat  = gs_new_matrix(size, size);
291         x    = XMALLOCN(double, size);
292
293         for (idx = dfs_get_n_nodes(dfs) - 1; idx >= 0; --idx) {
294                 ir_node *bb = (ir_node *) dfs_get_post_num_node(dfs, size - idx - 1);
295                 int i;
296
297                 freq = set_insert_freq(freqs, bb);
298                 freq->idx = idx;
299
300                 /* Sum of (execution frequency of predecessor * probability of cf edge) ... */
301                 for (i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
302                         ir_node *pred = get_Block_cfgpred_block(bb, i);
303                         int pred_idx  = size - dfs_get_post_num(dfs, pred) - 1;
304
305                         gs_matrix_set(mat, idx, pred_idx, get_cf_probability(bb, i, loop_weight));
306                 }
307                 /* ... equals my execution frequency */
308                 gs_matrix_set(mat, idx, idx, -1.0);
309         }
310
311         dfs_free(dfs);
312
313         /*
314          * Add an edge from end to start.
315          * The problem is then an eigenvalue problem:
316          * Solve A*x = 1*x => (A-I)x = 0
317          */
318         s = set_find_freq(freqs, get_irg_start_block(irg));
319
320         e = set_find_freq(freqs, get_irg_end_block(irg));
321         if (e->idx >= 0)
322                 gs_matrix_set(mat, s->idx, e->idx, 1.0);
323
324         /*
325          * Also add an edge for each kept block to start.
326          *
327          * This avoid strange results for e.g. an irg containing a exit()-call
328          * which block has no cfg successor.
329          */
330         n_keepalives = get_End_n_keepalives(end);
331         for (idx = n_keepalives - 1; idx >= 0; --idx) {
332                 ir_node *keep = get_End_keepalive(end, idx);
333
334                 if (is_Block(keep) && get_Block_n_cfg_outs(keep) == 0) {
335                         freq_t *k = set_find_freq(freqs, keep);
336                         if (k->idx >= 0)
337                                 gs_matrix_set(mat, s->idx, k->idx, 1.0);
338                 }
339         }
340
341         /* solve the system and delete the matrix */
342         solve_lgs(mat, x, size);
343         gs_delete_matrix(mat);
344
345         /*
346          * compute the normalization factor.
347          * 1.0 / exec freq of start block.
348          */
349         norm = x[s->idx] != 0.0 ? 1.0 / x[s->idx] : 1.0;
350
351         ef->max = 0.0;
352         foreach_set(freqs, freq_t, freq) {
353                 idx = freq->idx;
354
355                 /* take abs because it sometimes can be -0 in case of endless loops */
356                 freq->freq = fabs(x[idx]) * norm;
357
358                 /* get the maximum exec freq */
359                 ef->max = MAX(ef->max, freq->freq);
360
361                 /* Get the minimum non-zero execution frequency. */
362                 if (freq->freq > 0.0)
363                         ef->min_non_zero = MIN(ef->min_non_zero, freq->freq);
364         }
365
366         /* compute m and b of the transformation used to convert the doubles into scaled ints */
367         {
368                 double smallest_diff = 1.0;
369
370                 double l2 = ef->min_non_zero;
371                 double h2 = ef->max;
372                 double l1 = 1.0;
373                 double h1 = MAX_INT_FREQ;
374
375                 double *fs = (double*) malloc(set_count(freqs) * sizeof(fs[0]));
376                 int i, j, n = 0;
377
378                 foreach_set(freqs, freq_t, freq)
379                         fs[n++] = freq->freq;
380
381                 /*
382                  * find the smallest difference of the execution frequencies
383                  * we try to ressolve it with 1 integer.
384                  */
385                 for (i = 0; i < n; ++i) {
386                         if (fs[i] <= 0.0)
387                                 continue;
388
389                         for (j = i + 1; j < n; ++j) {
390                                 double diff = fabs(fs[i] - fs[j]);
391
392                                 if (!UNDEF(diff))
393                                         smallest_diff = MIN(diff, smallest_diff);
394                         }
395                 }
396
397                 /* according to that the slope of the translation function is 1.0 / smallest diff */
398                 ef->m = 1.0 / smallest_diff;
399
400                 /* the abscissa is then given by */
401                 ef->b = l1 - ef->m * l2;
402
403                 /*
404                  * if the slope is so high that the largest integer would be larger than MAX_INT_FREQ
405                  * set the largest int freq to that upper limit and recompute the translation function
406                  */
407                 if (ef->m * h2 + ef->b > MAX_INT_FREQ) {
408                         ef->m = (h1 - l1) / (h2 - l2);
409                         ef->b = l1 - ef->m * l2;
410                 }
411
412                 free(fs);
413         }
414
415         memset(&ef->hook, 0, sizeof(ef->hook));
416         ef->hook.context = ef;
417         ef->hook.hook._hook_node_info = exec_freq_node_info;
418         register_hook(hook_node_info, &ef->hook);
419
420         xfree(x);
421
422         return ef;
423 }
424
425 void free_execfreq(ir_exec_freq *ef)
426 {
427         del_set(ef->freqs);
428         unregister_hook(hook_node_info, &ef->hook);
429         free(ef);
430 }