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