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