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