Bugfix: fixed uninitialized variable.
[libfirm] / ir / opt / loop.c
1 /*
2  * Copyright (C) 1995-2010 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  * @author   Christian Helmer
23  * @brief    loop inversion and loop unrolling
24  *
25  * @version  $Id$
26  */
27
28 #include "config.h"
29
30 #include "iroptimize.h"
31 #include "opt_init.h"
32 #include "irnode.h"
33 #include "debug.h"
34 #include "error.h"
35
36 #include "ircons.h"
37 #include "irgopt.h"
38 #include "irgmod.h"
39 #include "irgwalk.h"
40 #include "irouts.h"
41 #include "iredges.h"
42 #include "irtools.h"
43 #include "array_t.h"
44 #include "beutil.h"
45 #include "irpass.h"
46 #include "irdom.h"
47
48 #include "irbackedge_t.h"
49 #include "irphase_t.h"
50 #include "irloop_t.h"
51
52
53 DEBUG_ONLY(static firm_dbg_module_t *dbg);
54
55 /* DBG print stats for every procedure.  */
56 #define LOOP_OPT_STATS 0
57
58 /* DBG: Ignore node limits and process every possible loop. */
59 #define LOOP_IGNORE_NODE_LIMITS 0
60
61 /**
62  * Convenience macro for iterating over every phi node of the given block.
63  * Requires phi list per block.
64  */
65 #define for_each_phi(block, phi) \
66         for ((phi) = get_Block_phis( (block) ); (phi) ; (phi) = get_Phi_next((phi)))
67
68 #define for_each_phi_safe(head, phi, next) \
69         for ((phi) = (head), (next) = (head) ? get_Phi_next((head)) : NULL; \
70                         (phi) ; (phi) = (next), (next) = (next) ? get_Phi_next((next)) : NULL)
71
72 /* Currently processed loop. */
73 static ir_loop *cur_loop;
74
75 /* Flag for kind of unrolling. */
76 typedef enum {
77         constant,
78         invariant
79 } unrolling_kind_flag;
80
81 /* Condition for performing visiting a node during copy_walk. */
82 typedef unsigned walker_condition(ir_node *);
83
84 /* Node and position of a predecessor. */
85 typedef struct entry_edge {
86         ir_node *node;
87         int pos;
88         ir_node *pred;
89 } entry_edge;
90
91 /* Node info for unrolling. */
92 typedef struct unrolling_node_info {
93         ir_node **copies;
94         /*ir_node **ins;*/
95 } unrolling_node_info;
96
97 /* Outs of the nodes head. */
98 static entry_edge *cur_head_outs;
99
100 /* Information about the loop head */
101 static ir_node *loop_head = NULL;
102 static unsigned loop_head_valid = 1;
103
104 /* List of all inner loops, that are processed. */
105 static ir_loop **loops;
106
107 #if LOOP_OPT_STATS
108
109 #define count_stats(val) (++val)
110 #define print_stats() (do_print_stats())
111 #define reset_stats() (do_reset_stats())
112
113 /* Stats */
114 typedef struct loop_stats_t {
115         unsigned loops;
116         unsigned inverted;
117         unsigned too_large;
118         unsigned too_large_adapted;
119         unsigned cc_limit_reached;
120         unsigned calls_limit;
121
122         unsigned u_simple_counting_loop;
123         unsigned constant_unroll;
124         unsigned invariant_unroll;
125
126         unsigned unhandled;
127 } loop_stats_t;
128
129 static loop_stats_t stats;
130
131 /* Set stats to sero */
132 static void do_reset_stats(void)
133 {
134         memset(&stats, 0, sizeof(loop_stats_t));
135 }
136
137 /* Print stats */
138 static void do_print_stats(void)
139 {
140         DB((dbg, LEVEL_2, "---------------------------------------\n"));
141         DB((dbg, LEVEL_2, "loops             :   %d\n",stats.loops));
142         DB((dbg, LEVEL_2, "inverted          :   %d\n",stats.inverted));
143         DB((dbg, LEVEL_2, "too_large         :   %d\n",stats.too_large));
144         DB((dbg, LEVEL_2, "too_large_adapted :   %d\n",stats.too_large_adapted));
145         DB((dbg, LEVEL_2, "cc_limit_reached  :   %d\n",stats.cc_limit_reached));
146         DB((dbg, LEVEL_2, "calls_limit       :   %d\n",stats.calls_limit));
147         DB((dbg, LEVEL_2, "u_simple_counting :   %d\n",stats.u_simple_counting_loop));
148         DB((dbg, LEVEL_2, "constant_unroll   :   %d\n",stats.constant_unroll));
149         DB((dbg, LEVEL_2, "invariant_unroll  :   %d\n",stats.invariant_unroll));
150         DB((dbg, LEVEL_2, "=======================================\n"));
151 }
152 #else
153 /* No stats */
154 #define count_stats(val) ((void)0)
155 #define print_stats() ((void)0)
156 #define reset_stats() ((void)0)
157
158 #endif
159
160 /* Commandline parameters */
161 typedef struct loop_opt_params_t {
162         unsigned max_loop_size;         /* Maximum number of nodes */
163         int      depth_adaption;        /* Loop nest depth adaption */
164         unsigned allowed_calls;         /* Number of calls allowed */
165         unsigned count_phi:1;           /* Count phi nodes */
166         unsigned count_proj:1;          /* Count projections */
167
168         unsigned max_cc_size;           /* Maximum condition chain size */
169
170         unsigned allow_const_unrolling:1;
171         unsigned allow_invar_unrolling:1;
172
173 } loop_opt_params_t;
174
175 static loop_opt_params_t opt_params;
176
177 /* Loop analysis informations */
178 typedef struct loop_info_t {
179         unsigned nodes;                 /* node count */
180         unsigned ld_st;                 /* load and store nodes */
181         unsigned calls;                 /* number of calls */
182         unsigned cf_outs;               /* number of cf edges which leave the loop */
183         entry_edge cf_out;              /* single loop leaving cf edge */
184         int be_src_pos;                 /* position of the single own backedge in the head */
185
186         /* for inversion */
187         unsigned cc_size;               /* nodes in the condition chain */
188
189         /* for unrolling */
190         unsigned max_unroll;            /* Number of unrolls satisfying max_loop_size */
191         unsigned exit_cond;                     /* 1 if condition==true exits the loop.  */
192         unsigned latest_value:1;        /* 1 if condition is checked against latest counter value */
193         unsigned needs_backedge:1;      /* 0 if loop is completely unrolled */
194         unsigned decreasing:1;          /* Step operation is_Sub, or step is<0 */
195
196         /* IV informations of a simple loop */
197         ir_node *start_val;
198         ir_node *step;
199         ir_node *end_val;
200         ir_node *iteration_phi;
201         ir_node *add;
202
203         tarval *count_tar;                                      /* Number of loop iterations */
204
205         ir_node *duff_cond;                                     /* Duff mod */
206         unrolling_kind_flag unroll_kind;        /* constant or invariant unrolling */
207 } loop_info_t;
208
209 /* Information about the current loop */
210 static loop_info_t loop_info;
211
212 /* Outs of the condition chain (loop inversion). */
213 static ir_node **cc_blocks;
214 /* df/cf edges with def in the condition chain */
215 static entry_edge *cond_chain_entries;
216 /* Array of df loops found in the condition chain. */
217 static entry_edge *head_df_loop;
218 /* Number of blocks in cc */
219 static unsigned inversion_blocks_in_cc;
220
221
222 /* Cf/df edges leaving the loop.
223  * Called entries here, as they are used to enter the loop with walkers. */
224 static entry_edge *loop_entries;
225 /* Number of unrolls to perform */
226 static int unroll_nr;
227 /* Phase is used to keep copies of nodes. */
228 static ir_phase *phase;
229
230 /* Loop operations.  */
231 typedef enum loop_op_t {
232         loop_op_inversion,
233         loop_op_unrolling,
234         loop_op_peeling
235 } loop_op_t;
236
237 /* Saves which loop operation to do until after basic tests. */
238 static loop_op_t loop_op;
239
240 /************************************************************************/
241
242 /* Returns the maximum nodes for the given nest depth */
243 static unsigned get_max_nodes_adapted(unsigned depth)
244 {
245         int adapt_permil = opt_params.depth_adaption * depth;
246         unsigned permil_change;
247
248         if (adapt_permil < -1000)
249                 return 0;
250
251         permil_change = 1000 + adapt_permil;
252         return (opt_params.max_loop_size * permil_change) / 1000;
253 }
254
255 /* Reset nodes link. For use with a walker. */
256 static void reset_link(ir_node *node, void *env)
257 {
258         (void)env;
259         set_irn_link(node, NULL);
260 }
261
262 /* Returns 0 if the node or block is not in cur_loop. */
263 static unsigned is_in_loop(ir_node *node)
264 {
265         return (get_irn_loop(get_block(node)) == cur_loop);
266 }
267
268 /* Returns 0 if the given edge is not a backedge
269  * with its pred in the cur_loop. */
270 static unsigned is_own_backedge(ir_node *n, int pos)
271 {
272         return (is_backedge(n, pos) && is_in_loop(get_irn_n(n, pos)));
273 }
274
275 /* Finds loop head and some loop_info as calls or else if necessary. */
276 static void get_loop_info(ir_node *node, void *env)
277 {
278         unsigned node_in_loop, pred_in_loop;
279         int i, arity;
280         (void)env;
281
282         arity = get_irn_arity(node);
283         for (i = 0; i < arity; i++) {
284                 ir_node *pred = get_irn_n(node, i);
285
286                 pred_in_loop = is_in_loop(pred);
287                 node_in_loop = is_in_loop(node);
288
289                 /* collect some loop information */
290                 if (node_in_loop) {
291                         if (is_Phi(node) && opt_params.count_phi)
292                                 ++loop_info.nodes;
293                         else if (is_Proj(node) && opt_params.count_proj)
294                                 ++loop_info.nodes;
295                         else if (!is_Confirm(node) && !is_Const(node) && !is_SymConst(node))
296                                 ++loop_info.nodes;
297
298                         if (is_Load(node) || is_Store(node))
299                                 ++loop_info.ld_st;
300
301                         if (is_Call(node))
302                                 ++loop_info.calls;
303                 }
304
305                 /* Find the loops head/the blocks with cfpred outside of the loop */
306                 if (is_Block(node) && node_in_loop && !pred_in_loop && loop_head_valid) {
307                         ir_node *cfgpred = get_Block_cfgpred(node, i);
308
309                         if (!is_in_loop(cfgpred)) {
310                                 DB((dbg, LEVEL_5, "potential head %+F because inloop and pred %+F not inloop\n",
311                                                         node, pred));
312                                 /* another head? We do not touch this. */
313                                 if (loop_head && loop_head != node) {
314                                         loop_head_valid = 0;
315                                 } else {
316                                         loop_head = node;
317                                 }
318                         }
319                 }
320         }
321 }
322
323 /* Finds all edges with users outside of the loop
324  * and definition inside the loop. */
325 static void get_loop_entries(ir_node *node, void *env)
326 {
327         unsigned node_in_loop, pred_in_loop;
328         int i, arity;
329         (void) env;
330
331         arity = get_irn_arity(node);
332         for (i = 0; i < arity; ++i) {
333                 ir_node *pred = get_irn_n(node, i);
334
335                 pred_in_loop = is_in_loop(pred);
336                 node_in_loop = is_in_loop(node);
337
338                 if (pred_in_loop && !node_in_loop) {
339                         entry_edge entry;
340                         entry.node = node;
341                         entry.pos = i;
342                         entry.pred = pred;
343                         ARR_APP1(entry_edge, loop_entries, entry);
344                         /* Count cf outs */
345                         if (is_Block(node)) {
346                                 ++loop_info.cf_outs;
347                                 loop_info.cf_out = entry;
348                         }
349                 }
350         }
351 }
352
353 /* ssa */
354 static ir_node *ssa_second_def;
355 static ir_node *ssa_second_def_block;
356
357 /**
358  * Walks the graph bottom up, searching for definitions and creates phis.
359  */
360 static ir_node *search_def_and_create_phis(ir_node *block, ir_mode *mode, int first)
361 {
362         int i;
363         int n_cfgpreds;
364         ir_graph *irg;
365         ir_node *phi;
366         ir_node **in;
367
368         DB((dbg, LEVEL_5, "ssa search_def_and_create_phis: block %N\n", block));
369
370         /* Prevents creation of phi that would be bad anyway.
371          * Dead and bad blocks. */
372         if (get_irn_arity(block) < 1 || is_Bad(block)) {
373                 DB((dbg, LEVEL_5, "ssa bad %N\n", block));
374                 return new_Bad();
375         }
376
377         if (block == ssa_second_def_block && !first) {
378                 DB((dbg, LEVEL_5, "ssa found second definition: use second def %N\n", ssa_second_def));
379                 return ssa_second_def;
380         }
381
382         /* already processed this block? */
383         if (irn_visited(block)) {
384                 ir_node *value = (ir_node *) get_irn_link(block);
385                 DB((dbg, LEVEL_5, "ssa already visited: use linked %N\n", value));
386                 return value;
387         }
388
389         irg = get_irn_irg(block);
390         assert(block != get_irg_start_block(irg));
391
392         /* a Block with only 1 predecessor needs no Phi */
393         n_cfgpreds = get_Block_n_cfgpreds(block);
394         if (n_cfgpreds == 1) {
395                 ir_node *pred_block = get_Block_cfgpred_block(block, 0);
396                 ir_node *value;
397
398                 DB((dbg, LEVEL_5, "ssa 1 pred: walk pred %N\n", pred_block));
399
400                 value = search_def_and_create_phis(pred_block, mode, 0);
401                 set_irn_link(block, value);
402                 mark_irn_visited(block);
403
404                 return value;
405         }
406
407         /* create a new Phi */
408         NEW_ARR_A(ir_node*, in, n_cfgpreds);
409         for (i = 0; i < n_cfgpreds; ++i)
410                 in[i] = new_Unknown(mode);
411
412         phi = new_r_Phi(block, n_cfgpreds, in, mode);
413         /* Important: always keep block phi list up to date. */
414         add_Block_phi(block, phi);
415         DB((dbg, LEVEL_5, "ssa phi creation: link new phi %N to block %N\n", phi, block));
416         set_irn_link(block, phi);
417         mark_irn_visited(block);
418
419         /* set Phi predecessors */
420         for (i = 0; i < n_cfgpreds; ++i) {
421                 ir_node *pred_val;
422                 ir_node *pred_block = get_Block_cfgpred_block(block, i);
423                 assert(pred_block != NULL);
424                 pred_val = search_def_and_create_phis(pred_block, mode, 0);
425
426                 assert(pred_val != NULL);
427
428                 DB((dbg, LEVEL_5, "ssa phi pred:phi %N, pred %N\n", phi, pred_val));
429                 set_irn_n(phi, i, pred_val);
430         }
431
432         return phi;
433 }
434
435
436 /**
437  * Given a set of values this function constructs SSA-form for the users of the
438  * first value (the users are determined through the out-edges of the value).
439  * Works without using the dominance tree.
440  */
441 static void construct_ssa(ir_node *orig_block, ir_node *orig_val,
442                 ir_node *second_block, ir_node *second_val)
443 {
444         ir_graph *irg;
445         ir_mode *mode;
446         const ir_edge_t *edge;
447         const ir_edge_t *next;
448
449         assert(orig_block && orig_val && second_block && second_val &&
450                         "no parameter of construct_ssa may be NULL");
451
452         if (orig_val == second_val)
453                 return;
454
455         irg = get_irn_irg(orig_val);
456
457         ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
458         inc_irg_visited(irg);
459
460         mode = get_irn_mode(orig_val);
461         set_irn_link(orig_block, orig_val);
462         mark_irn_visited(orig_block);
463
464         ssa_second_def_block = second_block;
465         ssa_second_def       = second_val;
466
467         /* Only fix the users of the first, i.e. the original node */
468         foreach_out_edge_safe(orig_val, edge, next) {
469                 ir_node *user = get_edge_src_irn(edge);
470                 int j = get_edge_src_pos(edge);
471                 ir_node *user_block = get_nodes_block(user);
472                 ir_node *newval;
473
474                 /* ignore keeps */
475                 if (is_End(user))
476                         continue;
477
478                 DB((dbg, LEVEL_5, "original user %N\n", user));
479
480                 if (is_Phi(user)) {
481                         ir_node *pred_block = get_Block_cfgpred_block(user_block, j);
482                         newval = search_def_and_create_phis(pred_block, mode, 1);
483                 } else {
484                         newval = search_def_and_create_phis(user_block, mode, 1);
485                 }
486                 if (newval != user && !is_Bad(newval))
487                         set_irn_n(user, j, newval);
488         }
489
490         ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
491 }
492
493
494 /***** Unrolling Helper Functions *****/
495
496 /* Assign the copy with index nr to node n */
497 static void set_unroll_copy(ir_node *n, int nr, ir_node *cp)
498 {
499         unrolling_node_info *info;
500         assert(nr != 0 && "0 reserved");
501
502         info = (unrolling_node_info *)phase_get_irn_data(phase, n);
503         if (! info) {
504                 ir_node **arr;
505
506                 info = XMALLOCZ(unrolling_node_info);
507                 arr = NEW_ARR_F(ir_node *, unroll_nr);
508                 info->copies = arr;
509                 memset(info->copies, 0, (unroll_nr) * sizeof(ir_node *));
510
511                 phase_set_irn_data(phase, n, info);
512         }
513         /* Original node */
514         info->copies[0] = n;
515
516         info->copies[nr] = cp;
517 }
518
519 /* Returns a nodes copy if it exists, else NULL. */
520 static ir_node *get_unroll_copy(ir_node *n, int nr)
521 {
522         ir_node             *cp;
523         unrolling_node_info *info = (unrolling_node_info *)phase_get_irn_data(phase, n);
524         if (! info)
525                 return NULL;
526
527         cp = info->copies[nr];
528         return cp;
529 }
530
531
532 /***** Inversion Helper Functions *****/
533
534 /* Sets copy cp of node n. */
535 static void set_inversion_copy(ir_node *n, ir_node *cp)
536 {
537         phase_set_irn_data(phase, n, cp);
538 }
539
540 /* Getter of copy of n for inversion */
541 static ir_node *get_inversion_copy(ir_node *n)
542 {
543         ir_node *cp = (ir_node *)phase_get_irn_data(phase, n);
544         return cp;
545 }
546
547 /* Resets block mark for given node. For use with walker */
548 static void reset_block_mark(ir_node *node, void * env)
549 {
550         (void) env;
551
552         if (is_Block(node))
553                 set_Block_mark(node, 0);
554 }
555
556 /* Returns mark of node, or its block if node is not a block.
557  * Used in this context to determine if node is in the condition chain. */
558 static unsigned is_nodes_block_marked(ir_node* node)
559 {
560         if (is_Block(node))
561                 return get_Block_mark(node);
562         else
563                 return get_Block_mark(get_block(node));
564 }
565
566 /* Extends a nodes ins by node new.
567  * NOTE: This is slow if a node n needs to be extended more than once. */
568 static int extend_irn(ir_node *n, ir_node *new)
569 {
570         ir_node **ins;
571         int i;
572         int arity = get_irn_arity(n);
573         int new_arity = arity + 1;
574
575         NEW_ARR_A(ir_node *, ins, new_arity);
576
577         for(i = 0; i < arity; ++i) {
578                 ins[i] = get_irn_n(n, i);
579         }
580         ins[i] = new;
581
582         set_irn_in(n, new_arity, ins);
583         return arity;
584 }
585
586 /* Extends a block by a copy of its pred at pos,
587  * fixing also the phis in the same way. */
588 static void extend_ins_by_copy(ir_node *block, int pos)
589 {
590         ir_node *new_in;
591         ir_node *phi;
592         ir_node *pred;
593         assert(is_Block(block));
594
595         /* Extend block by copy of definition at pos */
596         pred = get_irn_n(block, pos);
597         new_in = get_inversion_copy(pred);
598         DB((dbg, LEVEL_5, "Extend block %N by %N cp of %N\n", block, new_in, pred));
599         extend_irn(block, new_in);
600
601         /* Extend block phis by copy of definition at pos */
602         for_each_phi(block, phi) {
603                 ir_node *pred, *cp;
604
605                 pred = get_irn_n(phi, pos);
606                 cp = get_inversion_copy(pred);
607                 /* If the phis in is not in the condition chain (eg. a constant),
608                  * there is no copy. */
609                 if (cp == NULL)
610                         new_in = pred;
611                 else
612                         new_in = cp;
613
614                 DB((dbg, LEVEL_5, "Extend phi %N by %N cp of %N\n", phi, new_in, pred));
615                 extend_irn(phi, new_in);
616         }
617 }
618
619 /* Returns the number of blocks backedges. With or without alien bes. */
620 static int get_backedge_n(ir_node *block, unsigned with_alien)
621 {
622         int i;
623         int be_n = 0;
624         int arity = get_irn_arity(block);
625
626         assert(is_Block(block) && "We only required backedges of blocks.");
627
628         for (i = 0; i < arity; ++i) {
629                 ir_node *pred = get_irn_n(block, i);
630                 if (is_backedge(block, i) && (with_alien || is_in_loop(pred)))
631                         ++be_n;
632         }
633         return be_n;
634 }
635
636 /* Returns a raw copy of the given node.
637  * Attributes are kept/set according to the needs of loop inversion. */
638 static ir_node *copy_node(ir_node *node)
639 {
640         int i, arity;
641         ir_node *cp;
642
643         cp = exact_copy(node);
644         arity = get_irn_arity(node);
645
646         /* Keep backedge info */
647         for (i = 0; i < arity; ++i) {
648                 if (is_backedge(node, i))
649                         set_backedge(cp, i);
650         }
651
652         if (is_Block(cp)) {
653                 /* We may not keep the old macroblock. */
654                 set_Block_MacroBlock(cp, cp);
655                 set_Block_mark(cp, 0);
656         }
657
658         return cp;
659 }
660
661
662 /**
663  * This walker copies all walked nodes.
664  * If the walk_condition is true for a node, it is copied.
665  * All nodes node_info->copy have to be NULL prior to every walk.
666  * Order of ins is important for later usage.
667  */
668 static void copy_walk(ir_node *node, walker_condition *walk_condition,
669                 ir_loop *set_loop)
670 {
671         int i;
672         int arity;
673         ir_node *cp;
674         ir_node **cpin;
675         ir_graph *irg = current_ir_graph;
676
677         /**
678          * break condition and cycle resolver, creating temporary node copies
679          */
680         if (get_irn_visited(node) >= get_irg_visited(irg)) {
681                 /* Here we rely on nodestate's copy being initialized with NULL */
682                 DB((dbg, LEVEL_5, "copy_walk: We have already visited %N\n", node));
683                 if (get_inversion_copy(node) == NULL) {
684                         cp = copy_node(node);
685                         set_inversion_copy(node, cp);
686
687                         DB((dbg, LEVEL_5, "The TEMP copy of %N is created %N\n", node, cp));
688                 }
689                 return;
690         }
691
692         /* Walk */
693         mark_irn_visited(node);
694
695         if (!is_Block(node)) {
696                 ir_node *pred = get_nodes_block(node);
697                 if (walk_condition(pred))
698                         DB((dbg, LEVEL_5, "walk block %N\n", pred));
699                 copy_walk(pred, walk_condition, set_loop);
700         }
701
702         arity = get_irn_arity(node);
703
704         NEW_ARR_A(ir_node *, cpin, arity);
705
706         for (i = 0; i < arity; ++i) {
707                 ir_node *pred = get_irn_n(node, i);
708
709                 if (walk_condition(pred)) {
710                         DB((dbg, LEVEL_5, "walk node %N\n", pred));
711                         copy_walk(pred, walk_condition, set_loop);
712                         cpin[i] = get_inversion_copy(pred);
713                         DB((dbg, LEVEL_5, "copy of %N gets new in %N which is copy of %N\n",
714                                                 node, get_inversion_copy(pred), pred));
715                 } else {
716                         cpin[i] = pred;
717                 }
718         }
719
720         /* copy node / finalize temp node */
721         if (get_inversion_copy(node) == NULL) {
722                 /* No temporary copy existent */
723                 cp = copy_node(node);
724                 set_inversion_copy(node, cp);
725                 DB((dbg, LEVEL_5, "The FINAL copy of %N is CREATED %N\n", node, cp));
726         } else {
727                 /* temporary copy is existent but without correct ins */
728                 cp = get_inversion_copy(node);
729                 DB((dbg, LEVEL_5, "The FINAL copy of %N is EXISTENT %N\n", node, cp));
730         }
731
732         if (!is_Block(node)) {
733                 ir_node *cpblock = get_inversion_copy(get_nodes_block(node));
734
735                 set_nodes_block(cp, cpblock );
736                 if (is_Phi(cp))
737                         add_Block_phi(cpblock, cp);
738         }
739
740         /* Keeps phi list of temporary node. */
741         set_irn_in(cp, ARR_LEN(cpin), cpin);
742 }
743
744 /**
745  * This walker copies all walked nodes.
746  * If the walk_condition is true for a node, it is copied.
747  * All nodes node_info->copy have to be NULL prior to every walk.
748  * Order of ins is important for later usage.
749  * Takes copy_index, to phase-link copy at specific index.
750  */
751 static void copy_walk_n(ir_node *node,
752                 walker_condition *walk_condition, int copy_index)
753 {
754         int i;
755         int arity;
756         ir_node *cp;
757         ir_node **cpin;
758
759         /**
760          * break condition and cycle resolver, creating temporary node copies
761          */
762         if (irn_visited(node)) {
763                 /* Here we rely on nodestate's copy being initialized with NULL */
764                 DB((dbg, LEVEL_5, "copy_walk: We have already visited %N\n", node));
765                 if (get_unroll_copy(node, copy_index) == NULL) {
766                         ir_node *u;
767                         u = copy_node(node);
768                         set_unroll_copy(node, copy_index, u);
769                         DB((dbg, LEVEL_5, "The TEMP unknown of %N is created %N\n", node, u));
770                 }
771                 return;
772         }
773
774         /* Walk */
775         mark_irn_visited(node);
776
777         if (!is_Block(node)) {
778                 ir_node *block = get_nodes_block(node);
779                 if (walk_condition(block))
780                         DB((dbg, LEVEL_5, "walk block %N\n", block));
781                 copy_walk_n(block, walk_condition, copy_index);
782         }
783
784         arity = get_irn_arity(node);
785         NEW_ARR_A(ir_node *, cpin, arity);
786
787         for (i = 0; i < arity; ++i) {
788                 ir_node *pred = get_irn_n(node, i);
789
790                 if (walk_condition(pred)) {
791                         DB((dbg, LEVEL_5, "walk node %N\n", pred));
792                         copy_walk_n(pred, walk_condition, copy_index);
793                         cpin[i] = get_unroll_copy(pred, copy_index);
794                 } else {
795                         cpin[i] = pred;
796                 }
797         }
798
799         /* copy node / finalize temp node */
800         cp = get_unroll_copy(node, copy_index);
801         if (cp == NULL || is_Unknown(cp)) {
802                 cp = copy_node(node);
803                 set_unroll_copy(node, copy_index, cp);
804                 DB((dbg, LEVEL_5, "The FINAL copy of %N is CREATED %N\n", node, cp));
805         } else {
806                 /* temporary copy is existent but without correct ins */
807                 cp = get_unroll_copy(node, copy_index);
808                 DB((dbg, LEVEL_5, "The FINAL copy of %N is EXISTENT %N\n", node, cp));
809         }
810
811         if (!is_Block(node)) {
812                 ir_node *cpblock = get_unroll_copy(get_nodes_block(node), copy_index);
813
814                 set_nodes_block(cp, cpblock );
815                 if (is_Phi(cp))
816                         add_Block_phi(cpblock, cp);
817         }
818
819         /* Keeps phi list of temporary node. */
820         set_irn_in(cp, ARR_LEN(cpin), cpin);
821 }
822
823 /* Removes alle Blocks with non marked predecessors from the condition chain. */
824 static void unmark_not_allowed_cc_blocks(void)
825 {
826         int blocks = ARR_LEN(cc_blocks);
827         int i;
828
829         for(i = 0; i < blocks; ++i) {
830                 ir_node *block = cc_blocks[i];
831                 int a;
832                 int arity = get_irn_arity(block);
833
834                 /* Head is an exception. */
835                 if (block == loop_head)
836                         continue;
837
838                 for(a = 0; a < arity; ++a) {
839                         if (! is_nodes_block_marked(get_irn_n(block, a))) {
840                                 set_Block_mark(block, 0);
841                                 --inversion_blocks_in_cc;
842                                 DB((dbg, LEVEL_5, "Removed %N from cc (blocks in cc %d)\n",
843                                                 block, inversion_blocks_in_cc));
844
845                                 break;
846                         }
847                 }
848         }
849 }
850
851 /* Unmarks all cc blocks using cc_blocks except head. */
852 static void unmark_cc_blocks(void)
853 {
854         int blocks = ARR_LEN(cc_blocks);
855         int i;
856
857         for(i = 0; i < blocks; ++i) {
858                 ir_node *block = cc_blocks[i];
859
860                 /* Head is an exception. */
861                 if (block != loop_head)
862                         set_Block_mark(block, 0);
863         }
864         inversion_blocks_in_cc = 1;
865
866         /* invalidate */
867         loop_info.cc_size = 0;
868 }
869
870 /**
871  * Populates head_entries with (node, pred_pos) tuple
872  * whereas the node's pred at pred_pos is in the cc but not the node itself.
873  * Also finds df loops inside the cc.
874  * Head and condition chain blocks have been marked previously.
875  */
876 static void get_head_outs(ir_node *node, void *env)
877 {
878         int i;
879         int arity = get_irn_arity(node);
880         (void) env;
881
882         for (i = 0; i < arity; ++i) {
883                 if (!is_nodes_block_marked(node) && is_nodes_block_marked(get_irn_n(node, i))) {
884                         entry_edge entry;
885                         entry.node = node;
886                         entry.pos = i;
887                         /* Saving also predecessor seems redundant, but becomes
888                          * necessary when changing position of it, before
889                          * dereferencing it.*/
890                         entry.pred = get_irn_n(node, i);
891                         ARR_APP1(entry_edge, cur_head_outs, entry);
892                 }
893         }
894
895         arity = get_irn_arity(loop_head);
896
897         /* Find df loops inside the cc */
898         if (is_Phi(node) && get_nodes_block(node) == loop_head) {
899                 for (i = 0; i < arity; ++i) {
900                         if (is_own_backedge(loop_head, i)) {
901                                 if (is_nodes_block_marked(get_irn_n(node, i))) {
902                                         entry_edge entry;
903                                         entry.node = node;
904                                         entry.pos = i;
905                                         entry.pred = get_irn_n(node, i);
906                                         ARR_APP1(entry_edge, head_df_loop, entry);
907                                         DB((dbg, LEVEL_5, "Found incc assignment node %N @%d is pred %N, graph %N %N\n",
908                                                         node, i, entry.pred, current_ir_graph, get_irg_start_block(current_ir_graph)));
909                                 }
910                         }
911                 }
912         }
913 }
914
915 /**
916  * Find condition chains, and add them to be inverted
917  * A block belongs to the chain if a condition branches out of the loop.
918  * (Some blocks need to be removed once again.)
919  * Returns 1 if the given block belongs to the condition chain.
920  */
921 static unsigned find_condition_chain(ir_node *block)
922 {
923         const    ir_edge_t *edge;
924         unsigned mark = 0;
925         unsigned has_be = 0;
926         unsigned jmp_only;
927         unsigned nodes_n = 0;
928
929         mark_irn_visited(block);
930
931         DB((dbg, LEVEL_5, "condition_chains for block %N\n", block));
932
933         /* Get node count */
934         foreach_out_edge_kind(block, edge, EDGE_KIND_NORMAL) {
935                 ++nodes_n;
936         }
937
938         /* Check if node count would exceed maximum cc size.
939          * TODO
940          * This is not optimal, as we search depth-first and break here,
941          * continuing with another subtree. */
942         if (loop_info.cc_size + nodes_n > opt_params.max_cc_size) {
943                 set_Block_mark(block, 0);
944                 return 0;
945         }
946
947         /* Check if block only has a jmp instruction. */
948         jmp_only = 1;
949         foreach_out_edge(block, edge) {
950                 ir_node *src = get_edge_src_irn(edge);
951
952                 if (! is_Block(src) && ! is_Jmp(src)) {
953                         jmp_only = 0;
954                 }
955         }
956
957         /* Check cf outs if one is leaving the loop,
958          * or if this node has a backedge. */
959         foreach_block_succ(block, edge) {
960                 ir_node *src = get_edge_src_irn(edge);
961                 int pos = get_edge_src_pos(edge);
962
963                 if (! is_in_loop(src))
964                         mark = 1;
965
966                 /* Inverting blocks with backedge outs leads to a cf edge
967                  * from the inverted head, into the inverted head (skipping the body).
968                  * As the body becomes the new loop head,
969                  * this would introduce another loop in the existing loop.
970                  * This loop inversion cannot cope with this case. */
971                 if (is_backedge(src, pos)) {
972                         has_be = 1;
973                         break;
974                 }
975         }
976
977         /* We need all predecessors to already belong to the condition chain.
978          * Example of wrong case:  * == in cc
979          *
980          *     Head*             ,--.
981          *    /|   \            B   |
982          *   / A*  B           /    |
983          *  / /\   /          ?     |
984          *   /   C*      =>      D  |
985          *          /  D               Head |
986          *     /               A  \_|
987          *                      C
988          */
989         /* Collect blocks containing only a Jmp.
990          * Do not collect blocks with backedge outs. */
991         if ((jmp_only == 1 || mark == 1) && has_be == 0) {
992                 set_Block_mark(block, 1);
993                 ++inversion_blocks_in_cc;
994                 loop_info.cc_size += nodes_n;
995                 DB((dbg, LEVEL_5, "block %N is part of condition chain\n", block));
996                 ARR_APP1(ir_node *, cc_blocks, block);
997         } else {
998                 set_Block_mark(block, 0);
999         }
1000
1001         foreach_block_succ(block, edge) {
1002                 ir_node *src = get_edge_src_irn( edge );
1003
1004                 if (is_in_loop(src) && ! irn_visited(src))
1005                         find_condition_chain(src);
1006         }
1007
1008         return mark;
1009 }
1010
1011 /**
1012  * Rewires the copied condition chain. Removes backedges.
1013  * as this condition chain is prior to the loop.
1014  * Copy of loop_head must have phi list and old (unfixed) backedge info of the loop head.
1015  * (loop_head is already fixed, we cannot rely on it.)
1016  */
1017 static void fix_copy_inversion(void)
1018 {
1019         ir_node *new_head;
1020         ir_node **ins;
1021         ir_node **phis;
1022         ir_node *phi, *next;
1023         ir_node *head_cp        = get_inversion_copy(loop_head);
1024         int arity                       = get_irn_arity(head_cp);
1025         int backedges           = get_backedge_n(head_cp, 0);
1026         int new_arity           = arity - backedges;
1027         int pos;
1028         int i;
1029
1030         NEW_ARR_A(ir_node *, ins, new_arity);
1031
1032         pos = 0;
1033         /* Remove block backedges */
1034         for(i = 0; i < arity; ++i) {
1035                 if (!is_backedge(head_cp, i))
1036                         ins[pos++] = get_irn_n(head_cp, i);
1037         }
1038
1039         new_head = new_Block(new_arity, ins);
1040
1041         phis = NEW_ARR_F(ir_node *, 0);
1042
1043         for_each_phi_safe(get_Block_phis(head_cp), phi, next) {
1044                 ir_node *new_phi;
1045                 NEW_ARR_A(ir_node *, ins, new_arity);
1046                 pos = 0;
1047                 for(i = 0; i < arity; ++i) {
1048                         if (!is_backedge(head_cp, i))
1049                                 ins[pos++] = get_irn_n(phi, i);
1050                 }
1051                 new_phi = new_rd_Phi(get_irn_dbg_info(phi),
1052                                 new_head, new_arity, ins,
1053                                 get_irn_mode(phi));
1054                 ARR_APP1(ir_node *, phis, new_phi);
1055         }
1056
1057         pos = 0;
1058         for_each_phi_safe(get_Block_phis(head_cp), phi, next) {
1059                 exchange(phi, phis[pos++]);
1060         }
1061
1062         exchange(head_cp, new_head);
1063
1064         DEL_ARR_F(phis);
1065 }
1066
1067 /* Puts the original condition chain at the end of the loop,
1068  * subsequently to the body.
1069  * Relies on block phi list and correct backedges.
1070  */
1071 static void fix_head_inversion(void)
1072 {
1073         ir_node *new_head;
1074         ir_node **ins;
1075         ir_node *phi, *next;
1076         ir_node **phis;
1077         int arity                       = get_irn_arity(loop_head);
1078         int backedges           = get_backedge_n(loop_head, 0);
1079         int new_arity           = backedges;
1080         int pos;
1081         int i;
1082
1083         NEW_ARR_A(ir_node *, ins, new_arity);
1084
1085         pos = 0;
1086         /* Keep only backedges */
1087         for(i = 0; i < arity; ++i) {
1088                 if (is_own_backedge(loop_head, i))
1089                         ins[pos++] = get_irn_n(loop_head, i);
1090         }
1091
1092         new_head = new_Block(new_arity, ins);
1093
1094         phis = NEW_ARR_F(ir_node *, 0);
1095
1096         for_each_phi(loop_head, phi) {
1097                 ir_node *new_phi;
1098                 DB((dbg, LEVEL_5, "Fixing phi %N of loop head\n", phi));
1099
1100                 NEW_ARR_A(ir_node *, ins, new_arity);
1101
1102                 pos = 0;
1103                 for (i = 0; i < arity; ++i) {
1104                         ir_node *pred = get_irn_n(phi, i);
1105
1106                         if (is_own_backedge(loop_head, i)) {
1107                                 /* If assignment is in the condition chain,
1108                                  * we need to create a phi in the new loop head.
1109                                  * This can only happen for df, not cf. See find_condition_chains. */
1110                                 if (is_nodes_block_marked(pred)) {
1111                                         /* Cannot do this here. */
1112                                         ins[pos++] = pred; /*fix_inner_cc_definitions(phi, pred);*/
1113                                 } else {
1114                                         ins[pos++] = pred;
1115                                 }
1116                         }
1117                 }
1118
1119                 new_phi = new_rd_Phi(get_irn_dbg_info(phi),
1120                         new_head, new_arity, ins,
1121                         get_irn_mode(phi));
1122
1123                 ARR_APP1(ir_node *, phis, new_phi);
1124
1125                 DB((dbg, LEVEL_5, "fix inverted head should exch %N by %N (arity %d)\n", phi, new_phi, pos ));
1126         }
1127
1128         pos = 0;
1129         for_each_phi_safe(get_Block_phis(loop_head), phi, next) {
1130                 DB((dbg, LEVEL_5, "fix inverted exch phi %N by %N\n", phi, phis[pos]));
1131                 if (phis[pos] != phi)
1132                         exchange(phi, phis[pos++]);
1133         }
1134
1135         DEL_ARR_F(phis);
1136
1137         DB((dbg, LEVEL_5, "fix inverted head exch head block %N by %N\n", loop_head, new_head));
1138         exchange(loop_head, new_head);
1139 }
1140
1141 /* Does the loop inversion.  */
1142 static void inversion_walk(entry_edge *head_entries)
1143 {
1144         int i;
1145
1146         /*
1147          * The order of rewiring bottom-up is crucial.
1148          * Any change of the order leads to lost information that would be needed later.
1149          */
1150
1151         ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1152
1153         /* 1. clone condition chain */
1154         inc_irg_visited(current_ir_graph);
1155
1156         for (i = 0; i < ARR_LEN(head_entries); ++i) {
1157                 entry_edge entry = head_entries[i];
1158                 ir_node *pred = get_irn_n(entry.node, entry.pos);
1159
1160                 DB((dbg, LEVEL_5, "\nInit walk block %N\n", pred));
1161
1162                 copy_walk(pred, is_nodes_block_marked, cur_loop);
1163         }
1164
1165         ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1166
1167         /* 2. Extends the head control flow successors ins
1168          *    with the definitions of the copied head node. */
1169         for (i = 0; i < ARR_LEN(head_entries); ++i) {
1170                 entry_edge head_out = head_entries[i];
1171
1172                 if (is_Block(head_out.node))
1173                         extend_ins_by_copy(head_out.node, head_out.pos);
1174         }
1175
1176         /* 3. construct_ssa for users of definitions in the condition chain,
1177          *    as there is now a second definition. */
1178         for (i = 0; i < ARR_LEN(head_entries); ++i) {
1179                 entry_edge head_out = head_entries[i];
1180
1181                 /* Ignore keepalives */
1182                 if (is_End(head_out.node))
1183                         continue;
1184
1185                 /* Construct ssa for assignments in the condition chain. */
1186                 if (!is_Block(head_out.node)) {
1187                         ir_node *pred, *cppred, *block, *cpblock;
1188
1189                         pred = head_out.pred;
1190                         cppred = get_inversion_copy(pred);
1191                         block = get_nodes_block(pred);
1192                         cpblock = get_nodes_block(cppred);
1193                         construct_ssa(block, pred, cpblock, cppred);
1194                 }
1195         }
1196
1197         /*
1198          * If there is an assignment in the condition chain
1199          * with a user also in the condition chain,
1200          * the dominance frontier is in the new loop head.
1201          * The dataflow loop is completely in the condition chain.
1202          * Goal:
1203          *  To be wired: >|
1204          *
1205          *  | ,--.   |
1206          * Phi_cp |  | copied condition chain
1207          * >| |   |  |
1208          * >| ?__/   |
1209          * >| ,-.
1210          *  Phi* |   | new loop head with newly created phi.
1211          *   |   |
1212          *  Phi  |   | original, inverted condition chain
1213          *   |   |   |
1214          *   ?__/    |
1215          *
1216          */
1217         for (i = 0; i < ARR_LEN(head_df_loop); ++i) {
1218                 entry_edge head_out = head_df_loop[i];
1219
1220                 /* Construct ssa for assignments in the condition chain. */
1221                 ir_node *pred, *cppred, *block, *cpblock;
1222
1223                 pred = head_out.pred;
1224                 cppred = get_inversion_copy(pred);
1225                 assert(cppred && pred);
1226                 block = get_nodes_block(pred);
1227                 cpblock = get_nodes_block(cppred);
1228                 construct_ssa(block, pred, cpblock, cppred);
1229         }
1230
1231         /* 4. Remove the ins which are no backedges from the original condition chain
1232          *    as the cc is now subsequent to the body. */
1233         fix_head_inversion();
1234
1235         /* 5. Remove the backedges of the copied condition chain,
1236          *    because it is going to be the new 'head' in advance to the loop. */
1237         fix_copy_inversion();
1238 }
1239
1240 /* Performs loop inversion of cur_loop if possible and reasonable. */
1241 static void loop_inversion(void)
1242 {
1243         unsigned do_inversion = 1;
1244         unsigned has_cc = 0;
1245
1246         /*inversion_head_node_limit = INT_MAX;*/
1247         ir_reserve_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1248
1249         /* Reset block marks.
1250          * We use block marks to flag blocks of the original condition chain. */
1251         irg_walk_graph(current_ir_graph, reset_block_mark, NULL, NULL);
1252
1253         /*loop_info.blocks = get_loop_n_blocks(cur_loop);*/
1254         cond_chain_entries = NEW_ARR_F(entry_edge, 0);
1255         head_df_loop = NEW_ARR_F(entry_edge, 0);
1256
1257         /*head_inversion_node_count = 0;*/
1258         inversion_blocks_in_cc = 0;
1259
1260         /* Use phase to keep copy of nodes from the condition chain. */
1261         phase = new_phase(current_ir_graph, phase_irn_init_default);
1262
1263         /* Search for condition chains and temporarily save the blocks in an array. */
1264         cc_blocks = NEW_ARR_F(ir_node *, 0);
1265         inc_irg_visited(current_ir_graph);
1266         has_cc = find_condition_chain(loop_head);
1267
1268         unmark_not_allowed_cc_blocks();
1269         DEL_ARR_F(cc_blocks);
1270
1271 #if LOOP_IGNORE_NODE_LIMITS
1272         (void) unmark_cc_blocks;
1273 #else
1274         /* Condition chain too large.
1275          * Loop should better be small enough to fit into the cache. */
1276         /* FIXME Of course, we should take a small enough cc in the first place,
1277          * which is not that simple. (bin packing)  */
1278         if (loop_info.cc_size > opt_params.max_cc_size) {
1279                 count_stats(stats.cc_limit_reached);
1280
1281                 /* Only head taken? */
1282                 if (inversion_blocks_in_cc == 1)
1283                         do_inversion = 0;
1284                 else
1285                         /* Unmark cc blocks except the head.
1286                          * Invert head only for possible unrolling. */
1287                         unmark_cc_blocks();
1288         }
1289 #endif
1290
1291         /* We also catch endless loops here,
1292          * because they do not have a condition chain. */
1293         if (inversion_blocks_in_cc < 1) {
1294                 do_inversion = 0;
1295                 DB((dbg, LEVEL_3,
1296                         "Loop contains %d (less than 1) invertible blocks => No Inversion done.\n",
1297                         inversion_blocks_in_cc));
1298         }
1299
1300         if (do_inversion) {
1301                 cur_head_outs = NEW_ARR_F(entry_edge, 0);
1302
1303                 /* Get all edges pointing into the condition chain. */
1304                 irg_walk_graph(current_ir_graph, get_head_outs, NULL, NULL);
1305
1306                 /* Do the inversion */
1307                 inversion_walk(cur_head_outs);
1308
1309                 DEL_ARR_F(cur_head_outs);
1310
1311                 /* Duplicated blocks changed doms */
1312                 set_irg_doms_inconsistent(current_ir_graph);
1313                 /* Loop content changed */
1314                 set_irg_loopinfo_inconsistent(current_ir_graph);
1315                 /* TODO are they? Depends on set_irn_in and set_irn_n exchange and new_node. */
1316                 set_irg_outs_inconsistent(current_ir_graph);
1317
1318                 count_stats(stats.inverted);
1319         }
1320
1321         /* free */
1322         phase_free(phase);
1323         DEL_ARR_F(cond_chain_entries);
1324         DEL_ARR_F(head_df_loop);
1325
1326         ir_free_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1327 }
1328
1329 /* Fix the original loop_heads ins for invariant unrolling case. */
1330 static void unrolling_fix_loop_head_inv(void)
1331 {
1332         ir_node *ins[2];
1333         ir_node *phi;
1334         ir_node *proj = new_Proj(loop_info.duff_cond, mode_X, 0);
1335         ir_node *head_pred = get_irn_n(loop_head, loop_info.be_src_pos);
1336         ir_node *loop_condition = get_unroll_copy(head_pred, unroll_nr - 1);
1337
1338         /* Original loop_heads ins are:
1339          * duff block and the own backedge */
1340
1341         ins[0] = loop_condition;
1342         ins[1] = proj;
1343
1344         set_irn_in(loop_head, 2, ins);
1345
1346         for_each_phi(loop_head, phi) {
1347                 ir_node *pred = get_irn_n(phi, loop_info.be_src_pos);
1348                 ir_node *last_pred = get_unroll_copy(pred, unroll_nr - 1);
1349
1350                 ins[0] = last_pred;
1351                 ins[1] = get_irn_link(phi);
1352
1353                 set_irn_in(phi, 2, ins);
1354         }
1355 }
1356
1357 /* Removes previously created phis with only 1 in. */
1358 static void correct_phis(ir_node *node, void *env)
1359 {
1360         (void)env;
1361         if (is_Phi(node) && get_irn_arity(node) == 1) {
1362                 ir_node *exch;
1363                 ir_node *in[1];
1364
1365                 in[0] = get_irn_n(node, 0);
1366
1367                 exch = new_rd_Phi(get_irn_dbg_info(node),
1368                     get_nodes_block(node), 1, in,
1369                 get_irn_mode(node));
1370
1371                 exchange(node, exch);
1372         }
1373 }
1374
1375 /* Unrolling: Rewire floating copies. */
1376 static void place_copies(int copies)
1377 {
1378         ir_node *loophead = loop_head;
1379         int c, i;
1380         int be_src_pos = loop_info.be_src_pos;
1381
1382         /* Serialize loops by fixing their head ins.
1383          * Processed are the copies.
1384          * The original loop is done after that, to keep backedge infos. */
1385         for (c = 0; c < copies; ++c) {
1386                 ir_node *upper = get_unroll_copy(loophead, c);
1387                 ir_node *lower = get_unroll_copy(loophead, c + 1);
1388                 ir_node *phi;
1389                 ir_node *topmost_be_block = get_nodes_block(get_irn_n(loophead, be_src_pos));
1390
1391                 /* Important: get the preds first and then their copy. */
1392                 ir_node *upper_be_block = get_unroll_copy(topmost_be_block, c);
1393                 ir_node *new_jmp = new_r_Jmp(upper_be_block);
1394                 DB((dbg, LEVEL_5, " place_copies upper %N lower %N\n", upper, lower));
1395
1396                 DB((dbg, LEVEL_5, "topmost be block %N \n", topmost_be_block));
1397
1398                 if (loop_info.unroll_kind == constant) {
1399                         ir_node *ins[1];
1400                         ins[0] = new_jmp;
1401                         set_irn_in(lower, 1, ins);
1402
1403                         for_each_phi(loophead, phi) {
1404                                 ir_node *topmost_def = get_irn_n(phi, be_src_pos);
1405                                 ir_node *upper_def = get_unroll_copy(topmost_def, c);
1406                                 ir_node *lower_phi = get_unroll_copy(phi, c + 1);
1407
1408                                 /* It is possible, that the value used
1409                                  * in the OWN backedge path is NOT defined in this loop. */
1410                                 if (is_in_loop(topmost_def))
1411                                         ins[0] = upper_def;
1412                                 else
1413                                         ins[0] = topmost_def;
1414
1415                                 set_irn_in(lower_phi, 1, ins);
1416                                 /* Need to replace phis with 1 in later. */
1417                         }
1418                 } else {
1419                         /* Invariant case */
1420                         /* Every node has 2 ins. One from the duff blocks
1421                          * and one from the previous unrolled loop. */
1422                         ir_node *ins[2];
1423                         /* Calculate corresponding projection of mod result for this copy c */
1424                         ir_node *proj = new_Proj(loop_info.duff_cond, mode_X, unroll_nr - c - 1);
1425
1426                         ins[0] = new_jmp;
1427                         ins[1] = proj;
1428                         set_irn_in(lower, 1, ins);
1429
1430                         for_each_phi(loophead, phi) {
1431                                 ir_node *topmost_phi_pred = get_irn_n(phi, be_src_pos);
1432                                 ir_node *upper_phi_pred;
1433                                 ir_node *lower_phi;
1434                                 ir_node *duff_phi;
1435
1436                                 lower_phi = get_unroll_copy(phi, c + 1);
1437                                 duff_phi = get_irn_link(lower_phi);
1438
1439                                 if (is_in_loop(topmost_phi_pred)) {
1440                                         upper_phi_pred = get_unroll_copy(topmost_phi_pred, c);
1441                                 } else {
1442                                         upper_phi_pred = topmost_phi_pred;
1443                                 }
1444
1445                                 ins[0] = upper_phi_pred;
1446                                 ins[1] = duff_phi;
1447
1448                                 set_irn_in(lower_phi, 2, ins);
1449                         }
1450                 }
1451         }
1452
1453         /* Reconnect loop landing pad with last copy. */
1454         for (i = 0; i < ARR_LEN(loop_entries); ++i) {
1455                 entry_edge edge = loop_entries[i];
1456                 /* Last copy is at the bottom */
1457                 ir_node *new_pred = get_unroll_copy(edge.pred, copies);
1458                 set_irn_n(edge.node, edge.pos, new_pred);
1459         }
1460
1461         /* Fix original loops head.
1462          * Done in the end, as ins and be info were needed before. */
1463         if (loop_info.unroll_kind == constant) {
1464                 ir_node *phi;
1465                 ir_node *head_pred = get_irn_n(loop_head, be_src_pos);
1466                 ir_node *loop_condition = get_unroll_copy(head_pred, unroll_nr - 1);
1467
1468                 set_irn_n(loop_head, loop_info.be_src_pos, loop_condition);
1469
1470                 for_each_phi(loop_head, phi) {
1471                         ir_node *pred = get_irn_n(phi, be_src_pos);
1472                         ir_node *last_pred;
1473
1474                         /* It is possible, that the value used
1475                          * in the OWN backedge path is NOT defined in this loop. */
1476                         if (is_in_loop(pred))
1477                                 last_pred = get_unroll_copy(pred, copies);
1478                         else
1479                                 last_pred = pred;
1480                         set_irn_n(phi, be_src_pos, last_pred);
1481                 }
1482         } else {
1483                 unrolling_fix_loop_head_inv();
1484         }
1485 }
1486
1487 /* Copies the cur_loop several times. */
1488 static void copy_loop(entry_edge *cur_loop_outs, int copies)
1489 {
1490         int i, c;
1491
1492         ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1493
1494         for (c = 0; c < copies; ++c) {
1495
1496                 inc_irg_visited(current_ir_graph);
1497
1498                 DB((dbg, LEVEL_5, "         ### Copy_loop  copy nr: %d ###\n", c));
1499                 for (i = 0; i < ARR_LEN(cur_loop_outs); ++i) {
1500                         entry_edge entry = cur_loop_outs[i];
1501                         ir_node *pred = get_irn_n(entry.node, entry.pos);
1502
1503                         copy_walk_n(pred, is_in_loop, c + 1);
1504                 }
1505         }
1506
1507         ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1508 }
1509
1510
1511 /* Creates a new phi from the given phi node omitting own bes,
1512  * using be_block as supplier of backedge informations. */
1513 static ir_node *clone_phis_sans_bes(ir_node *node, ir_node *be_block)
1514 {
1515         ir_node **ins;
1516         int arity = get_irn_arity(node);
1517         int i, c = 0;
1518
1519         assert(get_irn_arity(node) == get_irn_arity(be_block));
1520         assert(is_Phi(node));
1521
1522         ins = NEW_ARR_F(ir_node *, arity);
1523         for (i = 0; i < arity; ++i) {
1524                 if (! is_own_backedge(be_block, i)) {
1525                         ins[c] = get_irn_n(node, i);
1526                         ++c;
1527                 }
1528         /*      } else {
1529                         ir_node *pred = get_inr_n(node, i);
1530                         if (! is_in_loop(pred)) {
1531                                 ins[c] = pred;
1532                                 ++c;
1533                         }
1534                 }*/
1535         }
1536
1537         return new_r_Phi(get_nodes_block(node), c, ins, get_irn_mode(node));
1538 }
1539
1540 /* Creates a new block from the given block node omitting own bes,
1541  * using be_block as supplier of backedge informations. */
1542 static ir_node *clone_block_sans_bes(ir_node *node, ir_node *be_block)
1543 {
1544         ir_node **ins;
1545         int arity = get_irn_arity(node);
1546         int i, c = 0;
1547
1548         assert(get_irn_arity(node) == get_irn_arity(be_block));
1549         assert(is_Block(node));
1550
1551         ins = NEW_ARR_F(ir_node *, arity);
1552         for (i = 0; i < arity; ++i) {
1553                 if (! is_own_backedge(be_block, i)) {
1554                         ins[c] = get_irn_n(node, i);
1555                         ++c;
1556                 }
1557         }
1558
1559         return new_Block(c, ins);
1560 }
1561
1562 /* Creates blocks for duffs device, using previously obtained
1563  * informations about the iv.
1564  * TODO split */
1565 static void create_duffs_block(void)
1566 {
1567         ir_mode *mode;
1568
1569         ir_node *block1, *count_block, *duff_block;
1570         ir_node *ems, *ems_divmod, *ems_mod_proj, *cmp_null,
1571                 *cmp_proj, *ems_mode_cond, *x_true, *x_false, *const_null;
1572         ir_node *true_val, *false_val;
1573         ir_node *ins[2];
1574
1575         ir_node *duff_mod, *proj, *cond;
1576
1577         ir_node *count, *correction, *unroll_c;
1578         ir_node *cmp_bad_count, *good_count, *bad_count, *count_phi, *bad_count_neg;
1579
1580         mode = get_irn_mode(loop_info.end_val);
1581         const_null = new_Const(get_mode_null(mode));
1582
1583         /* TODO naming
1584          * 1. Calculate first approach to count.
1585          *    Condition: (end - start) % step == 0 */
1586         block1 = clone_block_sans_bes(loop_head, loop_head);
1587
1588         /* Create loop entry phis in first duff block
1589          * as it becomes the loops preheader */
1590         if (loop_info.unroll_kind == invariant) {
1591                 ir_node *phi;
1592                 for_each_phi(loop_head, phi) {
1593                         ir_node *new_phi = clone_phis_sans_bes(phi, loop_head);
1594                         set_nodes_block(new_phi, block1);
1595                 }
1596         }
1597
1598         ems = new_r_Sub(block1, loop_info.end_val, loop_info.start_val,
1599                 get_irn_mode(loop_info.end_val));
1600
1601         ems_divmod = new_r_DivMod(block1,
1602                 new_NoMem(),
1603                 ems,
1604                 loop_info.step,
1605                 mode,
1606                 op_pin_state_pinned);
1607
1608         ems_mod_proj = new_r_Proj(ems_divmod, mode, pn_DivMod_res_mod);
1609         cmp_null = new_r_Cmp(block1, ems_mod_proj, const_null);
1610         cmp_proj = new_r_Proj(cmp_null, mode, pn_Cmp_Eq);
1611         ems_mode_cond = new_Cond(cmp_proj);
1612
1613         /* ems % step == 0 */
1614         x_true = new_Proj(ems_mode_cond, mode_X, pn_Cond_true);
1615         /* ems % step != 0 */
1616         x_false = new_Proj(ems_mode_cond, mode_X, pn_Cond_false);
1617
1618
1619         /* 2. Second block.
1620          * Assures, duffs device receives a valid count.
1621          * Condition:
1622          *     decreasing: count < 0
1623          *     increasing: count > 0
1624          */
1625         ins[0] = x_true;
1626         ins[1] = x_false;
1627
1628         count_block = new_Block(2, ins);
1629
1630         /* Increase loop-taken-count depending on the loop condition
1631          * uses the latest iv to compare to. */
1632         if (loop_info.latest_value == 1) {
1633                 /* ems % step == 0 :  +0 */
1634                 true_val = new_Const(get_mode_null(mode));
1635                 /* ems % step != 0 :  +1 */
1636                 false_val = new_Const(get_mode_one(mode));
1637         } else {
1638                 tarval *tv_two = new_tarval_from_long(2, mode);
1639                 /* ems % step == 0 :  +1 */
1640                 true_val = new_Const(get_mode_one(mode));
1641                 /* ems % step != 0 :  +2 */
1642                 false_val = new_Const(tv_two);
1643         }
1644
1645         ins[0] = true_val;
1646         ins[1] = false_val;
1647
1648         correction = new_r_Phi(count_block, 2, ins, mode);
1649
1650         count = new_r_Proj(ems_divmod, mode, pn_DivMod_res_div);
1651
1652         /* (end - start) / step  +  correction */
1653         count = new_Add(count, correction, mode);
1654
1655         cmp_bad_count = new_r_Cmp(count_block, count, const_null);
1656
1657         /* We preconditioned the loop to be tail-controlled.
1658          * So, if count is something 'wrong' like 0,
1659          * negative/positive (depending on step direction),
1660          * we may take the loop once (tail-contr.) and leave it
1661          * to the existing condition, to break; */
1662
1663         /* Depending on step direction, we have to check for > or < 0 */
1664         if (loop_info.decreasing == 1) {
1665                 bad_count_neg = new_r_Proj(cmp_bad_count, mode_X, pn_Cmp_Lt);
1666         } else {
1667                 bad_count_neg = new_r_Proj(cmp_bad_count, mode_X, pn_Cmp_Gt);
1668         }
1669
1670         bad_count_neg = new_Cond(bad_count_neg);
1671         good_count = new_Proj(bad_count_neg, mode_X, pn_Cond_true);
1672         bad_count = new_Proj(ems_mode_cond, mode_X, pn_Cond_false);
1673
1674         /* 3. Duff Block
1675          *    Contains module to decide which loop to start from. */
1676
1677         ins[0] = good_count;
1678         ins[1] = bad_count;
1679         duff_block = new_Block(2, ins);
1680
1681         /* count wants to be positive */
1682         ins[0] = get_Abs_op(count);
1683         /* Manually feed the aforementioned count = 1 (bad case)*/
1684         ins[1] = new_Const(get_mode_one(mode));
1685         count_phi = new_r_Phi(duff_block, 2, ins, mode);
1686
1687         unroll_c = new_Const(new_tarval_from_long((long)unroll_nr, mode));
1688
1689         /* count % unroll_nr */
1690         duff_mod = new_r_Mod(duff_block,
1691                 new_NoMem(),
1692                 count_phi,
1693                 unroll_c,
1694                 mode,
1695                 op_pin_state_pinned);
1696
1697         proj = new_Proj(duff_mod, mode_X, pn_Mod_res);
1698         cond = new_Cond(proj);
1699
1700         loop_info.duff_cond = cond;
1701 }
1702
1703 /* Returns 1 if given node is not in loop,
1704  * or if it is a phi of the loop head with only loop invariant defs.
1705  */
1706 static unsigned is_loop_invariant_def(ir_node *node)
1707 {
1708         int i;
1709
1710         if (! is_in_loop(node))
1711                 return 1;
1712
1713         /* If this is a phi of the loophead shared by more than 1 loop,
1714          * we need to check if all defs are not in the loop.  */
1715         if (is_Phi(node)) {
1716                 ir_node *block;
1717                 block = get_nodes_block(node);
1718
1719                 /* To prevent unexpected situations. */
1720                 if (block != loop_head)
1721                         return 0;
1722
1723                 for (i = 0; i < get_irn_arity(node); ++i) {
1724                         /* Check if all bes are just loopbacks. */
1725                         if (is_own_backedge(block, i) && get_irn_n(node, i) != node)
1726                                 return 0;
1727                 }
1728         }
1729         return 1;
1730 }
1731
1732 /* Returns 1 if one pred of node is invariant and the other is not.
1733  * invar_pred and other are set analogously. */
1734 static unsigned get_invariant_pred(ir_node *node, ir_node **invar_pred, ir_node **other)
1735 {
1736         ir_node *pred0 = get_irn_n(node, 0);
1737         ir_node *pred1 = get_irn_n(node, 1);
1738
1739         *invar_pred = NULL;
1740         *other = NULL;
1741
1742         if (is_loop_invariant_def(pred0)) {
1743                 *invar_pred = pred0;
1744                 *other = pred1;
1745         }
1746
1747         if (is_loop_invariant_def(pred1)) {
1748                 if (invar_pred != NULL)
1749                         /* RETURN. We do not want both preds to be invariant. */
1750                         return 0;
1751
1752                 *other = pred0;
1753                 *invar_pred = pred1;
1754                 return 1;
1755         } else {
1756                 return 0;
1757         }
1758 }
1759
1760 /* Starts from a phi that may belong to an iv.
1761  * If an add forms a loop with iteration_phi,
1762  * and add uses a constant, 1 is returned
1763  * and 'start' as well as 'add' are sane. */
1764 static unsigned get_start_and_add(ir_node *iteration_phi, unrolling_kind_flag role)
1765 {
1766         int i;
1767         ir_node *found_add = loop_info.add;
1768         int arity = get_irn_arity(iteration_phi);
1769
1770         DB((dbg, LEVEL_4, "Find start and add from %N\n", iteration_phi));
1771
1772         for (i = 0; i < arity; ++i) {
1773
1774                 /* Find start_val which needs to be pred of the iteration_phi.
1775                  * If start_val already known, sanity check. */
1776                 if (!is_backedge(get_nodes_block(loop_info.iteration_phi), i)) {
1777                         ir_node *found_start_val = get_irn_n(loop_info.iteration_phi, i);
1778
1779                         DB((dbg, LEVEL_4, "found_start_val %N\n", found_start_val));
1780
1781                         /* We already found a start_val it has to be always the same. */
1782                         if (loop_info.start_val && found_start_val != loop_info.start_val)
1783                                 return 0;
1784
1785                         if ((role == constant) && !(is_SymConst(found_start_val) || is_Const(found_start_val)))
1786                                         return 0;
1787                         else if((role == constant) && !(is_loop_invariant_def(found_start_val)))
1788                                         return 0;
1789
1790                         loop_info.start_val = found_start_val;
1791                 }
1792
1793                 /* The phi has to be in the loop head.
1794                  * Follow all own backedges. Every value supplied from these preds of the phi
1795                  * needs to origin from the same add. */
1796                 if (is_own_backedge(get_nodes_block(loop_info.iteration_phi), i)) {
1797                         ir_node *new_found = get_irn_n(loop_info.iteration_phi,i);
1798
1799                         DB((dbg, LEVEL_4, "is add? %N\n", new_found));
1800
1801                         if (! (is_Add(new_found) || is_Sub(new_found)) || (found_add && found_add != new_found))
1802                                 return 0;
1803                         else
1804                                 found_add = new_found;
1805                 }
1806         }
1807
1808         loop_info.add = found_add;
1809
1810         return 1;
1811 }
1812
1813
1814 /* Returns 1 if one pred of node is a const value and the other is not.
1815  * const_pred and other are set analogously. */
1816 static unsigned get_const_pred(ir_node *node, ir_node **const_pred, ir_node **other)
1817 {
1818         ir_node *pred0 = get_irn_n(node, 0);
1819         ir_node *pred1 = get_irn_n(node, 1);
1820
1821         DB((dbg, LEVEL_4, "Checking for constant pred of %N\n", node));
1822
1823         *const_pred = NULL;
1824         *other = NULL;
1825
1826         /*DB((dbg, LEVEL_4, "is %N const\n", pred0));*/
1827         if (is_Const(pred0) || is_SymConst(pred0)) {
1828                 DB((dbg, LEVEL_1, "%N is constant\n", pred0));
1829                 *const_pred = pred0;
1830                 *other = pred1;
1831         }
1832
1833         /*DB((dbg, LEVEL_4, "is %N const\n", pred1));*/
1834         if (is_Const(pred1) || is_SymConst(pred1)) {
1835                 if (*const_pred != NULL) {
1836                         DB((dbg, LEVEL_1, "%N is ALSO constant\n", pred1));
1837                         /* RETURN. We do not want both preds to be constant. */
1838                         return 0;
1839                 }
1840
1841                 DB((dbg, LEVEL_4, "%N is constant\n", pred1));
1842                 *other = pred0;
1843                 *const_pred = pred1;
1844         }
1845
1846         if (*const_pred == NULL)
1847                 return 0;
1848         else
1849                 return 1;
1850 }
1851
1852 /* Returns the mathematically inverted pn_Cmp. */
1853 static pn_Cmp get_math_inverted_case(pn_Cmp proj)
1854 {
1855         switch(proj) {
1856                 case pn_Cmp_Eq:
1857                         return pn_Cmp_Lg;
1858                 case pn_Cmp_Lg:
1859                         return pn_Cmp_Eq;
1860                 case pn_Cmp_Lt:
1861                         return pn_Cmp_Ge;
1862                 case pn_Cmp_Le:
1863                         return pn_Cmp_Gt;
1864                 case pn_Cmp_Gt:
1865                         return pn_Cmp_Le;
1866                 case pn_Cmp_Ge:
1867                         return pn_Cmp_Lt;
1868                 default:
1869                         panic("Unhandled pn_Cmp.");
1870         }
1871 }
1872
1873 /* norm_proj means we do not exit the loop. */
1874 static unsigned simulate_next(tarval **count_tar,
1875                 tarval *stepped, tarval *step_tar, tarval *end_tar, pn_Cmp norm_proj)
1876 {
1877         tarval *next;
1878
1879         DB((dbg, LEVEL_1, "Loop taken if (stepped)%ld %s (end)%ld ",
1880                                 get_tarval_long(stepped),
1881                                 get_pnc_string((norm_proj)),
1882                                 get_tarval_long(end_tar)));
1883         DB((dbg, LEVEL_1, "comparing latest value %d\n", loop_info.latest_value));
1884
1885         /* If current iv does not stay in the loop,
1886          * this run satisfied the exit condition. */
1887         if (! (tarval_cmp(stepped, end_tar) & norm_proj))
1888                 return 1;
1889
1890         DB((dbg, LEVEL_1, "Result: (stepped)%ld IS %s (end)%ld\n",
1891                                 get_tarval_long(stepped),
1892                                 get_pnc_string(tarval_cmp(stepped, end_tar)),
1893                                 get_tarval_long(end_tar)));
1894
1895         /* next step */
1896         if (is_Add(loop_info.add))
1897                 next = tarval_add(stepped, step_tar);
1898         else
1899                 /* sub */
1900                 next = tarval_sub(stepped, step_tar, get_irn_mode(loop_info.end_val));
1901
1902         DB((dbg, LEVEL_1, "Loop taken if %ld %s %ld ",
1903                                 get_tarval_long(next),
1904                                 get_pnc_string(norm_proj),
1905                                 get_tarval_long(end_tar)));
1906         DB((dbg, LEVEL_1, "comparing latest value %d\n", loop_info.latest_value));
1907
1908         /* Increase steps. */
1909         *count_tar = tarval_add(*count_tar, get_tarval_one(get_tarval_mode(*count_tar)));
1910
1911         /* Next has to fail the loop condition, or we will never exit. */
1912         if (! (tarval_cmp(next, end_tar) & norm_proj))
1913                 return 1;
1914         else
1915                 return 0;
1916 }
1917
1918 /* Check if loop meets requirements for a 'simple loop':
1919  * - Exactly one cf out
1920  * - Allowed calls
1921  * - Max nodes after unrolling
1922  * - tail-controlled
1923  * - exactly one be
1924  * - cmp
1925  * Returns Projection of cmp node or NULL; */
1926 static ir_node *is_simple_loop(void)
1927 {
1928         int arity, i;
1929         unsigned loop_depth, max_loop_nodes_adapted;
1930         ir_node *loop_block, *exit_block, *projx, *cond, *projres, *loop_condition;
1931
1932         /* Maximum of one condition, and no endless loops. */
1933         if (loop_info.cf_outs != 1)
1934                 return NULL;
1935
1936         DB((dbg, LEVEL_4, "1 loop exit\n"));
1937
1938 #if 0
1939         /* Ignore loop size. Probably not wise in other than testcases. */
1940         (void) max_loop_nodes_adapted;
1941         (void) loop_depth;
1942
1943         loop_info.max_unroll = 6;
1944 #else
1945         /* Calculate maximum unroll_nr keeping node count below limit. */
1946         loop_depth = get_loop_depth(cur_loop) - 1;
1947         max_loop_nodes_adapted = get_max_nodes_adapted(loop_depth);
1948
1949         loop_info.max_unroll = opt_params.max_loop_size / loop_info.nodes;
1950         if (loop_info.max_unroll < 2) {
1951                 count_stats(stats.too_large);
1952                 return NULL;
1953         }
1954 #endif
1955         DB((dbg, LEVEL_4, "maximum unroll factor %u, to not exceed node limit \n",
1956                 loop_info.max_unroll));
1957
1958         arity = get_irn_arity(loop_head);
1959         /* RETURN if we have more than 1 be. */
1960         /* Get my backedges without alien bes. */
1961         loop_block = NULL;
1962         for (i = 0; i < arity; ++i) {
1963                 ir_node *pred = get_irn_n(loop_head, i);
1964                 if (is_own_backedge(loop_head, i)) {
1965                         if (loop_block)
1966                                 /* Our simple loops may have only one backedge. */
1967                                 return NULL;
1968                         else {
1969                                 loop_block = get_nodes_block(pred);
1970                                 loop_info.be_src_pos = i;
1971                         }
1972                 }
1973         }
1974
1975         DB((dbg, LEVEL_4, "loop has 1 own backedge.\n"));
1976
1977         exit_block = get_nodes_block(loop_info.cf_out.pred);
1978         /* The loop has to be tail-controlled.
1979          * This can be changed/improved,
1980          * but we would need a duff iv. */
1981         if (exit_block != loop_block)
1982                 return NULL;
1983
1984         DB((dbg, LEVEL_4, "tail-controlled loop.\n"));
1985
1986         /* find value on which loop exit depends */
1987         projx = loop_info.cf_out.pred;
1988         cond = get_irn_n(projx, 0);
1989         projres = get_irn_n(cond, 0);
1990         loop_condition = get_irn_n(projres, 0);
1991
1992         if (!is_Cmp(loop_condition))
1993                 return NULL;
1994
1995         DB((dbg, LEVEL_5, "projection is %s\n", get_pnc_string(get_Proj_proj(projx))));
1996
1997         switch(get_Proj_proj(projx)) {
1998                 case pn_Cond_false:
1999                         loop_info.exit_cond = 0;
2000                         break;
2001                 case pn_Cond_true:
2002                         loop_info.exit_cond = 1;
2003                         break;
2004                 default:
2005                         panic("Cond Proj_proj other than true/false");
2006         }
2007
2008         DB((dbg, LEVEL_4, "Valid Cmp.\n"));
2009
2010         return projres;
2011 }
2012
2013 /* Returns 1 if all nodes are mode_Iu or mode_Is. */
2014 static unsigned are_mode_I(ir_node *n1, ir_node* n2, ir_node *n3)
2015 {
2016         ir_mode *m1 = get_irn_mode(n1);
2017         ir_mode *m2 = get_irn_mode(n2);
2018         ir_mode *m3 = get_irn_mode(n3);
2019
2020         if ((m1 == mode_Iu && m2 == mode_Iu && m3 == mode_Iu) ||
2021             (m1 == mode_Is && m2 == mode_Is && m3 == mode_Is))
2022                 return 1;
2023         else
2024                 return 0;
2025 }
2026
2027 /* Checks if cur_loop is a simple tail-controlled counting loop
2028  * with start and end value loop invariant, step constant. */
2029 static unsigned get_unroll_decision_invariant(void)
2030 {
2031
2032         ir_node         *projres, *loop_condition, *iteration_path;
2033         unsigned        success, is_latest_val;
2034         tarval          *start_tar, *step_tar;
2035         ir_mode         *mode;
2036
2037         /* RETURN if loop is not 'simple' */
2038         projres = is_simple_loop();
2039         if (projres == NULL)
2040                 return 0;
2041
2042         loop_condition = get_irn_n(projres, 0);
2043
2044         success = get_invariant_pred(loop_condition, &loop_info.end_val, &iteration_path);
2045         if (! success)
2046                 return 0;
2047
2048         DB((dbg, LEVEL_4, "Invariant End_val %N, other %N\n", loop_info.end_val, iteration_path));
2049
2050         /* We may find the add or the phi first.
2051          * Until now we only have end_val. */
2052         if (is_Add(iteration_path) || is_Sub(iteration_path)) {
2053
2054                 /* We test against the latest value of the iv. */
2055                 is_latest_val = 1;
2056
2057                 loop_info.add = iteration_path;
2058                 DB((dbg, LEVEL_4, "Got add %N (maybe not sane)\n", loop_info.add));
2059
2060                 /* Preds of the add should be step and the iteration_phi */
2061                 success = get_const_pred(loop_info.add, &loop_info.step, &loop_info.iteration_phi);
2062                 if (! success)
2063                         return 0;
2064
2065                 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2066
2067                 if (! is_Phi(loop_info.iteration_phi))
2068                         return 0;
2069
2070                 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2071
2072                 /* Find start_val.
2073                  * Does necessary sanity check of add, if it is already set.  */
2074                 success = get_start_and_add(loop_info.iteration_phi, invariant);
2075                 if (! success)
2076                         return 0;
2077
2078                 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2079
2080         } else if (is_Phi(iteration_path)) {
2081                 ir_node *new_iteration_phi;
2082
2083                 /* We compare with the value the iv had entering this run. */
2084                 is_latest_val = 0;
2085
2086                 loop_info.iteration_phi = iteration_path;
2087                 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2088
2089                 /* Find start_val and add-node.
2090                  * Does necessary sanity check of add, if it is already set.  */
2091                 success = get_start_and_add(loop_info.iteration_phi, invariant);
2092                 if (! success)
2093                         return 0;
2094
2095                 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2096                 DB((dbg, LEVEL_4, "Got add or sub %N\n", loop_info.add));
2097
2098                 success = get_const_pred(loop_info.add, &loop_info.step, &new_iteration_phi);
2099                 if (! success)
2100                         return 0;
2101
2102                 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2103
2104                 if (loop_info.iteration_phi != new_iteration_phi)
2105                         return 0;
2106
2107         } else {
2108                 return 0;
2109         }
2110
2111         mode = get_irn_mode(loop_info.end_val);
2112
2113         DB((dbg, LEVEL_4, "start %N, end %N, step %N\n",
2114                                 loop_info.start_val, loop_info.end_val, loop_info.step));
2115
2116         if (mode != mode_Is && mode != mode_Iu)
2117                 return 0;
2118
2119         /* TODO necessary? */
2120         if (!are_mode_I(loop_info.start_val, loop_info.step, loop_info.end_val))
2121                 return 0;
2122
2123         DB((dbg, LEVEL_4, "mode integer\n"));
2124
2125         step_tar = get_Const_tarval(loop_info.step);
2126         start_tar = get_Const_tarval(loop_info.start_val);
2127
2128         if (tarval_is_null(step_tar)) {
2129                 /* TODO Might be worth a warning. */
2130                 return 0;
2131         }
2132
2133         DB((dbg, LEVEL_4, "step is not 0\n"));
2134
2135         create_duffs_block();
2136
2137         return loop_info.max_unroll;
2138 }
2139
2140 /* Returns unroll factor,
2141  * given maximum unroll factor and number of loop passes. */
2142 static unsigned get_preferred_factor_constant(tarval *count_tar)
2143 {
2144         tarval *tar_6, *tar_5, *tar_4, *tar_3, *tar_2;
2145         unsigned prefer;
2146         ir_mode *mode = get_irn_mode(loop_info.end_val);
2147
2148         tar_6 = new_tarval_from_long(6, mode);
2149         tar_5 = new_tarval_from_long(5, mode);
2150         tar_4 = new_tarval_from_long(4, mode);
2151         tar_3 = new_tarval_from_long(3, mode);
2152         tar_2 = new_tarval_from_long(2, mode);
2153
2154         /* loop passes % {6, 5, 4, 3, 2} == 0  */
2155         if (tarval_is_null(tarval_mod(count_tar, tar_6)))
2156                 prefer = 6;
2157         else if (tarval_is_null(tarval_mod(count_tar, tar_5)))
2158                 prefer = 5;
2159         else if (tarval_is_null(tarval_mod(count_tar, tar_4)))
2160                 prefer = 4;
2161         else if (tarval_is_null(tarval_mod(count_tar, tar_3)))
2162                 prefer = 3;
2163         else if (tarval_is_null(tarval_mod(count_tar, tar_2)))
2164                 prefer = 2;
2165         else {
2166                 /* gcd(max_unroll, count_tar) */
2167                 int a = loop_info.max_unroll;
2168                 int b = (int)get_tarval_long(count_tar);
2169                 int c;
2170
2171                 DB((dbg, LEVEL_4, "gcd of max_unroll %d and count_tar %d: ", a, b));
2172
2173                 do {
2174                 c = a % b;
2175                 a = b; b = c;
2176                 } while( c != 0);
2177
2178                 DB((dbg, LEVEL_4, "%d\n", a));
2179                 return a;
2180         }
2181
2182         DB((dbg, LEVEL_4, "preferred unroll factor %d\n", prefer));
2183
2184         /*
2185          * If our preference is greater than the allowed unroll factor
2186          * we either might reduce the preferred factor and prevent a duffs device block,
2187          * or create a duffs device block, from which in this case (constants only)
2188          * we know the startloop at compiletime.
2189          * The latter yields the following graphs.
2190          * but for code generation we would want to use graph A.
2191          * The graphs are equivalent. So, we can only reduce the preferred factor.
2192          * A)                   B)
2193          *     PreHead             PreHead
2194          *        |      ,--.         |   ,--.
2195          *         \ Loop1   \        Loop2   \
2196          *          \  |     |       /  |     |
2197          *           Loop2   /      / Loop1   /
2198          *           |   `--'      |      `--'
2199          */
2200
2201         if (prefer <= loop_info.max_unroll)
2202                 return prefer;
2203         else {
2204                 switch(prefer) {
2205                         case 6:
2206                                 if (loop_info.max_unroll >= 3)
2207                                         return 3;
2208                                 else if (loop_info.max_unroll >= 2)
2209                                         return 2;
2210                                 else
2211                                         return 0;
2212
2213                         case 4:
2214                                 if (loop_info.max_unroll >= 2)
2215                                         return 2;
2216                                 else
2217                                         return 0;
2218
2219                         default:
2220                                 return 0;
2221                 }
2222         }
2223 }
2224
2225 /* Check if cur_loop is a simple counting loop.
2226  * Start, step and end are constants. */
2227 /* TODO split. */
2228 static unsigned get_unroll_decision_constant(void)
2229 {
2230         ir_node         *projres, *loop_condition, *iteration_path;
2231         unsigned        success, is_latest_val;
2232         tarval          *start_tar, *end_tar, *step_tar, *diff_tar, *count_tar, *stepped;
2233         pn_Cmp          proj_proj, norm_proj;
2234         ir_mode         *mode;
2235
2236         /* RETURN if loop is not 'simple' */
2237         projres = is_simple_loop();
2238         if (projres == NULL)
2239                 return 0;
2240
2241         /* One in of the loop condition needs to be loop invariant. => end_val
2242          * The other in is assigned by an add. => add
2243          * The add uses a loop invariant value => step
2244          * and a phi with a loop invariant start_val and the add node as ins.
2245
2246            ^   ^
2247            |   | .-,
2248            |   Phi |
2249                 \  |   |
2250           ^  Add   |
2251            \  | \__|
2252             cond
2253              /\
2254         */
2255
2256         loop_condition = get_irn_n(projres, 0);
2257
2258         success = get_const_pred(loop_condition, &loop_info.end_val, &iteration_path);
2259         if (! success)
2260                 return 0;
2261
2262         DB((dbg, LEVEL_4, "End_val %N, other %N\n", loop_info.end_val, iteration_path));
2263
2264         /* We may find the add or the phi first.
2265          * Until now we only have end_val. */
2266         if (is_Add(iteration_path) || is_Sub(iteration_path)) {
2267
2268                 /* We test against the latest value of the iv. */
2269                 is_latest_val = 1;
2270
2271                 loop_info.add = iteration_path;
2272                 DB((dbg, LEVEL_4, "Got add %N (maybe not sane)\n", loop_info.add));
2273
2274                 /* Preds of the add should be step and the iteration_phi */
2275                 success = get_const_pred(loop_info.add, &loop_info.step, &loop_info.iteration_phi);
2276                 if (! success)
2277                         return 0;
2278
2279                 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2280
2281                 if (! is_Phi(loop_info.iteration_phi))
2282                         return 0;
2283
2284                 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2285
2286                 /* Find start_val.
2287                  * Does necessary sanity check of add, if it is already set.  */
2288                 success = get_start_and_add(loop_info.iteration_phi, constant);
2289                 if (! success)
2290                         return 0;
2291
2292                 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2293
2294         } else if (is_Phi(iteration_path)) {
2295                 ir_node *new_iteration_phi;
2296
2297                 /* We compare with the value the iv had entering this run. */
2298                 is_latest_val = 0;
2299
2300                 loop_info.iteration_phi = iteration_path;
2301                 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2302
2303                 /* Find start_val and add-node.
2304                  * Does necessary sanity check of add, if it is already set.  */
2305                 success = get_start_and_add(loop_info.iteration_phi, constant);
2306                 if (! success)
2307                         return 0;
2308
2309                 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2310                 DB((dbg, LEVEL_4, "Got add or sub %N\n", loop_info.add));
2311
2312                 success = get_const_pred(loop_info.add, &loop_info.step, &new_iteration_phi);
2313                 if (! success)
2314                         return 0;
2315
2316                 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2317
2318                 if (loop_info.iteration_phi != new_iteration_phi)
2319                         return 0;
2320
2321         } else {
2322                 /* RETURN */
2323                 return 0;
2324         }
2325
2326         mode = get_irn_mode(loop_info.end_val);
2327
2328         DB((dbg, LEVEL_4, "start %N, end %N, step %N\n",
2329                                 loop_info.start_val, loop_info.end_val, loop_info.step));
2330
2331         if (mode != mode_Is && mode != mode_Iu)
2332                 return 0;
2333
2334         /* TODO necessary? */
2335         if (!are_mode_I(loop_info.start_val, loop_info.step, loop_info.end_val))
2336                 return 0;
2337
2338         DB((dbg, LEVEL_4, "mode integer\n"));
2339
2340         end_tar = get_Const_tarval(loop_info.end_val);
2341         start_tar = get_Const_tarval(loop_info.start_val);
2342         step_tar = get_Const_tarval(loop_info.step);
2343
2344         if (tarval_is_null(step_tar))
2345                 /* TODO Might be worth a warning. */
2346                 return 0;
2347
2348         DB((dbg, LEVEL_4, "step is not 0\n"));
2349
2350         if ((!tarval_is_negative(step_tar)) ^ (!is_Sub(loop_info.add)))
2351                 loop_info.decreasing = 1;
2352
2353         diff_tar = tarval_sub(end_tar, start_tar, mode);
2354
2355         /* We need at least count_tar steps to be close to end_val, maybe more.
2356          * No way, that we have gone too many steps.
2357          * This represents the 'latest value'.
2358          * (If condition checks against latest value, is checked later) */
2359         count_tar = tarval_div(diff_tar, step_tar);
2360
2361         /* Iv will not pass end_val (except overflows).
2362          * Nothing done, as it would yield to no advantage. */
2363         if (tarval_is_negative(count_tar)) {
2364                 DB((dbg, LEVEL_1, "Loop is endless or never taken."));
2365                 /* TODO Might be worth a warning. */
2366                 return 0;
2367         }
2368
2369         count_stats(stats.u_simple_counting_loop);
2370
2371         loop_info.latest_value = is_latest_val;
2372
2373         /* TODO split here
2374         if (! is_simple_counting_loop(&count_tar))
2375                 return 0;
2376         */
2377
2378         /* stepped can be negative, if step < 0 */
2379         stepped = tarval_mul(count_tar, step_tar);
2380
2381         /* step as close to end_val as possible, */
2382         /* |stepped| <= |end_tar|, and dist(stepped, end_tar) is smaller than a step. */
2383         if (is_Sub(loop_info.add))
2384                 stepped = tarval_sub(start_tar, stepped, mode_Is);
2385         else
2386                 stepped = tarval_add(start_tar, stepped);
2387
2388         DB((dbg, LEVEL_4, "stepped to %ld\n", get_tarval_long(stepped)));
2389
2390         proj_proj = get_Proj_proj(projres);
2391         /* Assure that norm_proj is the stay-in-loop case. */
2392         if (loop_info.exit_cond == 1)
2393                 norm_proj = get_math_inverted_case(proj_proj);
2394         else
2395                 norm_proj = proj_proj;
2396
2397         DB((dbg, LEVEL_4, "normalized projection %s\n", get_pnc_string(norm_proj)));
2398
2399         /* Executed at most once (stay in counting loop if a Eq b) */
2400         if (norm_proj == pn_Cmp_Eq)
2401                 /* TODO Might be worth a warning. */
2402                 return 0;
2403
2404         /* calculates next values and increases count_tar according to it */
2405         success = simulate_next(&count_tar, stepped, step_tar, end_tar, norm_proj);
2406         if (! success)
2407                 return 0;
2408
2409         /* We run loop once more, if we compare to the
2410          * not yet in-/decreased iv. */
2411         if (is_latest_val == 0) {
2412                 DB((dbg, LEVEL_4, "condition uses not latest iv value\n"));
2413                 count_tar = tarval_add(count_tar, get_tarval_one(mode));
2414         }
2415
2416         DB((dbg, LEVEL_4, "loop taken %ld times\n", get_tarval_long(count_tar)));
2417
2418         /* Assure the loop is taken at least 1 time. */
2419         if (tarval_is_null(count_tar)) {
2420                 /* TODO Might be worth a warning. */
2421                 return 0;
2422         }
2423
2424         loop_info.count_tar = count_tar;
2425         return get_preferred_factor_constant(count_tar);
2426 }
2427
2428 /**
2429  * Loop unrolling
2430  */
2431 static void unroll_loop(void)
2432 {
2433         unroll_nr = 0;
2434
2435         /* get_unroll_decision_constant and invariant are completely
2436          * independent for flexibility.
2437          * Some checks may be performed twice. */
2438
2439         /* constant case? */
2440         if (opt_params.allow_const_unrolling)
2441                 unroll_nr = get_unroll_decision_constant();
2442         if (unroll_nr > 1) {
2443                 loop_info.unroll_kind = constant;
2444
2445         } else {
2446                 /* invariant case? */
2447                 if (opt_params.allow_invar_unrolling)
2448                         unroll_nr = get_unroll_decision_invariant();
2449                 if (unroll_nr > 1)
2450                         loop_info.unroll_kind = invariant;
2451         }
2452
2453         DB((dbg, LEVEL_1, " *** Unrolling %d times ***\n", unroll_nr));
2454
2455         if (unroll_nr > 1) {
2456                 loop_entries = NEW_ARR_F(entry_edge, 0);
2457
2458                 /* Get loop outs */
2459                 irg_walk_graph(current_ir_graph, get_loop_entries, NULL, NULL);
2460
2461                 if ((int)get_tarval_long(loop_info.count_tar) == unroll_nr)
2462                         loop_info.needs_backedge = 0;
2463                 else
2464                         loop_info.needs_backedge = 1;
2465
2466                 /* Use phase to keep copy of nodes from the condition chain. */
2467                 phase = new_phase(current_ir_graph, phase_irn_init_default);
2468
2469                 /* Copies the loop */
2470                 copy_loop(loop_entries, unroll_nr - 1);
2471
2472                 /* Line up the floating copies. */
2473                 place_copies(unroll_nr - 1);
2474
2475                 /* Remove phis with 1 in*/
2476                 irg_walk_graph(current_ir_graph, correct_phis, NULL, NULL);
2477
2478                 /* dump_ir_block_graph(current_ir_graph, "-DONE"); */
2479
2480                 if (loop_info.unroll_kind == constant)
2481                         count_stats(stats.constant_unroll);
2482                 else
2483                         count_stats(stats.invariant_unroll);
2484
2485                 set_irg_doms_inconsistent(current_ir_graph);
2486                 set_irg_loopinfo_inconsistent(current_ir_graph);
2487                 /* TODO is it? */
2488                 set_irg_outs_inconsistent(current_ir_graph);
2489
2490                 DEL_ARR_F(loop_entries);
2491         }
2492
2493 }
2494
2495 /* Analyzes the loop, and checks if size is within allowed range.
2496  * Decides if loop will be processed. */
2497 static void init_analyze(ir_loop *loop)
2498 {
2499         /* Expect no benefit of big loops. */
2500         /* TODO tuning/make parameter */
2501         int      loop_depth;
2502         unsigned max_loop_nodes = opt_params.max_loop_size;
2503         unsigned max_loop_nodes_adapted;
2504         int      max_calls = opt_params.allowed_calls;
2505         int      depth_adaption = opt_params.depth_adaption;
2506
2507         cur_loop = loop;
2508
2509         loop_head = NULL;
2510         loop_head_valid = 1;
2511
2512         /* Reset loop info */
2513         memset(&loop_info, 0, sizeof(loop_info_t));
2514
2515         DB((dbg, LEVEL_1, "    >>>> current loop includes node %N <<<\n",
2516                 get_loop_node(loop, 0)));
2517
2518         /* Collect loop informations: head, node counts. */
2519         irg_walk_graph(current_ir_graph, get_loop_info, NULL, NULL);
2520
2521         /* Depth of 0 is the procedure and 1 a topmost loop. */
2522         loop_depth = get_loop_depth(loop) - 1;
2523
2524         /* Calculating in per mil. */
2525         max_loop_nodes_adapted = get_max_nodes_adapted(loop_depth);
2526
2527         DB((dbg, LEVEL_1, "max_nodes: %d\nmax_nodes_adapted %d at depth of %d (adaption %d)\n",
2528                         max_loop_nodes, max_loop_nodes_adapted, loop_depth, depth_adaption));
2529
2530         if (! (loop_info.nodes > 0))
2531                 return;
2532
2533 #if LOOP_IGNORE_NODE_LIMITS
2534         DB((dbg, LEVEL_1, "WARNING: Loop node limitations ignored."));
2535 #else
2536         if (loop_info.nodes > max_loop_nodes) {
2537                 /* Only for stats */
2538                 DB((dbg, LEVEL_1, "Nodes %d > allowed nodes %d\n",
2539                         loop_info.nodes, loop_depth, max_loop_nodes));
2540                 count_stats(stats.too_large);
2541                 /* no RETURN */
2542                 /* Adaption might change it */
2543         }
2544
2545         /* Limit processing to loops smaller than given parameter. */
2546         if (loop_info.nodes > max_loop_nodes_adapted) {
2547                 DB((dbg, LEVEL_1, "Nodes %d > allowed nodes (depth %d adapted) %d\n",
2548                         loop_info.nodes, loop_depth, max_loop_nodes_adapted));
2549                 count_stats(stats.too_large_adapted);
2550                 return;
2551         }
2552
2553         if (loop_info.calls > opt_params.allowed_calls) {
2554                 DB((dbg, LEVEL_1, "Calls %d > allowed calls %d\n",
2555                         loop_info.calls, max_calls));
2556                 count_stats(stats.calls_limit);
2557                 return;
2558         }
2559 #endif
2560
2561         /* RETURN if there is no valid head */
2562         if (!loop_head || !loop_head_valid) {
2563                 DB((dbg, LEVEL_1,   "No valid loop head. Nothing done.\n"));
2564                 return;
2565         } else {
2566                 DB((dbg, LEVEL_1,   "Loophead: %N\n", loop_head));
2567         }
2568
2569         switch (loop_op) {
2570                 case loop_op_inversion:
2571                         loop_inversion();
2572                         break;
2573
2574                 case loop_op_unrolling:
2575                         unroll_loop();
2576                         break;
2577
2578                 default:
2579                         panic("Loop optimization not implemented.");
2580         }
2581         DB((dbg, LEVEL_1, "       <<<< end of loop with node %N >>>>\n",
2582                 get_loop_node(loop, 0)));
2583 }
2584
2585 /* Find innermost loops and add them to loops. */
2586 static void find_innermost_loop(ir_loop *loop)
2587 {
2588         /* descend into sons */
2589         int sons = get_loop_n_sons(loop);
2590
2591         if (sons == 0) {
2592                 ARR_APP1(ir_loop *, loops, loop);
2593         } else {
2594                 int s;
2595                 for (s=0; s<sons; s++) {
2596                         find_innermost_loop(get_loop_son(loop, s));
2597                 }
2598         }
2599 }
2600
2601 /* Assure preconditions are met and go through all loops. */
2602 void loop_optimization(ir_graph *irg)
2603 {
2604         ir_loop *loop;
2605         int     i, sons, nr;
2606
2607         /* SPEC2000: Total time 98.9% with inversion only */
2608         opt_params.max_loop_size = 100;
2609         opt_params.depth_adaption = 400;
2610         opt_params.count_phi = 0;
2611         opt_params.count_proj = 0;
2612         opt_params.allowed_calls = 0;
2613
2614         opt_params.max_cc_size = 100;
2615
2616         /* Unrolling not yet tested */
2617         opt_params.allow_const_unrolling = 1;
2618         opt_params.allow_invar_unrolling = 1;
2619
2620         /* Reset stats for this procedure */
2621         reset_stats();
2622
2623         /* Preconditions */
2624         set_current_ir_graph(irg);
2625
2626         edges_assure(irg);
2627         assure_irg_outs(irg);
2628
2629         /* NOTE: sets only the loop attribute of blocks, not nodes */
2630         /* NOTE: Kills links */
2631         assure_cf_loop(irg);
2632
2633         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
2634         collect_phiprojs(irg);
2635         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2636
2637         loop = get_irg_loop(irg);
2638         sons = get_loop_n_sons(loop);
2639
2640         loops = NEW_ARR_F(ir_loop *, 0);
2641         /* List all inner loops */
2642         for (nr = 0; nr < sons; ++nr) {
2643                 find_innermost_loop(get_loop_son(loop, nr));
2644         }
2645
2646         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2647         /* Set all links to NULL */
2648         irg_walk_graph(current_ir_graph, reset_link, NULL, NULL);
2649
2650         for (i = 0; i < ARR_LEN(loops); ++i) {
2651                 ir_loop *loop = loops[i];
2652
2653                 count_stats(stats.loops);
2654
2655                 /* Analyze and handle loop */
2656                 init_analyze(loop);
2657
2658                 /* Copied blocks do not have their phi list yet */
2659                 collect_phiprojs(irg);
2660
2661                 /* Set links to NULL
2662                  * TODO Still necessary? */
2663                 irg_walk_graph(current_ir_graph, reset_link, NULL, NULL);
2664         }
2665
2666         print_stats();
2667
2668         DEL_ARR_F(loops);
2669         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2670         ir_free_resources(irg, IR_RESOURCE_PHI_LIST);
2671 }
2672
2673 void do_loop_unrolling(ir_graph *irg)
2674 {
2675         loop_op = loop_op_unrolling;
2676
2677         DB((dbg, LEVEL_1, " >>> unrolling (Startnode %N) <<<\n",
2678                                 get_irg_start(irg)));
2679
2680         loop_optimization(irg);
2681
2682         DB((dbg, LEVEL_1, " >>> unrolling done (Startnode %N) <<<\n",
2683                                 get_irg_start(irg)));
2684 }
2685
2686 void do_loop_inversion(ir_graph *irg)
2687 {
2688         loop_op = loop_op_inversion;
2689
2690         DB((dbg, LEVEL_1, " >>> inversion (Startnode %N) <<<\n",
2691                                 get_irg_start(irg)));
2692
2693         loop_optimization(irg);
2694
2695         DB((dbg, LEVEL_1, " >>> inversion done (Startnode %N) <<<\n",
2696                                 get_irg_start(irg)));
2697 }
2698
2699 void do_loop_peeling(ir_graph *irg)
2700 {
2701         loop_op = loop_op_peeling;
2702
2703         DB((dbg, LEVEL_1, " >>> peeling (Startnode %N) <<<\n",
2704                                 get_irg_start(irg)));
2705
2706         loop_optimization(irg);
2707
2708         DB((dbg, LEVEL_1, " >>> peeling done (Startnode %N) <<<\n",
2709                                 get_irg_start(irg)));
2710
2711 }
2712
2713 ir_graph_pass_t *loop_inversion_pass(const char *name)
2714 {
2715         return def_graph_pass(name ? name : "loop_inversion", do_loop_inversion);
2716 }
2717
2718 ir_graph_pass_t *loop_unroll_pass(const char *name)
2719 {
2720         return def_graph_pass(name ? name : "loop_unroll", do_loop_unrolling);
2721 }
2722
2723 ir_graph_pass_t *loop_peeling_pass(const char *name)
2724 {
2725         return def_graph_pass(name ? name : "loop_peeling", do_loop_peeling);
2726 }
2727
2728 void firm_init_loop_opt(void)
2729 {
2730         FIRM_DBG_REGISTER(dbg, "firm.opt.loop");
2731 }