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