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