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