Added if conversion
[libfirm] / ir / opt / ifconv.c
1 /**
2  * If conversion.
3  * Make Mux nodes from Conds where it its possible.
4  * @author Sebastian Hack
5  * @date 4.2.2005
6  */
7
8 #include <stdlib.h>
9 #include <alloca.h>
10
11 #include "irgraph_t.h"
12 #include "irnode_t.h"
13 #include "irmode_t.h"
14 #include "ircons_t.h"
15 #include "irdom_t.h"
16
17 #include "ifconv.h"
18 #include "irflag_t.h"
19
20 #include "debug.h"
21 #include "set.h"
22
23 #define MAX_DEPTH 4
24
25 /*
26  * Mux optimization routines.
27  */
28
29 #if 0
30 static ir_node *local_optimize_mux(ir_node *mux)
31 {
32         int i, n;
33         ir_node *res = mux;
34   ir_node *sel = get_Mux_sel(mux);
35         ir_node *cmp = skip_Proj(sel);
36
37         /* Optimize the children  */
38         for(i = 1, n = get_irn_arity(mux); i < n; ++i) {
39                 ir_node *operand = get_irn_n(mux, i);
40                 if(get_irn_op(operand) == op_Mux)
41                         optimize_mux(operand);
42         }
43
44         /* If we have no cmp above the mux, get out. */
45         if(is_Proj(sel) && get_irn_mode(sel) == mode_b && get_irn_opcode(cmp) == iro_Cmp) {
46
47                 pnc_number cc = get_Proj_proj(sel);
48                 ir_mode *mode = get_irn_mode(mux);
49                 ir_node *block = get_nodes_block(n);
50                 ir_node *cmp_left = get_Cmp_left(cmp);
51                 ir_node *cmp_right = get_Cmp_right(cmp);
52                 ir_node *mux_true = get_Mux_true(mux);
53                 ir_node *mux_false = get_Mux_false(mux);
54
55                 /*
56                  * Check for comparisons with signed integers.
57                  */
58                 if(mode_is_int(mode)                                    /* We need an integral mode */
59                                 && mode_is_signed(mode)   /* which is signed */
60                                 && cc == Lt) {                                          /* and have to compare for < */
61
62                         /*
63                          * Mux(x:T < 0, -1, 0) -> Shrs(x, sizeof_bits(T) - 1)
64                          * Conditions:
65                          * T must be signed.
66                          */
67                         if(classify_Const(cmp_right) == CNST_NULL
68                                 && classify_Const(mux_true) == CNST_ALL_ONE
69                                 && classify_Const(mux_false) == CNST_NULL) {
70
71                                 ir_mode *u_mode = find_unsigned_mode(mode);
72
73                                 res = new_r_Shrs(current_ir_graph, block, cmp_left,
74                                                 new_r_Const_long(current_ir_graph, block, u_mode,
75                                                         get_mode_size_bits(mode) - 1),
76                                                 mode);
77                         }
78
79                         /*
80                          * Mux(0 < x:T, 1, 0) -> Shr(-x, sizeof_bits(T) - 1)
81                          * Conditions:
82                          * T must be signed.
83                          */
84                         else if(classify_Const(cmp_left) == CNST_NULL
85                                 && classify_Const(mux_true) == CNST_ONE
86                                 && classify_Const(mux_false) == CNST_NULL) {
87
88                                 ir_mode *u_mode = find_unsigned_mode(mode);
89
90                                 res = new_r_Shr(current_ir_graph, block,
91
92                                                 /* -x goes to 0 - x in Firm (cmp_left is 0, see the if) */
93                                                 new_r_Sub(current_ir_graph, block, cmp_left, cmp_right, mode),
94
95                                                 /* This is sizeof_bits(T) - 1 */
96                                                 new_r_Const_long(current_ir_graph, block, u_mode,
97                                                         get_mode_size_bits(mode) - 1),
98                                                 mode);
99                         }
100                 }
101         }
102
103         return res;
104 }
105 #endif
106
107 static tarval *get_value_or(ir_node *cnst, tarval *or)
108 {
109         return get_irn_op(cnst) == op_Const ? get_Const_tarval(cnst) : or;
110 }
111
112
113 static ir_node *optimize_mux_chain(ir_node *mux)
114 {
115         int i;
116         ir_node *res;
117         ir_node *ops[2];
118         ir_mode *mode;
119         tarval *null;
120         tarval *minus_one;
121
122         if(get_irn_op(mux) != op_Mux)
123                 return mux;
124
125         res = mux;
126         mode = get_irn_mode(mux);
127         null = get_tarval_null(mode);
128         minus_one = tarval_sub(null, get_tarval_one(mode));
129
130         ops[0] = get_Mux_false(mux);
131         ops[1] = get_Mux_true(mux);
132
133         for(i = 0; i < 2; ++i) {
134                 ir_node *a, *b, *d;
135                 tarval *tva, *tvb, *tvd;
136                 ir_node *child_mux;
137
138                 /*
139                  * This is the or case, the child mux is the false operand
140                  * of the parent mux.
141                  *
142                  * mux(c1, mux(c2, a, b), d)
143                  *
144                  * This can be made into:
145                  * 1) mux(c1, 0, d) | mux(c2, a, b)
146                  *    if a | d == d and b | d == d
147                  *
148                  * 2) mux(c1, -1, d) & mux(c2, a, b)
149                  *    if a & d == d and a & b == b
150                  */
151                 if(get_irn_op(ops[i]) == op_Mux) {
152
153                         child_mux = ops[i];
154                         a = get_Mux_false(child_mux);
155                         b = get_Mux_true(child_mux);
156                         d = ops[1 - i];
157
158                         /* Try the or stuff */
159                         tva = get_value_or(a, minus_one);
160                         tvb = get_value_or(b, minus_one);
161                         tvd = get_value_or(d, null);
162
163                         if(tarval_cmp(tarval_or(tva, tvd), tvd) == Eq
164                                         && tarval_cmp(tarval_or(tvb, tvd), tvd) == Eq) {
165
166                                 ops[i] = new_Const(mode, null);
167                                 res = new_r_Or(current_ir_graph, get_nodes_block(mux),
168                                                 mux, child_mux, mode);
169                                 break;
170                         }
171
172                         /* If the or didn't go, try the and stuff */
173                         tva = get_value_or(a, null);
174                         tvb = get_value_or(b, null);
175                         tvd = get_value_or(d, minus_one);
176
177                         if(tarval_cmp(tarval_and(tva, tvd), tvd) == Eq
178                                         && tarval_cmp(tarval_and(tvb, tvd), tvd) == Eq) {
179
180                                 ops[i] = new_Const(mode, minus_one);
181                                 res = new_r_And(current_ir_graph, get_nodes_block(mux),
182                                                 mux, child_mux, mode);
183                                 break;
184                         }
185                 }
186         }
187
188         set_irn_n(mux, 1, optimize_mux_chain(ops[0]));
189         set_irn_n(mux, 2, optimize_mux_chain(ops[1]));
190
191         return res;
192 }
193
194
195 /***********************************************************
196  * The If conversion itself.
197  ***********************************************************/
198
199 /**
200  * Default options.
201  */
202 static opt_if_conv_info_t default_info = {
203         4
204 };
205
206 /** THe debugging module. */
207 static firm_dbg_module_t *dbg;
208
209 /**
210  * A simple check for sde effects upton an opcode of a ir node.
211  * @param irn The ir node to check,
212  * @return 1 if the opcode itself may produce side effects, 0 if not.
213  */
214 static INLINE int has_side_effects(const ir_node *irn)
215 {
216         opcode opc = get_irn_opcode(irn);
217
218         if(opc == iro_Cmp)
219                 return 0;
220
221         return !mode_is_datab(get_irn_mode(irn));
222 }
223
224 /**
225  * Decdies, if a given expression and its subexpressions
226  * (to certain, also given extent) can be moved to a block.
227  * @param expr The expression to examine.
228  * @param block The block where the expression should go.
229  * @param depth The current depth, passed recursively. Use 0 for
230  * non-recursive calls.
231  * @param max_depth The maximum depth to which the expression should be
232  * examined.
233  */
234 static int _can_move_to(ir_node *expr, ir_node *dest_block, int depth, int max_depth)
235 {
236         int i, n;
237         int res = 1;
238         ir_node *expr_block = get_nodes_block(expr);
239
240
241         /*
242          * If we are forced to look too deep into the expression,
243          * treat it like it could not be moved.
244          */
245         if(depth >= max_depth) {
246                 res = 0;
247                 goto end;
248         }
249
250         /*
251          * If the block of the expression dominates the specified
252          * destination block, it does not matter if the expression
253          * has side effects or anything else. It is executed on each
254          * path the destination block is reached.
255          */
256         if(block_dominates(expr_block, dest_block))
257                 goto end;
258
259         /*
260          * This should be superflous and could be converted into a assertion.
261          * The destination block _must_ dominate the block of the expression,
262          * else the expression could be used without its definition.
263          */
264         if(!block_dominates(dest_block, expr_block)) {
265                 res = 0;
266                 goto end;
267         }
268
269         /*
270          * Surely, if the expression does not have a data mode, it is not
271          * movable. Perhaps onw should also test the floating property of
272          * the opcode/node.
273          */
274         if(has_side_effects(expr)) {
275                 res = 0;
276                 goto end;
277         }
278
279         /*
280          * If the node looks alright so far, look at its operands and
281          * check them out. If one of them cannot be moved, this one
282          * cannot be moved either.
283          */
284         for(i = 0, n = get_irn_arity(expr); i < n; ++i) {
285                 ir_node *op = get_irn_n(expr, i);
286                 int new_depth = is_Proj(op) ? depth : depth + 1;
287                 if(!_can_move_to(op, dest_block, new_depth, max_depth)) {
288                         res = 0;
289                         goto end;
290                 }
291         }
292
293 end:
294         DBG((dbg, LEVEL_5, "\t\t\tcan move to(%d) %n: %d\n", depth, expr, res));
295
296         return res;
297 }
298
299 /**
300  * Convenience function for _can_move_to.
301  * Checks, if an expression can be moved to another block. The check can
302  * be limited to a expression depth meaning if we need to crawl in
303  * deeper into an expression than a given threshold to examine if
304  * it can be moved, the expression is rejected and the test returns
305  * false.
306  * @param expr The expression to check for.
307  * @param dest_block The destination block you want @p expr to be.
308  * @param max_depth The maximum depth @p expr should be investigated.
309  * @return 1, if the expression can be moved to the destination block,
310  * 0 if not.
311  */
312 static INLINE int can_move_to(ir_node *expr, ir_node *dest_block, int max_depth)
313 {
314         return _can_move_to(expr, dest_block, 0, max_depth);
315 }
316
317 static void move_to(ir_node *expr, ir_node *dest_block)
318 {
319         int i, n;
320         ir_node *expr_block = get_nodes_block(expr);
321
322         /*
323          * If we reached the dominator, we are done.
324          * We will never put code through the dominator
325          */
326         if(block_dominates(expr_block, dest_block))
327                 return;
328
329         for(i = 0, n = get_irn_arity(expr); i < n; ++i)
330                 move_to(get_irn_n(expr, i), dest_block);
331
332         set_nodes_block(expr, dest_block);
333 }
334
335 /**
336  * Information about a cond node.
337  */
338 typedef struct _cond_t {
339         ir_node *cond;                          /**< The cond node. */
340         ir_node *mux;                                   /**< The mux node, that will be generated for this cond. */
341
342         /**
343          * Information about the both 'branches'
344          * (true and false), the cond creates.
345          */
346         struct {
347                 int pos;                                                /**< Number of the predecessor of the
348                                                                                                         phi block by which this branch is
349                                                                                                         reached. It is -1, if this branch is
350                                                                                                         only reached through another cond. */
351
352                 ir_node *masked_by;     /**< If this cond's branch is only reached
353                                                                                                         through another cond, we store this
354                                                                                                         cond ir_node here. */
355         } cases[2];
356 } cond_t;
357
358 /**
359  * Compare two conds for use in a firm set.
360  * Two cond_t's are equal, if they designate the same cond node.
361  * @param a A cond_t
362  * @param b Another one.
363  * @param size Not used.
364  * @return 0 (!) if they are equal, != 0 otherwise.
365  */
366 static int cond_cmp(const void *a, const void *b, size_t size)
367 {
368         const cond_t *x = a;
369         const cond_t *y = b;
370         return x->cond != y->cond;
371 }
372
373 /**
374  * @see find_conds.
375  */
376 static void _find_conds(ir_node *irn, ir_node *start_block,
377                 ir_node *dominator, ir_node *masked_by, int pos, int depth, set *conds)
378 {
379         ir_node *block;
380
381         block = get_nodes_block(irn);
382
383         if(block_dominates(dominator, block)) {
384                 ir_node *cond = NULL;
385                 int i, n;
386
387                 /* We ran into a loop, since we saw the start block twice. */
388                 if(block == start_block && depth > 0)
389                         return;
390
391                 /* check, if we're on a ProjX */
392                 if(is_Proj(irn) && get_irn_mode(irn) == mode_X) {
393
394                         int proj = get_Proj_proj(irn);
395                         cond = get_Proj_pred(irn);
396
397                         /* Check, if the pred of the proj is a Cond
398                          * with a Projb as selector. */
399                         if(get_irn_opcode(cond) == iro_Cond
400                                         && get_irn_mode(get_Cond_selector(cond)) == mode_b) {
401
402                                 cond_t *res, c;
403
404                                 c.cond = cond;
405                                 c.mux = NULL;
406                                 c.cases[0].pos = -1;
407                                 c.cases[1].pos = -1;
408
409                                 /* get or insert the cond info into the set. */
410                                 res = set_insert(conds, &c, sizeof(c), HASH_PTR(cond));
411
412                                 /*
413                                  * Link it to the cond ir_node. We need that later, since
414                                  * one cond masks the other we want to retreive the cond_t
415                                  * data from the masking cond ir_node.
416                                  */
417                                 set_irn_link(cond, res);
418
419                                 /*
420                                  * Set masked by (either NULL or another cond node.
421                                  * If this cond is truly masked by another one, set
422                                  * the position of the actually investigated branch
423                                  * to -1. Since the cond is masked by another one,
424                                  * there could be more ways from the start block
425                                  * to this branch, so we choose -1.
426                                  */
427                                 res->cases[proj].masked_by = masked_by;
428                                 if(!masked_by)
429                                         res->cases[proj].pos = pos;
430
431                                 DBG((dbg, LEVEL_5, "found cond %n (%s branch) for pos %d in block %n reached by %n\n",
432                                                         cond, get_Proj_proj(irn) ? "true" : "false", pos, block, masked_by));
433                         }
434                 }
435
436                 /* Search recursively from this cond. */
437                 for(i = 0, n = get_irn_arity(block); i < n; ++i) {
438                         ir_node *pred = get_irn_n(block, i);
439
440                         /*
441                          * If the depth is 0 (the first recursion), we set the pos to
442                          * the current viewed predecessor, else we adopt the position
443                          * as given by the caller. We also increase the depth for the
444                          * recursively called functions.
445                          */
446                         _find_conds(pred, start_block, dominator, cond, depth == 0 ? i : pos, depth + 1, conds);
447                 }
448         }
449 }
450
451 /**
452  * A convenience function for _find_conds.
453  * It sets some parameters needed for recursion to appropriate start
454  * values. Always use this function.
455  * @param irn The node to start looking for conds from. This might
456  *      be the phi node we are investigating.
457  * @param dominator The dominator up to which we want to look for conds.
458  * @param conds The set to record the found conds in.
459  */
460 static INLINE void find_conds(ir_node *irn, ir_node *dominator, set *conds)
461 {
462         _find_conds(irn, get_nodes_block(irn), dominator, NULL, 0, 0, conds);
463 }
464
465
466 /**
467  * Make the mux for a given cond.
468  * @param phi The phi node which shall be replaced by a mux.
469  * @param dom The block where the muxes shall be placed.
470  * @param cond The cond information.
471  * @return The mux node made for this cond.
472  */
473 static ir_node *make_mux_on_demand(ir_node *phi, ir_node *dom, cond_t *cond)
474 {
475         int i;
476         ir_node *projb = get_Cond_selector(cond->cond);
477         ir_node *operands[2];
478
479         for(i = 0; i < 2; ++i) {
480
481                 /*
482                  * If this cond branch is masked by another cond, make the mux
483                  * for that cond first, since the mux for this cond takes
484                  * it as an operand.
485                  */
486                 if(cond->cases[i].masked_by) {
487                         cond_t *masking_cond = get_irn_link(cond->cases[i].masked_by);
488                         operands[i] = make_mux_on_demand(phi, dom, masking_cond);
489                 }
490
491                 /*
492                  * If this cond branch is not masked by another cond, take
493                  * the corresponding phi operand as an operand to the mux.
494                  */
495                 else {
496                         assert(cond->cases[i].pos >= 0);
497                         operands[i] = get_irn_n(phi, cond->cases[i].pos);
498                 }
499
500                 /* Move the selected operand to the dominator block. */
501                 move_to(operands[i], dom);
502         }
503
504         /* Move the comparison expression of the cond to the dominator. */
505         move_to(projb, dom);
506
507         /* Make the mux. */
508         cond->mux = new_r_Mux(current_ir_graph, dom, projb,
509                         operands[0], operands[1], get_irn_mode(operands[0]));
510
511         return cond->mux;
512 }
513
514 /**
515  * Examine a phi node if it can be replaced by some muxes.
516  * @param irn A phi node.
517  * @param info Parameters for the if conversion algorithm.
518  */
519 static void check_out_phi(ir_node *irn, opt_if_conv_info_t *info)
520 {
521         int max_depth = info->max_depth;
522         int i;
523         ir_node *block;
524         int arity;
525         ir_node *idom;
526         ir_node *mux = NULL;
527
528         cond_t **conds;
529         cond_t *cond;
530         cond_t *largest_cond;
531         set *cond_set;
532         int n_conds = 0;
533
534         if(!is_Phi(irn))
535                 return;
536
537         block = get_nodes_block(irn);
538         arity = get_irn_arity(irn);
539         idom = get_Block_idom(block);
540
541         assert(is_Phi(irn));
542         assert(get_irn_arity(irn) == get_irn_arity(block));
543         assert(arity > 0);
544
545         cond_set = get_irn_link(block);
546         assert(conds && "no cond set for this phi");
547
548         DBG((dbg, LEVEL_5, "phi candidate: %n\n", irn));
549
550         /*
551          * Check, if we can move all operands of the
552          * phi node to the dominator. Else exit.
553          */
554         for(i = 0; i < arity; ++i) {
555                 if(!can_move_to(get_irn_n(irn, i), idom, max_depth)) {
556                         DBG((dbg, LEVEL_5, "cannot move operand %d of %n to %n\n", i, irn, idom));
557                         return;
558                 }
559         }
560
561         n_conds = set_count(cond_set);
562
563         /* This should never happen and can be turned into an assertion */
564         if(n_conds == 0) {
565                 DBG((dbg, LEVEL_5, "no conds found. how can this be?"));
566                 return;
567         }
568
569         /*
570          * Put all cond information structures into an array.
571          * This is just done for convenience. It's not neccessary.
572          */
573         conds = alloca(n_conds * sizeof(conds[0]));
574         for(i = 0, cond = set_first(cond_set); cond; cond = set_next(cond_set))
575                 conds[i++] = cond;
576
577         /*
578          * Check, if we can move the compare nodes of the conds to
579          * the dominator.
580          */
581         for(i = 0; i < n_conds; ++i) {
582                 ir_node *projb = get_Cond_selector(conds[i]->cond);
583                 if(!can_move_to(projb, idom, max_depth)) {
584                         DBG((dbg, LEVEL_5, "cannot move Projb %d of %n to %n\n", i, projb, idom));
585                         return;
586                 }
587         }
588
589         /*
590          * Find the largest cond (the one that dominates all others)
591          * and start the mux generation from there.
592          */
593         largest_cond = conds[0];
594         DBG((dbg, LEVEL_5, "\tlargest cond %n\n", largest_cond->cond));
595         for(i = 1; i < n_conds; ++i) {
596                 ir_node *curr_largest_block = get_nodes_block(largest_cond->cond);
597                 ir_node *bl = get_nodes_block(conds[i]->cond);
598
599                 if(block_dominates(bl, curr_largest_block)) {
600                         DBG((dbg, LEVEL_5, "\tnew largest cond %n\n", largest_cond->cond));
601                         largest_cond = conds[i];
602                 }
603         }
604
605 #if 0
606         for(i = 0; i < n_conds; ++i) {
607                 cond_t *c = conds[i];
608                 DBG((dbg, LEVEL_5, "\tcond %n (t: (%d,%n), f: (%d,%n))\n", c->cond,
609                                         c->cases[1].pos, c->cases[1].masked_by,
610                                         c->cases[0].pos, c->cases[0].masked_by));
611         }
612 #endif
613
614         /*
615          * Make the mux for the 'largest' cond. This will also
616          * produce all other muxes.
617          * @see make_mux_on_demand.
618          */
619         mux = make_mux_on_demand(irn, idom, largest_cond);
620
621         mux = optimize_mux_chain(mux);
622         /*
623          * Set all preds of the phi node to the mux
624          * for the 'largest' cond.
625          */
626         for(i = 0; i < arity; ++i)
627                 set_irn_n(irn, i, mux);
628 }
629
630 static void annotate_cond_info_pre(ir_node *irn, void *data)
631 {
632         set_irn_link(irn, NULL);
633 }
634
635 static void annotate_cond_info_post(ir_node *irn, void *data)
636 {
637         /*
638          * Check, if the node is a phi
639          * we then compute a set of conds which are reachable from this
640          * phi's block up to its dominator.
641          * The set is attached to the blocks link field.
642          */
643         if(is_Phi(irn)) {
644                 ir_node *block = get_nodes_block(irn);
645                 ir_node **phi_list_head = (ir_node **) data;
646
647                 set *conds = get_irn_link(block);
648
649                 /* If the set is not yet computed, do it now. */
650                 if(!conds) {
651                         ir_node *idom = get_Block_idom(block);
652                         conds = new_set(cond_cmp, 8);
653
654                         /*
655                          * Fill the set with conds we find on the way from
656                          * the block to its dominator.
657                          */
658                         find_conds(irn, idom, conds);
659
660                         /*
661                          * If there where no suitable conds, delete the set
662                          * immediately and reset the set pointer to NULL
663                          */
664                         if(set_count(conds) == 0) {
665                                 del_set(conds);
666                                 conds = NULL;
667                         }
668                 }
669
670                 set_irn_link(block, conds);
671
672                 /*
673                  * If this phi node has a set of conds reachable, enqueue
674                  * the phi node in a list with its link field.
675                  * Then, we do not have to walk the graph again. We can
676                  * use the list to reach all phi nodes for which if conversion
677                  * can be tested.
678                  */
679                 if(conds) {
680                         ir_node *old = *phi_list_head;
681                         set_irn_link(irn, old);
682                         *phi_list_head = irn;
683                 }
684
685         }
686 }
687
688 static void free_sets(ir_node *irn, void *data)
689 {
690         if(is_Block(irn) && get_irn_link(irn)) {
691                 set *conds = get_irn_link(irn);
692                 del_set(conds);
693         }
694 }
695
696 void opt_if_conv(ir_graph *irg, opt_if_conv_info_t *params)
697 {
698         opt_if_conv_info_t *p = params ? params : &default_info;
699         ir_node *list_head = NULL;
700
701         if(!get_opt_if_conversion())
702                 return;
703
704         dbg = firm_dbg_register("firm.opt.ifconv");
705         firm_dbg_set_mask(dbg, -1);
706
707         compute_doms(irg);
708         DBG((dbg, LEVEL_4, "if conversion for irg %s(%p)\n",
709                                 get_entity_name(get_irg_entity(irg)), irg));
710
711         irg_walk_graph(irg, annotate_cond_info_pre, annotate_cond_info_post, &list_head);
712
713         /* traverse the list of linked phis */
714         while(list_head) {
715                 check_out_phi(list_head, p);
716                 list_head = get_irn_link(list_head);
717         }
718
719         irg_walk_graph(irg, free_sets, NULL, NULL);
720 }