Removed C99 construct
[libfirm] / ir / ana / execfreq.c
1 /*
2  * Copyright (C) 1995-2007 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 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #undef USE_GSL
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <limits.h>
36 #include <math.h>
37
38 #ifdef USE_GSL
39 #include <gsl/gsl_linalg.h>
40 #include <gsl/gsl_vector.h>
41 #else
42 #include "gaussjordan.h"
43 #endif
44
45 #include "firm_common_t.h"
46 #include "set.h"
47 #include "hashptr.h"
48 #include "debug.h"
49
50 #include "irprog_t.h"
51 #include "irgraph_t.h"
52 #include "irnode_t.h"
53 #include "irloop.h"
54 #include "irgwalk.h"
55 #include "iredges.h"
56 #include "irprintf.h"
57 #include "irhooks.h"
58
59 #include "execfreq.h"
60
61 #define set_foreach(s,i) for((i)=set_first((s)); (i); (i)=set_next((s)))
62
63 #define MAX_INT_FREQ 1000000
64
65 typedef struct _freq_t {
66         const ir_node    *irn;
67         double            freq;
68 } freq_t;
69
70
71 typedef struct _walkerdata_t {
72   set    *set;
73   size_t  idx;
74 } walkerdata_t;
75
76 struct ir_exec_freq {
77         set *set;
78         hook_entry_t hook;
79         double max;
80         double min_non_zero;
81         double m, b;
82         unsigned infeasible : 1;
83 };
84
85 static int
86 cmp_freq(const void *a, const void *b, size_t size)
87 {
88         const freq_t *p = a;
89         const freq_t *q = b;
90         (void) size;
91
92         return !(p->irn == q->irn);
93 }
94
95 static freq_t *
96 set_find_freq(set * set, const ir_node * irn)
97 {
98         freq_t     query;
99
100         query.irn = irn;
101         return set_find(set, &query, sizeof(query), HASH_PTR(irn));
102 }
103
104 static freq_t *
105 set_insert_freq(set * set, const ir_node * irn)
106 {
107         freq_t query;
108
109         query.irn = irn;
110         query.freq = 0.0;
111         return set_insert(set, &query, sizeof(query), HASH_PTR(irn));
112 }
113
114 double
115 get_block_execfreq(const ir_exec_freq *ef, const ir_node * irn)
116 {
117         if(!ef->infeasible) {
118                 set *freqs = ef->set;
119                 freq_t *freq;
120                 assert(is_Block(irn));
121                 freq = set_find_freq(freqs, irn);
122                 assert(freq);
123
124                 assert(freq->freq >= 0);
125                 return freq->freq;
126         }
127
128         return 1.0;
129 }
130
131 unsigned long
132 get_block_execfreq_ulong(const ir_exec_freq *ef, const ir_node *bb)
133 {
134         double f       = get_block_execfreq(ef, bb);
135         int res        = (int) (f > ef->min_non_zero ? ef->m * f + ef->b : 1.0);
136
137         // printf("%20.6f %10d\n", f, res);
138         return res;
139 }
140
141 #define EPSILON         0.0001
142 #define UNDEF(x)    !(x > EPSILON)
143
144 static void
145 block_walker(ir_node * bb, void * data)
146 {
147   walkerdata_t  *wd = data;
148
149   set_insert_freq(wd->set, bb);
150   set_irn_link(bb, (void*)wd->idx++);
151 }
152
153 #ifdef USE_GSL
154 static gsl_vector *
155 solve_lgs(double * a_data, double * b_data, size_t size)
156 {
157   gsl_matrix_view m
158     = gsl_matrix_view_array (a_data, size, size);
159
160   gsl_vector_view b
161     = gsl_vector_view_array (b_data, size);
162
163   gsl_vector *x = gsl_vector_alloc (size);
164
165   int s;
166
167   gsl_permutation * p = gsl_permutation_alloc (size);
168
169   gsl_linalg_LU_decomp (&m.matrix, p, &s);
170
171   gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x);
172
173   gsl_permutation_free (p);
174
175   return x;
176 }
177 #else
178 static double *
179 solve_lgs(double * A, double * b, size_t size)
180 {
181   if(firm_gaussjordansolve(A,b,size) == 0) {
182     return b;
183   } else {
184     return NULL;
185   }
186 }
187 #endif /* USE_GSL */
188
189 static double
190 get_cf_probability(ir_node *bb, int pos, double loop_weight)
191 {
192         double  sum = 0.0;
193         double  cur = 0.0;
194         const ir_node *pred = get_Block_cfgpred_block(bb, pos);
195         const ir_loop *pred_loop = get_irn_loop(pred);
196         int pred_depth = get_loop_depth(pred_loop);
197         const ir_edge_t *edge;
198
199         cur = get_loop_depth(get_irn_loop(bb)) < get_loop_depth(get_irn_loop(pred)) ? 1.0 : loop_weight;
200
201         foreach_block_succ(pred, edge) {
202                 const ir_node *block = get_edge_src_irn(edge);
203                 const ir_loop *loop = get_irn_loop(block);
204                 int depth = get_loop_depth(loop);
205                 sum += depth < pred_depth ? 1.0 : loop_weight;
206         }
207
208         return cur/sum;
209 }
210
211 static void exec_freq_node_info(void *ctx, FILE *f, const ir_node *irn)
212 {
213         if(is_Block(irn)) {
214                 ir_exec_freq *ef = ctx;
215                 fprintf(f, "execution frequency: %g/%lu\n", get_block_execfreq(ef, irn), get_block_execfreq_ulong(ef, irn));
216         }
217 }
218
219 ir_exec_freq *create_execfreq(ir_graph *irg)
220 {
221         ir_exec_freq *execfreq = xmalloc(sizeof(execfreq[0]));
222         memset(execfreq, 0, sizeof(execfreq[0]));
223         execfreq->set = new_set(cmp_freq, 32);
224
225         memset(&execfreq->hook, 0, sizeof(execfreq->hook));
226         execfreq->hook.context = execfreq;
227         execfreq->hook.hook._hook_node_info = exec_freq_node_info;
228         register_hook(hook_node_info, &execfreq->hook);
229         (void) irg;
230
231         return execfreq;
232 }
233
234 void set_execfreq(ir_exec_freq *execfreq, const ir_node *block, double freq)
235 {
236         freq_t *f = set_insert_freq(execfreq->set, block);
237         f->freq = freq;
238 }
239
240 ir_exec_freq *
241 compute_execfreq(ir_graph * irg, double loop_weight)
242 {
243         size_t        size;
244         double       *matrix;
245         double       *rhs;
246         int           i;
247         freq_t       *freq;
248         walkerdata_t  wd;
249         ir_exec_freq  *ef;
250         set          *freqs;
251 #ifdef USE_GSL
252         gsl_vector   *x;
253 #else
254         double       *x;
255 #endif
256
257         ef = xmalloc(sizeof(ef[0]));
258         memset(ef, 0, sizeof(ef[0]));
259         ef->min_non_zero = 1e50; /* initialize with a reasonable large number. */
260         freqs = ef->set = new_set(cmp_freq, 32);
261
262         construct_cf_backedges(irg);
263         /* TODO: edges are corrupt for EDGE_KIND_BLOCK after the local optimize
264                  graph phase merges blocks in the x86 backend */
265         edges_deactivate(irg);
266         edges_activate(irg);
267         /* edges_assure(irg); */
268
269         wd.idx = 0;
270         wd.set = freqs;
271
272         irg_block_walk_graph(irg, block_walker, NULL, &wd);
273
274         size = set_count(freqs);
275         matrix = xmalloc(size*size*sizeof(*matrix));
276         memset(matrix, 0, size*size*sizeof(*matrix));
277         rhs = xmalloc(size*sizeof(*rhs));
278         memset(rhs, 0, size*sizeof(*rhs));
279
280         set_foreach(freqs, freq) {
281                 ir_node *bb = (ir_node *)freq->irn;
282                 size_t  idx = (int)get_irn_link(bb);
283
284                 matrix[idx * (size + 1)] = -1.0;
285
286                 if (bb == get_irg_start_block(irg)) {
287                         rhs[(int)get_irn_link(bb)] = -1.0;
288                         continue;
289                 }
290
291                 for(i = get_Block_n_cfgpreds(bb) - 1; i >= 0; --i) {
292                         ir_node *pred    = get_Block_cfgpred_block(bb, i);
293                         size_t  pred_idx = (int)get_irn_link(pred);
294
295                         //      matrix[pred_idx + idx*size] += 1.0/(double)get_Block_n_cfg_outs(pred);
296                         matrix[pred_idx + idx * size] += get_cf_probability(bb, i, loop_weight);
297                 }
298         }
299
300         x = solve_lgs(matrix, rhs, size);
301         if (x == NULL) {
302                 DEBUG_ONLY(ir_fprintf(stderr, "Debug Warning: Couldn't estimate execution frequencies for %+F\n", irg));
303                 ef->infeasible = 1;
304         } else {
305                 ef->max = 0.0;
306
307                 set_foreach(freqs, freq) {
308                         const ir_node *bb = freq->irn;
309                         size_t        idx = PTR_TO_INT(get_irn_link(bb));
310
311 #ifdef USE_GSL
312                         freq->freq = UNDEF(gsl_vector_get(x, idx)) ? EPSILON : gsl_vector_get(x, idx);
313 #else
314                         freq->freq = UNDEF(x[idx]) ? EPSILON : x[idx];
315 #endif
316
317                         /* get the maximum exec freq */
318                         ef->max = MAX(ef->max, freq->freq);
319
320                         /* Get the minimum non-zero execution frequency. */
321                         if(freq->freq > 0.0)
322                                 ef->min_non_zero = MIN(ef->min_non_zero, freq->freq);
323                 }
324
325                 /* compute m and b of the transformation used to convert the doubles into scaled ints */
326                 {
327                         double smallest_diff = 1.0;
328
329                         double l2 = ef->min_non_zero;
330                         double h2 = ef->max;
331                         double l1 = 1.0;
332                         double h1 = MAX_INT_FREQ;
333
334                         double *fs = malloc(set_count(freqs) * sizeof(fs[0]));
335                         int i, j, n = 0;
336
337                         set_foreach(freqs, freq)
338                                 fs[n++] = freq->freq;
339
340                         /*
341                          * find the smallest difference of the execution frequencies
342                          * we try to ressolve it with 1 integer.
343                          */
344                         for(i = 0; i < n; ++i) {
345                                 if(fs[i] <= 0.0)
346                                         continue;
347
348                                 for(j = i + 1; j < n; ++j) {
349                                         double diff = fabs(fs[i] - fs[j]);
350
351                                         if(!UNDEF(diff))
352                                                 smallest_diff = MIN(diff, smallest_diff);
353                                 }
354                         }
355
356                         /* according to that the slope of the translation function is 1.0 / smallest diff */
357                         ef->m = 1.0 / smallest_diff;
358
359                         /* the abscissa is then given by */
360                         ef->b = l1 - ef->m * l2;
361
362                         /*
363                          * if the slope is so high that the largest integer would be larger than MAX_INT_FREQ
364                          * set the largest int freq to that upper limit and recompute the translation function
365                          */
366                         if(ef->m * h2 + ef->b > MAX_INT_FREQ) {
367                                 ef->m = (h1 - l1) / (h2 - l2);
368                                 ef->b = l1 - ef->m * l2;
369                         }
370
371                         // printf("smallest_diff: %g, l1: %f, h1: %f, l2: %f, h2: %f, m: %f, b: %f\n", smallest_diff, l1, h1, l2, h2, ef->m, ef->b);
372                         free(fs);
373                 }
374
375 #ifdef USE_GSL
376                 gsl_vector_free(x);
377 #endif
378                 memset(&ef->hook, 0, sizeof(ef->hook));
379                 ef->hook.context = ef;
380                 ef->hook.hook._hook_node_info = exec_freq_node_info;
381                 register_hook(hook_node_info, &ef->hook);
382         }
383
384         free(matrix);
385         free(rhs);
386
387         return ef;
388 }
389
390 void
391 free_execfreq(ir_exec_freq *ef)
392 {
393         del_set(ef->set);
394         unregister_hook(hook_node_info, &ef->hook);
395         free(ef);
396 }