2 * Copyright (C) 1995-2010 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
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.
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.
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
22 * @author Christian Helmer
23 * @brief loop inversion and loop unrolling
30 #include "iroptimize.h"
48 #include "irbackedge_t.h"
49 #include "irphase_t.h"
53 DEBUG_ONLY(static firm_dbg_module_t *dbg);
55 /* DBG print stats for every procedure. */
56 #define LOOP_OPT_STATS 0
58 /* DBG: Ignore node limits and process every possible loop. */
59 #define LOOP_IGNORE_NODE_LIMITS 0
62 * Convenience macro for iterating over every phi node of the given block.
63 * Requires phi list per block.
65 #define for_each_phi(block, phi) \
66 for ((phi) = get_Block_phis( (block) ); (phi) ; (phi) = get_Phi_next((phi)))
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)
72 /* Currently processed loop. */
73 static ir_loop *cur_loop;
75 /* Flag for kind of unrolling. */
79 } unrolling_kind_flag;
81 /* Condition for performing visiting a node during copy_walk. */
82 typedef unsigned walker_condition(ir_node *);
84 /* Node and position of a predecessor. */
85 typedef struct entry_edge {
91 /* Node info for unrolling. */
92 typedef struct unrolling_node_info {
95 } unrolling_node_info;
97 /* Outs of the nodes head. */
98 static entry_edge *cur_head_outs;
100 /* Information about the loop head */
101 static ir_node *loop_head = NULL;
102 static unsigned loop_head_valid = 1;
104 /* List of all inner loops, that are processed. */
105 static ir_loop **loops;
109 #define count_stats(val) (++val)
110 #define print_stats() (do_print_stats())
111 #define reset_stats() (do_reset_stats())
114 typedef struct loop_stats_t {
118 unsigned too_large_adapted;
119 unsigned cc_limit_reached;
120 unsigned calls_limit;
122 unsigned u_simple_counting_loop;
123 unsigned constant_unroll;
124 unsigned invariant_unroll;
129 static loop_stats_t stats;
131 /* Set stats to sero */
132 static void do_reset_stats(void)
134 memset(&stats, 0, sizeof(loop_stats_t));
138 static void do_print_stats(void)
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"));
154 #define count_stats(val) ((void)0)
155 #define print_stats() ((void)0)
156 #define reset_stats() ((void)0)
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 */
168 unsigned max_cc_size; /* Maximum condition chain size */
170 unsigned allow_const_unrolling:1;
171 unsigned allow_invar_unrolling:1;
175 static loop_opt_params_t opt_params;
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 */
187 unsigned cc_size; /* nodes in the condition chain */
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 */
196 /* IV informations of a simple loop */
200 ir_node *iteration_phi;
203 tarval *count_tar; /* Number of loop iterations */
205 ir_node *duff_cond; /* Duff mod */
206 unrolling_kind_flag unroll_kind; /* constant or invariant unrolling */
209 /* Information about the current loop */
210 static loop_info_t loop_info;
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;
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;
230 /* Loop operations. */
231 typedef enum loop_op_t {
237 /* Saves which loop operation to do until after basic tests. */
238 static loop_op_t loop_op;
240 /************************************************************************/
242 /* Returns the maximum nodes for the given nest depth */
243 static unsigned get_max_nodes_adapted(unsigned depth)
245 int adapt_permil = opt_params.depth_adaption * depth;
246 unsigned permil_change;
248 if (adapt_permil < -1000)
251 permil_change = 1000 + adapt_permil;
252 return (opt_params.max_loop_size * permil_change) / 1000;
255 /* Reset nodes link. For use with a walker. */
256 static void reset_link(ir_node *node, void *env)
259 set_irn_link(node, NULL);
262 /* Returns 0 if the node or block is not in cur_loop. */
263 static unsigned is_in_loop(ir_node *node)
265 return (get_irn_loop(get_block(node)) == cur_loop);
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)
272 return (is_backedge(n, pos) && is_in_loop(get_irn_n(n, pos)));
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)
278 unsigned node_in_loop, pred_in_loop;
282 arity = get_irn_arity(node);
283 for (i = 0; i < arity; i++) {
284 ir_node *pred = get_irn_n(node, i);
286 pred_in_loop = is_in_loop(pred);
287 node_in_loop = is_in_loop(node);
289 /* collect some loop information */
291 if (is_Phi(node) && opt_params.count_phi)
293 else if (is_Proj(node) && opt_params.count_proj)
295 else if (!is_Confirm(node) && !is_Const(node) && !is_SymConst(node))
298 if (is_Load(node) || is_Store(node))
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);
309 if (!is_in_loop(cfgpred)) {
310 DB((dbg, LEVEL_5, "potential head %+F because inloop and pred %+F not inloop\n",
312 /* another head? We do not touch this. */
313 if (loop_head && loop_head != node) {
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)
327 unsigned node_in_loop, pred_in_loop;
331 arity = get_irn_arity(node);
332 for (i = 0; i < arity; ++i) {
333 ir_node *pred = get_irn_n(node, i);
335 pred_in_loop = is_in_loop(pred);
336 node_in_loop = is_in_loop(node);
338 if (pred_in_loop && !node_in_loop) {
343 ARR_APP1(entry_edge, loop_entries, entry);
345 if (is_Block(node)) {
347 loop_info.cf_out = entry;
354 static ir_node *ssa_second_def;
355 static ir_node *ssa_second_def_block;
358 * Walks the graph bottom up, searching for definitions and creates phis.
360 static ir_node *search_def_and_create_phis(ir_node *block, ir_mode *mode, int first)
368 DB((dbg, LEVEL_5, "ssa search_def_and_create_phis: block %N\n", block));
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);
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;
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));
390 irg = get_irn_irg(block);
391 assert(block != get_irg_start_block(irg));
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);
399 DB((dbg, LEVEL_5, "ssa 1 pred: walk pred %N\n", pred_block));
401 value = search_def_and_create_phis(pred_block, mode, 0);
402 set_irn_link(block, value);
403 mark_irn_visited(block);
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);
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);
420 /* set Phi predecessors */
421 for (i = 0; i < n_cfgpreds; ++i) {
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);
427 assert(pred_val != NULL);
429 DB((dbg, LEVEL_5, "ssa phi pred:phi %N, pred %N\n", phi, pred_val));
430 set_irn_n(phi, i, pred_val);
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.
442 static void construct_ssa(ir_node *orig_block, ir_node *orig_val,
443 ir_node *second_block, ir_node *second_val)
447 const ir_edge_t *edge;
448 const ir_edge_t *next;
450 assert(orig_block && orig_val && second_block && second_val &&
451 "no parameter of construct_ssa may be NULL");
453 if (orig_val == second_val)
456 irg = get_irn_irg(orig_val);
458 ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
459 inc_irg_visited(irg);
461 mode = get_irn_mode(orig_val);
462 set_irn_link(orig_block, orig_val);
463 mark_irn_visited(orig_block);
465 ssa_second_def_block = second_block;
466 ssa_second_def = second_val;
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);
479 DB((dbg, LEVEL_5, "original user %N\n", user));
482 ir_node *pred_block = get_Block_cfgpred_block(user_block, j);
483 newval = search_def_and_create_phis(pred_block, mode, 1);
485 newval = search_def_and_create_phis(user_block, mode, 1);
487 if (newval != user && !is_Bad(newval))
488 set_irn_n(user, j, newval);
491 ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
495 /***** Unrolling Helper Functions *****/
497 /* Assign the copy with index nr to node n */
498 static void set_unroll_copy(ir_node *n, int nr, ir_node *cp)
500 unrolling_node_info *info;
501 assert(nr != 0 && "0 reserved");
503 info = (unrolling_node_info *)phase_get_irn_data(phase, n);
507 info = XMALLOCZ(unrolling_node_info);
508 arr = NEW_ARR_F(ir_node *, unroll_nr);
510 memset(info->copies, 0, (unroll_nr) * sizeof(ir_node *));
512 phase_set_irn_data(phase, n, info);
517 info->copies[nr] = cp;
520 /* Returns a nodes copy if it exists, else NULL. */
521 static ir_node *get_unroll_copy(ir_node *n, int nr)
524 unrolling_node_info *info = (unrolling_node_info *)phase_get_irn_data(phase, n);
528 cp = info->copies[nr];
533 /***** Inversion Helper Functions *****/
535 /* Sets copy cp of node n. */
536 static void set_inversion_copy(ir_node *n, ir_node *cp)
538 phase_set_irn_data(phase, n, cp);
541 /* Getter of copy of n for inversion */
542 static ir_node *get_inversion_copy(ir_node *n)
544 ir_node *cp = (ir_node *)phase_get_irn_data(phase, n);
548 /* Resets block mark for given node. For use with walker */
549 static void reset_block_mark(ir_node *node, void * env)
554 set_Block_mark(node, 0);
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)
562 return get_Block_mark(node);
564 return get_Block_mark(get_block(node));
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)
573 int arity = get_irn_arity(n);
574 int new_arity = arity + 1;
576 NEW_ARR_A(ir_node *, ins, new_arity);
578 for(i = 0; i < arity; ++i) {
579 ins[i] = get_irn_n(n, i);
583 set_irn_in(n, new_arity, ins);
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)
594 assert(is_Block(block));
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);
602 /* Extend block phis by copy of definition at pos */
603 for_each_phi(block, phi) {
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. */
615 DB((dbg, LEVEL_5, "Extend phi %N by %N cp of %N\n", phi, new_in, pred));
616 extend_irn(phi, new_in);
620 /* Returns the number of blocks backedges. With or without alien bes. */
621 static int get_backedge_n(ir_node *block, unsigned with_alien)
625 int arity = get_irn_arity(block);
627 assert(is_Block(block) && "We only required backedges of blocks.");
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)))
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)
644 cp = exact_copy(node);
645 arity = get_irn_arity(node);
647 /* Keep backedge info */
648 for (i = 0; i < arity; ++i) {
649 if (is_backedge(node, i))
654 set_Block_mark(cp, 0);
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.
667 static void copy_walk(ir_node *node, walker_condition *walk_condition,
674 ir_graph *irg = current_ir_graph;
677 * break condition and cycle resolver, creating temporary node copies
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);
686 DB((dbg, LEVEL_5, "The TEMP copy of %N is created %N\n", node, cp));
692 mark_irn_visited(node);
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);
701 arity = get_irn_arity(node);
703 NEW_ARR_A(ir_node *, cpin, arity);
705 for (i = 0; i < arity; ++i) {
706 ir_node *pred = get_irn_n(node, i);
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));
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));
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));
731 if (!is_Block(node)) {
732 ir_node *cpblock = get_inversion_copy(get_nodes_block(node));
734 set_nodes_block(cp, cpblock );
736 add_Block_phi(cpblock, cp);
739 /* Keeps phi list of temporary node. */
740 set_irn_in(cp, ARR_LEN(cpin), cpin);
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.
750 static void copy_walk_n(ir_node *node,
751 walker_condition *walk_condition, int copy_index)
759 * break condition and cycle resolver, creating temporary node copies
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) {
767 set_unroll_copy(node, copy_index, u);
768 DB((dbg, LEVEL_5, "The TEMP unknown of %N is created %N\n", node, u));
774 mark_irn_visited(node);
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);
783 arity = get_irn_arity(node);
784 NEW_ARR_A(ir_node *, cpin, arity);
786 for (i = 0; i < arity; ++i) {
787 ir_node *pred = get_irn_n(node, i);
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);
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));
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));
810 if (!is_Block(node)) {
811 ir_node *cpblock = get_unroll_copy(get_nodes_block(node), copy_index);
813 set_nodes_block(cp, cpblock );
815 add_Block_phi(cpblock, cp);
818 /* Keeps phi list of temporary node. */
819 set_irn_in(cp, ARR_LEN(cpin), cpin);
822 /* Removes alle Blocks with non marked predecessors from the condition chain. */
823 static void unmark_not_allowed_cc_blocks(void)
825 int blocks = ARR_LEN(cc_blocks);
828 for(i = 0; i < blocks; ++i) {
829 ir_node *block = cc_blocks[i];
831 int arity = get_irn_arity(block);
833 /* Head is an exception. */
834 if (block == loop_head)
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));
850 /* Unmarks all cc blocks using cc_blocks except head. */
851 static void unmark_cc_blocks(void)
853 int blocks = ARR_LEN(cc_blocks);
856 for(i = 0; i < blocks; ++i) {
857 ir_node *block = cc_blocks[i];
859 /* Head is an exception. */
860 if (block != loop_head)
861 set_Block_mark(block, 0);
863 inversion_blocks_in_cc = 1;
866 loop_info.cc_size = 0;
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.
875 static void get_head_outs(ir_node *node, void *env)
878 int arity = get_irn_arity(node);
881 for (i = 0; i < arity; ++i) {
882 if (!is_nodes_block_marked(node) && is_nodes_block_marked(get_irn_n(node, 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);
894 arity = get_irn_arity(loop_head);
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))) {
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)));
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.
920 static unsigned find_condition_chain(ir_node *block)
922 const ir_edge_t *edge;
926 unsigned nodes_n = 0;
928 mark_irn_visited(block);
930 DB((dbg, LEVEL_5, "condition_chains for block %N\n", block));
933 foreach_out_edge_kind(block, edge, EDGE_KIND_NORMAL) {
937 /* Check if node count would exceed maximum cc size.
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);
946 /* Check if block only has a jmp instruction. */
948 foreach_out_edge(block, edge) {
949 ir_node *src = get_edge_src_irn(edge);
951 if (! is_Block(src) && ! is_Jmp(src)) {
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);
962 if (! is_in_loop(src))
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)) {
976 /* We need all predecessors to already belong to the condition chain.
977 * Example of wrong case: * == in cc
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);
997 set_Block_mark(block, 0);
1000 foreach_block_succ(block, edge) {
1001 ir_node *src = get_edge_src_irn( edge );
1003 if (is_in_loop(src) && ! irn_visited(src))
1004 find_condition_chain(src);
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.)
1016 static void fix_copy_inversion(void)
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;
1030 NEW_ARR_A(ir_node *, ins, new_arity);
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);
1039 new_head = new_r_Block(irg, new_arity, ins);
1041 phis = NEW_ARR_F(ir_node *, 0);
1043 for_each_phi_safe(get_Block_phis(head_cp), phi, next) {
1045 NEW_ARR_A(ir_node *, ins, new_arity);
1047 for(i = 0; i < arity; ++i) {
1048 if (!is_backedge(head_cp, i))
1049 ins[pos++] = get_irn_n(phi, i);
1051 new_phi = new_rd_Phi(get_irn_dbg_info(phi),
1052 new_head, new_arity, ins,
1054 ARR_APP1(ir_node *, phis, new_phi);
1058 for_each_phi_safe(get_Block_phis(head_cp), phi, next) {
1059 exchange(phi, phis[pos++]);
1062 exchange(head_cp, new_head);
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.
1071 static void fix_head_inversion(void)
1075 ir_node *phi, *next;
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;
1084 NEW_ARR_A(ir_node *, ins, new_arity);
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);
1093 new_head = new_r_Block(irg, new_arity, ins);
1095 phis = NEW_ARR_F(ir_node *, 0);
1097 for_each_phi(loop_head, phi) {
1099 DB((dbg, LEVEL_5, "Fixing phi %N of loop head\n", phi));
1101 NEW_ARR_A(ir_node *, ins, new_arity);
1104 for (i = 0; i < arity; ++i) {
1105 ir_node *pred = get_irn_n(phi, i);
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);*/
1120 new_phi = new_rd_Phi(get_irn_dbg_info(phi),
1121 new_head, new_arity, ins,
1124 ARR_APP1(ir_node *, phis, new_phi);
1126 DB((dbg, LEVEL_5, "fix inverted head should exch %N by %N (arity %d)\n", phi, new_phi, pos ));
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++]);
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);
1142 /* Does the loop inversion. */
1143 static void inversion_walk(entry_edge *head_entries)
1148 * The order of rewiring bottom-up is crucial.
1149 * Any change of the order leads to lost information that would be needed later.
1152 ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1154 /* 1. clone condition chain */
1155 inc_irg_visited(current_ir_graph);
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);
1161 DB((dbg, LEVEL_5, "\nInit walk block %N\n", pred));
1163 copy_walk(pred, is_nodes_block_marked, cur_loop);
1166 ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
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];
1173 if (is_Block(head_out.node))
1174 extend_ins_by_copy(head_out.node, head_out.pos);
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];
1182 /* Ignore keepalives */
1183 if (is_End(head_out.node))
1186 /* Construct ssa for assignments in the condition chain. */
1187 if (!is_Block(head_out.node)) {
1188 ir_node *pred, *cppred, *block, *cpblock;
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);
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.
1207 * Phi_cp | | copied condition chain
1211 * Phi* | | new loop head with newly created phi.
1213 * Phi | | original, inverted condition chain
1218 for (i = 0; i < ARR_LEN(head_df_loop); ++i) {
1219 entry_edge head_out = head_df_loop[i];
1221 /* Construct ssa for assignments in the condition chain. */
1222 ir_node *pred, *cppred, *block, *cpblock;
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);
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();
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();
1241 /* Performs loop inversion of cur_loop if possible and reasonable. */
1242 static void loop_inversion(void)
1244 unsigned do_inversion = 1;
1245 unsigned has_cc = 0;
1247 /*inversion_head_node_limit = INT_MAX;*/
1248 ir_reserve_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
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);
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);
1258 /*head_inversion_node_count = 0;*/
1259 inversion_blocks_in_cc = 0;
1261 /* Use phase to keep copy of nodes from the condition chain. */
1262 phase = new_phase(current_ir_graph, phase_irn_init_default);
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);
1269 unmark_not_allowed_cc_blocks();
1270 DEL_ARR_F(cc_blocks);
1272 #if LOOP_IGNORE_NODE_LIMITS
1273 (void) unmark_cc_blocks;
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);
1282 /* Only head taken? */
1283 if (inversion_blocks_in_cc == 1)
1286 /* Unmark cc blocks except the head.
1287 * Invert head only for possible unrolling. */
1292 /* We also catch endless loops here,
1293 * because they do not have a condition chain. */
1294 if (inversion_blocks_in_cc < 1) {
1297 "Loop contains %d (less than 1) invertible blocks => No Inversion done.\n",
1298 inversion_blocks_in_cc));
1302 cur_head_outs = NEW_ARR_F(entry_edge, 0);
1304 /* Get all edges pointing into the condition chain. */
1305 irg_walk_graph(current_ir_graph, get_head_outs, NULL, NULL);
1307 /* Do the inversion */
1308 inversion_walk(cur_head_outs);
1310 DEL_ARR_F(cur_head_outs);
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);
1319 count_stats(stats.inverted);
1324 DEL_ARR_F(cond_chain_entries);
1325 DEL_ARR_F(head_df_loop);
1327 ir_free_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1330 /* Fix the original loop_heads ins for invariant unrolling case. */
1331 static void unrolling_fix_loop_head_inv(void)
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);
1339 /* Original loop_heads ins are:
1340 * duff block and the own backedge */
1342 ins[0] = loop_condition;
1345 set_irn_in(loop_head, 2, ins);
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);
1352 ins[1] = get_irn_link(phi);
1354 set_irn_in(phi, 2, ins);
1358 /* Removes previously created phis with only 1 in. */
1359 static void correct_phis(ir_node *node, void *env)
1362 if (is_Phi(node) && get_irn_arity(node) == 1) {
1366 in[0] = get_irn_n(node, 0);
1368 exch = new_rd_Phi(get_irn_dbg_info(node),
1369 get_nodes_block(node), 1, in,
1370 get_irn_mode(node));
1372 exchange(node, exch);
1376 /* Unrolling: Rewire floating copies. */
1377 static void place_copies(int copies)
1379 ir_node *loophead = loop_head;
1381 int be_src_pos = loop_info.be_src_pos;
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);
1390 ir_node *topmost_be_block = get_nodes_block(get_irn_n(loophead, be_src_pos));
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));
1397 DB((dbg, LEVEL_5, "topmost be block %N \n", topmost_be_block));
1399 if (loop_info.unroll_kind == constant) {
1402 set_irn_in(lower, 1, ins);
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);
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))
1414 ins[0] = topmost_def;
1416 set_irn_in(lower_phi, 1, ins);
1417 /* Need to replace phis with 1 in later. */
1420 /* Invariant case */
1421 /* Every node has 2 ins. One from the duff blocks
1422 * and one from the previous unrolled loop. */
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);
1429 set_irn_in(lower, 1, ins);
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;
1437 lower_phi = get_unroll_copy(phi, c + 1);
1438 duff_phi = get_irn_link(lower_phi);
1440 if (is_in_loop(topmost_phi_pred)) {
1441 upper_phi_pred = get_unroll_copy(topmost_phi_pred, c);
1443 upper_phi_pred = topmost_phi_pred;
1446 ins[0] = upper_phi_pred;
1449 set_irn_in(lower_phi, 2, ins);
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);
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) {
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);
1469 set_irn_n(loop_head, loop_info.be_src_pos, loop_condition);
1471 for_each_phi(loop_head, phi) {
1472 ir_node *pred = get_irn_n(phi, be_src_pos);
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);
1481 set_irn_n(phi, be_src_pos, last_pred);
1484 unrolling_fix_loop_head_inv();
1488 /* Copies the cur_loop several times. */
1489 static void copy_loop(entry_edge *cur_loop_outs, int copies)
1493 ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1495 for (c = 0; c < copies; ++c) {
1497 inc_irg_visited(current_ir_graph);
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);
1504 copy_walk_n(pred, is_in_loop, c + 1);
1508 ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
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)
1517 int arity = get_irn_arity(node);
1520 assert(get_irn_arity(node) == get_irn_arity(be_block));
1521 assert(is_Phi(node));
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);
1530 ir_node *pred = get_inr_n(node, i);
1531 if (! is_in_loop(pred)) {
1539 return new_r_Phi(get_nodes_block(node), c, ins, get_irn_mode(node));
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)
1547 ir_graph *irg = get_irn_irg(node);
1548 int arity = get_irn_arity(node);
1551 assert(get_irn_arity(node) == get_irn_arity(be_block));
1552 assert(is_Block(node));
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);
1562 return new_r_Block(irg, c, ins);
1565 /* Creates blocks for duffs device, using previously obtained
1566 * informations about the iv.
1568 static void create_duffs_block(void)
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;
1579 ir_node *duff_mod, *proj, *cond;
1581 ir_node *count, *correction, *unroll_c;
1582 ir_node *cmp_bad_count, *good_count, *bad_count, *count_phi, *bad_count_neg;
1584 mode = get_irn_mode(loop_info.end_val);
1585 const_null = new_r_Const(irg, get_mode_null(mode));
1588 * 1. Calculate first approach to count.
1589 * Condition: (end - start) % step == 0 */
1590 block1 = clone_block_sans_bes(loop_head, loop_head);
1592 /* Create loop entry phis in first duff block
1593 * as it becomes the loops preheader */
1594 if (loop_info.unroll_kind == invariant) {
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);
1602 ems = new_r_Sub(block1, loop_info.end_val, loop_info.start_val,
1603 get_irn_mode(loop_info.end_val));
1605 ems_divmod = new_r_DivMod(block1,
1610 op_pin_state_pinned);
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);
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);
1624 * Assures, duffs device receives a valid count.
1626 * decreasing: count < 0
1627 * increasing: count > 0
1632 count_block = new_r_Block(irg, 2, ins);
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));
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);
1652 correction = new_r_Phi(count_block, 2, ins, mode);
1654 count = new_r_Proj(ems_divmod, mode, pn_DivMod_res_div);
1656 /* (end - start) / step + correction */
1657 count = new_r_Add(count_block, count, correction, mode);
1659 cmp_bad_count = new_r_Cmp(count_block, count, const_null);
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; */
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);
1671 bad_count_neg = new_r_Proj(cmp_bad_count, mode_X, pn_Cmp_Gt);
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);
1679 * Contains module to decide which loop to start from. */
1681 ins[0] = good_count;
1683 duff_block = new_r_Block(irg, 2, ins);
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... */
1690 /* count wants to be positive */
1691 ins[0] = get_Abs_op(count);
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);
1697 unroll_c = new_r_Const(irg, new_tarval_from_long((long)unroll_nr, mode));
1699 /* count % unroll_nr */
1700 duff_mod = new_r_Mod(duff_block,
1705 op_pin_state_pinned);
1707 proj = new_r_Proj(duff_mod, mode_X, pn_Mod_res);
1708 cond = new_r_Cond(duff_block, proj);
1710 loop_info.duff_cond = cond;
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.
1716 static unsigned is_loop_invariant_def(ir_node *node)
1720 if (! is_in_loop(node))
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. */
1727 block = get_nodes_block(node);
1729 /* To prevent unexpected situations. */
1730 if (block != loop_head)
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)
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)
1746 ir_node *pred0 = get_irn_n(node, 0);
1747 ir_node *pred1 = get_irn_n(node, 1);
1752 if (is_loop_invariant_def(pred0)) {
1753 *invar_pred = pred0;
1757 if (is_loop_invariant_def(pred1)) {
1758 if (invar_pred != NULL)
1759 /* RETURN. We do not want both preds to be invariant. */
1763 *invar_pred = pred1;
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)
1777 ir_node *found_add = loop_info.add;
1778 int arity = get_irn_arity(iteration_phi);
1780 DB((dbg, LEVEL_4, "Find start and add from %N\n", iteration_phi));
1782 for (i = 0; i < arity; ++i) {
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);
1789 DB((dbg, LEVEL_4, "found_start_val %N\n", found_start_val));
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)
1795 if ((role == constant) && !(is_SymConst(found_start_val) || is_Const(found_start_val)))
1797 else if((role == constant) && !(is_loop_invariant_def(found_start_val)))
1800 loop_info.start_val = found_start_val;
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);
1809 DB((dbg, LEVEL_4, "is add? %N\n", new_found));
1811 if (! (is_Add(new_found) || is_Sub(new_found)) || (found_add && found_add != new_found))
1814 found_add = new_found;
1818 loop_info.add = found_add;
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)
1828 ir_node *pred0 = get_irn_n(node, 0);
1829 ir_node *pred1 = get_irn_n(node, 1);
1831 DB((dbg, LEVEL_4, "Checking for constant pred of %N\n", node));
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;
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. */
1851 DB((dbg, LEVEL_4, "%N is constant\n", pred1));
1853 *const_pred = pred1;
1856 if (*const_pred == NULL)
1862 /* Returns the mathematically inverted pn_Cmp. */
1863 static pn_Cmp get_math_inverted_case(pn_Cmp proj)
1879 panic("Unhandled pn_Cmp.");
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)
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));
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))
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)));
1906 if (is_Add(loop_info.add))
1907 next = tarval_add(stepped, step_tar);
1910 next = tarval_sub(stepped, step_tar, get_irn_mode(loop_info.end_val));
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));
1918 /* Increase steps. */
1919 *count_tar = tarval_add(*count_tar, get_tarval_one(get_tarval_mode(*count_tar)));
1921 /* Next has to fail the loop condition, or we will never exit. */
1922 if (! (tarval_cmp(next, end_tar) & norm_proj))
1928 /* Check if loop meets requirements for a 'simple loop':
1929 * - Exactly one cf out
1931 * - Max nodes after unrolling
1935 * Returns Projection of cmp node or NULL; */
1936 static ir_node *is_simple_loop(void)
1939 unsigned loop_depth, max_loop_nodes_adapted;
1940 ir_node *loop_block, *exit_block, *projx, *cond, *projres, *loop_condition;
1942 /* Maximum of one condition, and no endless loops. */
1943 if (loop_info.cf_outs != 1)
1946 DB((dbg, LEVEL_4, "1 loop exit\n"));
1949 /* Ignore loop size. Probably not wise in other than testcases. */
1950 (void) max_loop_nodes_adapted;
1953 loop_info.max_unroll = 6;
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);
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);
1965 DB((dbg, LEVEL_4, "maximum unroll factor %u, to not exceed node limit \n",
1966 loop_info.max_unroll));
1968 arity = get_irn_arity(loop_head);
1969 /* RETURN if we have more than 1 be. */
1970 /* Get my backedges without alien bes. */
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)) {
1976 /* Our simple loops may have only one backedge. */
1979 loop_block = get_nodes_block(pred);
1980 loop_info.be_src_pos = i;
1985 DB((dbg, LEVEL_4, "loop has 1 own backedge.\n"));
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)
1994 DB((dbg, LEVEL_4, "tail-controlled loop.\n"));
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);
2002 if (!is_Cmp(loop_condition))
2005 DB((dbg, LEVEL_5, "projection is %s\n", get_pnc_string(get_Proj_proj(projx))));
2007 switch(get_Proj_proj(projx)) {
2009 loop_info.exit_cond = 0;
2012 loop_info.exit_cond = 1;
2015 panic("Cond Proj_proj other than true/false");
2018 DB((dbg, LEVEL_4, "Valid Cmp.\n"));
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)
2026 ir_mode *m1 = get_irn_mode(n1);
2027 ir_mode *m2 = get_irn_mode(n2);
2028 ir_mode *m3 = get_irn_mode(n3);
2030 if ((m1 == mode_Iu && m2 == mode_Iu && m3 == mode_Iu) ||
2031 (m1 == mode_Is && m2 == mode_Is && m3 == mode_Is))
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)
2042 ir_node *projres, *loop_condition, *iteration_path;
2043 unsigned success, is_latest_val;
2044 tarval *start_tar, *step_tar;
2047 /* RETURN if loop is not 'simple' */
2048 projres = is_simple_loop();
2049 if (projres == NULL)
2052 loop_condition = get_irn_n(projres, 0);
2054 success = get_invariant_pred(loop_condition, &loop_info.end_val, &iteration_path);
2058 DB((dbg, LEVEL_4, "Invariant End_val %N, other %N\n", loop_info.end_val, iteration_path));
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)) {
2064 /* We test against the latest value of the iv. */
2067 loop_info.add = iteration_path;
2068 DB((dbg, LEVEL_4, "Got add %N (maybe not sane)\n", loop_info.add));
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);
2075 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2077 if (! is_Phi(loop_info.iteration_phi))
2080 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2083 * Does necessary sanity check of add, if it is already set. */
2084 success = get_start_and_add(loop_info.iteration_phi, invariant);
2088 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2090 } else if (is_Phi(iteration_path)) {
2091 ir_node *new_iteration_phi;
2093 /* We compare with the value the iv had entering this run. */
2096 loop_info.iteration_phi = iteration_path;
2097 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
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);
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));
2108 success = get_const_pred(loop_info.add, &loop_info.step, &new_iteration_phi);
2112 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2114 if (loop_info.iteration_phi != new_iteration_phi)
2121 mode = get_irn_mode(loop_info.end_val);
2123 DB((dbg, LEVEL_4, "start %N, end %N, step %N\n",
2124 loop_info.start_val, loop_info.end_val, loop_info.step));
2126 if (mode != mode_Is && mode != mode_Iu)
2129 /* TODO necessary? */
2130 if (!are_mode_I(loop_info.start_val, loop_info.step, loop_info.end_val))
2133 DB((dbg, LEVEL_4, "mode integer\n"));
2135 step_tar = get_Const_tarval(loop_info.step);
2136 start_tar = get_Const_tarval(loop_info.start_val);
2138 if (tarval_is_null(step_tar)) {
2139 /* TODO Might be worth a warning. */
2143 DB((dbg, LEVEL_4, "step is not 0\n"));
2145 create_duffs_block();
2147 return loop_info.max_unroll;
2150 /* Returns unroll factor,
2151 * given maximum unroll factor and number of loop passes. */
2152 static unsigned get_preferred_factor_constant(tarval *count_tar)
2154 tarval *tar_6, *tar_5, *tar_4, *tar_3, *tar_2;
2156 ir_mode *mode = get_irn_mode(loop_info.end_val);
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);
2164 /* loop passes % {6, 5, 4, 3, 2} == 0 */
2165 if (tarval_is_null(tarval_mod(count_tar, tar_6)))
2167 else if (tarval_is_null(tarval_mod(count_tar, tar_5)))
2169 else if (tarval_is_null(tarval_mod(count_tar, tar_4)))
2171 else if (tarval_is_null(tarval_mod(count_tar, tar_3)))
2173 else if (tarval_is_null(tarval_mod(count_tar, tar_2)))
2176 /* gcd(max_unroll, count_tar) */
2177 int a = loop_info.max_unroll;
2178 int b = (int)get_tarval_long(count_tar);
2181 DB((dbg, LEVEL_4, "gcd of max_unroll %d and count_tar %d: ", a, b));
2188 DB((dbg, LEVEL_4, "%d\n", a));
2192 DB((dbg, LEVEL_4, "preferred unroll factor %d\n", prefer));
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.
2211 if (prefer <= loop_info.max_unroll)
2216 if (loop_info.max_unroll >= 3)
2218 else if (loop_info.max_unroll >= 2)
2224 if (loop_info.max_unroll >= 2)
2235 /* Check if cur_loop is a simple counting loop.
2236 * Start, step and end are constants. */
2238 static unsigned get_unroll_decision_constant(void)
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;
2246 /* RETURN if loop is not 'simple' */
2247 projres = is_simple_loop();
2248 if (projres == NULL)
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.
2266 loop_condition = get_irn_n(projres, 0);
2268 success = get_const_pred(loop_condition, &loop_info.end_val, &iteration_path);
2272 DB((dbg, LEVEL_4, "End_val %N, other %N\n", loop_info.end_val, iteration_path));
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)) {
2278 /* We test against the latest value of the iv. */
2281 loop_info.add = iteration_path;
2282 DB((dbg, LEVEL_4, "Got add %N (maybe not sane)\n", loop_info.add));
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);
2289 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2291 if (! is_Phi(loop_info.iteration_phi))
2294 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2297 * Does necessary sanity check of add, if it is already set. */
2298 success = get_start_and_add(loop_info.iteration_phi, constant);
2302 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2304 } else if (is_Phi(iteration_path)) {
2305 ir_node *new_iteration_phi;
2307 /* We compare with the value the iv had entering this run. */
2310 loop_info.iteration_phi = iteration_path;
2311 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
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);
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));
2322 success = get_const_pred(loop_info.add, &loop_info.step, &new_iteration_phi);
2326 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2328 if (loop_info.iteration_phi != new_iteration_phi)
2336 mode = get_irn_mode(loop_info.end_val);
2338 DB((dbg, LEVEL_4, "start %N, end %N, step %N\n",
2339 loop_info.start_val, loop_info.end_val, loop_info.step));
2341 if (mode != mode_Is && mode != mode_Iu)
2344 /* TODO necessary? */
2345 if (!are_mode_I(loop_info.start_val, loop_info.step, loop_info.end_val))
2348 DB((dbg, LEVEL_4, "mode integer\n"));
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);
2354 if (tarval_is_null(step_tar))
2355 /* TODO Might be worth a warning. */
2358 DB((dbg, LEVEL_4, "step is not 0\n"));
2360 if ((!tarval_is_negative(step_tar)) ^ (!is_Sub(loop_info.add)))
2361 loop_info.decreasing = 1;
2363 diff_tar = tarval_sub(end_tar, start_tar, mode);
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);
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. */
2379 count_stats(stats.u_simple_counting_loop);
2381 loop_info.latest_value = is_latest_val;
2384 if (! is_simple_counting_loop(&count_tar))
2388 /* stepped can be negative, if step < 0 */
2389 stepped = tarval_mul(count_tar, step_tar);
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);
2396 stepped = tarval_add(start_tar, stepped);
2398 DB((dbg, LEVEL_4, "stepped to %ld\n", get_tarval_long(stepped)));
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);
2405 norm_proj = proj_proj;
2407 DB((dbg, LEVEL_4, "normalized projection %s\n", get_pnc_string(norm_proj)));
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. */
2414 /* calculates next values and increases count_tar according to it */
2415 success = simulate_next(&count_tar, stepped, step_tar, end_tar, norm_proj);
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));
2426 DB((dbg, LEVEL_4, "loop taken %ld times\n", get_tarval_long(count_tar)));
2428 /* Assure the loop is taken at least 1 time. */
2429 if (tarval_is_null(count_tar)) {
2430 /* TODO Might be worth a warning. */
2434 loop_info.count_tar = count_tar;
2435 return get_preferred_factor_constant(count_tar);
2441 static void unroll_loop(void)
2445 /* get_unroll_decision_constant and invariant are completely
2446 * independent for flexibility.
2447 * Some checks may be performed twice. */
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;
2456 /* invariant case? */
2457 if (opt_params.allow_invar_unrolling)
2458 unroll_nr = get_unroll_decision_invariant();
2460 loop_info.unroll_kind = invariant;
2463 DB((dbg, LEVEL_1, " *** Unrolling %d times ***\n", unroll_nr));
2465 if (unroll_nr > 1) {
2466 loop_entries = NEW_ARR_F(entry_edge, 0);
2469 irg_walk_graph(current_ir_graph, get_loop_entries, NULL, NULL);
2471 if ((int)get_tarval_long(loop_info.count_tar) == unroll_nr)
2472 loop_info.needs_backedge = 0;
2474 loop_info.needs_backedge = 1;
2476 /* Use phase to keep copy of nodes from the condition chain. */
2477 phase = new_phase(current_ir_graph, phase_irn_init_default);
2479 /* Copies the loop */
2480 copy_loop(loop_entries, unroll_nr - 1);
2482 /* Line up the floating copies. */
2483 place_copies(unroll_nr - 1);
2485 /* Remove phis with 1 in*/
2486 irg_walk_graph(current_ir_graph, correct_phis, NULL, NULL);
2488 /* dump_ir_block_graph(current_ir_graph, "-DONE"); */
2490 if (loop_info.unroll_kind == constant)
2491 count_stats(stats.constant_unroll);
2493 count_stats(stats.invariant_unroll);
2495 set_irg_doms_inconsistent(current_ir_graph);
2496 set_irg_loopinfo_inconsistent(current_ir_graph);
2498 set_irg_outs_inconsistent(current_ir_graph);
2500 DEL_ARR_F(loop_entries);
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)
2509 /* Expect no benefit of big loops. */
2510 /* TODO tuning/make parameter */
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;
2520 loop_head_valid = 1;
2522 /* Reset loop info */
2523 memset(&loop_info, 0, sizeof(loop_info_t));
2525 DB((dbg, LEVEL_1, " >>>> current loop includes node %N <<<\n",
2526 get_loop_node(loop, 0)));
2528 /* Collect loop informations: head, node counts. */
2529 irg_walk_graph(current_ir_graph, get_loop_info, NULL, NULL);
2531 /* Depth of 0 is the procedure and 1 a topmost loop. */
2532 loop_depth = get_loop_depth(loop) - 1;
2534 /* Calculating in per mil. */
2535 max_loop_nodes_adapted = get_max_nodes_adapted(loop_depth);
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));
2540 if (! (loop_info.nodes > 0))
2543 #if LOOP_IGNORE_NODE_LIMITS
2544 DB((dbg, LEVEL_1, "WARNING: Loop node limitations ignored."));
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);
2552 /* Adaption might change it */
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);
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);
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"));
2576 DB((dbg, LEVEL_1, "Loophead: %N\n", loop_head));
2580 case loop_op_inversion:
2584 case loop_op_unrolling:
2589 panic("Loop optimization not implemented.");
2591 DB((dbg, LEVEL_1, " <<<< end of loop with node %N >>>>\n",
2592 get_loop_node(loop, 0)));
2595 /* Find innermost loops and add them to loops. */
2596 static void find_innermost_loop(ir_loop *loop)
2598 /* descend into sons */
2599 int sons = get_loop_n_sons(loop);
2602 ARR_APP1(ir_loop *, loops, loop);
2605 for (s=0; s<sons; s++) {
2606 find_innermost_loop(get_loop_son(loop, s));
2611 /* Assure preconditions are met and go through all loops. */
2612 void loop_optimization(ir_graph *irg)
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;
2624 opt_params.max_cc_size = 100;
2626 /* Unrolling not yet tested */
2627 opt_params.allow_const_unrolling = 1;
2628 opt_params.allow_invar_unrolling = 1;
2630 /* Reset stats for this procedure */
2634 set_current_ir_graph(irg);
2637 assure_irg_outs(irg);
2639 /* NOTE: sets only the loop attribute of blocks, not nodes */
2640 /* NOTE: Kills links */
2641 assure_cf_loop(irg);
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);
2647 loop = get_irg_loop(irg);
2648 sons = get_loop_n_sons(loop);
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));
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);
2660 for (i = 0; i < ARR_LEN(loops); ++i) {
2661 ir_loop *loop = loops[i];
2663 count_stats(stats.loops);
2665 /* Analyze and handle loop */
2668 /* Copied blocks do not have their phi list yet */
2669 collect_phiprojs(irg);
2671 /* Set links to NULL
2672 * TODO Still necessary? */
2673 irg_walk_graph(current_ir_graph, reset_link, NULL, NULL);
2679 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2680 ir_free_resources(irg, IR_RESOURCE_PHI_LIST);
2683 void do_loop_unrolling(ir_graph *irg)
2685 loop_op = loop_op_unrolling;
2687 DB((dbg, LEVEL_1, " >>> unrolling (Startnode %N) <<<\n",
2688 get_irg_start(irg)));
2690 loop_optimization(irg);
2692 DB((dbg, LEVEL_1, " >>> unrolling done (Startnode %N) <<<\n",
2693 get_irg_start(irg)));
2696 void do_loop_inversion(ir_graph *irg)
2698 loop_op = loop_op_inversion;
2700 DB((dbg, LEVEL_1, " >>> inversion (Startnode %N) <<<\n",
2701 get_irg_start(irg)));
2703 loop_optimization(irg);
2705 DB((dbg, LEVEL_1, " >>> inversion done (Startnode %N) <<<\n",
2706 get_irg_start(irg)));
2709 void do_loop_peeling(ir_graph *irg)
2711 loop_op = loop_op_peeling;
2713 DB((dbg, LEVEL_1, " >>> peeling (Startnode %N) <<<\n",
2714 get_irg_start(irg)));
2716 loop_optimization(irg);
2718 DB((dbg, LEVEL_1, " >>> peeling done (Startnode %N) <<<\n",
2719 get_irg_start(irg)));
2723 ir_graph_pass_t *loop_inversion_pass(const char *name)
2725 return def_graph_pass(name ? name : "loop_inversion", do_loop_inversion);
2728 ir_graph_pass_t *loop_unroll_pass(const char *name)
2730 return def_graph_pass(name ? name : "loop_unroll", do_loop_unrolling);
2733 ir_graph_pass_t *loop_peeling_pass(const char *name)
2735 return def_graph_pass(name ? name : "loop_peeling", do_loop_peeling);
2738 void firm_init_loop_opt(void)
2740 FIRM_DBG_REGISTER(dbg, "firm.opt.loop");