Reverted changes from 25529
[libfirm] / ir / opt / opt_osr.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Operator Strength Reduction.
23  * @date    12.5.2006
24  * @author  Michael Beck
25  * @version $Id$
26  * @summary
27  *  Implementation of the Operator Strength Reduction algorithm
28  *  by Keith D. Cooper, L. Taylor Simpson, Christopher A. Vick.
29  *  Extended version.
30  */
31 #include "config.h"
32
33 #include "adt/pdeq.h"
34 #include "iroptimize.h"
35 #include "irgraph.h"
36 #include "ircons.h"
37 #include "irop_t.h"
38 #include "irdom.h"
39 #include "irgmod.h"
40 #include "irflag_t.h"
41 #include "irgwalk.h"
42 #include "irouts.h"
43 #include "iredges.h"
44 #include "debug.h"
45 #include "obst.h"
46 #include "set.h"
47 #include "tv.h"
48 #include "hashptr.h"
49 #include "irtools.h"
50 #include "irloop_t.h"
51 #include "array.h"
52 #include "firmstat.h"
53 #include "error.h"
54
55 /** The debug handle. */
56 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
57
58 /** A scc. */
59 typedef struct scc {
60         ir_node  *head;         /**< the head of the list */
61         tarval   *init;     /**< the init value iff only one exists. */
62         tarval   *incr;     /**< the induction variable increment if only a single const exists. */
63         unsigned code;      /**< == iro_Add if +incr, iro_Sub if -incr, 0 if not analysed, iro_Bad else */
64 } scc;
65
66 /** A node entry */
67 typedef struct node_entry {
68         unsigned DFSnum;    /**< the DFS number of this node */
69         unsigned low;       /**< the low number of this node */
70         ir_node  *header;   /**< the header of this node */
71         int      in_stack;  /**< flag, set if the node is on the stack */
72         ir_node  *next;     /**< link to the next node the the same scc */
73         scc      *pscc;     /**< the scc of this node */
74         unsigned POnum;     /**< the post order number for blocks */
75 } node_entry;
76
77 /** The environment. */
78 typedef struct iv_env {
79         struct obstack obst;    /**< an obstack for allocations */
80         ir_node  **stack;       /**< the node stack */
81         int      tos;           /**< tos index */
82         unsigned nextDFSnum;    /**< the current DFS number */
83         unsigned POnum;         /**< current post order number */
84         set      *quad_map;     /**< a map from (op, iv, rc) to node */
85         set      *lftr_edges;   /**< the set of lftr edges */
86         unsigned replaced;      /**< number of replaced ops */
87         unsigned lftr_replaced; /**< number of applied linear function test replacements */
88         unsigned flags;         /**< additional flags */
89         /** Function called to process a SCC. */
90         void (*process_scc)(scc *pscc, struct iv_env *env);
91 } iv_env;
92
93 /**
94  * An entry in the (op, node, node) -> node map.
95  */
96 typedef struct quadruple_t {
97         ir_opcode code;  /**< the opcode of the reduced operation */
98         ir_node   *op1;  /**< the first operand the reduced operation */
99         ir_node   *op2;  /**< the second operand of the reduced operation */
100
101         ir_node   *res; /**< the reduced operation */
102 } quadruple_t;
103
104 /**
105  * A LFTR edge.
106  */
107 typedef struct LFTR_edge {
108         ir_node   *src;   /**< the source node */
109         ir_node   *dst;   /**< the destination node */
110         ir_opcode code;   /**< the opcode that must be applied */
111         ir_node   *rc;    /**< the region const that must be applied */
112 } LFTR_edge;
113
114 /* forward */
115 static ir_node *reduce(ir_node *orig, ir_node *iv, ir_node *rc, iv_env *env);
116
117 /**
118  * Compare two LFTR edges.
119  */
120 static int LFTR_cmp(const void *e1, const void *e2, size_t size) {
121         const LFTR_edge *l1 = e1;
122         const LFTR_edge *l2 = e2;
123         (void) size;
124
125         return l1->src != l2->src;
126 }
127
128 /**
129  * Find a LFTR edge.
130  */
131 static LFTR_edge *LFTR_find(ir_node *src, iv_env *env) {
132         LFTR_edge key;
133
134         key.src  = src;
135
136         return set_find(env->lftr_edges, &key, sizeof(key), HASH_PTR(src));
137 }
138
139 /**
140  * Add a LFTR edge.
141  */
142 static void LFTR_add(ir_node *src, ir_node *dst, ir_opcode code, ir_node *rc, iv_env *env) {
143         LFTR_edge key;
144
145         key.src  = src;
146         key.dst  = dst;
147         key.code = code;
148         key.rc   = rc;
149
150         /*
151          * There might be more than one edge here. This is rather bad
152          * because we currently store only one.
153          */
154 //      assert(LFTR_find(src, env) == NULL);
155         set_insert(env->lftr_edges, &key, sizeof(key), HASH_PTR(src));
156 }
157
158 /**
159  * Gets the node_entry of a node
160  */
161 static node_entry *get_irn_ne(ir_node *irn, iv_env *env) {
162         node_entry *e = get_irn_link(irn);
163
164         if (! e) {
165                 e = obstack_alloc(&env->obst, sizeof(*e));
166                 memset(e, 0, sizeof(*e));
167                 set_irn_link(irn, e);
168         }
169         return e;
170 }
171
172 /**
173  * Gets the scc from an IV.
174  */
175 static scc *get_iv_scc(ir_node *iv, iv_env *env) {
176         node_entry *e = get_irn_ne(iv, env);
177         return e->pscc;
178 }
179
180 /**
181  * Check if irn is an IV.
182  *
183  * @param irn  the node to check
184  * @param env  the environment
185  *
186  * @returns the header if it is one, NULL else
187  */
188 static ir_node *is_iv(ir_node *irn, iv_env *env) {
189         return get_irn_ne(irn, env)->header;
190 }
191
192 /**
193  * Check if irn is a region constant.
194  * The block or irn must strictly dominate the header block.
195  *
196  * @param irn           the node to check
197  * @param header_block  the header block of the induction variable
198  */
199 static int is_rc(ir_node *irn, ir_node *header_block) {
200         ir_node *block = get_nodes_block(irn);
201
202         return (block != header_block) && block_dominates(block, header_block);
203 }
204
205 /**
206  * Set compare function for the quad set.
207  */
208 static int quad_cmp(const void *e1, const void *e2, size_t size) {
209         const quadruple_t *c1 = e1;
210         const quadruple_t *c2 = e2;
211         (void) size;
212
213         return c1->code != c2->code || c1->op1 != c2->op1 || c1->op2 != c2->op2;
214 }
215
216 /**
217  * Check if an reduced operation was already calculated.
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 env   the environment
223  *
224  * @return the already reduced node or NULL if this operation is not yet reduced
225  */
226 static ir_node *search(ir_opcode code, ir_node *op1, ir_node *op2, iv_env *env) {
227         quadruple_t key, *entry;
228
229         key.code = code;
230         key.op1 = op1;
231         key.op2 = op2;
232
233         entry = set_find(env->quad_map, &key, sizeof(key),
234                          (code * 9) ^ HASH_PTR(op1) ^HASH_PTR(op2));
235         if (entry)
236                 return entry->res;
237         return NULL;
238 }
239
240 /**
241  * Add an reduced operation.
242  *
243  * @param code    the opcode of the operation
244  * @param op1     the first operand of the operation
245  * @param op2     the second operand of the operation
246  * @param result  the result of the reduced operation
247  * @param env     the environment
248  */
249 static void add(ir_opcode code, ir_node *op1, ir_node *op2, ir_node *result, iv_env *env) {
250         quadruple_t key;
251
252         key.code = code;
253         key.op1  = op1;
254         key.op2  = op2;
255         key.res  = result;
256
257         set_insert(env->quad_map, &key, sizeof(key),
258                    (code * 9) ^ HASH_PTR(op1) ^HASH_PTR(op2));
259 }
260
261 /**
262  * Find a location where to place a bin-op whose operands are in
263  * block1 and block2.
264  *
265  * @param block1  the block of the first operand
266  * @param block2  the block of the second operand
267  *
268  * Note that we know here that such a place must exists. Moreover, this means
269  * that either block1 dominates block2 or vice versa. So, just return
270  * the "smaller" one.
271  */
272 static ir_node *find_location(ir_node *block1, ir_node *block2) {
273         if (block_dominates(block1, block2))
274                 return block2;
275         assert(block_dominates(block2, block1));
276         return block1;
277 }
278
279 /**
280  * Create a node that executes an op1 code op1 operation.
281  *
282  * @param code   the opcode to execute
283  * @param db     debug info to add to the new node
284  * @param op1    the first operand
285  * @param op2    the second operand
286  * @param mode   the mode of the new operation
287  *
288  * @return the newly created node
289  */
290 static ir_node *do_apply(ir_opcode code, dbg_info *db, ir_node *op1, ir_node *op2, ir_mode *mode) {
291         ir_graph *irg = current_ir_graph;
292         ir_node *result;
293         ir_node *block = find_location(get_nodes_block(op1), get_nodes_block(op2));
294
295         switch (code) {
296         case iro_Mul:
297                 result = new_rd_Mul(db, irg, block, op1, op2, mode);
298                 break;
299         case iro_Add:
300                 result = new_rd_Add(db, irg, block, op1, op2, mode);
301                 break;
302         case iro_Sub:
303                 result = new_rd_Sub(db, irg, block, op1, op2, mode);
304                 break;
305         default:
306                 panic("Unsupported opcode");
307                 result = NULL;
308         }
309         return result;
310 }
311
312 /**
313  * The Apply operation.
314  *
315  * @param orig   the node that represent the original operation and determines
316  *               the opcode, debug-info and mode of a newly created one
317  * @param op1    the first operand
318  * @param op2    the second operand
319  * @param env    the environment
320  *
321  * @return the newly created node
322  */
323 static ir_node *apply(ir_node *header, ir_node *orig, ir_node *op1, ir_node *op2, iv_env *env) {
324         ir_opcode code = get_irn_opcode(orig);
325         ir_node *result = search(code, op1, op2, env);
326
327         if (result == NULL) {
328                 dbg_info *db = get_irn_dbg_info(orig);
329                 ir_node *op1_header = get_irn_ne(op1, env)->header;
330                 ir_node *op2_header = get_irn_ne(op2, env)->header;
331
332                 if (op1_header == header && is_rc(op2, op1_header)) {
333                         result = reduce(orig, op1, op2, env);
334                 }
335                 else if (op2_header == header && is_rc(op1, op2_header)) {
336                         result = reduce(orig, op2, op1, env);
337                 }
338                 else {
339                         result = do_apply(code, db, op1, op2, get_irn_mode(orig));
340                         get_irn_ne(result, env)->header = NULL;
341                 }
342         }
343         return result;
344 }
345
346 /**
347  * The Reduce operation.
348  *
349  * @param orig   the node that represent the original operation and determines
350  *               the opcode, debug-info and mode of a newly created one
351  * @param iv     the induction variable
352  * @param rc     the region constant
353  * @param env    the environment
354  *
355  * @return the reduced node
356  */
357 static ir_node *reduce(ir_node *orig, ir_node *iv, ir_node *rc, iv_env *env) {
358         ir_opcode code = get_irn_opcode(orig);
359         ir_node *result = search(code, iv, rc, env);
360
361         if (result == NULL) {
362                 node_entry *e, *iv_e;
363                 int i, n;
364                 ir_mode *mode = get_irn_mode(orig);
365
366                 result = exact_copy(iv);
367
368                 /* Beware: we must always create a new induction variable with the same mode
369                    as the node we are replacing. Especially this means the mode might be changed
370                    from P to I and back. This is always possible, because we have only Phi, Add
371                    and Sub nodes. */
372                 set_irn_mode(result, mode);
373                 add(code, iv, rc, result, env);
374                 DB((dbg, LEVEL_3, "   Created new %+F for %+F (%s %+F)\n", result, iv,
375                         get_irn_opname(orig), rc));
376
377                 iv_e = get_irn_ne(iv, env);
378                 e    = get_irn_ne(result, env);
379                 e->header = iv_e->header;
380
381                 /* create the LFTR edge */
382                 LFTR_add(iv, result, code, rc, env);
383
384                 n = get_irn_arity(result);
385                 for (i = 0; i < n; ++i) {
386                         ir_node *o = get_irn_n(result, i);
387
388                         e = get_irn_ne(o, env);
389                         if (e->header == iv_e->header)
390                                 o = reduce(orig, o, rc, env);
391                         else if (is_Phi(result) || code == iro_Mul)
392                                 o = apply(iv_e->header, orig, o, rc, env);
393                         set_irn_n(result, i, o);
394                 }
395         }
396         else {
397                 DB((dbg, LEVEL_3, "   Already Created %+F for %+F (%s %+F)\n", result, iv,
398                         get_irn_opname(orig), rc));
399         }
400         return result;
401 }
402
403 /**
404  * Update the scc for a newly created IV.
405  */
406 static void update_scc(ir_node *iv, node_entry *e, iv_env *env) {
407         scc     *pscc   = e->pscc;
408         ir_node *header = e->header;
409         waitq    *wq = new_waitq();
410
411         DB((dbg, LEVEL_2, "  Creating SCC for new an induction variable:\n  "));
412         pscc->head = NULL;
413         waitq_put(wq, iv);
414         do {
415                 ir_node    *irn = waitq_get(wq);
416                 node_entry *ne  = get_irn_ne(irn, env);
417                 int        i;
418
419                 ne->pscc   = pscc;
420                 ne->next   = pscc->head;
421                 pscc->head = irn;
422                 DB((dbg, LEVEL_2, " %+F,", irn));
423
424                 for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
425                         ir_node    *pred = get_irn_n(irn, i);
426                         node_entry *pe   = get_irn_ne(pred, env);
427
428                         if (pe->header == header && pe->pscc == NULL) {
429                                 /* set the pscc here to ensure that the node is NOT enqueued another time */
430                                 pe->pscc = pscc;
431                                 waitq_put(wq, pred);
432                         }
433                 }
434         } while (! waitq_empty(wq));
435         del_waitq(wq);
436         DB((dbg, LEVEL_2, "\n"));
437 }
438
439 /**
440  * The Replace operation.
441  *
442  * @param irn   the node that will be replaced
443  * @param iv    the induction variable
444  * @param rc    the region constant
445  * @param env   the environment
446  */
447 static int replace(ir_node *irn, ir_node *iv, ir_node *rc, iv_env *env) {
448         ir_node *result;
449
450         DB((dbg, LEVEL_2, "  Replacing %+F\n", irn));
451
452         result = reduce(irn, iv, rc, env);
453         if (result != irn) {
454                 node_entry *e;
455
456                 hook_strength_red(current_ir_graph, irn);
457                 exchange(irn, result);
458                 e = get_irn_ne(result, env);
459                 if (e->pscc == NULL) {
460                         e->pscc = obstack_alloc(&env->obst, sizeof(*e->pscc));
461                         memset(e->pscc, 0, sizeof(*e->pscc));
462                         update_scc(result, e, env);
463                 }
464                 ++env->replaced;
465                 return 1;
466         }
467         return 0;
468 }
469
470 #if 0
471 /**
472  * check if a given node is a mul with 2, 4, 8
473  */
474 static int is_x86_shift_const(ir_node *mul) {
475         ir_node *rc;
476
477         if (! is_Mul(mul))
478                 return 0;
479
480         /* normalization put constants on the right side */
481         rc = get_Mul_right(mul);
482         if (is_Const(rc)) {
483                 tarval *tv = get_Const_tarval(rc);
484
485                 if (tarval_is_long(tv)) {
486                         long value = get_tarval_long(tv);
487
488                         if (value == 2 || value == 4 || value == 8) {
489                                 /* do not reduce multiplications by 2, 4, 8 */
490                                 return 1;
491                         }
492                 }
493         }
494         return 0;
495 }
496 #endif
497
498 /**
499  * Check if an IV represents a counter with constant limits.
500  */
501 static int is_counter_iv(ir_node *iv, iv_env *env) {
502         node_entry *e         = get_irn_ne(iv, env);
503         scc        *pscc      = e->pscc;
504         ir_node    *have_init = NULL;
505         ir_node    *have_incr = NULL;
506         ir_opcode  code       = iro_Bad;
507         ir_node    *irn;
508
509         if (pscc->code != 0) {
510                 /* already analysed */
511                 return pscc->code != iro_Bad;
512         }
513
514         pscc->code = iro_Bad;
515         for (irn = pscc->head; irn != NULL; irn = e->next) {
516                 if (is_Add(irn)) {
517                         if (have_incr != NULL)
518                                 return 0;
519
520                         have_incr = get_Add_right(irn);
521                         if (! is_Const(have_incr)) {
522                                 have_incr = get_Add_left(irn);
523                                 if (! is_Const(have_incr))
524                                         return 0;
525                         }
526                         code = iro_Add;
527                 } else if (is_Sub(irn)) {
528                         if (have_incr != NULL)
529                                 return 0;
530
531                         have_incr = get_Sub_right(irn);
532                         if (! is_Const(have_incr))
533                                 return 0;
534                         code = iro_Sub;
535                 } else if (is_Phi(irn)) {
536                         int i;
537
538                         for (i = get_Phi_n_preds(irn) - 1; i >= 0; --i) {
539                                 ir_node    *pred = get_Phi_pred(irn, i);
540                                 node_entry *ne   = get_irn_ne(pred, env);
541
542                                 if (ne->header == e->header)
543                                         continue;
544                                 if (have_init != NULL)
545                                         return 0;
546                                 have_init = pred;
547                                 if (! is_Const(pred))
548                                         return 0;
549                         }
550                 } else
551                         return 0;
552                 e = get_irn_ne(irn, env);
553         }
554         pscc->init = get_Const_tarval(have_init);
555         pscc->incr = get_Const_tarval(have_incr);
556         pscc->code = code;
557         return code != iro_Bad;
558 }
559
560 /**
561  * Check the users of an induction variable for register pressure.
562  */
563 static int check_users_for_reg_pressure(ir_node *iv, iv_env *env) {
564         ir_node    *irn, *header;
565         ir_node    *have_user = NULL;
566         ir_node    *have_cmp  = NULL;
567         node_entry *e         = get_irn_ne(iv, env);
568         scc        *pscc      = e->pscc;
569
570         header = e->header;
571         for (irn = pscc->head; irn != NULL; irn = e->next) {
572                 const ir_edge_t *edge;
573
574                 foreach_out_edge(irn, edge) {
575                         ir_node    *user = get_edge_src_irn(edge);
576                         node_entry *ne = get_irn_ne(user, env);
577
578                         if (e->header == ne->header) {
579                                 /* found user from the same IV */
580                                 continue;
581                         }
582                         if (is_Cmp(user)) {
583                                 if (have_cmp != NULL) {
584                                         /* more than one cmp, for now end here */
585                                         return 0;
586                                 }
587                                 have_cmp = user;
588                         } else {
589                                 /* user is a real user of the IV */
590                                 if (have_user != NULL) {
591                                         /* found the second user */
592                                         return 0;
593                                 }
594                                 have_user = user;
595                         }
596                 }
597                 e = get_irn_ne(irn, env);
598         }
599
600         if (have_user == NULL) {
601                 /* no user, ignore */
602                 return 1;
603         }
604
605         if (have_cmp == NULL) {
606                 /* fine, only one user, try to reduce */
607                 return 1;
608         }
609         /*
610          * We found one user AND at least one cmp.
611          * We should check here if we can transform the Cmp.
612          *
613          * For now our capabilities for doing linear function test
614          * are limited, so check if the iv has the right form: Only ONE
615          * phi, only one Add/Sub with a Const
616          */
617         if (! is_counter_iv(iv, env))
618                 return 0;
619
620         /*
621          * Ok, we have only one increment AND it is a Const, we might be able
622          * to do a linear function test replacement, so go on.
623          */
624         return 1;
625 }
626
627 /**
628  * Check if a node can be replaced (+, -, *).
629  *
630  * @param irn   the node to check
631  * @param env   the environment
632  *
633  * @return non-zero if irn should be Replace'd
634  */
635 static int check_replace(ir_node *irn, iv_env *env) {
636         ir_node   *left, *right, *iv, *rc;
637         ir_op     *op  = get_irn_op(irn);
638         ir_opcode code = get_op_code(op);
639         ir_node   *liv, *riv;
640
641         switch (code) {
642         case iro_Mul:
643         case iro_Add:
644         case iro_Sub:
645                 iv = rc = NULL;
646
647                 left  = get_binop_left(irn);
648                 right = get_binop_right(irn);
649
650                 liv = is_iv(left, env);
651                 riv = is_iv(right, env);
652                 if (liv && is_rc(right, liv)) {
653                         iv = left; rc = right;
654                 }
655                 else if (riv && is_op_commutative(op) &&
656                                     is_rc(left, riv)) {
657                         iv = right; rc = left;
658                 }
659
660                 if (iv) {
661                         if (env->flags & osr_flag_keep_reg_pressure) {
662                                 if (! check_users_for_reg_pressure(iv, env))
663                                         return 0;
664                         }
665                         return replace(irn, iv, rc, env);
666                 }
667                 break;
668         default:
669                 break;
670         }
671         return 0;
672 }
673
674 /**
675  * Check which SCC's are induction variables.
676  *
677  * @param pscc  a SCC
678  * @param env   the environment
679  */
680 static void classify_iv(scc *pscc, iv_env *env) {
681         ir_node *irn, *next, *header = NULL;
682         node_entry *b, *h = NULL;
683         int j, only_phi, num_outside;
684         ir_node *out_rc;
685
686         /* find the header block for this scc */
687         for (irn = pscc->head; irn; irn = next) {
688                 node_entry *e = get_irn_link(irn);
689                 ir_node *block = get_nodes_block(irn);
690
691                 next = e->next;
692                 b = get_irn_ne(block, env);
693
694                 if (header) {
695                         if (h->POnum < b->POnum) {
696                                 header = block;
697                                 h      = b;
698                         }
699                 }
700                 else {
701                         header = block;
702                         h      = b;
703                 }
704         }
705
706         /* check if this scc contains only Phi, Add or Sub nodes */
707         only_phi    = 1;
708         num_outside = 0;
709         out_rc      = NULL;
710         for (irn = pscc->head; irn; irn = next) {
711                 node_entry *e = get_irn_ne(irn, env);
712
713                 next = e->next;
714                 switch (get_irn_opcode(irn)) {
715                 case iro_Add:
716                 case iro_Sub:
717                         only_phi = 0;
718                         /* fall through */
719                 case iro_Phi:
720                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
721                                 ir_node *pred  = get_irn_n(irn, j);
722                                 node_entry *pe = get_irn_ne(pred, env);
723
724                                 if (pe->pscc != e->pscc) {
725                                         /* not in the same SCC, must be a region const */
726                                         if (! is_rc(pred, header)) {
727                                                 /* not an induction variable */
728                                                 goto fail;
729                                         }
730                                         if (! out_rc) {
731                                                 out_rc = pred;
732                                                 ++num_outside;
733                                         } else if (out_rc != pred) {
734                                                 ++num_outside;
735                                         }
736                                 }
737                         }
738                         break;
739                 default:
740                         /* not an induction variable */
741                         goto fail;
742                 }
743         }
744         /* found an induction variable */
745         DB((dbg, LEVEL_2, "  Found an induction variable:\n  "));
746         if (only_phi && num_outside == 1) {
747                 /* a phi cycle with only one real predecessor can be collapsed */
748                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
749
750                 for (irn = pscc->head; irn; irn = next) {
751                         node_entry *e = get_irn_ne(irn, env);
752                         next = e->next;
753                         e->header = NULL;
754                         exchange(irn, out_rc);
755                 }
756                 ++env->replaced;
757                 return;
758         }
759
760         /* set the header for every node in this scc */
761         for (irn = pscc->head; irn; irn = next) {
762                 node_entry *e = get_irn_ne(irn, env);
763                 e->header = header;
764                 next = e->next;
765                 DB((dbg, LEVEL_2, " %+F,", irn));
766         }
767         DB((dbg, LEVEL_2, "\n"));
768         return;
769
770 fail:
771         for (irn = pscc->head; irn; irn = next) {
772                 node_entry *e = get_irn_ne(irn, env);
773
774                 next = e->next;
775                 e->header = NULL;
776         }
777 }
778
779 /**
780  * Process a SCC for the operator strength reduction.
781  *
782  * @param pscc  the SCC
783  * @param env   the environment
784  */
785 static void process_scc(scc *pscc, iv_env *env) {
786         ir_node *head = pscc->head;
787         node_entry *e = get_irn_link(head);
788
789 #ifdef DEBUG_libfirm
790         {
791                 ir_node *irn, *next;
792
793                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
794                 for (irn = pscc->head; irn; irn = next) {
795                         node_entry *e = get_irn_link(irn);
796
797                         next = e->next;
798
799                         DB((dbg, LEVEL_4, " %+F,", irn));
800                 }
801                 DB((dbg, LEVEL_4, "\n"));
802         }
803 #endif
804
805         if (e->next == NULL) {
806                 /* this SCC has only a single member */
807                 check_replace(head, env);
808         } else {
809                 classify_iv(pscc, env);
810         }
811 }
812
813 /**
814  * If an SCC is a Phi only cycle, remove it.
815  */
816 static void remove_phi_cycle(scc *pscc, iv_env *env) {
817         ir_node *irn, *next;
818         int j;
819         ir_node *out_rc;
820
821         /* check if this scc contains only Phi, Add or Sub nodes */
822         out_rc      = NULL;
823         for (irn = pscc->head; irn; irn = next) {
824                 node_entry *e = get_irn_ne(irn, env);
825
826                 next = e->next;
827                 if (! is_Phi(irn))
828                         return;
829
830                 for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
831                         ir_node *pred  = get_irn_n(irn, j);
832                         node_entry *pe = get_irn_ne(pred, env);
833
834                         if (pe->pscc != e->pscc) {
835                                 /* not in the same SCC, must be the only input */
836                                 if (! out_rc) {
837                                         out_rc = pred;
838                                 } else if (out_rc != pred) {
839                                         return;
840                                 }
841                         }
842                 }
843         }
844         /* found a Phi cycle */
845         DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
846
847         for (irn = pscc->head; irn; irn = next) {
848                 node_entry *e = get_irn_ne(irn, env);
849                 next = e->next;
850                 e->header = NULL;
851                 exchange(irn, out_rc);
852         }
853         ++env->replaced;
854 }
855
856 /**
857  * Process a SCC for the Phi cycle removement.
858  *
859  * @param pscc  the SCC
860  * @param env   the environment
861  */
862 static void process_phi_only_scc(scc *pscc, iv_env *env) {
863         ir_node *head = pscc->head;
864         node_entry *e = get_irn_link(head);
865
866 #ifdef DEBUG_libfirm
867         {
868                 ir_node *irn, *next;
869
870                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
871                 for (irn = pscc->head; irn; irn = next) {
872                         node_entry *e = get_irn_link(irn);
873
874                         next = e->next;
875
876                         DB((dbg, LEVEL_4, " %+F,", irn));
877                 }
878                 DB((dbg, LEVEL_4, "\n"));
879         }
880 #endif
881
882         if (e->next != NULL)
883                 remove_phi_cycle(pscc, env);
884 }
885
886
887 /**
888  * Push a node onto the stack.
889  *
890  * @param env   the environment
891  * @param n     the node to push
892  */
893 static void push(iv_env *env, ir_node *n) {
894         node_entry *e;
895
896         if (env->tos == ARR_LEN(env->stack)) {
897                 int nlen = ARR_LEN(env->stack) * 2;
898                 ARR_RESIZE(ir_node *, env->stack, nlen);
899         }
900         env->stack[env->tos++] = n;
901         e = get_irn_ne(n, env);
902         e->in_stack = 1;
903 }
904
905 /**
906  * pop a node from the stack
907  *
908  * @param env   the environment
909  *
910  * @return  The topmost node
911  */
912 static ir_node *pop(iv_env *env)
913 {
914         ir_node *n = env->stack[--env->tos];
915         node_entry *e = get_irn_ne(n, env);
916
917         e->in_stack = 0;
918         return n;
919 }
920
921 /**
922  * Do Tarjan's SCC algorithm and drive OSR.
923  *
924  * @param irn  start at this node
925  * @param env  the environment
926  */
927 static void dfs(ir_node *irn, iv_env *env)
928 {
929         int i, n;
930         node_entry *node = get_irn_ne(irn, env);
931
932         mark_irn_visited(irn);
933
934         /* do not put blocks into the scc */
935         if (is_Block(irn)) {
936                 n = get_irn_arity(irn);
937                 for (i = 0; i < n; ++i) {
938                         ir_node *pred = get_irn_n(irn, i);
939
940                         if (!irn_visited(pred))
941                                 dfs(pred, env);
942                 }
943         }
944         else {
945                 ir_node *block = get_nodes_block(irn);
946
947                 node->DFSnum = env->nextDFSnum++;
948                 node->low    = node->DFSnum;
949                 push(env, irn);
950
951                 /* handle the block */
952                 if (!irn_visited(block))
953                         dfs(block, env);
954
955                 n = get_irn_arity(irn);
956                 for (i = 0; i < n; ++i) {
957                         ir_node *pred = get_irn_n(irn, i);
958                         node_entry *o = get_irn_ne(pred, env);
959
960                         if (!irn_visited(pred)) {
961                                 dfs(pred, env);
962                                 node->low = MIN(node->low, o->low);
963                         }
964                         if (o->DFSnum < node->DFSnum && o->in_stack)
965                                 node->low = MIN(o->DFSnum, node->low);
966                 }
967                 if (node->low == node->DFSnum) {
968                         scc *pscc = obstack_alloc(&env->obst, sizeof(*pscc));
969                         ir_node *x;
970
971                         memset(pscc, 0, sizeof(*pscc));
972                         do {
973                                 node_entry *e;
974
975                                 x = pop(env);
976                                 e = get_irn_ne(x, env);
977                                 e->pscc    = pscc;
978                                 e->next    = pscc->head;
979                                 pscc->head = x;
980                         } while (x != irn);
981
982                         env->process_scc(pscc, env);
983                 }
984         }
985 }
986
987 /**
988  * Do the DFS by starting at the End node of a graph.
989  *
990  * @param irg  the graph to process
991  * @param env  the environment
992  */
993 static void do_dfs(ir_graph *irg, iv_env *env) {
994         ir_graph *rem = current_ir_graph;
995         ir_node *end = get_irg_end(irg);
996         int i, n;
997
998         ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
999
1000         current_ir_graph = irg;
1001         inc_irg_visited(irg);
1002
1003         /* visit all visible nodes */
1004         dfs(end, env);
1005
1006         /* visit the keep-alives */
1007         n = get_End_n_keepalives(end);
1008         for (i = 0; i < n; ++i) {
1009                 ir_node *ka = get_End_keepalive(end, i);
1010
1011                 if (!irn_visited(ka))
1012                         dfs(ka, env);
1013         }
1014
1015         ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
1016
1017         current_ir_graph = rem;
1018 }
1019
1020 /**
1021  * Post-block-walker: assign the post-order number.
1022  */
1023 static void assign_po(ir_node *block, void *ctx) {
1024         iv_env *env = ctx;
1025         node_entry *e = get_irn_ne(block, env);
1026
1027         e->POnum = env->POnum++;
1028 }
1029
1030 /**
1031  * Follows the LFTR edges and return the last node in the chain.
1032  *
1033  * @param irn  the node that should be followed
1034  * @param env  the IV environment
1035  *
1036  * @note
1037  * In the current implementation only the last edge is stored, so
1038  * only one chain exists. That's why we might miss some opportunities.
1039  */
1040 static ir_node *followEdges(ir_node *irn, iv_env *env) {
1041         for (;;) {
1042                 LFTR_edge *e = LFTR_find(irn, env);
1043                 if (e)
1044                         irn = e->dst;
1045                 else
1046                         return irn;
1047         }
1048 }
1049
1050 /**
1051  * Apply one LFTR edge operation.
1052  * Return NULL if the transformation cannot be done safely without
1053  * an Overflow.
1054  *
1055  * @param iv   the induction variable
1056  * @param rc   the constant that should be translated
1057  * @param e    the LFTR edge
1058  * @param env  the IV environment
1059  *
1060  * @return the translated region constant or NULL
1061  *         if the translation was not possible
1062  *
1063  * @note
1064  * In the current implementation only the last edge is stored, so
1065  * only one chain exists. That's why we might miss some opportunities.
1066  */
1067 static ir_node *applyOneEdge(ir_node *iv, ir_node *rc, LFTR_edge *e, iv_env *env) {
1068         if (env->flags & osr_flag_lftr_with_ov_check) {
1069                 tarval *tv_l, *tv_r, *tv, *tv_init, *tv_incr;
1070                 tarval_int_overflow_mode_t ovmode;
1071                 scc *pscc;
1072
1073                 if (! is_counter_iv(iv, env)) {
1074                         DB((dbg, LEVEL_4, " not counter IV"));
1075                         return NULL;
1076                 }
1077
1078                 /* overflow can only be decided for Consts */
1079                 if (! is_Const(e->rc)) {
1080                         DB((dbg, LEVEL_4, " = UNKNOWN (%+F)", e->rc));
1081                         return NULL;
1082                 }
1083
1084                 tv_l = get_Const_tarval(rc);
1085                 tv_r = get_Const_tarval(e->rc);
1086
1087                 ovmode = tarval_get_integer_overflow_mode();
1088                 tarval_set_integer_overflow_mode(TV_OVERFLOW_BAD);
1089
1090                 pscc    = get_iv_scc(iv, env);
1091                 tv_incr = pscc->incr;
1092                 tv_init = pscc->init;
1093
1094                 /*
1095                  * Check that no overflow occurs:
1096                  * init must be transformed without overflow
1097                  * the new rc must be transformed without overflow
1098                  * rc +/- incr must be possible without overflow
1099                  */
1100                 switch (e->code) {
1101                 case iro_Mul:
1102                         tv      = tarval_mul(tv_l, tv_r);
1103                         tv_init = tarval_mul(tv_init, tv_r);
1104                         tv_incr = tarval_mul(tv_incr, tv_r);
1105                         DB((dbg, LEVEL_4, " * %+F", tv_r));
1106                         break;
1107                 case iro_Add:
1108                         tv      = tarval_add(tv_l, tv_r);
1109                         tv_init = tarval_add(tv_init, tv_r);
1110                         DB((dbg, LEVEL_4, " + %+F", tv_r));
1111                         break;
1112                 case iro_Sub:
1113                         tv      = tarval_sub(tv_l, tv_r, NULL);
1114                         tv_init = tarval_sub(tv_init, tv_r, NULL);
1115                         DB((dbg, LEVEL_4, " - %+F", tv_r));
1116                         break;
1117                 default:
1118                         panic("Unsupported opcode");
1119                         tv = tarval_bad;
1120                 }
1121
1122                 if (pscc->code == iro_Add) {
1123                         tv = tarval_add(tv, tv_incr);
1124                 } else {
1125                         assert(pscc->code == iro_Sub);
1126                         tv = tarval_sub(tv, tv_incr, NULL);
1127                 }
1128
1129                 tarval_set_integer_overflow_mode(ovmode);
1130
1131                 if (tv == tarval_bad || tv_init == tarval_bad) {
1132                         DB((dbg, LEVEL_4, " = OVERFLOW"));
1133                         return NULL;
1134                 }
1135                 return new_Const(tv);
1136         }
1137         return do_apply(e->code, NULL, rc, e->rc, get_irn_mode(rc));
1138 }
1139
1140 /**
1141  * Applies the operations represented by the LFTR edges to a
1142  * region constant and returns the value.
1143  * Return NULL if the transformation cannot be done safely without
1144  * an Overflow.
1145  *
1146  * @param iv   the IV node that starts the LFTR edge chain
1147  * @param rc   the region constant that should be translated
1148  * @param env  the IV environment
1149  *
1150  * @return the translated region constant or NULL
1151  *         if the translation was not possible
1152  */
1153 static ir_node *applyEdges(ir_node *iv, ir_node *rc, iv_env *env) {
1154         if (env->flags & osr_flag_lftr_with_ov_check) {
1155                 /* overflow can only be decided for Consts */
1156                 if (! is_counter_iv(iv, env)) {
1157                         DB((dbg, LEVEL_4, "not counter IV\n", rc));
1158                         return NULL;
1159                 }
1160                 if (! is_Const(rc)) {
1161                         DB((dbg, LEVEL_4, " = UNKNOWN (%+F)\n", rc));
1162                         return NULL;
1163                 }
1164                 DB((dbg, LEVEL_4, "%+F", get_Const_tarval(rc)));
1165         }
1166
1167         for (; rc;) {
1168                 LFTR_edge *e = LFTR_find(iv, env);
1169                 if (e) {
1170                         rc = applyOneEdge(iv, rc, e, env);
1171                         iv = e->dst;
1172                 }
1173                 else
1174                         break;
1175         }
1176         DB((dbg, LEVEL_3, "\n"));
1177         return rc;
1178 }
1179
1180 /**
1181  * Walker, finds Cmp(iv, rc) or Cmp(rc, iv)
1182  * and tries to optimize them.
1183  */
1184 static void do_lftr(ir_node *cmp, void *ctx) {
1185         iv_env *env = ctx;
1186         ir_node *left, *right, *liv, *riv;
1187         ir_node *iv, *rc;
1188         ir_node *nleft = NULL, *nright = NULL;
1189
1190         if (!is_Cmp(cmp))
1191                 return;
1192
1193         left  = get_Cmp_left(cmp);
1194         right = get_Cmp_right(cmp);
1195
1196         liv = is_iv(left, env);
1197         riv = is_iv(right, env);
1198         if (liv && is_rc(right, liv)) {
1199                 iv = left; rc = right;
1200
1201                 nright = applyEdges(iv, rc, env);
1202                 if (nright && nright != rc) {
1203                         nleft = followEdges(iv, env);
1204                 }
1205         }
1206         else if (riv && is_rc(left, riv)) {
1207                 iv = right; rc = left;
1208
1209                 nleft = applyEdges(iv, rc, env);
1210                 if (nleft && nleft != rc) {
1211                         nright = followEdges(iv, env);
1212                 }
1213         }
1214
1215         if (nleft && nright) {
1216                 DB((dbg, LEVEL_2, "  LFTR for %+F\n", cmp));
1217                 set_Cmp_left(cmp, nleft);
1218                 set_Cmp_right(cmp, nright);
1219                 ++env->lftr_replaced;
1220         }
1221 }
1222
1223 /**
1224  * do linear function test replacement.
1225  *
1226  * @param irg   the graph that should be optimized
1227  * @param env   the IV environment
1228  */
1229 static void lftr(ir_graph *irg, iv_env *env) {
1230         irg_walk_graph(irg, NULL, do_lftr, env);
1231 }
1232
1233 /**
1234  * Pre-walker: set all node links to NULL and fix the
1235  * block of Proj nodes.
1236  */
1237 static void clear_and_fix(ir_node *irn, void *env)
1238 {
1239         (void) env;
1240         set_irn_link(irn, NULL);
1241
1242         if (is_Proj(irn)) {
1243                 ir_node *pred = get_Proj_pred(irn);
1244                 set_nodes_block(irn, get_nodes_block(pred));
1245         }
1246 }
1247
1248 /* Performs Operator Strength Reduction for the passed graph. */
1249 void opt_osr(ir_graph *irg, unsigned flags) {
1250         iv_env   env;
1251         ir_graph *rem;
1252         int      edges;
1253
1254         if (! get_opt_strength_red()) {
1255                 /* only kill Phi cycles  */
1256                 remove_phi_cycles(irg);
1257                 return;
1258         }
1259
1260         rem = current_ir_graph;
1261         current_ir_graph = irg;
1262
1263         FIRM_DBG_REGISTER(dbg, "firm.opt.osr");
1264
1265         DB((dbg, LEVEL_1, "Doing Operator Strength Reduction for %+F\n", irg));
1266
1267         obstack_init(&env.obst);
1268         env.stack         = NEW_ARR_F(ir_node *, 128);
1269         env.tos           = 0;
1270         env.nextDFSnum    = 0;
1271         env.POnum         = 0;
1272         env.quad_map      = new_set(quad_cmp, 64);
1273         env.lftr_edges    = new_set(LFTR_cmp, 64);
1274         env.replaced      = 0;
1275         env.lftr_replaced = 0;
1276         env.flags         = flags;
1277         env.process_scc   = process_scc;
1278
1279         /* Clear all links and move Proj nodes into the
1280            the same block as it's predecessors.
1281            This can improve the placement of new nodes.
1282          */
1283         irg_walk_graph(irg, NULL, clear_and_fix, NULL);
1284
1285         /* we need dominance */
1286         assure_doms(irg);
1287
1288         edges = edges_assure(irg);
1289
1290         /* calculate the post order number for blocks. */
1291         irg_block_edges_walk(get_irg_start_block(irg), NULL, assign_po, &env);
1292
1293         /* calculate the SCC's and drive OSR. */
1294         do_dfs(irg, &env);
1295
1296         if (env.replaced) {
1297                 /* try linear function test replacements */
1298                 //lftr(irg, &env); // currently buggy :-(
1299                 (void) lftr;
1300
1301                 set_irg_outs_inconsistent(irg);
1302                 DB((dbg, LEVEL_1, "Replacements: %u + %u (lftr)\n\n", env.replaced, env.lftr_replaced));
1303         }
1304
1305         del_set(env.lftr_edges);
1306         del_set(env.quad_map);
1307         DEL_ARR_F(env.stack);
1308         obstack_free(&env.obst, NULL);
1309
1310         if (! edges)
1311                 edges_deactivate(irg);
1312
1313         current_ir_graph = rem;
1314 }
1315
1316 /* Remove any Phi cycles with only one real input. */
1317 void remove_phi_cycles(ir_graph *irg) {
1318         iv_env   env;
1319         ir_graph *rem;
1320
1321         rem = current_ir_graph;
1322         current_ir_graph = irg;
1323
1324         FIRM_DBG_REGISTER(dbg, "firm.opt.remove_phi");
1325
1326         DB((dbg, LEVEL_1, "Doing Phi cycle removement for %+F\n", irg));
1327
1328         obstack_init(&env.obst);
1329         env.stack         = NEW_ARR_F(ir_node *, 128);
1330         env.tos           = 0;
1331         env.nextDFSnum    = 0;
1332         env.POnum         = 0;
1333         env.quad_map      = NULL;
1334         env.lftr_edges    = NULL;
1335         env.replaced      = 0;
1336         env.lftr_replaced = 0;
1337         env.flags         = 0;
1338         env.process_scc   = process_phi_only_scc;
1339
1340         /* Clear all links and move Proj nodes into the
1341            the same block as it's predecessors.
1342            This can improve the placement of new nodes.
1343          */
1344         irg_walk_graph(irg, NULL, clear_and_fix, NULL);
1345
1346         /* we need outs for calculating the post order */
1347         assure_irg_outs(irg);
1348
1349         /* calculate the post order number for blocks. */
1350         irg_out_block_walk(get_irg_start_block(irg), NULL, assign_po, &env);
1351
1352         /* calculate the SCC's and drive OSR. */
1353         do_dfs(irg, &env);
1354
1355         if (env.replaced) {
1356                 set_irg_outs_inconsistent(irg);
1357                 DB((dbg, LEVEL_1, "remove_phi_cycles: %u Cycles removed\n\n", env.replaced));
1358         }
1359
1360         DEL_ARR_F(env.stack);
1361         obstack_free(&env.obst, NULL);
1362
1363         current_ir_graph = rem;
1364 }