be752dd3d8807c6d1c20d0df4e77440012b0b135
[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 #include "irnodehashmap.h"
53
54 #include "execfreq_t.h"
55
56 #define EPSILON          1e-5
57 #define UNDEF(x)         (fabs(x) < EPSILON)
58 #define SEIDEL_TOLERANCE 1e-7
59
60 #define MAX_INT_FREQ 1000000
61
62 typedef struct freq_t {
63         double freq;
64 } freq_t;
65
66 static ir_nodehashmap_t freq_map;
67 static struct obstack   obst;
68 static hook_entry_t     hook;
69
70 double get_block_execfreq(const ir_node *block)
71 {
72         const freq_t *freq = ir_nodehashmap_get(freq_t, &freq_map, block);
73         if (freq == NULL)
74                 return 0.0;
75         return freq->freq;
76 }
77
78 void set_block_execfreq(ir_node *block, double newfreq)
79 {
80         freq_t *freq = ir_nodehashmap_get(freq_t, &freq_map, block);
81         if (freq == NULL) {
82                 freq = OALLOC(&obst, freq_t);
83                 ir_nodehashmap_insert(&freq_map, block, freq);
84         }
85         freq->freq = newfreq;
86 }
87
88 static void exec_freq_node_info(void *ctx, FILE *f, const ir_node *irn)
89 {
90         (void)ctx;
91         if (!is_Block(irn))
92                 return;
93         fprintf(f, "execution frequency: %g\n", get_block_execfreq(irn));
94 }
95
96 void init_execfreq(void)
97 {
98         ir_nodehashmap_init(&freq_map);
99         obstack_init(&obst);
100
101         memset(&hook, 0, sizeof(hook));
102         hook.hook._hook_node_info = exec_freq_node_info;
103         register_hook(hook_node_info, &hook);
104 }
105
106 void exit_execfreq(void)
107 {
108         unregister_hook(hook_node_info, &hook);
109
110         obstack_free(&obst, NULL);
111         ir_nodehashmap_destroy(&freq_map);
112 }
113
114
115 static double *solve_lgs(gs_matrix_t *mat, double *x, int size)
116 {
117         double init = 1.0 / size;
118         double dev;
119         int i, iter = 0;
120
121         /* better convergence. */
122         for (i = 0; i < size; ++i)
123                 x[i] = init;
124
125         stat_ev_dbl("execfreq_matrix_size", size);
126         stat_ev_tim_push();
127         do {
128                 ++iter;
129                 dev = gs_matrix_gauss_seidel(mat, x, size);
130         } while (fabs(dev) > SEIDEL_TOLERANCE);
131         stat_ev_tim_pop("execfreq_seidel_time");
132         stat_ev_dbl("execfreq_seidel_iter", iter);
133
134         return x;
135 }
136
137 /*
138  * Determine probability that predecessor pos takes this cf edge.
139  */
140 static double get_cf_probability(const ir_node *bb, int pos, double loop_weight)
141 {
142         double         sum = 0.0;
143         double         cur = 1.0;
144         double         inv_loop_weight = 1./loop_weight;
145         const ir_node *pred = get_Block_cfgpred_block(bb, pos);
146         const ir_loop *pred_loop;
147         int            pred_depth;
148         const ir_loop *loop;
149         int            depth;
150         int            d;
151
152         if (is_Bad(pred))
153                 return 0;
154
155         loop       = get_irn_loop(bb);
156         depth      = get_loop_depth(loop);
157         pred_loop  = get_irn_loop(pred);
158         pred_depth = get_loop_depth(pred_loop);
159
160         for (d = depth; d < pred_depth; ++d) {
161                 cur *= inv_loop_weight;
162         }
163
164         foreach_block_succ(pred, edge) {
165                 const ir_node *succ       = get_edge_src_irn(edge);
166                 const ir_loop *succ_loop  = get_irn_loop(succ);
167                 int            succ_depth = get_loop_depth(succ_loop);
168
169                 double         fac = 1.0;
170                 for (d = succ_depth; d < pred_depth; ++d) {
171                         fac *= inv_loop_weight;
172                 }
173                 sum += fac;
174         }
175
176         return cur/sum;
177 }
178
179 static double *freqs;
180 static double  min_non_zero;
181 static double  max_freq;
182
183 static void collect_freqs(ir_node *node, void *data)
184 {
185         (void) data;
186         double freq = get_block_execfreq(node);
187         if (freq > max_freq)
188                 max_freq = freq;
189         if (freq > 0.0 && freq < min_non_zero)
190                 min_non_zero = freq;
191         ARR_APP1(double, freqs, freq);
192 }
193
194 void ir_calculate_execfreq_int_factors(ir_execfreq_int_factors *factors,
195                                        ir_graph *irg)
196 {
197         /* compute m and b of the transformation used to convert the doubles into
198          * scaled ints */
199         freqs = NEW_ARR_F(double, 0);
200         min_non_zero = HUGE_VAL;
201         max_freq     = 0.0;
202         irg_block_walk_graph(irg, collect_freqs, NULL, NULL);
203
204         /*
205          * find the smallest difference of the execution frequencies
206          * we try to ressolve it with 1 integer.
207          */
208         size_t n_freqs       = ARR_LEN(freqs);
209         double smallest_diff = 1.0;
210         for (size_t i = 0; i < n_freqs; ++i) {
211                 if (freqs[i] <= 0.0)
212                         continue;
213
214                 for (size_t j = i + 1; j < n_freqs; ++j) {
215                         double diff = fabs(freqs[i] - freqs[j]);
216
217                         if (!UNDEF(diff))
218                                 smallest_diff = MIN(diff, smallest_diff);
219                 }
220         }
221
222         double l2 = min_non_zero;
223         double h2 = max_freq;
224         double l1 = 1.0;
225         double h1 = MAX_INT_FREQ;
226
227         /* according to that the slope of the translation function is
228          * 1.0 / smallest_diff */
229         factors->m = 1.0 / smallest_diff;
230
231         /* the abscissa is then given by */
232         factors->b = l1 - factors->m * l2;
233
234         /*
235          * if the slope is so high that the largest integer would be larger than
236          * MAX_INT_FREQ set the largest int freq to that upper limit and recompute
237          * the translation function
238          */
239         if (factors->m * h2 + factors->b > MAX_INT_FREQ) {
240                 factors->m = (h1 - l1) / (h2 - l2);
241                 factors->b = l1 - factors->m * l2;
242         }
243
244         DEL_ARR_F(freqs);
245 }
246
247 int get_block_execfreq_int(const ir_execfreq_int_factors *factors,
248                            const ir_node *block)
249 {
250         double f   = get_block_execfreq(block);
251         int    res = (int) (f > factors->min_non_zero ? factors->m * f + factors->b : 1.0);
252         return res;
253 }
254
255 void ir_estimate_execfreq(ir_graph *irg)
256 {
257         double loop_weight = 10.0;
258
259         assure_irg_properties(irg,
260                 IR_GRAPH_PROPERTY_CONSISTENT_OUT_EDGES
261                 | IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO);
262
263         /* compute a DFS.
264          * using a toposort on the CFG (without back edges) will propagate
265          * the values better for the gauss/seidel iteration.
266          * => they can "flow" from start to end.
267          */
268         dfs_t *dfs = dfs_new(&absgraph_irg_cfg_succ, irg);
269
270         int          size = dfs_get_n_nodes(dfs);
271         gs_matrix_t *mat  = gs_new_matrix(size, size);
272
273         ir_node *end_block = get_irg_end_block(irg);
274
275         for (int idx = dfs_get_n_nodes(dfs) - 1; idx >= 0; --idx) {
276                 const ir_node *bb = (ir_node*)dfs_get_post_num_node(dfs, size-idx-1);
277
278                 /* Sum of (execution frequency of predecessor * probability of cf edge) ... */
279                 for (int i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
280                         const ir_node *pred           = get_Block_cfgpred_block(bb, i);
281                         int            pred_idx       = size - dfs_get_post_num(dfs, pred)-1;
282                         double         cf_probability = get_cf_probability(bb, i, loop_weight);
283                         gs_matrix_set(mat, idx, pred_idx, cf_probability);
284                 }
285                 /* ... equals my execution frequency */
286                 gs_matrix_set(mat, idx, idx, -1.0);
287
288                 /* Add an edge from end to start.
289                  * The problem is then an eigenvalue problem:
290                  * Solve A*x = 1*x => (A-I)x = 0
291                  */
292                 if (bb == end_block) {
293                         const ir_node *start_block = get_irg_start_block(irg);
294                         int            s_idx = size - dfs_get_post_num(dfs, start_block)-1;
295                         gs_matrix_set(mat, s_idx, idx, 1.0);
296                 }
297         }
298
299         /*
300          * Also add an edge for each kept block to start.
301          *
302          * This avoid strange results for e.g. an irg containing a exit()-call
303          * which block has no cfg successor.
304          */
305         ir_node       *start_block  = get_irg_start_block(irg);
306         int            s_idx        = size - dfs_get_post_num(dfs, start_block)-1;
307         const ir_node *end          = get_irg_end(irg);
308         int            n_keepalives = get_End_n_keepalives(end);
309         for (int idx = n_keepalives - 1; idx >= 0; --idx) {
310                 ir_node *keep = get_End_keepalive(end, idx);
311                 if (!is_Block(keep) || get_irn_n_edges_kind(keep, EDGE_KIND_BLOCK) > 0)
312                         continue;
313
314                 int k_idx = size-dfs_get_post_num(dfs, keep)-1;
315                 if (k_idx > 0)
316                         gs_matrix_set(mat, s_idx, k_idx, 1.0);
317         }
318
319         /* solve the system and delete the matrix */
320         double *x = XMALLOCN(double, size);
321         solve_lgs(mat, x, size);
322         gs_delete_matrix(mat);
323
324         /* compute the normalization factor.
325          * 1.0 / exec freq of start block.
326          * (note: start_idx is != 0 in strange cases involving endless loops,
327          *  probably a misfeature/bug)
328          */
329         int    start_idx  = size-dfs_get_post_num(dfs, get_irg_start_block(irg))-1;
330         double start_freq = x[start_idx];
331         double norm       = start_freq != 0.0 ? 1.0 / start_freq : 1.0;
332
333         for (int idx = dfs_get_n_nodes(dfs) - 1; idx >= 0; --idx) {
334                 ir_node *bb = (ir_node *) dfs_get_post_num_node(dfs, size - idx - 1);
335
336                 /* take abs because it sometimes can be -0 in case of endless loops */
337                 double freq = fabs(x[idx]) * norm;
338                 set_block_execfreq(bb, freq);
339         }
340
341         dfs_free(dfs);
342
343         xfree(x);
344 }