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