2 * Copyright (C) 1995-2011 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
29 #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 1
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 {
94 } unrolling_node_info;
96 /* Outs of the nodes head. */
97 static entry_edge *cur_head_outs;
99 /* Information about the loop head */
100 static ir_node *loop_head = NULL;
101 static unsigned loop_head_valid = 1;
103 /* List of all inner loops, that are processed. */
104 static ir_loop **loops;
108 #define count_stats(val) (++val)
109 #define print_stats() (do_print_stats())
110 #define reset_stats() (do_reset_stats())
113 typedef struct loop_stats_t {
117 unsigned too_large_adapted;
118 unsigned cc_limit_reached;
119 unsigned calls_limit;
121 unsigned u_simple_counting_loop;
122 unsigned constant_unroll;
123 unsigned invariant_unroll;
128 static loop_stats_t stats;
130 /* Set stats to sero */
131 static void do_reset_stats(void)
133 memset(&stats, 0, sizeof(loop_stats_t));
137 static void do_print_stats(void)
139 DB((dbg, LEVEL_2, "---------------------------------------\n"));
140 DB((dbg, LEVEL_2, "loops : %d\n",stats.loops));
141 DB((dbg, LEVEL_2, "inverted : %d\n",stats.inverted));
142 DB((dbg, LEVEL_2, "too_large : %d\n",stats.too_large));
143 DB((dbg, LEVEL_2, "too_large_adapted : %d\n",stats.too_large_adapted));
144 DB((dbg, LEVEL_2, "cc_limit_reached : %d\n",stats.cc_limit_reached));
145 DB((dbg, LEVEL_2, "calls_limit : %d\n",stats.calls_limit));
146 DB((dbg, LEVEL_2, "u_simple_counting : %d\n",stats.u_simple_counting_loop));
147 DB((dbg, LEVEL_2, "constant_unroll : %d\n",stats.constant_unroll));
148 DB((dbg, LEVEL_2, "invariant_unroll : %d\n",stats.invariant_unroll));
149 DB((dbg, LEVEL_2, "=======================================\n"));
153 #define count_stats(val) ((void)0)
154 #define print_stats() ((void)0)
155 #define reset_stats() ((void)0)
159 /* Commandline parameters */
160 typedef struct loop_opt_params_t {
161 unsigned max_loop_size; /* Maximum number of nodes [nodes]*/
162 int depth_adaption; /* Loop nest depth adaption [percent] */
163 unsigned allowed_calls; /* Number of calls allowed [number] */
164 unsigned count_phi:1; /* Count phi nodes */
165 unsigned count_proj:1; /* Count projections */
167 unsigned max_cc_size; /* Maximum condition chain size [nodes] */
168 unsigned max_branches;
170 unsigned max_unrolled_loop_size; /* [nodes] */
171 unsigned allow_const_unrolling:1;
172 unsigned allow_invar_unrolling:1;
173 unsigned invar_unrolling_min_size; /* [nodes] */
177 static loop_opt_params_t opt_params;
179 /* Loop analysis informations */
180 typedef struct loop_info_t {
181 unsigned nodes; /* node count */
182 unsigned ld_st; /* load and store nodes */
183 unsigned branches; /* number of conditions */
184 unsigned calls; /* number of calls */
185 unsigned cf_outs; /* number of cf edges which leave the loop */
186 entry_edge cf_out; /* single loop leaving cf edge */
187 int be_src_pos; /* position of the single own backedge in the head */
190 unsigned cc_size; /* nodes in the condition chain */
193 unsigned max_unroll; /* Number of unrolls satisfying max_loop_size */
194 unsigned exit_cond; /* 1 if condition==true exits the loop. */
195 unsigned latest_value:1; /* 1 if condition is checked against latest counter value */
196 unsigned needs_backedge:1; /* 0 if loop is completely unrolled */
197 unsigned decreasing:1; /* Step operation is_Sub, or step is<0 */
199 /* IV informations of a simple loop */
203 ir_node *iteration_phi;
206 ir_tarval *count_tar; /* Number of loop iterations */
208 ir_node *duff_cond; /* Duff mod */
209 unrolling_kind_flag unroll_kind; /* constant or invariant unrolling */
212 /* Information about the current loop */
213 static loop_info_t loop_info;
215 /* Outs of the condition chain (loop inversion). */
216 static ir_node **cc_blocks;
217 /* df/cf edges with def in the condition chain */
218 static entry_edge *cond_chain_entries;
219 /* Array of df loops found in the condition chain. */
220 static entry_edge *head_df_loop;
221 /* Number of blocks in cc */
222 static unsigned inversion_blocks_in_cc;
225 /* Cf/df edges leaving the loop.
226 * Called entries here, as they are used to enter the loop with walkers. */
227 static entry_edge *loop_entries;
228 /* Number of unrolls to perform */
229 static int unroll_nr;
230 /* Phase is used to keep copies of nodes. */
231 static ir_phase *phase;
233 /* Loop operations. */
234 typedef enum loop_op_t {
240 /* Saves which loop operation to do until after basic tests. */
241 static loop_op_t loop_op;
243 /* Returns the maximum nodes for the given nest depth */
244 static unsigned get_max_nodes_adapted(unsigned depth)
246 double perc = 100.0 + (double)opt_params.depth_adaption;
247 double factor = pow(perc / 100.0, depth);
249 return (int)((double)opt_params.max_loop_size * factor);
252 /* Reset nodes link. For use with a walker. */
253 static void reset_link(ir_node *node, void *env)
256 set_irn_link(node, NULL);
259 /* Returns 0 if the node or block is not in cur_loop. */
260 static unsigned is_in_loop(ir_node *node)
262 return (get_irn_loop(get_block(node)) == cur_loop);
265 /* Returns 0 if the given edge is not a backedge
266 * with its pred in the cur_loop. */
267 static unsigned is_own_backedge(ir_node *n, int pos)
269 return (is_backedge(n, pos) && is_in_loop(get_irn_n(n, pos)));
272 /* Finds loop head and some loop_info as calls or else if necessary. */
273 static void get_loop_info(ir_node *node, void *env)
275 unsigned node_in_loop, pred_in_loop;
279 arity = get_irn_arity(node);
280 for (i = 0; i < arity; i++) {
281 ir_node *pred = get_irn_n(node, i);
283 pred_in_loop = is_in_loop(pred);
284 node_in_loop = is_in_loop(node);
286 if (!node_in_loop && pred_in_loop && is_Block(node))
294 loop_info.cf_out = entry;
297 /* collect some loop information */
299 if (is_Phi(node) && opt_params.count_phi)
301 else if (is_Proj(node) && opt_params.count_proj)
303 else if (!is_Confirm(node) && !is_Const(node) && !is_SymConst(node))
306 if (is_Load(node) || is_Store(node))
314 /* Find the loops head/the blocks with cfpred outside of the loop */
315 if (is_Block(node)) {
316 const ir_edge_t *edge;
319 /* Count innerloop branches */
320 foreach_out_edge_kind(node, edge, EDGE_KIND_NORMAL) {
321 if (is_Block(get_edge_src_irn(edge)) && is_in_loop(get_edge_src_irn(edge)))
325 ++loop_info.branches;
327 if (node_in_loop && !pred_in_loop && loop_head_valid) {
328 ir_node *cfgpred = get_Block_cfgpred(node, i);
330 if (!is_in_loop(cfgpred)) {
331 DB((dbg, LEVEL_5, "potential head %+F because inloop and pred %+F not inloop\n",
333 /* another head? We do not touch this. */
334 if (loop_head && loop_head != node) {
345 /* Finds all edges with users outside of the loop
346 * and definition inside the loop. */
347 static void get_loop_entries(ir_node *node, void *env)
349 unsigned node_in_loop, pred_in_loop;
353 arity = get_irn_arity(node);
354 for (i = 0; i < arity; ++i) {
355 ir_node *pred = get_irn_n(node, i);
357 pred_in_loop = is_in_loop(pred);
358 node_in_loop = is_in_loop(node);
360 if (pred_in_loop && !node_in_loop) {
365 ARR_APP1(entry_edge, loop_entries, entry);
371 static ir_node *ssa_second_def;
372 static ir_node *ssa_second_def_block;
375 * Walks the graph bottom up, searching for definitions and creates phis.
377 static ir_node *search_def_and_create_phis(ir_node *block, ir_mode *mode, int first)
385 DB((dbg, LEVEL_5, "ssa search_def_and_create_phis: block %N\n", block));
387 /* Prevents creation of phi that would be bad anyway.
388 * Dead and bad blocks. */
389 if (get_irn_arity(block) < 1 || is_Bad(block)) {
390 DB((dbg, LEVEL_5, "ssa bad %N\n", block));
394 if (block == ssa_second_def_block && !first) {
395 DB((dbg, LEVEL_5, "ssa found second definition: use second def %N\n", ssa_second_def));
396 return ssa_second_def;
399 /* already processed this block? */
400 if (irn_visited(block)) {
401 ir_node *value = (ir_node *) get_irn_link(block);
402 DB((dbg, LEVEL_5, "ssa already visited: use linked %N\n", value));
406 irg = get_irn_irg(block);
407 assert(block != get_irg_start_block(irg));
409 /* a Block with only 1 predecessor needs no Phi */
410 n_cfgpreds = get_Block_n_cfgpreds(block);
411 if (n_cfgpreds == 1) {
412 ir_node *pred_block = get_Block_cfgpred_block(block, 0);
415 DB((dbg, LEVEL_5, "ssa 1 pred: walk pred %N\n", pred_block));
417 value = search_def_and_create_phis(pred_block, mode, 0);
418 set_irn_link(block, value);
419 mark_irn_visited(block);
424 /* create a new Phi */
425 NEW_ARR_A(ir_node*, in, n_cfgpreds);
426 for (i = 0; i < n_cfgpreds; ++i)
427 in[i] = new_r_Dummy(irg, mode);
429 phi = new_r_Phi(block, n_cfgpreds, in, mode);
430 /* Important: always keep block phi list up to date. */
431 add_Block_phi(block, phi);
432 DB((dbg, LEVEL_5, "ssa phi creation: link new phi %N to block %N\n", phi, block));
433 set_irn_link(block, phi);
434 mark_irn_visited(block);
436 /* set Phi predecessors */
437 for (i = 0; i < n_cfgpreds; ++i) {
439 ir_node *pred_block = get_Block_cfgpred_block(block, i);
440 assert(pred_block != NULL);
441 pred_val = search_def_and_create_phis(pred_block, mode, 0);
443 assert(pred_val != NULL);
445 DB((dbg, LEVEL_5, "ssa phi pred:phi %N, pred %N\n", phi, pred_val));
446 set_irn_n(phi, i, pred_val);
454 * Given a set of values this function constructs SSA-form for the users of the
455 * first value (the users are determined through the out-edges of the value).
456 * Works without using the dominance tree.
458 static void construct_ssa(ir_node *orig_block, ir_node *orig_val,
459 ir_node *second_block, ir_node *second_val)
463 const ir_edge_t *edge;
464 const ir_edge_t *next;
466 assert(orig_block && orig_val && second_block && second_val &&
467 "no parameter of construct_ssa may be NULL");
469 if (orig_val == second_val)
472 irg = get_irn_irg(orig_val);
474 ir_reserve_resources(irg, IR_RESOURCE_IRN_VISITED);
475 inc_irg_visited(irg);
477 mode = get_irn_mode(orig_val);
478 set_irn_link(orig_block, orig_val);
479 mark_irn_visited(orig_block);
481 ssa_second_def_block = second_block;
482 ssa_second_def = second_val;
484 /* Only fix the users of the first, i.e. the original node */
485 foreach_out_edge_safe(orig_val, edge, next) {
486 ir_node *user = get_edge_src_irn(edge);
487 int j = get_edge_src_pos(edge);
488 ir_node *user_block = get_nodes_block(user);
495 DB((dbg, LEVEL_5, "original user %N\n", user));
498 ir_node *pred_block = get_Block_cfgpred_block(user_block, j);
499 newval = search_def_and_create_phis(pred_block, mode, 1);
501 newval = search_def_and_create_phis(user_block, mode, 1);
503 if (newval != user && !is_Bad(newval))
504 set_irn_n(user, j, newval);
507 ir_free_resources(irg, IR_RESOURCE_IRN_VISITED);
511 /***** Unrolling Helper Functions *****/
513 /* Assign the copy with index nr to node n */
514 static void set_unroll_copy(ir_node *n, int nr, ir_node *cp)
516 unrolling_node_info *info;
517 assert(nr != 0 && "0 reserved");
519 info = (unrolling_node_info *)phase_get_irn_data(phase, n);
523 info = XMALLOCZ(unrolling_node_info);
524 arr = NEW_ARR_F(ir_node *, unroll_nr);
526 memset(info->copies, 0, (unroll_nr) * sizeof(ir_node *));
528 phase_set_irn_data(phase, n, info);
533 info->copies[nr] = cp;
536 /* Returns a nodes copy if it exists, else NULL. */
537 static ir_node *get_unroll_copy(ir_node *n, int nr)
540 unrolling_node_info *info = (unrolling_node_info *)phase_get_irn_data(phase, n);
544 cp = info->copies[nr];
549 /***** Inversion Helper Functions *****/
551 /* Sets copy cp of node n. */
552 static void set_inversion_copy(ir_node *n, ir_node *cp)
554 phase_set_irn_data(phase, n, cp);
557 /* Getter of copy of n for inversion */
558 static ir_node *get_inversion_copy(ir_node *n)
560 ir_node *cp = (ir_node *)phase_get_irn_data(phase, n);
564 /* Resets block mark for given node. For use with walker */
565 static void reset_block_mark(ir_node *node, void * env)
570 set_Block_mark(node, 0);
573 /* Returns mark of node, or its block if node is not a block.
574 * Used in this context to determine if node is in the condition chain. */
575 static unsigned is_nodes_block_marked(ir_node* node)
578 return get_Block_mark(node);
580 return get_Block_mark(get_block(node));
583 /* Extends a nodes ins by node new.
584 * NOTE: This is slow if a node n needs to be extended more than once. */
585 static void extend_irn(ir_node *n, ir_node *newnode, int new_is_backedge)
589 int arity = get_irn_arity(n);
590 int new_arity = arity + 1;
593 NEW_ARR_A(int, bes, new_arity);
594 NEW_ARR_A(ir_node *, ins, new_arity);
597 /* Bes are important!
598 * Another way would be recreating the looptree,
599 * but after that we cannot distinguish already processed loops
600 * from not yet processed ones. */
602 for(i = 0; i < arity; ++i) {
603 bes[i] = is_backedge(n, i);
605 bes[i] = new_is_backedge;
608 for(i = 0; i < arity; ++i) {
609 ins[i] = get_irn_n(n, i);
613 set_irn_in(n, new_arity, ins);
617 for(i = 0; i < new_arity; ++i) {
624 /* Extends a block by a copy of its pred at pos,
625 * fixing also the phis in the same way. */
626 static void extend_ins_by_copy(ir_node *block, int pos)
631 assert(is_Block(block));
633 /* Extend block by copy of definition at pos */
634 pred = get_irn_n(block, pos);
635 new_in = get_inversion_copy(pred);
636 DB((dbg, LEVEL_5, "Extend block %N by %N cp of %N\n", block, new_in, pred));
637 extend_irn(block, new_in, 0);
639 /* Extend block phis by copy of definition at pos */
640 for_each_phi(block, phi) {
643 pred = get_irn_n(phi, pos);
644 cp = get_inversion_copy(pred);
645 /* If the phis in is not in the condition chain (eg. a constant),
646 * there is no copy. */
652 DB((dbg, LEVEL_5, "Extend phi %N by %N cp of %N\n", phi, new_in, pred));
653 extend_irn(phi, new_in, 0);
657 /* Returns the number of blocks backedges. With or without alien bes. */
658 static int get_backedge_n(ir_node *block, unsigned with_alien)
662 int arity = get_irn_arity(block);
664 assert(is_Block(block));
666 for (i = 0; i < arity; ++i) {
667 ir_node *pred = get_irn_n(block, i);
668 if (is_backedge(block, i) && (with_alien || is_in_loop(pred)))
674 /* Returns a raw copy of the given node.
675 * Attributes are kept/set according to the needs of loop inversion. */
676 static ir_node *copy_node(ir_node *node)
681 cp = exact_copy(node);
682 arity = get_irn_arity(node);
684 /* Keep backedge info */
685 for (i = 0; i < arity; ++i) {
686 if (is_backedge(node, i))
691 set_Block_mark(cp, 0);
699 * This walker copies all walked nodes.
700 * If the walk_condition is true for a node, it is copied.
701 * All nodes node_info->copy have to be NULL prior to every walk.
702 * Order of ins is important for later usage.
704 static void copy_walk(ir_node *node, walker_condition *walk_condition,
711 ir_graph *irg = current_ir_graph;
714 * break condition and cycle resolver, creating temporary node copies
716 if (get_irn_visited(node) >= get_irg_visited(irg)) {
717 /* Here we rely on nodestate's copy being initialized with NULL */
718 DB((dbg, LEVEL_5, "copy_walk: We have already visited %N\n", node));
719 if (get_inversion_copy(node) == NULL) {
720 cp = copy_node(node);
721 set_inversion_copy(node, cp);
723 DB((dbg, LEVEL_5, "The TEMP copy of %N is created %N\n", node, cp));
729 mark_irn_visited(node);
731 if (!is_Block(node)) {
732 ir_node *pred = get_nodes_block(node);
733 if (walk_condition(pred))
734 DB((dbg, LEVEL_5, "walk block %N\n", pred));
735 copy_walk(pred, walk_condition, set_loop);
738 arity = get_irn_arity(node);
740 NEW_ARR_A(ir_node *, cpin, arity);
742 for (i = 0; i < arity; ++i) {
743 ir_node *pred = get_irn_n(node, i);
745 if (walk_condition(pred)) {
746 DB((dbg, LEVEL_5, "walk node %N\n", pred));
747 copy_walk(pred, walk_condition, set_loop);
748 cpin[i] = get_inversion_copy(pred);
749 DB((dbg, LEVEL_5, "copy of %N gets new in %N which is copy of %N\n",
750 node, get_inversion_copy(pred), pred));
756 /* copy node / finalize temp node */
757 if (get_inversion_copy(node) == NULL) {
758 /* No temporary copy existent */
759 cp = copy_node(node);
760 set_inversion_copy(node, cp);
761 DB((dbg, LEVEL_5, "The FINAL copy of %N is CREATED %N\n", node, cp));
763 /* temporary copy is existent but without correct ins */
764 cp = get_inversion_copy(node);
765 DB((dbg, LEVEL_5, "The FINAL copy of %N is EXISTENT %N\n", node, cp));
768 if (!is_Block(node)) {
769 ir_node *cpblock = get_inversion_copy(get_nodes_block(node));
771 set_nodes_block(cp, cpblock );
773 add_Block_phi(cpblock, cp);
776 /* Keeps phi list of temporary node. */
777 set_irn_in(cp, ARR_LEN(cpin), cpin);
781 * This walker copies all walked nodes.
782 * If the walk_condition is true for a node, it is copied.
783 * All nodes node_info->copy have to be NULL prior to every walk.
784 * Order of ins is important for later usage.
785 * Takes copy_index, to phase-link copy at specific index.
787 static void copy_walk_n(ir_node *node, walker_condition *walk_condition,
796 * break condition and cycle resolver, creating temporary node copies
798 if (irn_visited(node)) {
799 /* Here we rely on nodestate's copy being initialized with NULL */
800 DB((dbg, LEVEL_5, "copy_walk: We have already visited %N\n", node));
801 if (get_unroll_copy(node, copy_index) == NULL) {
804 set_unroll_copy(node, copy_index, u);
805 DB((dbg, LEVEL_5, "The TEMP unknown of %N is created %N\n", node, u));
811 mark_irn_visited(node);
813 if (!is_Block(node)) {
814 ir_node *block = get_nodes_block(node);
815 if (walk_condition(block))
816 DB((dbg, LEVEL_5, "walk block %N\n", block));
817 copy_walk_n(block, walk_condition, copy_index);
820 arity = get_irn_arity(node);
821 NEW_ARR_A(ir_node *, cpin, arity);
823 for (i = 0; i < arity; ++i) {
824 ir_node *pred = get_irn_n(node, i);
826 if (walk_condition(pred)) {
827 DB((dbg, LEVEL_5, "walk node %N\n", pred));
828 copy_walk_n(pred, walk_condition, copy_index);
829 cpin[i] = get_unroll_copy(pred, copy_index);
835 /* copy node / finalize temp node */
836 cp = get_unroll_copy(node, copy_index);
837 if (cp == NULL || is_Unknown(cp)) {
838 cp = copy_node(node);
839 set_unroll_copy(node, copy_index, cp);
840 DB((dbg, LEVEL_5, "The FINAL copy of %N is CREATED %N\n", node, cp));
842 /* temporary copy is existent but without correct ins */
843 cp = get_unroll_copy(node, copy_index);
844 DB((dbg, LEVEL_5, "The FINAL copy of %N is EXISTENT %N\n", node, cp));
847 if (!is_Block(node)) {
848 ir_node *cpblock = get_unroll_copy(get_nodes_block(node), copy_index);
850 set_nodes_block(cp, cpblock );
852 add_Block_phi(cpblock, cp);
855 /* Keeps phi list of temporary node. */
856 set_irn_in(cp, ARR_LEN(cpin), cpin);
859 /* Removes alle Blocks with non marked predecessors from the condition chain. */
860 static void unmark_not_allowed_cc_blocks(void)
862 size_t blocks = ARR_LEN(cc_blocks);
865 for(i = 0; i < blocks; ++i) {
866 ir_node *block = cc_blocks[i];
868 int arity = get_irn_arity(block);
870 /* Head is an exception. */
871 if (block == loop_head)
874 for(a = 0; a < arity; ++a) {
875 if (! is_nodes_block_marked(get_irn_n(block, a))) {
876 set_Block_mark(block, 0);
877 --inversion_blocks_in_cc;
878 DB((dbg, LEVEL_5, "Removed %N from cc (blocks in cc %d)\n",
879 block, inversion_blocks_in_cc));
887 /* Unmarks all cc blocks using cc_blocks except head.
888 * TODO: invert head for unrolling? */
889 static void unmark_cc_blocks(void)
891 size_t blocks = ARR_LEN(cc_blocks);
894 for(i = 0; i < blocks; ++i) {
895 ir_node *block = cc_blocks[i];
897 /* TODO Head is an exception. */
898 /*if (block != loop_head)*/
899 set_Block_mark(block, 0);
901 /*inversion_blocks_in_cc = 1;*/
902 inversion_blocks_in_cc = 0;
905 loop_info.cc_size = 0;
909 * Populates head_entries with (node, pred_pos) tuple
910 * whereas the node's pred at pred_pos is in the cc but not the node itself.
911 * Also finds df loops inside the cc.
912 * Head and condition chain blocks have been marked previously.
914 static void get_head_outs(ir_node *node, void *env)
917 int arity = get_irn_arity(node);
920 for (i = 0; i < arity; ++i) {
921 if (!is_nodes_block_marked(node) && is_nodes_block_marked(get_irn_n(node, i))) {
925 /* Saving also predecessor seems redundant, but becomes
926 * necessary when changing position of it, before
927 * dereferencing it.*/
928 entry.pred = get_irn_n(node, i);
929 ARR_APP1(entry_edge, cur_head_outs, entry);
933 arity = get_irn_arity(loop_head);
935 /* Find df loops inside the cc */
936 if (is_Phi(node) && get_nodes_block(node) == loop_head) {
937 for (i = 0; i < arity; ++i) {
938 if (is_own_backedge(loop_head, i)) {
939 if (is_nodes_block_marked(get_irn_n(node, i))) {
943 entry.pred = get_irn_n(node, i);
944 ARR_APP1(entry_edge, head_df_loop, entry);
945 DB((dbg, LEVEL_5, "Found incc assignment node %N @%d is pred %N, graph %N %N\n",
946 node, i, entry.pred, current_ir_graph, get_irg_start_block(current_ir_graph)));
954 * Find condition chains, and add them to be inverted.
955 * A block belongs to the chain if a condition branches out of the loop.
956 * (Some blocks need to be removed once again.)
957 * Returns 1 if the given block belongs to the condition chain.
959 static unsigned find_condition_chain(ir_node *block)
961 const ir_edge_t *edge;
965 unsigned nodes_n = 0;
967 mark_irn_visited(block);
969 DB((dbg, LEVEL_5, "condition_chains for block %N\n", block));
972 foreach_out_edge_kind(block, edge, EDGE_KIND_NORMAL) {
976 /* Check if node count would exceed maximum cc size.
978 * This is not optimal, as we search depth-first and break here,
979 * continuing with another subtree. */
980 if (loop_info.cc_size + nodes_n > opt_params.max_cc_size) {
981 set_Block_mark(block, 0);
985 /* Check if block only has a jmp instruction. */
987 foreach_out_edge(block, edge) {
988 ir_node *src = get_edge_src_irn(edge);
990 if (! is_Block(src) && ! is_Jmp(src)) {
995 /* Check cf outs if one is leaving the loop,
996 * or if this node has a backedge. */
997 foreach_block_succ(block, edge) {
998 ir_node *src = get_edge_src_irn(edge);
999 int pos = get_edge_src_pos(edge);
1001 if (! is_in_loop(src))
1004 /* Inverting blocks with backedge outs leads to a cf edge
1005 * from the inverted head, into the inverted head (skipping the body).
1006 * As the body becomes the new loop head,
1007 * this would introduce another loop in the existing loop.
1008 * This loop inversion cannot cope with this case. */
1009 if (is_backedge(src, pos)) {
1015 /* We need all predecessors to already belong to the condition chain.
1016 * Example of wrong case: * == in cc
1027 /* Collect blocks containing only a Jmp.
1028 * Do not collect blocks with backedge outs. */
1029 if ((jmp_only == 1 || mark == 1) && has_be == 0) {
1030 set_Block_mark(block, 1);
1031 ++inversion_blocks_in_cc;
1032 loop_info.cc_size += nodes_n;
1033 DB((dbg, LEVEL_5, "block %N is part of condition chain\n", block));
1034 ARR_APP1(ir_node *, cc_blocks, block);
1036 set_Block_mark(block, 0);
1039 foreach_block_succ(block, edge) {
1040 ir_node *src = get_edge_src_irn( edge );
1042 if (is_in_loop(src) && ! irn_visited(src))
1043 find_condition_chain(src);
1050 * Rewires the copied condition chain. Removes backedges
1051 * as this condition chain is prior to the loop.
1052 * Copy of loop_head must have phi list and old (unfixed) backedge info of the loop head.
1053 * (loop_head is already fixed, we cannot rely on it.)
1055 static void fix_copy_inversion(void)
1060 ir_node *phi, *next;
1061 ir_node *head_cp = get_inversion_copy(loop_head);
1062 ir_graph *irg = get_irn_irg(head_cp);
1063 int arity = get_irn_arity(head_cp);
1064 int backedges = get_backedge_n(head_cp, 0);
1065 int new_arity = arity - backedges;
1069 NEW_ARR_A(ir_node *, ins, new_arity);
1072 /* Remove block backedges */
1073 for(i = 0; i < arity; ++i) {
1074 if (!is_backedge(head_cp, i))
1075 ins[pos++] = get_irn_n(head_cp, i);
1078 new_head = new_r_Block(irg, new_arity, ins);
1080 phis = NEW_ARR_F(ir_node *, 0);
1082 for_each_phi_safe(get_Block_phis(head_cp), phi, next) {
1084 NEW_ARR_A(ir_node *, ins, new_arity);
1086 for(i = 0; i < arity; ++i) {
1087 if (!is_backedge(head_cp, i))
1088 ins[pos++] = get_irn_n(phi, i);
1090 new_phi = new_rd_Phi(get_irn_dbg_info(phi),
1091 new_head, new_arity, ins,
1093 ARR_APP1(ir_node *, phis, new_phi);
1097 for_each_phi_safe(get_Block_phis(head_cp), phi, next) {
1098 exchange(phi, phis[pos++]);
1101 exchange(head_cp, new_head);
1107 /* Puts the original condition chain at the end of the loop,
1108 * subsequently to the body.
1109 * Relies on block phi list and correct backedges.
1111 static void fix_head_inversion(void)
1115 ir_node *phi, *next;
1117 ir_graph *irg = get_irn_irg(loop_head);
1118 int arity = get_irn_arity(loop_head);
1119 int backedges = get_backedge_n(loop_head, 0);
1120 int new_arity = backedges;
1124 NEW_ARR_A(ir_node *, ins, new_arity);
1127 /* Keep only backedges */
1128 for(i = 0; i < arity; ++i) {
1129 if (is_own_backedge(loop_head, i))
1130 ins[pos++] = get_irn_n(loop_head, i);
1133 new_head = new_r_Block(irg, new_arity, ins);
1135 phis = NEW_ARR_F(ir_node *, 0);
1137 for_each_phi(loop_head, phi) {
1139 DB((dbg, LEVEL_5, "Fixing phi %N of loop head\n", phi));
1141 NEW_ARR_A(ir_node *, ins, new_arity);
1144 for (i = 0; i < arity; ++i) {
1145 ir_node *pred = get_irn_n(phi, i);
1147 if (is_own_backedge(loop_head, i)) {
1148 /* If assignment is in the condition chain,
1149 * we need to create a phi in the new loop head.
1150 * This can only happen for df, not cf. See find_condition_chains. */
1151 /*if (is_nodes_block_marked(pred)) {
1159 new_phi = new_rd_Phi(get_irn_dbg_info(phi),
1160 new_head, new_arity, ins,
1163 ARR_APP1(ir_node *, phis, new_phi);
1165 DB((dbg, LEVEL_5, "fix inverted head should exch %N by %N (pos %d)\n", phi, new_phi, pos ));
1169 for_each_phi_safe(get_Block_phis(loop_head), phi, next) {
1170 DB((dbg, LEVEL_5, "fix inverted exch phi %N by %N\n", phi, phis[pos]));
1171 if (phis[pos] != phi)
1172 exchange(phi, phis[pos++]);
1177 DB((dbg, LEVEL_5, "fix inverted head exch head block %N by %N\n", loop_head, new_head));
1178 exchange(loop_head, new_head);
1181 /* Does the loop inversion. */
1182 static void inversion_walk(entry_edge *head_entries)
1187 * The order of rewiring bottom-up is crucial.
1188 * Any change of the order leads to lost information that would be needed later.
1191 ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1193 /* 1. clone condition chain */
1194 inc_irg_visited(current_ir_graph);
1196 for (i = 0; i < ARR_LEN(head_entries); ++i) {
1197 entry_edge entry = head_entries[i];
1198 ir_node *pred = get_irn_n(entry.node, entry.pos);
1200 DB((dbg, LEVEL_5, "\nInit walk block %N\n", pred));
1202 copy_walk(pred, is_nodes_block_marked, cur_loop);
1205 ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1207 /* 2. Extends the head control flow successors ins
1208 * with the definitions of the copied head node. */
1209 for (i = 0; i < ARR_LEN(head_entries); ++i) {
1210 entry_edge head_out = head_entries[i];
1212 if (is_Block(head_out.node))
1213 extend_ins_by_copy(head_out.node, head_out.pos);
1216 /* 3. construct_ssa for users of definitions in the condition chain,
1217 * as there is now a second definition. */
1218 for (i = 0; i < ARR_LEN(head_entries); ++i) {
1219 entry_edge head_out = head_entries[i];
1221 /* Ignore keepalives */
1222 if (is_End(head_out.node))
1225 /* Construct ssa for assignments in the condition chain. */
1226 if (!is_Block(head_out.node)) {
1227 ir_node *pred, *cppred, *block, *cpblock;
1229 pred = head_out.pred;
1230 cppred = get_inversion_copy(pred);
1231 block = get_nodes_block(pred);
1232 cpblock = get_nodes_block(cppred);
1233 construct_ssa(block, pred, cpblock, cppred);
1238 * If there is an assignment in the condition chain
1239 * with a user also in the condition chain,
1240 * the dominance frontier is in the new loop head.
1241 * The dataflow loop is completely in the condition chain.
1246 * Phi_cp | | copied condition chain
1250 * Phi* | | new loop head with newly created phi.
1252 * Phi | | original, inverted condition chain
1257 for (i = 0; i < ARR_LEN(head_df_loop); ++i) {
1258 entry_edge head_out = head_df_loop[i];
1260 /* Construct ssa for assignments in the condition chain. */
1261 ir_node *pred, *cppred, *block, *cpblock;
1263 pred = head_out.pred;
1264 cppred = get_inversion_copy(pred);
1265 assert(cppred && pred);
1266 block = get_nodes_block(pred);
1267 cpblock = get_nodes_block(cppred);
1268 construct_ssa(block, pred, cpblock, cppred);
1271 /* 4. Remove the ins which are no backedges from the original condition chain
1272 * as the cc is now subsequent to the body. */
1273 fix_head_inversion();
1275 /* 5. Remove the backedges of the copied condition chain,
1276 * because it is going to be the new 'head' in advance to the loop. */
1277 fix_copy_inversion();
1281 /* Performs loop inversion of cur_loop if possible and reasonable. */
1282 static void loop_inversion(void)
1285 unsigned max_loop_nodes = opt_params.max_loop_size;
1286 unsigned max_loop_nodes_adapted;
1287 int depth_adaption = opt_params.depth_adaption;
1289 unsigned do_inversion = 1;
1290 unsigned has_cc = 0;
1292 /* Depth of 0 is the procedure and 1 a topmost loop. */
1293 loop_depth = get_loop_depth(cur_loop) - 1;
1295 /* Calculating in per mil. */
1296 max_loop_nodes_adapted = get_max_nodes_adapted(loop_depth);
1298 DB((dbg, LEVEL_1, "max_nodes: %d\nmax_nodes_adapted %d at depth of %d (adaption %d)\n",
1299 max_loop_nodes, max_loop_nodes_adapted, loop_depth, depth_adaption));
1301 if (! (loop_info.nodes > 0))
1304 #if LOOP_IGNORE_NODE_LIMITS
1305 DB((dbg, LEVEL_1, "WARNING: Loop node limitations ignored."));
1307 if (loop_info.nodes > max_loop_nodes) {
1308 /* Only for stats */
1309 DB((dbg, LEVEL_1, "Nodes %d > allowed nodes %d\n",
1310 loop_info.nodes, loop_depth, max_loop_nodes));
1311 count_stats(stats.too_large);
1313 /* Adaption might change it */
1316 /* Limit processing to loops smaller than given parameter. */
1317 if (loop_info.nodes > max_loop_nodes_adapted) {
1318 DB((dbg, LEVEL_1, "Nodes %d > allowed nodes (depth %d adapted) %d\n",
1319 loop_info.nodes, loop_depth, max_loop_nodes_adapted));
1320 count_stats(stats.too_large_adapted);
1324 if (loop_info.calls > opt_params.allowed_calls) {
1325 DB((dbg, LEVEL_1, "Calls %d > allowed calls %d\n",
1326 loop_info.calls, opt_params.allowed_calls));
1327 count_stats(stats.calls_limit);
1332 /*inversion_head_node_limit = INT_MAX;*/
1333 ir_reserve_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1335 /* Reset block marks.
1336 * We use block marks to flag blocks of the original condition chain. */
1337 irg_walk_graph(current_ir_graph, reset_block_mark, NULL, NULL);
1339 /*loop_info.blocks = get_loop_n_blocks(cur_loop);*/
1340 cond_chain_entries = NEW_ARR_F(entry_edge, 0);
1341 head_df_loop = NEW_ARR_F(entry_edge, 0);
1343 /*head_inversion_node_count = 0;*/
1344 inversion_blocks_in_cc = 0;
1346 /* Use phase to keep copy of nodes from the condition chain. */
1347 phase = new_phase(current_ir_graph, phase_irn_init_default);
1349 /* Search for condition chains and temporarily save the blocks in an array. */
1350 cc_blocks = NEW_ARR_F(ir_node *, 0);
1351 inc_irg_visited(current_ir_graph);
1352 has_cc = find_condition_chain(loop_head);
1354 unmark_not_allowed_cc_blocks();
1355 DEL_ARR_F(cc_blocks);
1357 #if LOOP_IGNORE_NODE_LIMITS
1358 (void) unmark_cc_blocks;
1360 /* Condition chain too large.
1361 * Loop should better be small enough to fit into the cache. */
1362 /* TODO Of course, we should take a small enough cc in the first place,
1363 * which is not that simple. (bin packing) */
1364 if (loop_info.cc_size > opt_params.max_cc_size) {
1365 count_stats(stats.cc_limit_reached);
1369 /* Unmark cc blocks except the head.
1370 * Invert head only for possible unrolling. */
1376 /* We also catch endless loops here,
1377 * because they do not have a condition chain. */
1378 if (inversion_blocks_in_cc < 1) {
1381 "Loop contains %d (less than 1) invertible blocks => No Inversion done.\n",
1382 inversion_blocks_in_cc));
1386 cur_head_outs = NEW_ARR_F(entry_edge, 0);
1388 /* Get all edges pointing into the condition chain. */
1389 irg_walk_graph(current_ir_graph, get_head_outs, NULL, NULL);
1391 /* Do the inversion */
1392 inversion_walk(cur_head_outs);
1394 DEL_ARR_F(cur_head_outs);
1396 /* Duplicated blocks changed doms */
1397 set_irg_doms_inconsistent(current_ir_graph);
1398 /* Loop content changed */
1399 set_irg_loopinfo_inconsistent(current_ir_graph);
1400 /* TODO are they? Depends on set_irn_in and set_irn_n exchange and new_node. */
1401 set_irg_outs_inconsistent(current_ir_graph);
1403 count_stats(stats.inverted);
1408 DEL_ARR_F(cond_chain_entries);
1409 DEL_ARR_F(head_df_loop);
1411 ir_free_resources(current_ir_graph, IR_RESOURCE_BLOCK_MARK);
1414 /* Fix the original loop_heads ins for invariant unrolling case. */
1415 static void unrolling_fix_loop_head_inv(void)
1419 ir_node *proj = new_Proj(loop_info.duff_cond, mode_X, 0);
1420 ir_node *head_pred = get_irn_n(loop_head, loop_info.be_src_pos);
1421 ir_node *loop_condition = get_unroll_copy(head_pred, unroll_nr - 1);
1423 /* Original loop_heads ins are:
1424 * duff block and the own backedge */
1426 ins[0] = loop_condition;
1428 set_irn_in(loop_head, 2, ins);
1429 DB((dbg, LEVEL_4, "Rewire ins of block loophead %N to pred %N and duffs entry %N \n" , loop_head, ins[0], ins[1]));
1431 for_each_phi(loop_head, phi) {
1432 ir_node *pred = get_irn_n(phi, loop_info.be_src_pos);
1433 /* TODO we think it is a phi, but for Mergesort it is not the case.*/
1435 ir_node *last_pred = get_unroll_copy(pred, unroll_nr - 1);
1438 ins[1] = (ir_node*)get_irn_link(phi);
1439 set_irn_in(phi, 2, ins);
1440 DB((dbg, LEVEL_4, "Rewire ins of loophead phi %N to pred %N and duffs entry %N \n" , phi, ins[0], ins[1]));
1444 /* Removes previously created phis with only 1 in. */
1445 static void correct_phis(ir_node *node, void *env)
1449 if (is_Phi(node) && get_irn_arity(node) == 1) {
1453 in[0] = get_irn_n(node, 0);
1455 exch = new_rd_Phi(get_irn_dbg_info(node),
1456 get_nodes_block(node), 1, in,
1457 get_irn_mode(node));
1459 exchange(node, exch);
1463 /* Unrolling: Rewire floating copies. */
1464 static void place_copies(int copies)
1466 ir_node *loophead = loop_head;
1469 int be_src_pos = loop_info.be_src_pos;
1471 /* Serialize loops by fixing their head ins.
1472 * Processed are the copies.
1473 * The original loop is done after that, to keep backedge infos. */
1474 for (c = 0; c < copies; ++c) {
1475 ir_node *upper = get_unroll_copy(loophead, c);
1476 ir_node *lower = get_unroll_copy(loophead, c + 1);
1478 ir_node *topmost_be_block = get_nodes_block(get_irn_n(loophead, be_src_pos));
1480 /* Important: get the preds first and then their copy. */
1481 ir_node *upper_be_block = get_unroll_copy(topmost_be_block, c);
1482 ir_node *new_jmp = new_r_Jmp(upper_be_block);
1483 DB((dbg, LEVEL_5, " place_copies upper %N lower %N\n", upper, lower));
1485 DB((dbg, LEVEL_5, "topmost be block %N \n", topmost_be_block));
1487 if (loop_info.unroll_kind == constant) {
1490 set_irn_in(lower, 1, ins);
1492 for_each_phi(loophead, phi) {
1493 ir_node *topmost_def = get_irn_n(phi, be_src_pos);
1494 ir_node *upper_def = get_unroll_copy(topmost_def, c);
1495 ir_node *lower_phi = get_unroll_copy(phi, c + 1);
1497 /* It is possible, that the value used
1498 * in the OWN backedge path is NOT defined in this loop. */
1499 if (is_in_loop(topmost_def))
1502 ins[0] = topmost_def;
1504 set_irn_in(lower_phi, 1, ins);
1505 /* Need to replace phis with 1 in later. */
1508 /* Invariant case */
1509 /* Every node has 2 ins. One from the duff blocks
1510 * and one from the previously unrolled loop. */
1512 /* Calculate corresponding projection of mod result for this copy c */
1513 ir_node *proj = new_Proj(loop_info.duff_cond, mode_X, unroll_nr - c - 1);
1514 DB((dbg, LEVEL_4, "New duff proj %N\n" , proj));
1518 set_irn_in(lower, 2, ins);
1519 DB((dbg, LEVEL_4, "Rewire ins of Block %N to pred %N and duffs entry %N \n" , lower, ins[0], ins[1]));
1521 for_each_phi(loophead, phi) {
1522 ir_node *topmost_phi_pred = get_irn_n(phi, be_src_pos);
1523 ir_node *upper_phi_pred;
1527 lower_phi = get_unroll_copy(phi, c + 1);
1528 duff_phi = (ir_node*)get_irn_link(phi);
1529 DB((dbg, LEVEL_4, "DD Link of %N is %N\n" , phi, duff_phi));
1532 if (is_in_loop(topmost_phi_pred)) {
1533 upper_phi_pred = get_unroll_copy(topmost_phi_pred, c);
1535 upper_phi_pred = topmost_phi_pred;
1538 ins[0] = upper_phi_pred;
1540 set_irn_in(lower_phi, 2, ins);
1541 DB((dbg, LEVEL_4, "Rewire ins of %N to pred %N and duffs entry %N \n" , lower_phi, ins[0], ins[1]));
1546 /* Reconnect last copy. */
1547 for (i = 0; i < ARR_LEN(loop_entries); ++i) {
1548 entry_edge edge = loop_entries[i];
1549 /* Last copy is at the bottom */
1550 ir_node *new_pred = get_unroll_copy(edge.pred, copies);
1551 set_irn_n(edge.node, edge.pos, new_pred);
1554 /* Fix original loops head.
1555 * Done in the end, as ins and be info were needed before. */
1556 if (loop_info.unroll_kind == constant) {
1558 ir_node *head_pred = get_irn_n(loop_head, be_src_pos);
1559 ir_node *loop_condition = get_unroll_copy(head_pred, unroll_nr - 1);
1561 set_irn_n(loop_head, loop_info.be_src_pos, loop_condition);
1563 for_each_phi(loop_head, phi) {
1564 ir_node *pred = get_irn_n(phi, be_src_pos);
1567 /* It is possible, that the value used
1568 * in the OWN backedge path is NOT assigned in this loop. */
1569 if (is_in_loop(pred))
1570 last_pred = get_unroll_copy(pred, copies);
1573 set_irn_n(phi, be_src_pos, last_pred);
1577 unrolling_fix_loop_head_inv();
1581 /* Copies the cur_loop several times. */
1582 static void copy_loop(entry_edge *cur_loop_outs, int copies)
1586 ir_reserve_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1588 for (c = 0; c < copies; ++c) {
1591 inc_irg_visited(current_ir_graph);
1593 DB((dbg, LEVEL_5, " ### Copy_loop copy nr: %d ###\n", c));
1594 for (i = 0; i < ARR_LEN(cur_loop_outs); ++i) {
1595 entry_edge entry = cur_loop_outs[i];
1596 ir_node *pred = get_irn_n(entry.node, entry.pos);
1598 copy_walk_n(pred, is_in_loop, c + 1);
1602 ir_free_resources(current_ir_graph, IR_RESOURCE_IRN_VISITED);
1606 /* Creates a new phi from the given phi node omitting own bes,
1607 * using be_block as supplier of backedge informations. */
1608 static ir_node *clone_phis_sans_bes(ir_node *phi, ir_node *be_block, ir_node *dest_block)
1611 int arity = get_irn_arity(phi);
1615 assert(get_irn_arity(phi) == get_irn_arity(be_block));
1616 assert(is_Phi(phi));
1618 ins = NEW_ARR_F(ir_node *, arity);
1619 for (i = 0; i < arity; ++i) {
1620 if (! is_own_backedge(be_block, i)) {
1621 ins[c] = get_irn_n(phi, i);
1626 newphi = new_r_Phi(dest_block, c, ins, get_irn_mode(phi));
1628 set_irn_link(phi, newphi);
1629 DB((dbg, LEVEL_4, "Linking for duffs device %N to %N\n", phi, newphi));
1634 /* Creates a new block from the given block node omitting own bes,
1635 * using be_block as supplier of backedge informations. */
1636 static ir_node *clone_block_sans_bes(ir_node *node, ir_node *be_block)
1639 int arity = get_irn_arity(node);
1642 assert(get_irn_arity(node) == get_irn_arity(be_block));
1643 assert(is_Block(node));
1645 NEW_ARR_A(ir_node *, ins, arity);
1646 for (i = 0; i < arity; ++i) {
1647 if (! is_own_backedge(be_block, i)) {
1648 ins[c] = get_irn_n(node, i);
1653 return new_Block(c, ins);
1656 /* Creates a structure to calculate absolute value of node op.
1657 * Returns mux node with absolute value. */
1658 static ir_node *new_Abs(ir_node *op, ir_mode *mode)
1660 ir_graph *irg = get_irn_irg(op);
1661 ir_node *block = get_nodes_block(op);
1662 ir_node *zero = new_r_Const(irg, get_mode_null(mode));
1663 ir_node *cmp = new_r_Cmp(block, op, zero, ir_relation_less);
1664 ir_node *minus_op = new_r_Minus(block, op, mode);
1665 ir_node *mux = new_r_Mux(block, cmp, op, minus_op, mode);
1671 /* Creates blocks for duffs device, using previously obtained
1672 * informations about the iv.
1674 static void create_duffs_block(void)
1678 ir_node *block1, *count_block, *duff_block;
1679 ir_node *ems, *ems_mod, *ems_div, *ems_mod_proj, *cmp_null,
1680 *ems_mode_cond, *x_true, *x_false, *const_null;
1681 ir_node *true_val, *false_val;
1684 ir_node *duff_mod, *proj, *cond;
1686 ir_node *count, *correction, *unroll_c;
1687 ir_node *cmp_bad_count, *good_count, *bad_count, *count_phi, *bad_count_neg;
1690 mode = get_irn_mode(loop_info.end_val);
1691 const_null = new_Const(get_mode_null(mode));
1694 * 1. Calculate first approach to count.
1695 * Condition: (end - start) % step == 0 */
1696 block1 = clone_block_sans_bes(loop_head, loop_head);
1697 DB((dbg, LEVEL_4, "Duff block 1 %N\n", block1));
1699 /* Create loop entry phis in first duff block
1700 * as it becomes the loops preheader */
1701 for_each_phi(loop_head, phi) {
1702 /* Returns phis pred if phi would have arity 1*/
1703 ir_node *new_phi = clone_phis_sans_bes(phi, loop_head, block1);
1705 DB((dbg, LEVEL_4, "HEAD %N phi %N\n", loop_head, phi));
1706 DB((dbg, LEVEL_4, "BLOCK1 %N phi %N\n", block1, new_phi));
1709 ems = new_r_Sub(block1, loop_info.end_val, loop_info.start_val,
1710 get_irn_mode(loop_info.end_val));
1711 DB((dbg, LEVEL_4, "BLOCK1 sub %N\n", ems));
1714 ems = new_Sub(loop_info.end_val, loop_info.start_val,
1715 get_irn_mode(loop_info.end_val));
1717 DB((dbg, LEVEL_4, "mod ins %N %N\n", ems, loop_info.step));
1718 ems_mod = new_r_Mod(block1,
1723 op_pin_state_pinned);
1724 ems_div = new_r_Div(block1,
1729 op_pin_state_pinned);
1731 DB((dbg, LEVEL_4, "New module node %N\n", ems_mod));
1733 ems_mod_proj = new_r_Proj(ems_mod, mode_Iu, pn_Mod_res);
1734 cmp_null = new_r_Cmp(block1, ems_mod_proj, const_null, ir_relation_less);
1735 ems_mode_cond = new_r_Cond(block1, cmp_null);
1737 /* ems % step == 0 */
1738 x_true = new_r_Proj(ems_mode_cond, mode_X, pn_Cond_true);
1739 /* ems % step != 0 */
1740 x_false = new_r_Proj(ems_mode_cond, mode_X, pn_Cond_false);
1743 * Assures, duffs device receives a valid count.
1745 * decreasing: count < 0
1746 * increasing: count > 0
1751 count_block = new_Block(2, ins);
1752 DB((dbg, LEVEL_4, "Duff block 2 %N\n", count_block));
1755 /* Increase loop-taken-count depending on the loop condition
1756 * uses the latest iv to compare to. */
1757 if (loop_info.latest_value == 1) {
1758 /* ems % step == 0 : +0 */
1759 true_val = new_Const(get_mode_null(mode));
1760 /* ems % step != 0 : +1 */
1761 false_val = new_Const(get_mode_one(mode));
1763 ir_tarval *tv_two = new_tarval_from_long(2, mode);
1764 /* ems % step == 0 : +1 */
1765 true_val = new_Const(get_mode_one(mode));
1766 /* ems % step != 0 : +2 */
1767 false_val = new_Const(tv_two);
1773 correction = new_r_Phi(count_block, 2, ins, mode);
1775 count = new_r_Proj(ems_div, mode, pn_Div_res);
1777 /* (end - start) / step + correction */
1778 count = new_Add(count, correction, mode);
1780 /* We preconditioned the loop to be tail-controlled.
1781 * So, if count is something 'wrong' like 0,
1782 * negative/positive (depending on step direction),
1783 * we may take the loop once (tail-contr.) and leave it
1784 * to the existing condition, to break; */
1786 /* Depending on step direction, we have to check for > or < 0 */
1787 if (loop_info.decreasing == 1) {
1788 cmp_bad_count = new_r_Cmp(count_block, count, const_null,
1791 cmp_bad_count = new_r_Cmp(count_block, count, const_null,
1792 ir_relation_greater);
1795 bad_count_neg = new_r_Cond(count_block, cmp_bad_count);
1796 good_count = new_Proj(bad_count_neg, mode_X, pn_Cond_true);
1797 bad_count = new_Proj(ems_mode_cond, mode_X, pn_Cond_false);
1800 * Contains module to decide which loop to start from. */
1802 ins[0] = good_count;
1804 duff_block = new_Block(2, ins);
1805 DB((dbg, LEVEL_4, "Duff block 3 %N\n", duff_block));
1807 /* Get absolute value */
1808 ins[0] = new_Abs(count, mode);
1809 /* Manually feed the aforementioned count = 1 (bad case)*/
1810 ins[1] = new_Const(get_mode_one(mode));
1811 count_phi = new_r_Phi(duff_block, 2, ins, mode);
1813 unroll_c = new_Const(new_tarval_from_long((long)unroll_nr, mode));
1815 /* count % unroll_nr */
1816 duff_mod = new_r_Mod(duff_block,
1821 op_pin_state_pinned);
1824 proj = new_Proj(duff_mod, mode, pn_Mod_res);
1825 /* condition does NOT create itself in the block of the proj! */
1826 cond = new_r_Cond(duff_block, proj);
1828 loop_info.duff_cond = cond;
1831 /* Returns 1 if given node is not in loop,
1832 * or if it is a phi of the loop head with only loop invariant defs.
1834 static unsigned is_loop_invariant_def(ir_node *node)
1838 if (! is_in_loop(node)) {
1839 DB((dbg, LEVEL_4, "Not in loop %N\n", node));
1840 /* || is_Const(node) || is_SymConst(node)) {*/
1844 /* If this is a phi of the loophead shared by more than 1 loop,
1845 * we need to check if all defs are not in the loop. */
1848 block = get_nodes_block(node);
1850 /* To prevent unexpected situations. */
1851 if (block != loop_head) {
1855 for (i = 0; i < get_irn_arity(node); ++i) {
1856 /* Check if all bes are just loopbacks. */
1857 if (is_own_backedge(block, i) && get_irn_n(node, i) != node)
1860 DB((dbg, LEVEL_4, "invar %N\n", node));
1863 DB((dbg, LEVEL_4, "Not invar %N\n", node));
1868 /* Returns 1 if one pred of node is invariant and the other is not.
1869 * invar_pred and other are set analogously. */
1870 static unsigned get_invariant_pred(ir_node *node, ir_node **invar_pred, ir_node **other)
1872 ir_node *pred0 = get_irn_n(node, 0);
1873 ir_node *pred1 = get_irn_n(node, 1);
1878 if (is_loop_invariant_def(pred0)) {
1879 DB((dbg, LEVEL_4, "pred0 invar %N\n", pred0));
1880 *invar_pred = pred0;
1884 if (is_loop_invariant_def(pred1)) {
1885 DB((dbg, LEVEL_4, "pred1 invar %N\n", pred1));
1887 if (*invar_pred != NULL) {
1888 /* RETURN. We do not want both preds to be invariant. */
1893 *invar_pred = pred1;
1896 DB((dbg, LEVEL_4, "pred1 not invar %N\n", pred1));
1898 if (*invar_pred != NULL)
1905 /* Starts from a phi that may belong to an iv.
1906 * If an add forms a loop with iteration_phi,
1907 * and add uses a constant, 1 is returned
1908 * and 'start' as well as 'add' are sane. */
1909 static unsigned get_start_and_add(ir_node *iteration_phi, unrolling_kind_flag role)
1912 ir_node *found_add = loop_info.add;
1913 int arity = get_irn_arity(iteration_phi);
1915 DB((dbg, LEVEL_4, "Find start and add from %N\n", iteration_phi));
1917 for (i = 0; i < arity; ++i) {
1919 /* Find start_val which needs to be pred of the iteration_phi.
1920 * If start_val already known, sanity check. */
1921 if (!is_backedge(get_nodes_block(loop_info.iteration_phi), i)) {
1922 ir_node *found_start_val = get_irn_n(loop_info.iteration_phi, i);
1924 DB((dbg, LEVEL_4, "found_start_val %N\n", found_start_val));
1926 /* We already found a start_val it has to be always the same. */
1927 if (loop_info.start_val && found_start_val != loop_info.start_val)
1930 if ((role == constant) && !(is_SymConst(found_start_val) || is_Const(found_start_val)))
1932 else if((role == constant) && !(is_loop_invariant_def(found_start_val)))
1935 loop_info.start_val = found_start_val;
1938 /* The phi has to be in the loop head.
1939 * Follow all own backedges. Every value supplied from these preds of the phi
1940 * needs to origin from the same add. */
1941 if (is_own_backedge(get_nodes_block(loop_info.iteration_phi), i)) {
1942 ir_node *new_found = get_irn_n(loop_info.iteration_phi,i);
1944 DB((dbg, LEVEL_4, "is add? %N\n", new_found));
1946 if (! (is_Add(new_found) || is_Sub(new_found)) || (found_add && found_add != new_found))
1949 found_add = new_found;
1953 loop_info.add = found_add;
1959 /* Returns 1 if one pred of node is a const value and the other is not.
1960 * const_pred and other are set analogously. */
1961 static unsigned get_const_pred(ir_node *node, ir_node **const_pred, ir_node **other)
1963 ir_node *pred0 = get_irn_n(node, 0);
1964 ir_node *pred1 = get_irn_n(node, 1);
1966 DB((dbg, LEVEL_4, "Checking for constant pred of %N\n", node));
1971 /*DB((dbg, LEVEL_4, "is %N const\n", pred0));*/
1972 if (is_Const(pred0) || is_SymConst(pred0)) {
1973 *const_pred = pred0;
1977 /*DB((dbg, LEVEL_4, "is %N const\n", pred1));*/
1978 if (is_Const(pred1) || is_SymConst(pred1)) {
1979 if (*const_pred != NULL) {
1980 /* RETURN. We do not want both preds to be constant. */
1985 *const_pred = pred1;
1988 if (*const_pred == NULL)
1994 /* Returns 1 if loop exits within 2 steps of the iv.
1995 * Norm_proj means we do not exit the loop.*/
1996 static unsigned simulate_next(ir_tarval **count_tar,
1997 ir_tarval *stepped, ir_tarval *step_tar, ir_tarval *end_tar,
1998 ir_relation norm_proj)
2002 DB((dbg, LEVEL_4, "Loop taken if (stepped)%ld %s (end)%ld ",
2003 get_tarval_long(stepped),
2004 get_relation_string((norm_proj)),
2005 get_tarval_long(end_tar)));
2006 DB((dbg, LEVEL_4, "comparing latest value %d\n", loop_info.latest_value));
2008 /* If current iv does not stay in the loop,
2009 * this run satisfied the exit condition. */
2010 if (! (tarval_cmp(stepped, end_tar) & norm_proj))
2013 DB((dbg, LEVEL_4, "Result: (stepped)%ld IS %s (end)%ld\n",
2014 get_tarval_long(stepped),
2015 get_relation_string(tarval_cmp(stepped, end_tar)),
2016 get_tarval_long(end_tar)));
2019 if (is_Add(loop_info.add))
2020 next = tarval_add(stepped, step_tar);
2023 next = tarval_sub(stepped, step_tar, get_irn_mode(loop_info.end_val));
2025 DB((dbg, LEVEL_4, "Loop taken if %ld %s %ld ",
2026 get_tarval_long(next),
2027 get_relation_string(norm_proj),
2028 get_tarval_long(end_tar)));
2029 DB((dbg, LEVEL_4, "comparing latest value %d\n", loop_info.latest_value));
2031 /* Increase steps. */
2032 *count_tar = tarval_add(*count_tar, get_tarval_one(get_tarval_mode(*count_tar)));
2034 /* Next has to fail the loop condition, or we will never exit. */
2035 if (! (tarval_cmp(next, end_tar) & norm_proj))
2041 /* Check if loop meets requirements for a 'simple loop':
2042 * - Exactly one cf out
2044 * - Max nodes after unrolling
2048 * Returns Projection of cmp node or NULL; */
2049 static ir_node *is_simple_loop(void)
2052 ir_node *loop_block, *exit_block, *projx, *cond, *cmp;
2054 /* Maximum of one condition, and no endless loops. */
2055 if (loop_info.cf_outs != 1)
2058 DB((dbg, LEVEL_4, "1 loop exit\n"));
2060 #if LOOP_IGNORE_NODE_LIMITS
2061 /* Ignore loop size. Probably not wise in other than testcases. */
2062 loop_info.max_unroll = 40;
2064 /* Calculate maximum unroll_nr keeping node count below limit. */
2065 loop_info.max_unroll = (int)((double)opt_params.max_unrolled_loop_size / (double)loop_info.nodes);
2066 if (loop_info.max_unroll < 2) {
2067 count_stats(stats.too_large);
2073 DB((dbg, LEVEL_4, "maximum unroll factor %u, to not exceed node limit \n",
2074 opt_params.max_unrolled_loop_size));
2076 arity = get_irn_arity(loop_head);
2077 /* RETURN if we have more than 1 be. */
2078 /* Get my backedges without alien bes. */
2080 for (i = 0; i < arity; ++i) {
2081 ir_node *pred = get_irn_n(loop_head, i);
2082 if (is_own_backedge(loop_head, i)) {
2084 /* Our simple loops may have only one backedge. */
2087 loop_block = get_nodes_block(pred);
2088 loop_info.be_src_pos = i;
2093 DB((dbg, LEVEL_4, "loop has 1 own backedge.\n"));
2095 exit_block = get_nodes_block(loop_info.cf_out.pred);
2096 /* The loop has to be tail-controlled.
2097 * This can be changed/improved,
2098 * but we would need a duff iv. */
2099 if (exit_block != loop_block)
2102 DB((dbg, LEVEL_4, "tail-controlled loop.\n"));
2104 /* find value on which loop exit depends */
2105 projx = loop_info.cf_out.pred;
2106 cond = get_irn_n(projx, 0);
2107 cmp = get_irn_n(cond, 0);
2112 DB((dbg, LEVEL_5, "projection is %s\n", get_relation_string(get_Proj_proj(projx))));
2114 switch(get_Proj_proj(projx)) {
2116 loop_info.exit_cond = 0;
2119 loop_info.exit_cond = 1;
2122 panic("Cond Proj_proj other than true/false");
2125 DB((dbg, LEVEL_4, "Valid Cmp.\n"));
2129 /* Returns 1 if all nodes are mode_Iu or mode_Is. */
2130 static unsigned are_mode_I(ir_node *n1, ir_node* n2, ir_node *n3)
2132 ir_mode *m1 = get_irn_mode(n1);
2133 ir_mode *m2 = get_irn_mode(n2);
2134 ir_mode *m3 = get_irn_mode(n3);
2136 if ((m1 == mode_Iu && m2 == mode_Iu && m3 == mode_Iu) ||
2137 (m1 == mode_Is && m2 == mode_Is && m3 == mode_Is))
2143 /* Checks if cur_loop is a simple tail-controlled counting loop
2144 * with start and end value loop invariant, step constant. */
2145 static unsigned get_unroll_decision_invariant(void)
2148 ir_node *projres, *loop_condition, *iteration_path;
2149 unsigned success, is_latest_val;
2150 ir_tarval *step_tar;
2154 /* RETURN if loop is not 'simple' */
2155 projres = is_simple_loop();
2156 if (projres == NULL)
2159 /* Use a minimal size for the invariant unrolled loop,
2160 * as duffs device produces overhead */
2161 if (loop_info.nodes < opt_params.invar_unrolling_min_size)
2164 loop_condition = get_irn_n(projres, 0);
2166 success = get_invariant_pred(loop_condition, &loop_info.end_val, &iteration_path);
2167 DB((dbg, LEVEL_4, "pred invar %d\n", success));
2172 DB((dbg, LEVEL_4, "Invariant End_val %N, other %N\n", loop_info.end_val, iteration_path));
2174 /* We may find the add or the phi first.
2175 * Until now we only have end_val. */
2176 if (is_Add(iteration_path) || is_Sub(iteration_path)) {
2178 /* We test against the latest value of the iv. */
2181 loop_info.add = iteration_path;
2182 DB((dbg, LEVEL_4, "Case 1: Got add %N (maybe not sane)\n", loop_info.add));
2184 /* Preds of the add should be step and the iteration_phi */
2185 success = get_const_pred(loop_info.add, &loop_info.step, &loop_info.iteration_phi);
2189 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2191 if (! is_Phi(loop_info.iteration_phi))
2194 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2197 * Does necessary sanity check of add, if it is already set. */
2198 success = get_start_and_add(loop_info.iteration_phi, invariant);
2202 DB((dbg, LEVEL_4, "Got start A %N\n", loop_info.start_val));
2204 } else if (is_Phi(iteration_path)) {
2205 ir_node *new_iteration_phi;
2207 /* We compare with the value the iv had entering this run. */
2210 loop_info.iteration_phi = iteration_path;
2211 DB((dbg, LEVEL_4, "Case 2: Got phi %N\n", loop_info.iteration_phi));
2213 /* Find start_val and add-node.
2214 * Does necessary sanity check of add, if it is already set. */
2215 success = get_start_and_add(loop_info.iteration_phi, invariant);
2219 DB((dbg, LEVEL_4, "Got start B %N\n", loop_info.start_val));
2220 DB((dbg, LEVEL_4, "Got add or sub %N\n", loop_info.add));
2222 success = get_const_pred(loop_info.add, &loop_info.step, &new_iteration_phi);
2226 DB((dbg, LEVEL_4, "Got step (B) %N\n", loop_info.step));
2228 if (loop_info.iteration_phi != new_iteration_phi)
2235 mode = get_irn_mode(loop_info.end_val);
2237 DB((dbg, LEVEL_4, "start %N, end %N, step %N\n",
2238 loop_info.start_val, loop_info.end_val, loop_info.step));
2240 if (mode != mode_Is && mode != mode_Iu)
2243 /* TODO necessary? */
2244 if (!are_mode_I(loop_info.start_val, loop_info.step, loop_info.end_val))
2247 DB((dbg, LEVEL_4, "mode integer\n"));
2249 step_tar = get_Const_tarval(loop_info.step);
2251 if (tarval_is_null(step_tar)) {
2252 /* TODO Might be worth a warning. */
2256 DB((dbg, LEVEL_4, "step is not 0\n"));
2258 create_duffs_block();
2260 return loop_info.max_unroll;
2263 /* Returns unroll factor,
2264 * given maximum unroll factor and number of loop passes. */
2265 static unsigned get_preferred_factor_constant(ir_tarval *count_tar)
2267 ir_tarval *tar_6, *tar_5, *tar_4, *tar_3, *tar_2;
2269 ir_mode *mode = get_irn_mode(loop_info.end_val);
2271 tar_6 = new_tarval_from_long(6, mode);
2272 tar_5 = new_tarval_from_long(5, mode);
2273 tar_4 = new_tarval_from_long(4, mode);
2274 tar_3 = new_tarval_from_long(3, mode);
2275 tar_2 = new_tarval_from_long(2, mode);
2277 /* loop passes % {6, 5, 4, 3, 2} == 0 */
2278 if (tarval_is_null(tarval_mod(count_tar, tar_6)))
2280 else if (tarval_is_null(tarval_mod(count_tar, tar_5)))
2282 else if (tarval_is_null(tarval_mod(count_tar, tar_4)))
2284 else if (tarval_is_null(tarval_mod(count_tar, tar_3)))
2286 else if (tarval_is_null(tarval_mod(count_tar, tar_2)))
2289 /* gcd(max_unroll, count_tar) */
2290 int a = loop_info.max_unroll;
2291 int b = (int)get_tarval_long(count_tar);
2294 DB((dbg, LEVEL_4, "gcd of max_unroll %d and count_tar %d: ", a, b));
2301 DB((dbg, LEVEL_4, "%d\n", a));
2305 DB((dbg, LEVEL_4, "preferred unroll factor %d\n", prefer));
2308 * If our preference is greater than the allowed unroll factor
2309 * we either might reduce the preferred factor and prevent a duffs device block,
2310 * or create a duffs device block, from which in this case (constants only)
2311 * we know the startloop at compiletime.
2312 * The latter yields the following graphs.
2313 * but for code generation we would want to use graph A.
2314 * The graphs are equivalent. So, we can only reduce the preferred factor.
2324 if (prefer <= loop_info.max_unroll)
2329 if (loop_info.max_unroll >= 3)
2331 else if (loop_info.max_unroll >= 2)
2337 if (loop_info.max_unroll >= 2)
2348 /* Check if cur_loop is a simple counting loop.
2349 * Start, step and end are constants.
2350 * TODO The whole constant case should use procedures similar to
2351 * the invariant case, as they are more versatile. */
2353 static unsigned get_unroll_decision_constant(void)
2355 ir_node *cmp, *iteration_path;
2356 unsigned success, is_latest_val;
2357 ir_tarval *start_tar, *end_tar, *step_tar, *diff_tar, *count_tar;
2359 ir_relation proj_proj, norm_proj;
2362 /* RETURN if loop is not 'simple' */
2363 cmp = is_simple_loop();
2367 /* One in of the loop condition needs to be loop invariant. => end_val
2368 * The other in is assigned by an add. => add
2369 * The add uses a loop invariant value => step
2370 * and a phi with a loop invariant start_val and the add node as ins.
2382 success = get_const_pred(cmp, &loop_info.end_val, &iteration_path);
2386 DB((dbg, LEVEL_4, "End_val %N, other %N\n", loop_info.end_val, iteration_path));
2388 /* We may find the add or the phi first.
2389 * Until now we only have end_val. */
2390 if (is_Add(iteration_path) || is_Sub(iteration_path)) {
2392 /* We test against the latest value of the iv. */
2395 loop_info.add = iteration_path;
2396 DB((dbg, LEVEL_4, "Case 2: Got add %N (maybe not sane)\n", loop_info.add));
2398 /* Preds of the add should be step and the iteration_phi */
2399 success = get_const_pred(loop_info.add, &loop_info.step, &loop_info.iteration_phi);
2403 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2405 if (! is_Phi(loop_info.iteration_phi))
2408 DB((dbg, LEVEL_4, "Got phi %N\n", loop_info.iteration_phi));
2411 * Does necessary sanity check of add, if it is already set. */
2412 success = get_start_and_add(loop_info.iteration_phi, constant);
2416 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2418 } else if (is_Phi(iteration_path)) {
2419 ir_node *new_iteration_phi;
2421 /* We compare with the value the iv had entering this run. */
2424 loop_info.iteration_phi = iteration_path;
2425 DB((dbg, LEVEL_4, "Case 1: Got phi %N \n", loop_info.iteration_phi));
2427 /* Find start_val and add-node.
2428 * Does necessary sanity check of add, if it is already set. */
2429 success = get_start_and_add(loop_info.iteration_phi, constant);
2433 DB((dbg, LEVEL_4, "Got start %N\n", loop_info.start_val));
2434 DB((dbg, LEVEL_4, "Got add or sub %N\n", loop_info.add));
2436 success = get_const_pred(loop_info.add, &loop_info.step, &new_iteration_phi);
2440 DB((dbg, LEVEL_4, "Got step %N\n", loop_info.step));
2442 if (loop_info.iteration_phi != new_iteration_phi)
2450 mode = get_irn_mode(loop_info.end_val);
2452 DB((dbg, LEVEL_4, "start %N, end %N, step %N\n",
2453 loop_info.start_val, loop_info.end_val, loop_info.step));
2455 if (mode != mode_Is && mode != mode_Iu)
2458 /* TODO necessary? */
2459 if (!are_mode_I(loop_info.start_val, loop_info.step, loop_info.end_val))
2462 DB((dbg, LEVEL_4, "mode integer\n"));
2464 end_tar = get_Const_tarval(loop_info.end_val);
2465 start_tar = get_Const_tarval(loop_info.start_val);
2466 step_tar = get_Const_tarval(loop_info.step);
2468 if (tarval_is_null(step_tar))
2469 /* TODO Might be worth a warning. */
2472 DB((dbg, LEVEL_4, "step is not 0\n"));
2474 if ((!tarval_is_negative(step_tar)) ^ (!is_Sub(loop_info.add)))
2475 loop_info.decreasing = 1;
2477 diff_tar = tarval_sub(end_tar, start_tar, mode);
2479 /* We need at least count_tar steps to be close to end_val, maybe more.
2480 * No way, that we have gone too many steps.
2481 * This represents the 'latest value'.
2482 * (If condition checks against latest value, is checked later) */
2483 count_tar = tarval_div(diff_tar, step_tar);
2485 /* Iv will not pass end_val (except overflows).
2486 * Nothing done, as it would yield to no advantage. */
2487 if (tarval_is_negative(count_tar)) {
2488 DB((dbg, LEVEL_4, "Loop is endless or never taken."));
2489 /* TODO Might be worth a warning. */
2493 count_stats(stats.u_simple_counting_loop);
2495 loop_info.latest_value = is_latest_val;
2498 if (! is_simple_counting_loop(&count_tar))
2502 /* stepped can be negative, if step < 0 */
2503 stepped = tarval_mul(count_tar, step_tar);
2505 /* step as close to end_val as possible, */
2506 /* |stepped| <= |end_tar|, and dist(stepped, end_tar) is smaller than a step. */
2507 if (is_Sub(loop_info.add))
2508 stepped = tarval_sub(start_tar, stepped, mode_Is);
2510 stepped = tarval_add(start_tar, stepped);
2512 DB((dbg, LEVEL_4, "stepped to %ld\n", get_tarval_long(stepped)));
2514 proj_proj = get_Cmp_relation(cmp);
2515 /* Assure that norm_proj is the stay-in-loop case. */
2516 if (loop_info.exit_cond == 1)
2517 norm_proj = get_negated_relation(proj_proj);
2519 norm_proj = proj_proj;
2521 DB((dbg, LEVEL_4, "normalized projection %s\n", get_relation_string(norm_proj)));
2522 /* Executed at most once (stay in counting loop if a Eq b) */
2523 if (norm_proj == ir_relation_equal)
2524 /* TODO Might be worth a warning. */
2527 /* calculates next values and increases count_tar according to it */
2528 success = simulate_next(&count_tar, stepped, step_tar, end_tar, norm_proj);
2532 /* We run loop once more, if we compare to the
2533 * not yet in-/decreased iv. */
2534 if (is_latest_val == 0) {
2535 DB((dbg, LEVEL_4, "condition uses not latest iv value\n"));
2536 count_tar = tarval_add(count_tar, get_tarval_one(mode));
2539 DB((dbg, LEVEL_4, "loop taken %ld times\n", get_tarval_long(count_tar)));
2541 /* Assure the loop is taken at least 1 time. */
2542 if (tarval_is_null(count_tar)) {
2543 /* TODO Might be worth a warning. */
2547 loop_info.count_tar = count_tar;
2548 return get_preferred_factor_constant(count_tar);
2554 static void unroll_loop(void)
2557 if (! (loop_info.nodes > 0))
2560 #if LOOP_IGNORE_NODE_LIMITS
2561 DB((dbg, LEVEL_1, "WARNING: Loop node limitations ignored."));
2563 if (loop_info.nodes > opt_params.max_unrolled_loop_size) {
2564 DB((dbg, LEVEL_2, "Nodes %d > allowed nodes %d\n",
2565 loop_info.nodes, opt_params.max_unrolled_loop_size));
2566 count_stats(stats.too_large);
2570 if (loop_info.calls > 0) {
2571 DB((dbg, LEVEL_2, "Calls %d > allowed calls 0\n",
2573 count_stats(stats.calls_limit);
2580 /* get_unroll_decision_constant and invariant are completely
2581 * independent for flexibility.
2582 * Some checks may be performed twice. */
2584 /* constant case? */
2585 if (opt_params.allow_const_unrolling)
2586 unroll_nr = get_unroll_decision_constant();
2587 if (unroll_nr > 1) {
2588 loop_info.unroll_kind = constant;
2591 /* invariant case? */
2592 if (opt_params.allow_invar_unrolling)
2593 unroll_nr = get_unroll_decision_invariant();
2595 loop_info.unroll_kind = invariant;
2598 DB((dbg, LEVEL_2, " *** Unrolling %d times ***\n", unroll_nr));
2600 if (unroll_nr > 1) {
2601 loop_entries = NEW_ARR_F(entry_edge, 0);
2604 irg_walk_graph(current_ir_graph, get_loop_entries, NULL, NULL);
2606 if (loop_info.unroll_kind == constant) {
2607 if ((int)get_tarval_long(loop_info.count_tar) == unroll_nr)
2608 loop_info.needs_backedge = 0;
2610 loop_info.needs_backedge = 1;
2612 loop_info.needs_backedge = 1;
2615 /* Use phase to keep copy of nodes from the condition chain. */
2616 phase = new_phase(current_ir_graph, phase_irn_init_default);
2618 /* Copies the loop */
2619 copy_loop(loop_entries, unroll_nr - 1);
2621 /* Line up the floating copies. */
2622 place_copies(unroll_nr - 1);
2624 /* Remove phis with 1 in
2625 * If there were no nested phis, this would not be necessary.
2626 * Avoiding the creation in the first place
2627 * leads to complex special cases. */
2628 irg_walk_graph(current_ir_graph, correct_phis, NULL, NULL);
2630 if (loop_info.unroll_kind == constant)
2631 count_stats(stats.constant_unroll);
2633 count_stats(stats.invariant_unroll);
2635 set_irg_doms_inconsistent(current_ir_graph);
2636 set_irg_loopinfo_inconsistent(current_ir_graph);
2638 set_irg_outs_inconsistent(current_ir_graph);
2640 DEL_ARR_F(loop_entries);
2645 /* Analyzes the loop, and checks if size is within allowed range.
2646 * Decides if loop will be processed. */
2647 static void init_analyze(ir_loop *loop)
2652 loop_head_valid = 1;
2654 /* Reset loop info */
2655 memset(&loop_info, 0, sizeof(loop_info_t));
2657 DB((dbg, LEVEL_1, " >>>> current loop includes node %N <<<\n",
2658 get_loop_node(loop, 0)));
2660 /* Collect loop informations: head, node counts. */
2661 irg_walk_graph(current_ir_graph, get_loop_info, NULL, NULL);
2663 /* RETURN if there is no valid head */
2664 if (!loop_head || !loop_head_valid) {
2665 DB((dbg, LEVEL_1, "No valid loop head. Nothing done.\n"));
2668 DB((dbg, LEVEL_1, "Loophead: %N\n", loop_head));
2671 if (loop_info.branches > opt_params.max_branches) {
2672 DB((dbg, LEVEL_1, "Branches %d > allowed branches %d\n",
2673 loop_info.branches, opt_params.max_branches));
2674 count_stats(stats.calls_limit);
2679 case loop_op_inversion:
2683 case loop_op_unrolling:
2688 panic("Loop optimization not implemented.");
2690 DB((dbg, LEVEL_1, " <<<< end of loop with node %N >>>>\n",
2691 get_loop_node(loop, 0)));
2694 /* Find innermost loops and add them to loops. */
2695 static void find_innermost_loop(ir_loop *loop)
2697 /* descend into sons */
2698 size_t sons = get_loop_n_sons(loop);
2701 ARR_APP1(ir_loop *, loops, loop);
2704 for (s = 0; s < sons; ++s) {
2705 find_innermost_loop(get_loop_son(loop, s));
2710 static void set_loop_params(void)
2712 opt_params.max_loop_size = 100;
2713 opt_params.depth_adaption = -50;
2714 opt_params.count_phi = 1;
2715 opt_params.count_proj = 0;
2716 opt_params.allowed_calls = 0;
2718 opt_params.max_cc_size = 5;
2721 opt_params.allow_const_unrolling = 1;
2722 opt_params.allow_invar_unrolling = 0;
2724 opt_params.invar_unrolling_min_size = 20;
2725 opt_params.max_unrolled_loop_size = 400;
2726 opt_params.max_branches = 9999;
2729 /* Assure preconditions are met and go through all loops. */
2730 void loop_optimization(ir_graph *irg)
2738 /* Reset stats for this procedure */
2742 set_current_ir_graph(irg);
2745 assure_irg_outs(irg);
2747 /* NOTE: sets only the loop attribute of blocks, not nodes */
2748 /* NOTE: Kills links */
2749 assure_cf_loop(irg);
2751 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
2752 collect_phiprojs(irg);
2753 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2755 loop = get_irg_loop(irg);
2756 sons = get_loop_n_sons(loop);
2758 loops = NEW_ARR_F(ir_loop *, 0);
2759 /* List all inner loops */
2760 for (nr = 0; nr < sons; ++nr) {
2761 find_innermost_loop(get_loop_son(loop, nr));
2764 ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2765 /* Set all links to NULL */
2766 irg_walk_graph(current_ir_graph, reset_link, NULL, NULL);
2768 for (i = 0; i < ARR_LEN(loops); ++i) {
2769 ir_loop *loop = loops[i];
2771 count_stats(stats.loops);
2773 /* Analyze and handle loop */
2776 /* Copied blocks do not have their phi list yet */
2777 collect_phiprojs(irg);
2779 /* Set links to NULL
2780 * TODO Still necessary? */
2781 irg_walk_graph(current_ir_graph, reset_link, NULL, NULL);
2787 ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2788 ir_free_resources(irg, IR_RESOURCE_PHI_LIST);
2791 void do_loop_unrolling(ir_graph *irg)
2793 loop_op = loop_op_unrolling;
2795 DB((dbg, LEVEL_1, " >>> unrolling (Startnode %N) <<<\n",
2796 get_irg_start(irg)));
2798 loop_optimization(irg);
2800 DB((dbg, LEVEL_1, " >>> unrolling done (Startnode %N) <<<\n",
2801 get_irg_start(irg)));
2804 void do_loop_inversion(ir_graph *irg)
2806 loop_op = loop_op_inversion;
2808 DB((dbg, LEVEL_1, " >>> inversion (Startnode %N) <<<\n",
2809 get_irg_start(irg)));
2811 loop_optimization(irg);
2813 assure_cf_loop(irg);
2815 DB((dbg, LEVEL_1, " >>> inversion done (Startnode %N) <<<\n",
2816 get_irg_start(irg)));
2819 void do_loop_peeling(ir_graph *irg)
2821 loop_op = loop_op_peeling;
2823 DB((dbg, LEVEL_1, " >>> peeling (Startnode %N) <<<\n",
2824 get_irg_start(irg)));
2826 loop_optimization(irg);
2828 DB((dbg, LEVEL_1, " >>> peeling done (Startnode %N) <<<\n",
2829 get_irg_start(irg)));
2833 ir_graph_pass_t *loop_inversion_pass(const char *name)
2835 return def_graph_pass(name ? name : "loop_inversion", do_loop_inversion);
2838 ir_graph_pass_t *loop_unroll_pass(const char *name)
2840 return def_graph_pass(name ? name : "loop_unroll", do_loop_unrolling);
2843 ir_graph_pass_t *loop_peeling_pass(const char *name)
2845 return def_graph_pass(name ? name : "loop_peeling", do_loop_peeling);
2848 void firm_init_loop_opt(void)
2850 FIRM_DBG_REGISTER(dbg, "firm.opt.loop");