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