workaround
[libfirm] / ir / ana / execution_frequency.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    Goetz Lindenmaier
24  * @date      5.11.2004
25  * @version   $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "execution_frequency.h"
32
33 #include "firm_common_t.h"
34 #include "set.h"
35 #include "pdeq.h"
36 #include "hashptr.h"
37
38 #include "irprog_t.h"
39 #include "irgraph_t.h"
40 #include "irnode_t.h"
41 #include "irloop.h"
42 #include "irgwalk.h"
43
44 #include "interval_analysis.h"
45
46 void set_irp_exec_freq_state(exec_freq_state s);
47
48 /*------------------------------------------------------------------*/
49 /* A hashmap mapping the frequency to block and loop nodes.  Block
50  * and loop nodes are regions.                                      */
51 /*------------------------------------------------------------------*/
52
53 typedef struct {
54   void   *reg;
55   double  freq;
56   int     prob;
57 } reg_exec_freq;
58
59 /* We use this set for all nodes in all irgraphs. */
60 static set *exec_freq_set = NULL;
61
62 static int exec_freq_cmp(const void *e1, const void *e2, size_t size) {
63   reg_exec_freq *ef1 = (reg_exec_freq *)e1;
64   reg_exec_freq *ef2 = (reg_exec_freq *)e2;
65   return (ef1->reg != ef2->reg);
66 }
67
68 static INLINE unsigned int exec_freq_hash(reg_exec_freq *e) {
69   return HASH_PTR(e->reg);
70 }
71
72 static INLINE void set_region_exec_freq(void *reg, double freq) {
73   reg_exec_freq ef;
74   ef.reg  = reg;
75   ef.freq = freq;
76   set_insert(exec_freq_set, &ef, sizeof(ef), exec_freq_hash(&ef));
77 }
78
79 double get_region_exec_freq(void *reg) {
80   reg_exec_freq ef, *found;
81   ef.reg  = reg;
82   assert(exec_freq_set);
83
84   found = set_find(exec_freq_set, &ef, sizeof(ef), exec_freq_hash(&ef));
85
86   /* Not found if information is invalid. */
87   if (found)
88     return found->freq;
89   else
90     return 0;
91 }
92
93 /* Returns the number of times the block is executed. */
94 double     get_Block_exec_freq(ir_node *b) {
95   return get_region_exec_freq((void *)b);
96 }
97
98 double get_irn_exec_freq(ir_node *n) {
99   if (!is_Block(n)) n = get_nodes_block(n);
100   return get_Block_exec_freq(n);
101 }
102
103
104 /*------------------------------------------------------------------*/
105 /* A algorithm that precomputes whether Conds lead to an exception.
106  * Computes a field for all Projs from Conds that says the following:
107  *   - The Proj projs from a normal dual Cond with probability 50:50
108  *   - This Proj of the Cond leads to an exception, i.e., a raise node.
109  *     It is taken with exception probability.
110  *   - The Proj of the Cond avoids an exception.  It is taken with
111  *     1 - exception probability.                                   */
112 /*------------------------------------------------------------------*/
113
114 #include "irouts.h"
115
116 typedef enum {
117   Cond_prob_none,
118   Cond_prob_normal,
119   Cond_prob_avoid_exception,
120   Cond_prob_exception_taken,
121   Cond_prob_was_exception_taken,
122 } Cond_prob;
123
124 static int just_passed_a_Raise = 0;
125 static ir_node *Cond_list = NULL;
126
127 /* We do not use an extra set, as Projs are not yet in the existing one. */
128 void set_ProjX_probability(ir_node *n, Cond_prob prob) {
129   reg_exec_freq ef;
130   ef.reg  = n;
131   ef.prob = prob;
132   set_insert(exec_freq_set, &ef, sizeof(ef), exec_freq_hash(&ef));
133 }
134
135 Cond_prob get_ProjX_probability(ir_node *n) {
136   reg_exec_freq ef, *found;
137   ef.reg  = n;
138
139   found = set_find(exec_freq_set, &ef, sizeof(ef), exec_freq_hash(&ef));
140
141   if (found)
142     return (Cond_prob)found->prob;
143   else
144     return Cond_prob_none;
145 }
146
147 /* A walker that only visits the nodes we want to see. */
148
149 static void
150 my_irg_walk_2_both(ir_node *node, irg_walk_func *pre, irg_walk_func *post, void * env) {
151   int i;
152   set_irn_visited(node, current_ir_graph->visited);
153
154   pre(node, env);
155
156   if (node->op != op_Block) {
157     ir_node *pred;
158     if (node->op == op_Proj)
159       pred = get_irn_n(node, 0);
160     else
161       pred = get_irn_n(node, -1);
162     if (pred->visited < current_ir_graph->visited)
163       my_irg_walk_2_both(pred, pre, post, env);
164   }
165
166   else {  /* a Block */
167     for (i = get_irn_arity(node) - 1; i >= 0; --i) {
168       ir_node *pred = get_irn_n(node, i);
169       if (pred->visited < current_ir_graph->visited)
170         my_irg_walk_2_both(pred, pre, post, env);
171     }
172   }
173
174   if (node->op == op_End) {
175     for (i = get_irn_arity(node) - 1; i >= 0; --i) {
176       ir_node *pred = get_irn_n(node, i);
177       if ((pred->op == op_Block) && (pred->visited < current_ir_graph->visited))
178         my_irg_walk_2_both(pred, pre, post, env);
179     }
180   }
181
182   post(node, env);
183 }
184 static void my_irg_walk_current_graph(irg_walk_func *pre, irg_walk_func *post, void *env) {
185   inc_irg_visited(current_ir_graph);
186   my_irg_walk_2_both(get_irg_end(current_ir_graph), pre, post, env);
187 }
188
189
190 static void walk_pre(ir_node *n, void *env) {
191
192   if (get_irn_op(n) == op_Raise)
193     just_passed_a_Raise = 1;
194
195   if (   (get_irn_op(n) == op_Proj)
196       && (get_irn_op(get_Proj_pred(n)) == op_Cond)
197       && (just_passed_a_Raise)) {
198     ir_node *other_proj;
199     ir_node *c = get_Proj_pred(n);
200
201     /* If we already visited the other Proj, and it also leads to a Raise,
202        we are in the middle of something. Continue searching. */
203     assert(get_irn_n_outs(c) == 2 && "encountered a switch cond");
204     other_proj = get_irn_out(c, 0);
205     if (other_proj == n) other_proj = get_irn_out(c, 1);
206     if (get_ProjX_probability(other_proj) == Cond_prob_exception_taken) {
207       set_ProjX_probability(other_proj, Cond_prob_was_exception_taken);
208       /* Keep searching for the Proj, so keep just_passed_a_Raise. */
209     } else {
210       set_ProjX_probability(n, Cond_prob_exception_taken);
211       just_passed_a_Raise = 0;
212     }
213   }
214
215   if (get_irn_op(n) == op_Cond) {
216     set_irn_link(n, Cond_list);
217     Cond_list = n;
218   }
219 }
220
221 static void walk_post(ir_node *n, void *env) {
222
223   if (get_irn_op(n) == op_Raise)
224     just_passed_a_Raise = 0;
225
226   if (   (get_irn_op(n) == op_Proj)
227       && (get_irn_op(get_Proj_pred(n)) == op_Cond)
228       && ((get_ProjX_probability(n) == Cond_prob_exception_taken)    ||
229           (get_ProjX_probability(n) == Cond_prob_was_exception_taken)   )) {
230     just_passed_a_Raise = 1;
231   }
232 }
233
234 /** Precompute which Conds test for an exception.
235  *
236  *  Operates on current_ir_graph. */
237 void precompute_cond_evaluation(void) {
238   ir_node *c;
239
240   compute_irg_outs(current_ir_graph);
241
242   just_passed_a_Raise = 0;
243   Cond_list = NULL;
244   my_irg_walk_current_graph(walk_pre, walk_post, NULL);
245
246   for (c = Cond_list; c; c = get_irn_link(c)) {
247     ir_node *p0, *p1;
248
249     assert(get_irn_n_outs(c) == 2 && "encountered a switch cond");
250     p0 = get_irn_out(c, 0);
251     p1 = get_irn_out(c, 1);
252
253     /* both are exceptions */
254     if ((get_ProjX_probability(p0) == Cond_prob_exception_taken) &&
255         (get_ProjX_probability(p1) == Cond_prob_exception_taken)   ) {
256       assert(0 && "I tried to avoid these!");
257       /* It's a */
258       set_ProjX_probability(p0, Cond_prob_normal);
259       set_ProjX_probability(p1, Cond_prob_normal);
260     }
261
262     /* p0 is exception */
263     else if (get_ProjX_probability(p0) == Cond_prob_exception_taken) {
264       set_ProjX_probability(p1, Cond_prob_avoid_exception);
265     }
266
267     /* p1 is exception */
268     else if (get_ProjX_probability(p1) == Cond_prob_exception_taken) {
269       set_ProjX_probability(p0, Cond_prob_avoid_exception);
270     }
271
272     /* none is exception */
273     else {
274       set_ProjX_probability(p0, Cond_prob_normal);
275       set_ProjX_probability(p1, Cond_prob_normal);
276     }
277   }
278 }
279
280 int is_fragile_Proj(ir_node *n) {
281   return is_Proj(n) && (get_ProjX_probability(n) == Cond_prob_exception_taken);
282 }
283
284 /*------------------------------------------------------------------*/
285 /* The algorithm to compute the execution frequencies.
286  *
287  * Walk the control flow loop tree which we consider the interval
288  * tree.  Compute the execution for the lowest loop, add inner loops
289  * to worklist.  Consider the inner loops as simple nodes.  Check that
290  * there is only one loop header in each loop.                      */
291 /*------------------------------------------------------------------*/
292
293 static double exception_prob = 0.001;
294
295 static INLINE int is_loop_head(ir_node *cond) {
296   return 0;
297 }
298
299 /** Weight a single region in edge.
300  *
301  *  Given all outs of the predecessor region, we can compute the weight of
302  *  this single edge. */
303 static INLINE double get_weighted_region_exec_freq(void *reg, int pos) {
304   void *pred_reg        = get_region_in(reg, pos);
305   double res, full_freq = get_region_exec_freq (pred_reg);
306   int n_outs            = get_region_n_outs    (pred_reg);
307   int n_exc_outs        = get_region_n_exc_outs(pred_reg);
308
309   ir_node *cfop;
310   if (is_ir_node(reg)) {
311     cfop = get_Block_cfgpred((ir_node *)reg, pos);
312     if (is_Proj(cfop) && (get_irn_op(get_Proj_pred(cfop)) != op_Cond))
313       cfop = skip_Proj(cfop);
314   } else {
315     assert(is_ir_loop(reg));
316     cfop = get_loop_cfop(reg, pos);
317   }
318
319   if (is_fragile_op(cfop) || is_fragile_Proj(cfop)) {
320     res = full_freq * exception_prob;
321   } else {
322
323     /* Equally distribute the weight after exceptions to the left over outs. */
324     res = (full_freq *(1 - exception_prob * n_exc_outs)) / (n_outs - n_exc_outs);
325   }
326
327   return res;
328 }
329
330 static INLINE void compute_region_freqency(void *reg, double head_weight) {
331   int i, n_ins = get_region_n_ins(reg);
332   double my_freq = 0;
333
334   //printf("head weight %lf: ", head_weight); DDMR(reg);
335
336   for (i = 0; i < n_ins; ++i) {
337     void *pred_reg = get_region_in(reg, i);
338     if (pred_reg) {
339       my_freq += get_weighted_region_exec_freq(reg, i);
340     }
341   }
342
343   if (my_freq == 0.0) {
344     /* All preds are from outer loop. We are a head or so. */
345     my_freq = head_weight;
346   }
347   set_region_exec_freq(reg, my_freq);
348 }
349
350 static void check_proper_head(ir_loop *l, void *reg) {
351   int i, n_ins = get_region_n_ins(reg);
352   for (i = 0; i < n_ins; ++i) {
353     assert(!get_region_in(reg, i));
354   }
355 }
356
357 /* Compute the ex freq for current_ir_graph */
358 static void compute_frequency(int default_loop_weight) {
359   ir_loop *outermost_l = get_irg_loop(current_ir_graph);
360   pdeq *block_worklist = new_pdeq1(outermost_l);
361
362   /* Outermost start is considered a loop head.  We will soon multiply
363      by default_loop_weight. */
364   set_region_exec_freq(outermost_l, 1.0/default_loop_weight);
365
366   while (!pdeq_empty(block_worklist)) {
367     ir_loop *l = (ir_loop *)pdeq_getl(block_worklist);
368     int i, n_elems = get_loop_n_elements(l);
369
370     /* The header is initialized with the frequency of the full loop times the iteration weight. */
371     check_proper_head(l, get_loop_element(l, 0).son);
372
373     for (i = 0; i < n_elems; ++i) {
374       loop_element e = get_loop_element(l, i);
375       if (is_ir_loop(e.son)) pdeq_putr(block_worklist, e.son);
376       compute_region_freqency(e.son, default_loop_weight * get_region_exec_freq(l));
377     }
378   }
379   del_pdeq(block_worklist);
380 }
381
382 /* Compute the execution frequency for all blocks in the given
383  * graph.
384  *
385  * irg:                 The graph to be analyzed.
386  * default_loop_weight: The number of executions of a loop.
387  */
388 void compute_execution_frequency(ir_graph *irg, int default_loop_weight, double exception_probability) {
389   ir_graph *rem = current_ir_graph;
390   current_ir_graph = irg;
391   exception_prob = exception_probability;
392   if (!exec_freq_set) exec_freq_set = new_set(exec_freq_cmp, 256);
393
394   precompute_cond_evaluation();
395   construct_intervals(current_ir_graph);
396   compute_frequency(default_loop_weight);
397
398   set_irg_exec_freq_state(irg, exec_freq_consistent);
399   if (get_irp_exec_freq_state() == exec_freq_none)
400     set_irp_exec_freq_state(exec_freq_inconsistent);
401
402   /*
403     dump_loop_tree     (current_ir_graph, "-execfreq");
404     dump_ir_block_graph(current_ir_graph, "-execfreq");
405     dump_interval_graph(current_ir_graph, "-execfreq");
406   */
407
408   current_ir_graph = rem;
409 }
410
411
412 void compute_execution_frequencies(int default_loop_weight, double exception_probability) {
413   int i, n_irgs = get_irp_n_irgs();
414   free_intervals();
415   for (i = 0; i < n_irgs; ++i) {
416     compute_execution_frequency(get_irp_irg(i), default_loop_weight, exception_probability);
417   }
418   set_irp_exec_freq_state(exec_freq_consistent);
419 }
420
421 /** free occupied memory, reset */
422 void free_execution_frequency(void) {
423   int i, n_irgs = get_irp_n_irgs();
424   free_intervals();
425   del_set(exec_freq_set);
426
427   for (i = 0; i < n_irgs; ++i)
428     set_irg_exec_freq_state(get_irp_irg(i), exec_freq_none);
429   set_irp_exec_freq_state(exec_freq_none);
430 }
431
432 exec_freq_state get_irg_exec_freq_state(ir_graph *irg) {
433   return irg->execfreq_state;
434 }
435 void            set_irg_exec_freq_state(ir_graph *irg, exec_freq_state s) {
436   if ((get_irp_exec_freq_state() == exec_freq_consistent && s != exec_freq_consistent) ||
437       (get_irp_exec_freq_state() == exec_freq_none       && s != exec_freq_none))
438     irp->execfreq_state = exec_freq_inconsistent;
439   irg->execfreq_state = s;
440 }
441
442 /* Sets irg and irp exec freq state to inconsistent if it is set to consistent. */
443 void            set_irg_exec_freq_state_inconsistent(ir_graph *irg) {
444   if (get_irg_exec_freq_state(irg) == exec_freq_consistent)
445     set_irg_exec_freq_state(irg, exec_freq_inconsistent);
446 }
447
448 void set_irp_exec_freq_state(exec_freq_state s) {
449   irp->execfreq_state = s;
450 }
451
452 exec_freq_state get_irp_exec_freq_state(void) {
453   return irp->execfreq_state;
454 }
455
456 /* Sets irp and all irg exec freq states to inconsistent if it is set to consistent. */
457 void            set_irp_exec_freq_state_inconsistent(void) {
458   if (get_irp_exec_freq_state() != exec_freq_none) {
459     int i, n_irgs = get_irp_n_irgs();
460     set_irp_exec_freq_state(exec_freq_inconsistent);
461     for (i = 0; i < n_irgs; ++i) {
462       ir_graph *irg = get_irp_irg(i);
463       if (get_irg_exec_freq_state(irg) != exec_freq_none)
464         irg->execfreq_state = exec_freq_inconsistent;
465     }
466   }
467 }