becopyilp: Inline struct size_red_t into struct ilp_env_t.
[libfirm] / ir / ana / execfreq.c
1 /*
2  * This file is part of libFirm.
3  * Copyright (C) 2012 University of Karlsruhe.
4  */
5
6 /**
7  * @file
8  * @brief       Compute an estimate of basic block executions.
9  * @author      Adam M. Szalkowski
10  * @date        28.05.2006
11  */
12 #include "config.h"
13
14 #include <stdio.h>
15 #include <string.h>
16 #include <limits.h>
17 #include <math.h>
18
19 #include "gaussseidel.h"
20
21 #include "set.h"
22 #include "hashptr.h"
23 #include "debug.h"
24 #include "statev_t.h"
25 #include "dfs_t.h"
26 #include "absgraph.h"
27
28 #include "irprog_t.h"
29 #include "irgraph_t.h"
30 #include "irnode_t.h"
31 #include "irloop.h"
32 #include "irgwalk.h"
33 #include "iredges.h"
34 #include "irouts.h"
35 #include "irprintf.h"
36 #include "util.h"
37 #include "irhooks.h"
38 #include "irnodehashmap.h"
39
40 #include "execfreq_t.h"
41
42 #define EPSILON          1e-5
43 #define UNDEF(x)         (fabs(x) < EPSILON)
44 #define SEIDEL_TOLERANCE 1e-7
45
46 #define MAX_INT_FREQ 1000000
47
48 static hook_entry_t hook;
49
50 double get_block_execfreq(const ir_node *block)
51 {
52         return block->attr.block.execfreq;
53 }
54
55 void set_block_execfreq(ir_node *block, double newfreq)
56 {
57         block->attr.block.execfreq = newfreq;
58 }
59
60 static void exec_freq_node_info(void *ctx, FILE *f, const ir_node *irn)
61 {
62         (void)ctx;
63         if (!is_Block(irn))
64                 return;
65         double freq = get_block_execfreq(irn);
66         if (freq != 0.0)
67                 fprintf(f, "execution frequency: %g\n", freq);
68 }
69
70 void init_execfreq(void)
71 {
72         memset(&hook, 0, sizeof(hook));
73         hook.hook._hook_node_info = exec_freq_node_info;
74         register_hook(hook_node_info, &hook);
75 }
76
77 void exit_execfreq(void)
78 {
79         unregister_hook(hook_node_info, &hook);
80 }
81
82
83 static double *solve_lgs(gs_matrix_t *mat, double *x, int size)
84 {
85         double init = 1.0 / size;
86         double dev;
87         int i, iter = 0;
88
89         /* better convergence. */
90         for (i = 0; i < size; ++i)
91                 x[i] = init;
92
93         stat_ev_dbl("execfreq_matrix_size", size);
94         stat_ev_tim_push();
95         do {
96                 ++iter;
97                 dev = gs_matrix_gauss_seidel(mat, x, size);
98         } while (fabs(dev) > SEIDEL_TOLERANCE);
99         stat_ev_tim_pop("execfreq_seidel_time");
100         stat_ev_dbl("execfreq_seidel_iter", iter);
101
102         return x;
103 }
104
105 /*
106  * Determine probability that predecessor pos takes this cf edge.
107  */
108 static double get_cf_probability(const ir_node *bb, int pos, double loop_weight)
109 {
110         double         sum = 0.0;
111         double         cur = 1.0;
112         double         inv_loop_weight = 1./loop_weight;
113         const ir_node *pred = get_Block_cfgpred_block(bb, pos);
114         const ir_loop *pred_loop;
115         int            pred_depth;
116         const ir_loop *loop;
117         int            depth;
118         int            d;
119
120         if (is_Bad(pred))
121                 return 0;
122
123         loop       = get_irn_loop(bb);
124         depth      = get_loop_depth(loop);
125         pred_loop  = get_irn_loop(pred);
126         pred_depth = get_loop_depth(pred_loop);
127
128         for (d = depth; d < pred_depth; ++d) {
129                 cur *= inv_loop_weight;
130         }
131
132         foreach_block_succ(pred, edge) {
133                 const ir_node *succ       = get_edge_src_irn(edge);
134                 const ir_loop *succ_loop  = get_irn_loop(succ);
135                 int            succ_depth = get_loop_depth(succ_loop);
136
137                 double         fac = 1.0;
138                 for (d = succ_depth; d < pred_depth; ++d) {
139                         fac *= inv_loop_weight;
140                 }
141                 sum += fac;
142         }
143
144         return cur/sum;
145 }
146
147 static double *freqs;
148 static double  min_non_zero;
149 static double  max_freq;
150
151 static void collect_freqs(ir_node *node, void *data)
152 {
153         (void) data;
154         double freq = get_block_execfreq(node);
155         if (freq > max_freq)
156                 max_freq = freq;
157         if (freq > 0.0 && freq < min_non_zero)
158                 min_non_zero = freq;
159         ARR_APP1(double, freqs, freq);
160 }
161
162 void ir_calculate_execfreq_int_factors(ir_execfreq_int_factors *factors,
163                                        ir_graph *irg)
164 {
165         /* compute m and b of the transformation used to convert the doubles into
166          * scaled ints */
167         freqs = NEW_ARR_F(double, 0);
168         min_non_zero = HUGE_VAL;
169         max_freq     = 0.0;
170         irg_block_walk_graph(irg, collect_freqs, NULL, NULL);
171
172         /*
173          * find the smallest difference of the execution frequencies
174          * we try to ressolve it with 1 integer.
175          */
176         size_t n_freqs       = ARR_LEN(freqs);
177         double smallest_diff = 1.0;
178         for (size_t i = 0; i < n_freqs; ++i) {
179                 if (freqs[i] <= 0.0)
180                         continue;
181
182                 for (size_t j = i + 1; j < n_freqs; ++j) {
183                         double diff = fabs(freqs[i] - freqs[j]);
184
185                         if (!UNDEF(diff))
186                                 smallest_diff = MIN(diff, smallest_diff);
187                 }
188         }
189
190         double l2 = min_non_zero;
191         double h2 = max_freq;
192         double l1 = 1.0;
193         double h1 = MAX_INT_FREQ;
194
195         /* according to that the slope of the translation function is
196          * 1.0 / smallest_diff */
197         factors->m = 1.0 / smallest_diff;
198
199         /* the abscissa is then given by */
200         factors->b = l1 - factors->m * l2;
201
202         /*
203          * if the slope is so high that the largest integer would be larger than
204          * MAX_INT_FREQ set the largest int freq to that upper limit and recompute
205          * the translation function
206          */
207         if (factors->m * h2 + factors->b > MAX_INT_FREQ) {
208                 factors->m = (h1 - l1) / (h2 - l2);
209                 factors->b = l1 - factors->m * l2;
210         }
211
212         DEL_ARR_F(freqs);
213 }
214
215 int get_block_execfreq_int(const ir_execfreq_int_factors *factors,
216                            const ir_node *block)
217 {
218         double f   = get_block_execfreq(block);
219         int    res = (int) (f > factors->min_non_zero ? factors->m * f + factors->b : 1.0);
220         return res;
221 }
222
223 void ir_estimate_execfreq(ir_graph *irg)
224 {
225         double loop_weight = 10.0;
226
227         assure_irg_properties(irg,
228                 IR_GRAPH_PROPERTY_CONSISTENT_OUT_EDGES
229                 | IR_GRAPH_PROPERTY_CONSISTENT_LOOPINFO
230                 | IR_GRAPH_PROPERTY_NO_UNREACHABLE_CODE);
231
232         /* compute a DFS.
233          * using a toposort on the CFG (without back edges) will propagate
234          * the values better for the gauss/seidel iteration.
235          * => they can "flow" from start to end.
236          */
237         dfs_t *dfs = dfs_new(&absgraph_irg_cfg_succ, irg);
238
239         int          size = dfs_get_n_nodes(dfs);
240         gs_matrix_t *mat  = gs_new_matrix(size, size);
241
242         ir_node *const start_block = get_irg_start_block(irg);
243         ir_node *const end_block   = get_irg_end_block(irg);
244
245         for (int idx = size - 1; idx >= 0; --idx) {
246                 const ir_node *bb = (ir_node*)dfs_get_post_num_node(dfs, size-idx-1);
247
248                 /* Sum of (execution frequency of predecessor * probability of cf edge) ... */
249                 for (int i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
250                         const ir_node *pred           = get_Block_cfgpred_block(bb, i);
251                         int            pred_idx       = size - dfs_get_post_num(dfs, pred)-1;
252                         double         cf_probability = get_cf_probability(bb, i, loop_weight);
253                         gs_matrix_set(mat, idx, pred_idx, cf_probability);
254                 }
255                 /* ... equals my execution frequency */
256                 gs_matrix_set(mat, idx, idx, -1.0);
257
258                 /* Add an edge from end to start.
259                  * The problem is then an eigenvalue problem:
260                  * Solve A*x = 1*x => (A-I)x = 0
261                  */
262                 if (bb == end_block) {
263                         int const s_idx = size - dfs_get_post_num(dfs, start_block) - 1;
264                         gs_matrix_set(mat, s_idx, idx, 1.0);
265                 }
266         }
267
268         /*
269          * Also add an edge for each kept block to start.
270          *
271          * This avoid strange results for e.g. an irg containing a exit()-call
272          * which block has no cfg successor.
273          */
274         int            s_idx        = size - dfs_get_post_num(dfs, start_block)-1;
275         const ir_node *end          = get_irg_end(irg);
276         int            n_keepalives = get_End_n_keepalives(end);
277         for (int idx = n_keepalives - 1; idx >= 0; --idx) {
278                 ir_node *keep = get_End_keepalive(end, idx);
279                 if (!is_Block(keep) || get_irn_n_edges_kind(keep, EDGE_KIND_BLOCK) > 0)
280                         continue;
281
282                 int k_idx = size-dfs_get_post_num(dfs, keep)-1;
283                 if (k_idx > 0)
284                         gs_matrix_set(mat, s_idx, k_idx, 1.0);
285         }
286
287         /* solve the system and delete the matrix */
288         double *x = XMALLOCN(double, size);
289         solve_lgs(mat, x, size);
290         gs_delete_matrix(mat);
291
292         /* compute the normalization factor.
293          * 1.0 / exec freq of start block.
294          * (note: start_idx is != 0 in strange cases involving endless loops,
295          *  probably a misfeature/bug)
296          */
297         int    start_idx  = size - dfs_get_post_num(dfs, start_block) - 1;
298         double start_freq = x[start_idx];
299         double norm       = start_freq != 0.0 ? 1.0 / start_freq : 1.0;
300
301         for (int idx = size - 1; idx >= 0; --idx) {
302                 ir_node *bb = (ir_node *) dfs_get_post_num_node(dfs, size - idx - 1);
303
304                 /* take abs because it sometimes can be -0 in case of endless loops */
305                 double freq = fabs(x[idx]) * norm;
306                 set_block_execfreq(bb, freq);
307         }
308
309         dfs_free(dfs);
310
311         xfree(x);
312 }