9b48729c4b1340b216dce0b8f9a392f5805c10a3
[libfirm] / ir / opt / opt_osr.c
1 /**
2  * Project:     libFIRM
3  * File name:   ir/opt/opt_osr.c
4  * Purpose:     Operator Strength Reduction, based on
5  *              Keith D. Cooper, L. Taylor Simpson, Christopher A. Vick
6  * Author:      Michael Beck
7  * Modified by:
8  * Created:     12.5.2006
9  * CVS-ID:      $Id$
10  * Copyright:   (c) 2006 Universität Karlsruhe
11  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
12  */
13 #ifdef HAVE_CONFIG_H
14 #include "config.h"
15 #endif
16
17 #ifdef HAVE_MALLOC_H
18 #include <malloc.h>
19 #endif
20 #ifdef HAVE_ALLOCA_H
21 #include <alloca.h>
22 #endif
23
24 #include "opt_osr.h"
25 #include "irgraph.h"
26 #include "ircons.h"
27 #include "irop_t.h"
28 #include "irloop.h"
29 #include "irdom.h"
30 #include "irgmod.h"
31 #include "irflag_t.h"
32 #include "irgwalk.h"
33 #include "irouts.h"
34 #include "debug.h"
35 #include "obst.h"
36 #include "set.h"
37 #include "tv.h"
38 #include "hashptr.h"
39 #include "irtools.h"
40 #include "irloop_t.h"
41 #include "array.h"
42 #include "firmstat.h"
43
44 /** The debug handle. */
45 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
46
47 /** A scc. */
48 typedef struct scc {
49         ir_node *head;          /**< the head of the list */
50 } scc;
51
52 /** A node entry */
53 typedef struct node_entry {
54         unsigned DFSnum;    /**< the DFS number of this node */
55         unsigned low;       /**< the low number of this node */
56         ir_node  *header;   /**< the header of this node */
57         int      in_stack;  /**< flag, set if the node is on the stack */
58         ir_node  *next;     /**< link to the next node the the same scc */
59         scc      *pscc;     /**< the scc of this node */
60         unsigned POnum;     /**< the post order number for blocks */
61 } node_entry;
62
63 /** The environment. */
64 typedef struct iv_env {
65         struct obstack obst;    /**< an obstack for allocations */
66         ir_node  **stack;       /**< the node stack */
67         int      tos;           /**< tos index */
68         unsigned nextDFSnum;    /**< the current DFS number */
69         unsigned POnum;         /**< current post order number */
70         set      *quad_map;     /**< a map from (op, iv, rc) to node */
71         set      *lftr_edges;   /**< the set of lftr edges */
72         unsigned replaced;      /**< number of replaced ops */
73         unsigned lftr_replaced; /**< number of applied linear function test replacements */
74         unsigned flags;         /**< additional flags */
75         /** Function called to process a SCC. */
76         void (*process_scc)(scc *pscc, struct iv_env *env);
77 } iv_env;
78
79 /**
80  * An entry in the (op, node, node) -> node map.
81  */
82 typedef struct quad_t {
83         opcode  code;  /**< the opcode of the reduced operation */
84         ir_node *op1;  /**< the first operand the reduced operation */
85         ir_node *op2;  /**< the second operand of the reduced operation */
86
87         ir_node *res; /**< the reduced operation */
88 } quad_t;
89
90 /**
91  * A LFTR edge.
92  */
93 typedef struct LFTR_edge {
94         ir_node *src;   /**< the source node */
95         ir_node *dst;   /**< the destination node */
96         opcode  code;   /**< the opcode that must be applied */
97         ir_node *rc;    /**< the region const that must be applied */
98 } LFTR_edge;
99
100 /* forward */
101 static ir_node *reduce(ir_node *orig, ir_node *iv, ir_node *rc, iv_env *env);
102
103 /**
104  * Compare two LFTR edges.
105  */
106 static int LFTR_cmp(const void *e1, const void *e2, size_t size) {
107         const LFTR_edge *l1 = e1;
108         const LFTR_edge *l2 = e2;
109
110         return l1->src != l2->src;
111 }
112
113 /**
114  * Find a LFTR edge.
115  */
116 static LFTR_edge *LFTR_find(ir_node *src, iv_env *env) {
117         LFTR_edge key;
118
119         key.src  = src;
120
121         return set_find(env->lftr_edges, &key, sizeof(key), HASH_PTR(src));
122 }
123
124 /**
125  * Add a LFTR edge.
126  */
127 static void LFTR_add(ir_node *src, ir_node *dst, opcode code, ir_node *rc, iv_env *env) {
128         LFTR_edge key;
129
130         key.src  = src;
131         key.dst  = dst;
132         key.code = code;
133         key.rc   = rc;
134
135         /*
136          * There might be more than one edge here. This is rather bad
137          * because we currently store only one.
138          */
139 //      assert(LFTR_find(src, env) == NULL);
140         set_insert(env->lftr_edges, &key, sizeof(key), HASH_PTR(src));
141 }
142
143 /**
144  * Gets the node_entry of a node
145  */
146 static node_entry *get_irn_ne(ir_node *irn, iv_env *env) {
147         node_entry *e = get_irn_link(irn);
148
149         if (! e) {
150                 e = obstack_alloc(&env->obst, sizeof(*e));
151                 memset(e, 0, sizeof(*e));
152                 set_irn_link(irn, e);
153         }
154         return e;
155 }
156
157 /**
158  * Check if irn is an IV.
159  *
160  * @param irn  the node to check
161  * @param env  the environment
162  *
163  * @returns the header if it is one, NULL else
164  */
165 static ir_node *is_iv(ir_node *irn, iv_env *env) {
166         return get_irn_ne(irn, env)->header;
167 }
168
169 /**
170  * Check if irn is a region constant.
171  * The block or irn must strictly dominate the header block.
172  *
173  * @param irn           the node to check
174  * @param header_block  the header block of the induction variable
175  */
176 static int is_rc(ir_node *irn, ir_node *header_block) {
177         ir_node *block = get_nodes_block(irn);
178
179         return (block != header_block) && block_dominates(block, header_block);
180 }
181
182 /**
183  * Set compare function for the quad set.
184  */
185 static int quad_cmp(const void *e1, const void *e2, size_t size) {
186         const quad_t *c1 = e1;
187         const quad_t *c2 = e2;
188
189         return c1->code != c2->code || c1->op1 != c2->op1 || c1->op2 != c2->op2;
190 }
191
192 /**
193  * Check if an reduced operation was already calculated.
194  *
195  * @param code  the opcode of the operation
196  * @param op1   the first operand of the operation
197  * @param op2   the second operand of the operation
198  * @param env   the environment
199  *
200  * @return the already reduced node or NULL if this operation is not yet reduced
201  */
202 static ir_node *search(opcode code, ir_node *op1, ir_node *op2, iv_env *env) {
203         quad_t key, *entry;
204
205         key.code = code;
206         key.op1 = op1;
207         key.op2 = op2;
208
209         entry = set_find(env->quad_map, &key, sizeof(key),
210                          (code * 9) ^ HASH_PTR(op1) ^HASH_PTR(op2));
211         if (entry)
212                 return entry->res;
213         return NULL;
214 }
215
216 /**
217  * Add an reduced operation.
218  *
219  * @param code    the opcode of the operation
220  * @param op1     the first operand of the operation
221  * @param op2     the second operand of the operation
222  * @param result  the result of the reduced operation
223  * @param env     the environment
224  */
225 static void add(opcode code, ir_node *op1, ir_node *op2, ir_node *result, iv_env *env) {
226         quad_t key;
227
228         key.code = code;
229         key.op1  = op1;
230         key.op2  = op2;
231         key.res  = result;
232
233         set_insert(env->quad_map, &key, sizeof(key),
234                    (code * 9) ^ HASH_PTR(op1) ^HASH_PTR(op2));
235 }
236
237 /**
238  * Find a location where to place a bin-op whose operands are in
239  * block1 and block2.
240  *
241  * @param block1  the block of the first operand
242  * @param block2  the block of the second operand
243  *
244  * Note that we know here that such a place must exists. Moreover, this means
245  * that either block1 dominates block2 or vice versa. So, just return
246  * the "smaller" one.
247  */
248 static ir_node *find_location(ir_node *block1, ir_node *block2) {
249         if (block_dominates(block1, block2))
250                 return block2;
251         assert(block_dominates(block2, block1));
252         return block1;
253 }
254
255 /**
256  * Create a node that executes an op1 code op1 operation.
257  *
258  * @param code   the opcode to execute
259  * @param db     debug info to add to the new node
260  * @param op1    the first operand
261  * @param op2    the second operand
262  * @param mode   the mode of the new operation
263  *
264  * @return the newly created node
265  */
266 static ir_node *do_apply(opcode code, dbg_info *db, ir_node *op1, ir_node *op2, ir_mode *mode) {
267         ir_graph *irg = current_ir_graph;
268         ir_node *result;
269         ir_node *block = find_location(get_nodes_block(op1), get_nodes_block(op2));
270
271         switch (code) {
272         case iro_Mul:
273                 result = new_rd_Mul(db, irg, block, op1, op2, mode);
274                 break;
275         case iro_Add:
276                 result = new_rd_Add(db, irg, block, op1, op2, mode);
277                 break;
278         case iro_Sub:
279                 result = new_rd_Sub(db, irg, block, op1, op2, mode);
280                 break;
281         default:
282                 assert(0);
283                 result = NULL;
284         }
285         return result;
286 }
287
288 /**
289  * The Apply operation.
290  *
291  * @param orig   the node that represent the original operation and determines
292  *               the opcode, debug-info and mode of a newly created one
293  * @param op1    the first operand
294  * @param op2    the second operand
295  * @param env    the environment
296  *
297  * @return the newly created node
298  */
299 static ir_node *apply(ir_node *orig, ir_node *op1, ir_node *op2, iv_env *env) {
300         opcode code = get_irn_opcode(orig);
301         ir_node *result = search(code, op1, op2, env);
302
303         if (! result) {
304                 dbg_info *db = get_irn_dbg_info(orig);
305                 ir_node *op1_header = get_irn_ne(op1, env)->header;
306                 ir_node *op2_header = get_irn_ne(op2, env)->header;
307
308                 if (op1_header != NULL && is_rc(op2, op1_header)) {
309                         result = reduce(orig, op1, op2, env);
310                 }
311                 else if (op2_header != NULL && is_rc(op1, op2_header)) {
312                         result = reduce(orig, op2, op1, env);
313                 }
314                 else {
315                         result = do_apply(code, db, op1, op2, get_irn_mode(orig));
316                         get_irn_ne(result, env)->header = NULL;         }
317         }
318         return result;
319 }
320
321 /**
322  * The Reduce operation.
323  *
324  * @param orig   the node that represent the original operation and determines
325  *               the opcode, debug-info and mode of a newly created one
326  * @param iv     the induction variable
327  * @param rc     the region constant
328  * @param env    the environment
329  *
330  * @return the reduced node
331  */
332 static ir_node *reduce(ir_node *orig, ir_node *iv, ir_node *rc, iv_env *env) {
333         opcode code = get_irn_opcode(orig);
334         ir_node *result = search(code, iv, rc, env);
335
336         if (! result) {
337                 node_entry *e, *iv_e;
338                 int i, n;
339                 ir_mode *mode = get_irn_mode(orig);
340
341                 result = exact_copy(iv);
342
343                 /* Beware: we must always create a new nduction variable with the same mode
344                    as the node we are replacing. Espicially this means the mode might be changed
345                    from P to I and back. This is always possible, because we have only Phi, Add
346                    and Sub nodes. */
347                 set_irn_mode(result, mode);
348                 add(code, iv, rc, result, env);
349                 DB((dbg, LEVEL_3, "   Created new %+F for %+F (%s %+F)\n", result, iv,
350                         get_irn_opname(orig), rc));
351
352                 iv_e = get_irn_ne(iv, env);
353                 e    = get_irn_ne(result, env);
354                 e->header = iv_e->header;
355
356                 /* create the LFTR edge */
357                 LFTR_add(iv, result, code, rc, env);
358
359                 n = get_irn_arity(result);
360                 for (i = 0; i < n; ++i) {
361                         ir_node *o = get_irn_n(result, i);
362
363                         e = get_irn_ne(o, env);
364                         if (e->header == iv_e->header)
365                                 o = reduce(orig, o, rc, env);
366                         else if (is_Phi(result))
367                                 o = apply(orig, o, rc, env);
368                         else {
369                                 if (code == iro_Mul)
370                                         o = apply(orig, o, rc, env);
371                         }
372                         set_irn_n(result, i, o);
373                 }
374         }
375         else {
376                 DB((dbg, LEVEL_3, "   Already Created %+F for %+F (%s %+F)\n", result, iv,
377                         get_irn_opname(orig), rc));
378         }
379         return result;
380 }
381
382 /**
383  * The Replace operation.
384  *
385  * @param irn   the node that will be replaced
386  * @param iv    the induction variable
387  * @param rc    the region constant
388  * @param env   the environment
389  */
390 static int replace(ir_node *irn, ir_node *iv, ir_node *rc, iv_env *env) {
391         ir_node *result;
392         ir_loop *iv_loop  = get_irn_loop(get_nodes_block(iv));
393         ir_loop *irn_loop = get_irn_loop(get_nodes_block(irn));
394
395         /* only replace nodes that are in the same (or deeper loops) */
396         if (get_loop_depth(irn_loop) >= get_loop_depth(iv_loop)) {
397                 DB((dbg, LEVEL_2, "  Replacing %+F\n", irn));
398
399                 result = reduce(irn, iv, rc, env);
400                 if (result != irn) {
401                         node_entry *e, *iv_e;
402
403                         hook_strength_red(current_ir_graph, irn);
404                         exchange(irn, result);
405                         e = get_irn_ne(result, env);
406                         iv_e = get_irn_ne(iv, env);
407                         e->header = iv_e->header;
408                 }
409                 return 1;
410         }
411         return 0;
412 }
413
414 /**
415  * Check if a node can be replaced (+, -, *).
416  *
417  * @param irn   the node to check
418  * @param env   the environment
419  *
420  * @return non-zero if irn should be Replace'd
421  */
422 static int check_replace(ir_node *irn, iv_env *env) {
423         ir_node *left, *right, *iv, *rc;
424         ir_op   *op  = get_irn_op(irn);
425         opcode  code = get_op_code(op);
426         ir_node *liv, *riv;
427
428         switch (code) {
429         case iro_Mul:
430         case iro_Add:
431         case iro_Sub:
432                 iv = rc = NULL;
433
434                 left  = get_binop_left(irn);
435                 right = get_binop_right(irn);
436
437                 liv = is_iv(left, env);
438                 riv = is_iv(right, env);
439                 if (liv && is_rc(right, liv)) {
440                         iv = left; rc = right;
441                 }
442                 else if (riv && is_op_commutative(op) &&
443                                     is_rc(left, riv)) {
444                         iv = right; rc = left;
445                 }
446
447                 if (iv) {
448                         if (code == iro_Mul && env->flags & osr_flag_ignore_x86_shift) {
449                                 if (is_Const(rc)) {
450                                         tarval *tv = get_Const_tarval(rc);
451
452                                         if (tarval_is_long(tv)) {
453                                                 long value = get_tarval_long(tv);
454
455                                                 if (value == 2 || value == 4 || value == 8) {
456                                                         /* do not reduce multiplications by 2, 4, 8 */
457                                                         break;
458                                                 }
459                                         }
460                                 }
461                         }
462
463                         return replace(irn, iv, rc, env);
464                 }
465                 break;
466         default:
467                 break;
468         }
469         return 0;
470 }
471
472 /**
473  * Check which SCC's are induction variables.
474  *
475  * @param pscc  a SCC
476  * @param env   the environment
477  */
478 static void classify_iv(scc *pscc, iv_env *env) {
479         ir_node *irn, *next, *header = NULL;
480         node_entry *b, *h = NULL;
481         int j, only_phi, num_outside;
482         ir_node *out_rc;
483
484         /* find the header block for this scc */
485         for (irn = pscc->head; irn; irn = next) {
486                 node_entry *e = get_irn_link(irn);
487                 ir_node *block = get_nodes_block(irn);
488
489                 next = e->next;
490                 b = get_irn_ne(block, env);
491
492                 if (header) {
493                         if (h->POnum < b->POnum) {
494                                 header = block;
495                                 h      = b;
496                         }
497                 }
498                 else {
499                         header = block;
500                         h      = b;
501                 }
502         }
503
504         /* check if this scc contains only Phi, Add or Sub nodes */
505         only_phi    = 1;
506         num_outside = 0;
507         out_rc      = NULL;
508         for (irn = pscc->head; irn; irn = next) {
509                 node_entry *e = get_irn_ne(irn, env);
510
511                 next = e->next;
512                 switch (get_irn_opcode(irn)) {
513                 case iro_Add:
514                 case iro_Sub:
515                         only_phi = 0;
516                         /* fall through */
517                 case iro_Phi:
518                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
519                                 ir_node *pred  = get_irn_n(irn, j);
520                                 node_entry *pe = get_irn_ne(pred, env);
521
522                                 if (pe->pscc != e->pscc) {
523                                         /* not in the same SCC, must be a region const */
524                                         if (! is_rc(pred, header)) {
525                                                 /* not an induction variable */
526                                                 goto fail;
527                                         }
528                                         if (! out_rc) {
529                                                 out_rc = pred;
530                                                 ++num_outside;
531                                         } else if (out_rc != pred) {
532                                                 ++num_outside;
533                                         }
534                                 }
535                         }
536                         break;
537                 default:
538                         /* not an induction variable */
539                         goto fail;
540                 }
541         }
542         /* found an induction variable */
543         DB((dbg, LEVEL_2, "  Found an induction variable:\n  "));
544         if (only_phi && num_outside == 1) {
545                 /* a phi cycle with only one real predecessor can be collapsed */
546                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
547
548                 for (irn = pscc->head; irn; irn = next) {
549                         node_entry *e = get_irn_ne(irn, env);
550                         next = e->next;
551                         e->header = NULL;
552                         exchange(irn, out_rc);
553                 }
554                 ++env->replaced;
555                 return;
556         }
557
558         /* set the header for every node in this scc */
559         for (irn = pscc->head; irn; irn = next) {
560                 node_entry *e = get_irn_ne(irn, env);
561                 e->header = header;
562                 next = e->next;
563                 DB((dbg, LEVEL_2, " %+F,", irn));
564         }
565         DB((dbg, LEVEL_2, "\n"));
566         return;
567
568 fail:
569         for (irn = pscc->head; irn; irn = next) {
570                 node_entry *e = get_irn_ne(irn, env);
571
572                 next = e->next;
573                 if (! check_replace(irn, env))
574                         e->header = NULL;
575         }
576 }
577
578 /**
579  * Process a SCC for the operator strength reduction.
580  *
581  * @param pscc  the SCC
582  * @param env   the environment
583  */
584 static void process_scc(scc *pscc, iv_env *env) {
585         ir_node *head = pscc->head;
586         node_entry *e = get_irn_link(head);
587
588 #ifdef DEBUG_libfirm
589         {
590                 ir_node *irn, *next;
591
592                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
593                 for (irn = pscc->head; irn; irn = next) {
594                         node_entry *e = get_irn_link(irn);
595
596                         next = e->next;
597
598                         DB((dbg, LEVEL_4, " %+F,", irn));
599                 }
600                 DB((dbg, LEVEL_4, "\n"));
601         }
602 #endif
603
604         if (e->next == NULL) {
605                 /* this SCC has only a single member */
606                 check_replace(head, env);
607         } else {
608                 classify_iv(pscc, env);
609         }
610 }
611
612 /**
613  * If an SCC is a Phi only cycle, remove it.
614  */
615 static void remove_phi_cycle(scc *pscc, iv_env *env) {
616         ir_node *irn, *next;
617         int j;
618         ir_node *out_rc;
619
620         /* check if this scc contains only Phi, Add or Sub nodes */
621         out_rc      = NULL;
622         for (irn = pscc->head; irn; irn = next) {
623                 node_entry *e = get_irn_ne(irn, env);
624
625                 next = e->next;
626                 if (! is_Phi(irn))
627                         return;
628
629                 for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
630                         ir_node *pred  = get_irn_n(irn, j);
631                         node_entry *pe = get_irn_ne(pred, env);
632
633                         if (pe->pscc != e->pscc) {
634                                 /* not in the same SCC, must be the only input */
635                                 if (! out_rc) {
636                                         out_rc = pred;
637                                 } else if (out_rc != pred) {
638                                         return;
639                                 }
640                         }
641                 }
642         }
643         /* found a Phi cycle */
644         DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
645
646         for (irn = pscc->head; irn; irn = next) {
647                 node_entry *e = get_irn_ne(irn, env);
648                 next = e->next;
649                 e->header = NULL;
650                 exchange(irn, out_rc);
651         }
652         ++env->replaced;
653 }
654
655 /**
656  * Process a SCC for the Phi cycle removement.
657  *
658  * @param pscc  the SCC
659  * @param env   the environment
660  */
661 static void process_phi_only_scc(scc *pscc, iv_env *env) {
662         ir_node *head = pscc->head;
663         node_entry *e = get_irn_link(head);
664
665 #ifdef DEBUG_libfirm
666         {
667                 ir_node *irn, *next;
668
669                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
670                 for (irn = pscc->head; irn; irn = next) {
671                         node_entry *e = get_irn_link(irn);
672
673                         next = e->next;
674
675                         DB((dbg, LEVEL_4, " %+F,", irn));
676                 }
677                 DB((dbg, LEVEL_4, "\n"));
678         }
679 #endif
680
681         if (e->next != NULL)
682                 remove_phi_cycle(pscc, env);
683 }
684
685
686 /**
687  * Push a node onto the stack.
688  *
689  * @param env   the environment
690  * @param n     the node to push
691  */
692 static void push(iv_env *env, ir_node *n) {
693         node_entry *e;
694
695         if (env->tos == ARR_LEN(env->stack)) {
696                 int nlen = ARR_LEN(env->stack) * 2;
697                 ARR_RESIZE(ir_node *, env->stack, nlen);
698         }
699         env->stack[env->tos++] = n;
700         e = get_irn_ne(n, env);
701         e->in_stack = 1;
702 }
703
704 /**
705  * pop a node from the stack
706  *
707  * @param env   the environment
708  *
709  * @return  The topmost node
710  */
711 static ir_node *pop(iv_env *env)
712 {
713         ir_node *n = env->stack[--env->tos];
714         node_entry *e = get_irn_ne(n, env);
715
716         e->in_stack = 0;
717         return n;
718 }
719
720 /**
721  * Do Tarjan's SCC algorithm and drive OSR.
722  *
723  * @param irn  start at this node
724  * @param env  the environment
725  */
726 static void dfs(ir_node *irn, iv_env *env)
727 {
728         int i, n;
729         node_entry *node = get_irn_ne(irn, env);
730
731         mark_irn_visited(irn);
732
733         /* do not put blocks into the scc */
734         if (is_Block(irn)) {
735                 n = get_irn_arity(irn);
736                 for (i = 0; i < n; ++i) {
737                         ir_node *pred = get_irn_n(irn, i);
738
739                         if (irn_not_visited(pred))
740                                 dfs(pred, env);
741                 }
742         }
743         else {
744                 ir_node *block = get_nodes_block(irn);
745
746                 node->DFSnum = env->nextDFSnum++;
747                 node->low    = node->DFSnum;
748                 push(env, irn);
749
750                 /* handle the block */
751                 if (irn_not_visited(block))
752                         dfs(block, env);
753
754                 n = get_irn_arity(irn);
755                 for (i = 0; i < n; ++i) {
756                         ir_node *pred = get_irn_n(irn, i);
757                         node_entry *o = get_irn_ne(pred, env);
758
759                         if (irn_not_visited(pred)) {
760                                 dfs(pred, env);
761                                 node->low = MIN(node->low, o->low);
762                         }
763                         if (o->DFSnum < node->DFSnum && o->in_stack)
764                                 node->low = MIN(o->DFSnum, node->low);
765                 }
766                 if (node->low == node->DFSnum) {
767                         scc *pscc = obstack_alloc(&env->obst, sizeof(*pscc));
768                         ir_node *x;
769
770                         pscc->head = NULL;
771                         do {
772                                 node_entry *e;
773
774                                 x = pop(env);
775                                 e = get_irn_ne(x, env);
776                                 e->pscc    = pscc;
777                                 e->next    = pscc->head;
778                                 pscc->head = x;
779                         } while (x != irn);
780
781                         env->process_scc(pscc, env);
782                 }
783         }
784 }
785
786 /**
787  * Do the DFS by starting at the End node of a graph.
788  *
789  * @param irg  the graph to process
790  * @param env  the environment
791  */
792 static void do_dfs(ir_graph *irg, iv_env *env) {
793         ir_graph *rem = current_ir_graph;
794         ir_node *end = get_irg_end(irg);
795         int i, n;
796
797         current_ir_graph = irg;
798         inc_irg_visited(irg);
799
800         /* visit all visible nodes */
801         dfs(end, env);
802
803         /* visit the keep-alives */
804         n = get_End_n_keepalives(end);
805         for (i = 0; i < n; ++i) {
806                 ir_node *ka = get_End_keepalive(end, i);
807
808                 if (irn_not_visited(ka))
809                         dfs(ka, env);
810         }
811
812         current_ir_graph = rem;
813 }
814
815 /**
816  * Post-block-walker: assign the post-order number.
817  */
818 static void assign_po(ir_node *block, void *ctx) {
819         iv_env *env = ctx;
820         node_entry *e = get_irn_ne(block, env);
821
822         e->POnum = env->POnum++;
823 }
824
825 /**
826  * Follows the LFTR edges and return the last node in the chain.
827  *
828  * @param irn  the node that should be followed
829  * @param env  the IV environment
830  *
831  * @note
832  * In the current implementation only the last edge is stored, so
833  * only one chain exists. That's why we might miss some opportunities.
834  */
835 static ir_node *followEdges(ir_node *irn, iv_env *env) {
836         for (;;) {
837                 LFTR_edge *e = LFTR_find(irn, env);
838                 if (e)
839                         irn = e->dst;
840                 else
841                         return irn;
842         }
843 }
844
845 /**
846  * Apply one LFTR edge operation.
847  * Return NULL if the transformation cannot be done safely without
848  * an Overflow.
849  *
850  * @param rc   the IV node that should be translated
851  * @param e    the LFTR edge
852  * @param env  the IV environment
853  *
854  * @return the translated region constant or NULL
855  *         if the translation was not possible
856  *
857  * @note
858  * In the current implementation only the last edge is stored, so
859  * only one chain exists. That's why we might miss some opportunities.
860  */
861 static ir_node *applyOneEdge(ir_node *rc, LFTR_edge *e, iv_env *env) {
862         if (env->flags & osr_flag_lftr_with_ov_check) {
863                 tarval *tv_l, *tv_r, *tv;
864                 tarval_int_overflow_mode_t ovmode;
865
866                 /* overflow can only be decided for Consts */
867                 if (! is_Const(e->rc)) {
868                         DB((dbg, LEVEL_4, " = UNKNOWN (%+F)", e->rc));
869                         return NULL;
870                 }
871
872                 tv_l = get_Const_tarval(rc);
873                 tv_r = get_Const_tarval(e->rc);
874
875                 ovmode = tarval_get_integer_overflow_mode();
876                 tarval_set_integer_overflow_mode(TV_OVERFLOW_BAD);
877
878                 switch (e->code) {
879                 case iro_Mul:
880                         tv = tarval_mul(tv_l, tv_r);
881                         DB((dbg, LEVEL_4, " * %+F", tv_r));
882                         break;
883                 case iro_Add:
884                         tv = tarval_add(tv_l, tv_r);
885                         DB((dbg, LEVEL_4, " + %+F", tv_r));
886                         break;
887                 case iro_Sub:
888                         tv = tarval_sub(tv_l, tv_r);
889                         DB((dbg, LEVEL_4, " - %+F", tv_r));
890                         break;
891                 default:
892                         assert(0);
893                         tv = tarval_bad;
894                 }
895                 tarval_set_integer_overflow_mode(ovmode);
896
897                 if (tv == tarval_bad) {
898                         DB((dbg, LEVEL_4, " = OVERFLOW"));
899                         return NULL;
900                 }
901                 return new_r_Const(current_ir_graph, get_irn_n(rc, -1), get_tarval_mode(tv), tv);
902         }
903         return do_apply(e->code, NULL, rc, e->rc, get_irn_mode(rc));
904 }
905
906 /**
907  * Applies the operations represented by the LFTR edges to a
908  * region constant and returns the value.
909  * Return NULL if the transformation cannot be done safely without
910  * an Overflow.
911  *
912  * @param iv   the IV node that starts the LFTR edge chain
913  * @param rc   the region constant that should be translated
914  * @param env  the IV environment
915  *
916  * @return the translated region constant or NULL
917  *         if the translation was not possible
918  */
919 static ir_node *applyEdges(ir_node *iv, ir_node *rc, iv_env *env) {
920         ir_node *irn = iv;
921
922         if (env->flags & osr_flag_lftr_with_ov_check) {
923                 /* overflow can only be decided for Consts */
924                 if (! is_Const(rc)) {
925                         DB((dbg, LEVEL_4, " = UNKNOWN (%+F)\n", rc));
926                         return NULL;
927                 }
928                 DB((dbg, LEVEL_4, "%+F", get_Const_tarval(rc)));
929         }
930
931         for (irn = iv; rc;) {
932                 LFTR_edge *e = LFTR_find(irn, env);
933                 if (e) {
934                         rc = applyOneEdge(rc, e, env);
935                         irn = e->dst;
936                 }
937                 else
938                         break;
939         }
940         DB((dbg, LEVEL_3, "\n"));
941         return rc;
942 }
943
944 /**
945  * Walker, finds Cmp(iv, rc) or Cmp(rc, iv)
946  * and tries to optimize them.
947  */
948 static void do_lftr(ir_node *cmp, void *ctx) {
949         iv_env *env = ctx;
950         ir_node *left, *right, *liv, *riv;
951         ir_node *iv, *rc;
952         ir_node *nleft = NULL, *nright = NULL;
953
954         if (get_irn_op(cmp) != op_Cmp)
955                 return;
956
957         left  = get_Cmp_left(cmp);
958         right = get_Cmp_right(cmp);
959
960         liv = is_iv(left, env);
961         riv = is_iv(right, env);
962         if (liv && is_rc(right, liv)) {
963                 iv = left; rc = right;
964
965                 nright = applyEdges(iv, rc, env);
966                 if (nright && nright != rc) {
967                         nleft = followEdges(iv, env);
968                 }
969         }
970         else if (riv && is_rc(left, riv)) {
971                 iv = right; rc = left;
972
973                 nleft = applyEdges(iv, rc, env);
974                 if (nleft && nleft != rc) {
975                         nright = followEdges(iv, env);
976                 }
977         }
978
979         if (nleft && nright) {
980                 DB((dbg, LEVEL_2, "  LFTR for %+F\n", cmp));
981                 set_Cmp_left(cmp, nleft);
982                 set_Cmp_right(cmp, nright);
983                 ++env->lftr_replaced;
984         }
985 }
986
987 /**
988  * do linear function test replacement.
989  *
990  * @param irg   the graph that should be optimized
991  * @param env   the IV environment
992  */
993 static void lftr(ir_graph *irg, iv_env *env) {
994         irg_walk_graph(irg, NULL, do_lftr, env);
995 }
996
997 /**
998  * Pre-walker: set all node links to NULL and fix the
999  * block of Proj nodes.
1000  */
1001 static void clear_and_fix(ir_node *irn, void *env)
1002 {
1003         set_irn_link(irn, NULL);
1004
1005         if (is_Proj(irn)) {
1006                 ir_node *pred = get_Proj_pred(irn);
1007                 set_irn_n(irn, -1, get_irn_n(pred, -1));
1008         }
1009 }
1010
1011 /* Performs Operator Strength Reduction for the passed graph. */
1012 void opt_osr(ir_graph *irg, unsigned flags) {
1013         iv_env   env;
1014         ir_graph *rem;
1015
1016         if (! get_opt_strength_red()) {
1017                 /* only kill Phi cycles  */
1018                 remove_phi_cycles(irg);
1019                 return;
1020         }
1021
1022         rem = current_ir_graph;
1023         current_ir_graph = irg;
1024
1025         FIRM_DBG_REGISTER(dbg, "firm.opt.osr");
1026
1027         DB((dbg, LEVEL_1, "Doing Operator Strength Reduction for %+F\n", irg));
1028
1029         obstack_init(&env.obst);
1030         env.stack         = NEW_ARR_F(ir_node *, 128);
1031         env.tos           = 0;
1032         env.nextDFSnum    = 0;
1033         env.POnum         = 0;
1034         env.quad_map      = new_set(quad_cmp, 64);
1035         env.lftr_edges    = new_set(LFTR_cmp, 64);
1036         env.replaced      = 0;
1037         env.lftr_replaced = 0;
1038         env.flags         = flags;
1039         env.process_scc   = process_scc;
1040
1041         /* Clear all links and move Proj nodes into the
1042            the same block as it's predecessors.
1043            This can improve the placement of new nodes.
1044          */
1045         irg_walk_graph(irg, NULL, clear_and_fix, NULL);
1046
1047         /* we need dominance */
1048         assure_doms(irg);
1049         assure_irg_outs(irg);
1050
1051         /* calculate the post order number for blocks. */
1052         irg_out_block_walk(get_irg_start_block(irg), NULL, assign_po, &env);
1053
1054         /* calculate the SCC's and drive OSR. */
1055         do_dfs(irg, &env);
1056
1057         if (env.replaced) {
1058                 /* try linear function test replacements */
1059                 //lftr(irg, &env);
1060
1061                 set_irg_outs_inconsistent(irg);
1062                 DB((dbg, LEVEL_1, "Replacements: %u + %u (lftr)\n\n", env.replaced, env.lftr_replaced));
1063         }
1064
1065         del_set(env.lftr_edges);
1066         del_set(env.quad_map);
1067         DEL_ARR_F(env.stack);
1068         obstack_free(&env.obst, NULL);
1069
1070         current_ir_graph = rem;
1071 }
1072
1073 /* Remove any Phi cycles with only one real input. */
1074 void remove_phi_cycles(ir_graph *irg) {
1075         iv_env   env;
1076         ir_graph *rem;
1077
1078         rem = current_ir_graph;
1079         current_ir_graph = irg;
1080
1081         FIRM_DBG_REGISTER(dbg, "firm.opt.remove_phi");
1082
1083         DB((dbg, LEVEL_1, "Doing Phi cycle removement for %+F\n", irg));
1084
1085         obstack_init(&env.obst);
1086         env.stack         = NEW_ARR_F(ir_node *, 128);
1087         env.tos           = 0;
1088         env.nextDFSnum    = 0;
1089         env.POnum         = 0;
1090         env.quad_map      = NULL;
1091         env.lftr_edges    = NULL;
1092         env.replaced      = 0;
1093         env.lftr_replaced = 0;
1094         env.flags         = 0;
1095         env.process_scc   = process_phi_only_scc;
1096
1097         /* Clear all links and move Proj nodes into the
1098            the same block as it's predecessors.
1099            This can improve the placement of new nodes.
1100          */
1101         irg_walk_graph(irg, NULL, clear_and_fix, NULL);
1102
1103         /* we need dominance */
1104         assure_irg_outs(irg);
1105
1106         /* calculate the post order number for blocks. */
1107         irg_out_block_walk(get_irg_start_block(irg), NULL, assign_po, &env);
1108
1109         /* calculate the SCC's and drive OSR. */
1110         do_dfs(irg, &env);
1111
1112         if (env.replaced) {
1113                 set_irg_outs_inconsistent(irg);
1114         }
1115
1116         DEL_ARR_F(env.stack);
1117         obstack_free(&env.obst, NULL);
1118
1119         current_ir_graph = rem;
1120 }