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