1 /* High-level loop manipulation functions.
2 Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
22 #include "coretypes.h"
27 #include "hard-reg-set.h"
28 #include "basic-block.h"
30 #include "diagnostic.h"
31 #include "tree-flow.h"
32 #include "tree-dump.h"
35 #include "tree-pass.h"
36 #include "cfglayout.h"
37 #include "tree-scalar-evolution.h"
39 #include "tree-inline.h"
40 #include "langhooks.h"
42 /* Creates an induction variable with value BASE + STEP * iteration in LOOP.
43 It is expected that neither BASE nor STEP are shared with other expressions
44 (unless the sharing rules allow this). Use VAR as a base var_decl for it
45 (if NULL, a new temporary will be created). The increment will occur at
46 INCR_POS (after it if AFTER is true, before it otherwise). INCR_POS and
47 AFTER can be computed using standard_iv_increment_position. The ssa versions
48 of the variable before and after increment will be stored in VAR_BEFORE and
49 VAR_AFTER (unless they are NULL). */
52 create_iv (tree base, tree step, tree var, struct loop *loop,
53 gimple_stmt_iterator *incr_pos, bool after,
54 tree *var_before, tree *var_after)
60 enum tree_code incr_op = PLUS_EXPR;
61 edge pe = loop_preheader_edge (loop);
65 var = create_tmp_var (TREE_TYPE (base), "ivtmp");
66 add_referenced_var (var);
69 vb = make_ssa_name (var, NULL);
72 va = make_ssa_name (var, NULL);
76 /* For easier readability of the created code, produce MINUS_EXPRs
78 if (TREE_CODE (step) == INTEGER_CST)
80 if (TYPE_UNSIGNED (TREE_TYPE (step)))
82 step1 = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
83 if (tree_int_cst_lt (step1, step))
93 if (!tree_expr_nonnegative_warnv_p (step, &ovf)
94 && may_negate_without_overflow_p (step))
97 step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
101 if (POINTER_TYPE_P (TREE_TYPE (base)))
103 if (TREE_CODE (base) == ADDR_EXPR)
104 mark_addressable (TREE_OPERAND (base, 0));
105 step = fold_convert (sizetype, step);
106 if (incr_op == MINUS_EXPR)
107 step = fold_build1 (NEGATE_EXPR, sizetype, step);
108 incr_op = POINTER_PLUS_EXPR;
110 /* Gimplify the step if necessary. We put the computations in front of the
111 loop (i.e. the step should be loop invariant). */
112 step = force_gimple_operand (step, &stmts, true, NULL_TREE);
114 gsi_insert_seq_on_edge_immediate (pe, stmts);
116 stmt = gimple_build_assign_with_ops (incr_op, va, vb, step);
118 gsi_insert_after (incr_pos, stmt, GSI_NEW_STMT);
120 gsi_insert_before (incr_pos, stmt, GSI_NEW_STMT);
122 initial = force_gimple_operand (base, &stmts, true, var);
124 gsi_insert_seq_on_edge_immediate (pe, stmts);
126 stmt = create_phi_node (vb, loop->header);
127 SSA_NAME_DEF_STMT (vb) = stmt;
128 add_phi_arg (stmt, initial, loop_preheader_edge (loop));
129 add_phi_arg (stmt, va, loop_latch_edge (loop));
132 /* Add exit phis for the USE on EXIT. */
135 add_exit_phis_edge (basic_block exit, tree use)
137 gimple phi, def_stmt = SSA_NAME_DEF_STMT (use);
138 basic_block def_bb = gimple_bb (def_stmt);
139 struct loop *def_loop;
143 /* Check that some of the edges entering the EXIT block exits a loop in
144 that USE is defined. */
145 FOR_EACH_EDGE (e, ei, exit->preds)
147 def_loop = find_common_loop (def_bb->loop_father, e->src->loop_father);
148 if (!flow_bb_inside_loop_p (def_loop, e->dest))
155 phi = create_phi_node (use, exit);
156 create_new_def_for (gimple_phi_result (phi), phi,
157 gimple_phi_result_ptr (phi));
158 FOR_EACH_EDGE (e, ei, exit->preds)
159 add_phi_arg (phi, use, e);
162 /* Add exit phis for VAR that is used in LIVEIN.
163 Exits of the loops are stored in EXITS. */
166 add_exit_phis_var (tree var, bitmap livein, bitmap exits)
170 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
173 if (is_gimple_reg (var))
174 bitmap_clear_bit (livein, def_bb->index);
176 bitmap_set_bit (livein, def_bb->index);
178 def = BITMAP_ALLOC (NULL);
179 bitmap_set_bit (def, def_bb->index);
180 compute_global_livein (livein, def);
183 EXECUTE_IF_AND_IN_BITMAP (exits, livein, 0, index, bi)
185 add_exit_phis_edge (BASIC_BLOCK (index), var);
189 /* Add exit phis for the names marked in NAMES_TO_RENAME.
190 Exits of the loops are stored in EXITS. Sets of blocks where the ssa
191 names are used are stored in USE_BLOCKS. */
194 add_exit_phis (bitmap names_to_rename, bitmap *use_blocks, bitmap loop_exits)
199 EXECUTE_IF_SET_IN_BITMAP (names_to_rename, 0, i, bi)
201 add_exit_phis_var (ssa_name (i), use_blocks[i], loop_exits);
205 /* Returns a bitmap of all loop exit edge targets. */
208 get_loops_exits (void)
210 bitmap exits = BITMAP_ALLOC (NULL);
217 FOR_EACH_EDGE (e, ei, bb->preds)
218 if (e->src != ENTRY_BLOCK_PTR
219 && !flow_bb_inside_loop_p (e->src->loop_father, bb))
221 bitmap_set_bit (exits, bb->index);
229 /* For USE in BB, if it is used outside of the loop it is defined in,
230 mark it for rewrite. Record basic block BB where it is used
231 to USE_BLOCKS. Record the ssa name index to NEED_PHIS bitmap. */
234 find_uses_to_rename_use (basic_block bb, tree use, bitmap *use_blocks,
239 struct loop *def_loop;
241 if (TREE_CODE (use) != SSA_NAME)
244 /* We don't need to keep virtual operands in loop-closed form. */
245 if (!is_gimple_reg (use))
248 ver = SSA_NAME_VERSION (use);
249 def_bb = gimple_bb (SSA_NAME_DEF_STMT (use));
252 def_loop = def_bb->loop_father;
254 /* If the definition is not inside a loop, it is not interesting. */
255 if (!loop_outer (def_loop))
258 /* If the use is not outside of the loop it is defined in, it is not
260 if (flow_bb_inside_loop_p (def_loop, bb))
263 if (!use_blocks[ver])
264 use_blocks[ver] = BITMAP_ALLOC (NULL);
265 bitmap_set_bit (use_blocks[ver], bb->index);
267 bitmap_set_bit (need_phis, ver);
270 /* For uses in STMT, mark names that are used outside of the loop they are
271 defined to rewrite. Record the set of blocks in that the ssa
272 names are defined to USE_BLOCKS and the ssa names themselves to
276 find_uses_to_rename_stmt (gimple stmt, bitmap *use_blocks, bitmap need_phis)
280 basic_block bb = gimple_bb (stmt);
282 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_USES)
283 find_uses_to_rename_use (bb, var, use_blocks, need_phis);
286 /* Marks names that are used in BB and outside of the loop they are
287 defined in for rewrite. Records the set of blocks in that the ssa
288 names are defined to USE_BLOCKS. Record the SSA names that will
289 need exit PHIs in NEED_PHIS. */
292 find_uses_to_rename_bb (basic_block bb, bitmap *use_blocks, bitmap need_phis)
294 gimple_stmt_iterator bsi;
298 FOR_EACH_EDGE (e, ei, bb->succs)
299 for (bsi = gsi_start_phis (e->dest); !gsi_end_p (bsi); gsi_next (&bsi))
300 find_uses_to_rename_use (bb, PHI_ARG_DEF_FROM_EDGE (gsi_stmt (bsi), e),
301 use_blocks, need_phis);
303 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
304 find_uses_to_rename_stmt (gsi_stmt (bsi), use_blocks, need_phis);
307 /* Marks names that are used outside of the loop they are defined in
308 for rewrite. Records the set of blocks in that the ssa
309 names are defined to USE_BLOCKS. If CHANGED_BBS is not NULL,
310 scan only blocks in this set. */
313 find_uses_to_rename (bitmap changed_bbs, bitmap *use_blocks, bitmap need_phis)
319 if (changed_bbs && !bitmap_empty_p (changed_bbs))
321 EXECUTE_IF_SET_IN_BITMAP (changed_bbs, 0, index, bi)
323 find_uses_to_rename_bb (BASIC_BLOCK (index), use_blocks, need_phis);
330 find_uses_to_rename_bb (bb, use_blocks, need_phis);
335 /* Rewrites the program into a loop closed ssa form -- i.e. inserts extra
336 phi nodes to ensure that no variable is used outside the loop it is
339 This strengthening of the basic ssa form has several advantages:
341 1) Updating it during unrolling/peeling/versioning is trivial, since
342 we do not need to care about the uses outside of the loop.
343 2) The behavior of all uses of an induction variable is the same.
344 Without this, you need to distinguish the case when the variable
345 is used outside of the loop it is defined in, for example
347 for (i = 0; i < 100; i++)
349 for (j = 0; j < 100; j++)
357 Looking from the outer loop with the normal SSA form, the first use of k
358 is not well-behaved, while the second one is an induction variable with
361 If CHANGED_BBS is not NULL, we look for uses outside loops only in
362 the basic blocks in this set.
364 UPDATE_FLAG is used in the call to update_ssa. See
365 TODO_update_ssa* for documentation. */
368 rewrite_into_loop_closed_ssa (bitmap changed_bbs, unsigned update_flag)
372 unsigned i, old_num_ssa_names;
373 bitmap names_to_rename;
375 loops_state_set (LOOP_CLOSED_SSA);
376 if (number_of_loops () <= 1)
379 loop_exits = get_loops_exits ();
380 names_to_rename = BITMAP_ALLOC (NULL);
382 /* If the pass has caused the SSA form to be out-of-date, update it
384 update_ssa (update_flag);
386 old_num_ssa_names = num_ssa_names;
387 use_blocks = XCNEWVEC (bitmap, old_num_ssa_names);
389 /* Find the uses outside loops. */
390 find_uses_to_rename (changed_bbs, use_blocks, names_to_rename);
392 /* Add the PHI nodes on exits of the loops for the names we need to
394 add_exit_phis (names_to_rename, use_blocks, loop_exits);
396 for (i = 0; i < old_num_ssa_names; i++)
397 BITMAP_FREE (use_blocks[i]);
399 BITMAP_FREE (loop_exits);
400 BITMAP_FREE (names_to_rename);
402 /* Fix up all the names found to be used outside their original
404 update_ssa (TODO_update_ssa);
407 /* Check invariants of the loop closed ssa form for the USE in BB. */
410 check_loop_closed_ssa_use (basic_block bb, tree use)
415 if (TREE_CODE (use) != SSA_NAME || !is_gimple_reg (use))
418 def = SSA_NAME_DEF_STMT (use);
419 def_bb = gimple_bb (def);
421 || flow_bb_inside_loop_p (def_bb->loop_father, bb));
424 /* Checks invariants of loop closed ssa form in statement STMT in BB. */
427 check_loop_closed_ssa_stmt (basic_block bb, gimple stmt)
432 FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_USES)
433 check_loop_closed_ssa_use (bb, var);
436 /* Checks that invariants of the loop closed ssa form are preserved. */
439 verify_loop_closed_ssa (void)
442 gimple_stmt_iterator bsi;
447 if (number_of_loops () <= 1)
454 for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
456 phi = gsi_stmt (bsi);
457 FOR_EACH_EDGE (e, ei, bb->preds)
458 check_loop_closed_ssa_use (e->src,
459 PHI_ARG_DEF_FROM_EDGE (phi, e));
462 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
463 check_loop_closed_ssa_stmt (bb, gsi_stmt (bsi));
467 /* Split loop exit edge EXIT. The things are a bit complicated by a need to
468 preserve the loop closed ssa form. The newly created block is returned. */
471 split_loop_exit_edge (edge exit)
473 basic_block dest = exit->dest;
474 basic_block bb = split_edge (exit);
478 gimple_stmt_iterator psi;
480 for (psi = gsi_start_phis (dest); !gsi_end_p (psi); gsi_next (&psi))
482 phi = gsi_stmt (psi);
483 op_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, single_succ_edge (bb));
485 name = USE_FROM_PTR (op_p);
487 /* If the argument of the PHI node is a constant, we do not need
488 to keep it inside loop. */
489 if (TREE_CODE (name) != SSA_NAME)
492 /* Otherwise create an auxiliary phi node that will copy the value
493 of the SSA name out of the loop. */
494 new_name = duplicate_ssa_name (name, NULL);
495 new_phi = create_phi_node (new_name, bb);
496 SSA_NAME_DEF_STMT (new_name) = new_phi;
497 add_phi_arg (new_phi, name, exit);
498 SET_USE (op_p, new_name);
504 /* Returns the basic block in that statements should be emitted for induction
505 variables incremented at the end of the LOOP. */
508 ip_end_pos (struct loop *loop)
513 /* Returns the basic block in that statements should be emitted for induction
514 variables incremented just before exit condition of a LOOP. */
517 ip_normal_pos (struct loop *loop)
523 if (!single_pred_p (loop->latch))
526 bb = single_pred (loop->latch);
527 last = last_stmt (bb);
529 || gimple_code (last) != GIMPLE_COND)
532 exit = EDGE_SUCC (bb, 0);
533 if (exit->dest == loop->latch)
534 exit = EDGE_SUCC (bb, 1);
536 if (flow_bb_inside_loop_p (loop, exit->dest))
542 /* Stores the standard position for induction variable increment in LOOP
543 (just before the exit condition if it is available and latch block is empty,
544 end of the latch block otherwise) to BSI. INSERT_AFTER is set to true if
545 the increment should be inserted after *BSI. */
548 standard_iv_increment_position (struct loop *loop, gimple_stmt_iterator *bsi,
551 basic_block bb = ip_normal_pos (loop), latch = ip_end_pos (loop);
552 gimple last = last_stmt (latch);
555 || (last && gimple_code (last) != GIMPLE_LABEL))
557 *bsi = gsi_last_bb (latch);
558 *insert_after = true;
562 *bsi = gsi_last_bb (bb);
563 *insert_after = false;
567 /* Copies phi node arguments for duplicated blocks. The index of the first
568 duplicated block is FIRST_NEW_BLOCK. */
571 copy_phi_node_args (unsigned first_new_block)
575 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
576 BASIC_BLOCK (i)->flags |= BB_DUPLICATED;
578 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
579 add_phi_args_after_copy_bb (BASIC_BLOCK (i));
581 for (i = first_new_block; i < (unsigned) last_basic_block; i++)
582 BASIC_BLOCK (i)->flags &= ~BB_DUPLICATED;
586 /* The same as cfgloopmanip.c:duplicate_loop_to_header_edge, but also
587 updates the PHI nodes at start of the copied region. In order to
588 achieve this, only loops whose exits all lead to the same location
591 Notice that we do not completely update the SSA web after
592 duplication. The caller is responsible for calling update_ssa
593 after the loop has been duplicated. */
596 gimple_duplicate_loop_to_header_edge (struct loop *loop, edge e,
597 unsigned int ndupl, sbitmap wont_exit,
598 edge orig, VEC (edge, heap) **to_remove,
601 unsigned first_new_block;
603 if (!loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
605 if (!loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS))
608 #ifdef ENABLE_CHECKING
609 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
610 verify_loop_closed_ssa ();
613 first_new_block = last_basic_block;
614 if (!duplicate_loop_to_header_edge (loop, e, ndupl, wont_exit,
615 orig, to_remove, flags))
618 /* Readd the removed phi args for e. */
619 flush_pending_stmts (e);
621 /* Copy the phi node arguments. */
622 copy_phi_node_args (first_new_block);
629 /* Returns true if we can unroll LOOP FACTOR times. Number
630 of iterations of the loop is returned in NITER. */
633 can_unroll_loop_p (struct loop *loop, unsigned factor,
634 struct tree_niter_desc *niter)
638 /* Check whether unrolling is possible. We only want to unroll loops
639 for that we are able to determine number of iterations. We also
640 want to split the extra iterations of the loop from its end,
641 therefore we require that the loop has precisely one
644 exit = single_dom_exit (loop);
648 if (!number_of_iterations_exit (loop, exit, niter, false)
649 || niter->cmp == ERROR_MARK
650 /* Scalar evolutions analysis might have copy propagated
651 the abnormal ssa names into these expressions, hence
652 emitting the computations based on them during loop
653 unrolling might create overlapping life ranges for
654 them, and failures in out-of-ssa. */
655 || contains_abnormal_ssa_name_p (niter->may_be_zero)
656 || contains_abnormal_ssa_name_p (niter->control.base)
657 || contains_abnormal_ssa_name_p (niter->control.step)
658 || contains_abnormal_ssa_name_p (niter->bound))
661 /* And of course, we must be able to duplicate the loop. */
662 if (!can_duplicate_loop_p (loop))
665 /* The final loop should be small enough. */
666 if (tree_num_loop_insns (loop, &eni_size_weights) * factor
667 > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS))
673 /* Determines the conditions that control execution of LOOP unrolled FACTOR
674 times. DESC is number of iterations of LOOP. ENTER_COND is set to
675 condition that must be true if the main loop can be entered.
676 EXIT_BASE, EXIT_STEP, EXIT_CMP and EXIT_BOUND are set to values describing
677 how the exit from the unrolled loop should be controlled. */
680 determine_exit_conditions (struct loop *loop, struct tree_niter_desc *desc,
681 unsigned factor, tree *enter_cond,
682 tree *exit_base, tree *exit_step,
683 enum tree_code *exit_cmp, tree *exit_bound)
686 tree base = desc->control.base;
687 tree step = desc->control.step;
688 tree bound = desc->bound;
689 tree type = TREE_TYPE (step);
691 tree min = lower_bound_in_type (type, type);
692 tree max = upper_bound_in_type (type, type);
693 enum tree_code cmp = desc->cmp;
694 tree cond = boolean_true_node, assum;
696 /* For pointers, do the arithmetics in the type of step (sizetype). */
697 base = fold_convert (type, base);
698 bound = fold_convert (type, bound);
700 *enter_cond = boolean_false_node;
701 *exit_base = NULL_TREE;
702 *exit_step = NULL_TREE;
703 *exit_cmp = ERROR_MARK;
704 *exit_bound = NULL_TREE;
705 gcc_assert (cmp != ERROR_MARK);
707 /* We only need to be correct when we answer question
708 "Do at least FACTOR more iterations remain?" in the unrolled loop.
709 Thus, transforming BASE + STEP * i <> BOUND to
710 BASE + STEP * i < BOUND is ok. */
713 if (tree_int_cst_sign_bit (step))
718 else if (cmp == LT_EXPR)
720 gcc_assert (!tree_int_cst_sign_bit (step));
722 else if (cmp == GT_EXPR)
724 gcc_assert (tree_int_cst_sign_bit (step));
729 /* The main body of the loop may be entered iff:
731 1) desc->may_be_zero is false.
732 2) it is possible to check that there are at least FACTOR iterations
733 of the loop, i.e., BOUND - step * FACTOR does not overflow.
734 3) # of iterations is at least FACTOR */
736 if (!integer_zerop (desc->may_be_zero))
737 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
738 invert_truthvalue (desc->may_be_zero),
741 bigstep = fold_build2 (MULT_EXPR, type, step,
742 build_int_cst_type (type, factor));
743 delta = fold_build2 (MINUS_EXPR, type, bigstep, step);
745 assum = fold_build2 (GE_EXPR, boolean_type_node,
747 fold_build2 (PLUS_EXPR, type, min, delta));
749 assum = fold_build2 (LE_EXPR, boolean_type_node,
751 fold_build2 (PLUS_EXPR, type, max, delta));
752 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
754 bound = fold_build2 (MINUS_EXPR, type, bound, delta);
755 assum = fold_build2 (cmp, boolean_type_node, base, bound);
756 cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
758 cond = force_gimple_operand (unshare_expr (cond), &stmts, false, NULL_TREE);
760 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
761 /* cond now may be a gimple comparison, which would be OK, but also any
762 other gimple rhs (say a && b). In this case we need to force it to
764 if (!is_gimple_condexpr (cond))
766 cond = force_gimple_operand (cond, &stmts, true, NULL_TREE);
768 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
772 base = force_gimple_operand (unshare_expr (base), &stmts, true, NULL_TREE);
774 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
775 bound = force_gimple_operand (unshare_expr (bound), &stmts, true, NULL_TREE);
777 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
780 *exit_step = bigstep;
785 /* Scales the frequencies of all basic blocks in LOOP that are strictly
786 dominated by BB by NUM/DEN. */
789 scale_dominated_blocks_in_loop (struct loop *loop, basic_block bb,
797 for (son = first_dom_son (CDI_DOMINATORS, bb);
799 son = next_dom_son (CDI_DOMINATORS, son))
801 if (!flow_bb_inside_loop_p (loop, son))
803 scale_bbs_frequencies_int (&son, 1, num, den);
804 scale_dominated_blocks_in_loop (loop, son, num, den);
808 /* Unroll LOOP FACTOR times. DESC describes number of iterations of LOOP.
809 EXIT is the exit of the loop to that DESC corresponds.
811 If N is number of iterations of the loop and MAY_BE_ZERO is the condition
812 under that loop exits in the first iteration even if N != 0,
816 x = phi (init, next);
824 becomes (with possibly the exit conditions formulated a bit differently,
825 avoiding the need to create a new iv):
827 if (MAY_BE_ZERO || N < FACTOR)
832 x = phi (init, next);
843 } while (N >= FACTOR);
846 init' = phi (init, x);
850 x = phi (init', next);
858 Before the loop is unrolled, TRANSFORM is called for it (only for the
859 unrolled loop, but not for its versioned copy). DATA is passed to
862 /* Probability in % that the unrolled loop is entered. Just a guess. */
863 #define PROB_UNROLLED_LOOP_ENTERED 90
866 tree_transform_and_unroll_loop (struct loop *loop, unsigned factor,
867 edge exit, struct tree_niter_desc *desc,
868 transform_callback transform,
872 tree ctr_before, ctr_after;
873 tree enter_main_cond, exit_base, exit_step, exit_bound;
874 enum tree_code exit_cmp;
875 gimple phi_old_loop, phi_new_loop, phi_rest;
876 gimple_stmt_iterator psi_old_loop, psi_new_loop;
877 tree init, next, new_init, var;
878 struct loop *new_loop;
879 basic_block rest, exit_bb;
880 edge old_entry, new_entry, old_latch, precond_edge, new_exit;
882 gimple_stmt_iterator bsi;
885 unsigned est_niter, prob_entry, scale_unrolled, scale_rest, freq_e, freq_h;
886 unsigned new_est_niter, i, prob;
887 unsigned irr = loop_preheader_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP;
889 VEC (edge, heap) *to_remove = NULL;
891 est_niter = expected_loop_iterations (loop);
892 determine_exit_conditions (loop, desc, factor,
893 &enter_main_cond, &exit_base, &exit_step,
894 &exit_cmp, &exit_bound);
896 /* Let us assume that the unrolled loop is quite likely to be entered. */
897 if (integer_nonzerop (enter_main_cond))
898 prob_entry = REG_BR_PROB_BASE;
900 prob_entry = PROB_UNROLLED_LOOP_ENTERED * REG_BR_PROB_BASE / 100;
902 /* The values for scales should keep profile consistent, and somewhat close
905 TODO: The current value of SCALE_REST makes it appear that the loop that
906 is created by splitting the remaining iterations of the unrolled loop is
907 executed the same number of times as the original loop, and with the same
908 frequencies, which is obviously wrong. This does not appear to cause
909 problems, so we do not bother with fixing it for now. To make the profile
910 correct, we would need to change the probability of the exit edge of the
911 loop, and recompute the distribution of frequencies in its body because
912 of this change (scale the frequencies of blocks before and after the exit
913 by appropriate factors). */
914 scale_unrolled = prob_entry;
915 scale_rest = REG_BR_PROB_BASE;
917 new_loop = loop_version (loop, enter_main_cond, NULL,
918 prob_entry, scale_unrolled, scale_rest, true);
919 gcc_assert (new_loop != NULL);
920 update_ssa (TODO_update_ssa);
922 /* Determine the probability of the exit edge of the unrolled loop. */
923 new_est_niter = est_niter / factor;
925 /* Without profile feedback, loops for that we do not know a better estimate
926 are assumed to roll 10 times. When we unroll such loop, it appears to
927 roll too little, and it may even seem to be cold. To avoid this, we
928 ensure that the created loop appears to roll at least 5 times (but at
929 most as many times as before unrolling). */
930 if (new_est_niter < 5)
933 new_est_niter = est_niter;
938 /* Prepare the cfg and update the phi nodes. Move the loop exit to the
939 loop latch (and make its condition dummy, for the moment). */
940 rest = loop_preheader_edge (new_loop)->src;
941 precond_edge = single_pred_edge (rest);
942 split_edge (loop_latch_edge (loop));
943 exit_bb = single_pred (loop->latch);
945 /* Since the exit edge will be removed, the frequency of all the blocks
946 in the loop that are dominated by it must be scaled by
947 1 / (1 - exit->probability). */
948 scale_dominated_blocks_in_loop (loop, exit->src,
950 REG_BR_PROB_BASE - exit->probability);
952 bsi = gsi_last_bb (exit_bb);
953 exit_if = gimple_build_cond (EQ_EXPR, integer_zero_node,
955 NULL_TREE, NULL_TREE);
957 gsi_insert_after (&bsi, exit_if, GSI_NEW_STMT);
958 new_exit = make_edge (exit_bb, rest, EDGE_FALSE_VALUE | irr);
959 rescan_loop_exit (new_exit, true, false);
961 /* Set the probability of new exit to the same of the old one. Fix
962 the frequency of the latch block, by scaling it back by
963 1 - exit->probability. */
964 new_exit->count = exit->count;
965 new_exit->probability = exit->probability;
966 new_nonexit = single_pred_edge (loop->latch);
967 new_nonexit->probability = REG_BR_PROB_BASE - exit->probability;
968 new_nonexit->flags = EDGE_TRUE_VALUE;
969 new_nonexit->count -= exit->count;
970 if (new_nonexit->count < 0)
971 new_nonexit->count = 0;
972 scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
975 old_entry = loop_preheader_edge (loop);
976 new_entry = loop_preheader_edge (new_loop);
977 old_latch = loop_latch_edge (loop);
978 for (psi_old_loop = gsi_start_phis (loop->header),
979 psi_new_loop = gsi_start_phis (new_loop->header);
980 !gsi_end_p (psi_old_loop);
981 gsi_next (&psi_old_loop), gsi_next (&psi_new_loop))
983 phi_old_loop = gsi_stmt (psi_old_loop);
984 phi_new_loop = gsi_stmt (psi_new_loop);
986 init = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_entry);
987 op = PHI_ARG_DEF_PTR_FROM_EDGE (phi_new_loop, new_entry);
988 gcc_assert (operand_equal_for_phi_arg_p (init, USE_FROM_PTR (op)));
989 next = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_latch);
991 /* Prefer using original variable as a base for the new ssa name.
992 This is necessary for virtual ops, and useful in order to avoid
993 losing debug info for real ops. */
994 if (TREE_CODE (next) == SSA_NAME
995 && useless_type_conversion_p (TREE_TYPE (next),
997 var = SSA_NAME_VAR (next);
998 else if (TREE_CODE (init) == SSA_NAME
999 && useless_type_conversion_p (TREE_TYPE (init),
1001 var = SSA_NAME_VAR (init);
1002 else if (useless_type_conversion_p (TREE_TYPE (next), TREE_TYPE (init)))
1004 var = create_tmp_var (TREE_TYPE (next), "unrinittmp");
1005 add_referenced_var (var);
1009 var = create_tmp_var (TREE_TYPE (init), "unrinittmp");
1010 add_referenced_var (var);
1013 new_init = make_ssa_name (var, NULL);
1014 phi_rest = create_phi_node (new_init, rest);
1015 SSA_NAME_DEF_STMT (new_init) = phi_rest;
1017 add_phi_arg (phi_rest, init, precond_edge);
1018 add_phi_arg (phi_rest, next, new_exit);
1019 SET_USE (op, new_init);
1024 /* Transform the loop. */
1026 (*transform) (loop, data);
1028 /* Unroll the loop and remove the exits in all iterations except for the
1030 wont_exit = sbitmap_alloc (factor);
1031 sbitmap_ones (wont_exit);
1032 RESET_BIT (wont_exit, factor - 1);
1034 ok = gimple_duplicate_loop_to_header_edge
1035 (loop, loop_latch_edge (loop), factor - 1,
1036 wont_exit, new_exit, &to_remove, DLTHE_FLAG_UPDATE_FREQ);
1040 for (i = 0; VEC_iterate (edge, to_remove, i, e); i++)
1042 ok = remove_path (e);
1045 VEC_free (edge, heap, to_remove);
1046 update_ssa (TODO_update_ssa);
1048 /* Ensure that the frequencies in the loop match the new estimated
1049 number of iterations, and change the probability of the new
1051 freq_h = loop->header->frequency;
1052 freq_e = EDGE_FREQUENCY (loop_preheader_edge (loop));
1054 scale_loop_frequencies (loop, freq_e * (new_est_niter + 1), freq_h);
1056 exit_bb = single_pred (loop->latch);
1057 new_exit = find_edge (exit_bb, rest);
1058 new_exit->count = loop_preheader_edge (loop)->count;
1059 new_exit->probability = REG_BR_PROB_BASE / (new_est_niter + 1);
1061 rest->count += new_exit->count;
1062 rest->frequency += EDGE_FREQUENCY (new_exit);
1064 new_nonexit = single_pred_edge (loop->latch);
1065 prob = new_nonexit->probability;
1066 new_nonexit->probability = REG_BR_PROB_BASE - new_exit->probability;
1067 new_nonexit->count = exit_bb->count - new_exit->count;
1068 if (new_nonexit->count < 0)
1069 new_nonexit->count = 0;
1071 scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
1074 /* Finally create the new counter for number of iterations and add the new
1075 exit instruction. */
1076 bsi = gsi_last_bb (exit_bb);
1077 exit_if = gsi_stmt (bsi);
1078 create_iv (exit_base, exit_step, NULL_TREE, loop,
1079 &bsi, false, &ctr_before, &ctr_after);
1080 gimple_cond_set_code (exit_if, exit_cmp);
1081 gimple_cond_set_lhs (exit_if, ctr_after);
1082 gimple_cond_set_rhs (exit_if, exit_bound);
1083 update_stmt (exit_if);
1085 #ifdef ENABLE_CHECKING
1086 verify_flow_info ();
1087 verify_dominators (CDI_DOMINATORS);
1088 verify_loop_structure ();
1089 verify_loop_closed_ssa ();
1093 /* Wrapper over tree_transform_and_unroll_loop for case we do not
1094 want to transform the loop before unrolling. The meaning
1095 of the arguments is the same as for tree_transform_and_unroll_loop. */
1098 tree_unroll_loop (struct loop *loop, unsigned factor,
1099 edge exit, struct tree_niter_desc *desc)
1101 tree_transform_and_unroll_loop (loop, factor, exit, desc,
1105 /* Rewrite the phi node at position PSI in function of the main
1106 induction variable MAIN_IV and insert the generated code at GSI. */
1109 rewrite_phi_with_iv (loop_p loop,
1110 gimple_stmt_iterator *psi,
1111 gimple_stmt_iterator *gsi,
1115 gimple stmt, phi = gsi_stmt (*psi);
1116 tree atype, mtype, val, res = PHI_RESULT (phi);
1118 if (!is_gimple_reg (res) || res == main_iv)
1124 if (!simple_iv (loop, loop, res, &iv, true))
1130 remove_phi_node (psi, false);
1132 atype = TREE_TYPE (res);
1133 mtype = POINTER_TYPE_P (atype) ? sizetype : atype;
1134 val = fold_build2 (MULT_EXPR, mtype, unshare_expr (iv.step),
1135 fold_convert (mtype, main_iv));
1136 val = fold_build2 (POINTER_TYPE_P (atype)
1137 ? POINTER_PLUS_EXPR : PLUS_EXPR,
1138 atype, unshare_expr (iv.base), val);
1139 val = force_gimple_operand_gsi (gsi, val, false, NULL_TREE, true,
1141 stmt = gimple_build_assign (res, val);
1142 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1143 SSA_NAME_DEF_STMT (res) = stmt;
1146 /* Rewrite all the phi nodes of LOOP in function of the main induction
1147 variable MAIN_IV. */
1150 rewrite_all_phi_nodes_with_iv (loop_p loop, tree main_iv)
1153 basic_block *bbs = get_loop_body_in_dom_order (loop);
1154 gimple_stmt_iterator psi;
1156 for (i = 0; i < loop->num_nodes; i++)
1158 basic_block bb = bbs[i];
1159 gimple_stmt_iterator gsi = gsi_after_labels (bb);
1161 if (bb->loop_father != loop)
1164 for (psi = gsi_start_phis (bb); !gsi_end_p (psi); )
1165 rewrite_phi_with_iv (loop, &psi, &gsi, main_iv);
1171 /* Bases all the induction variables in LOOP on a single induction
1172 variable (unsigned with base 0 and step 1), whose final value is
1173 compared with *NIT. When the IV type precision has to be larger
1174 than *NIT type precision, *NIT is converted to the larger type, the
1175 conversion code is inserted before the loop, and *NIT is updated to
1176 the new definition. The induction variable is incremented in the
1177 loop latch. Return the induction variable that was created. */
1180 canonicalize_loop_ivs (struct loop *loop, tree *nit)
1182 unsigned precision = TYPE_PRECISION (TREE_TYPE (*nit));
1183 unsigned original_precision = precision;
1184 tree type, var_before;
1185 gimple_stmt_iterator gsi, psi;
1187 edge exit = single_dom_exit (loop);
1190 for (psi = gsi_start_phis (loop->header);
1191 !gsi_end_p (psi); gsi_next (&psi))
1193 gimple phi = gsi_stmt (psi);
1194 tree res = PHI_RESULT (phi);
1196 if (is_gimple_reg (res) && TYPE_PRECISION (TREE_TYPE (res)) > precision)
1197 precision = TYPE_PRECISION (TREE_TYPE (res));
1200 type = lang_hooks.types.type_for_size (precision, 1);
1202 if (original_precision != precision)
1204 *nit = fold_convert (type, *nit);
1205 *nit = force_gimple_operand (*nit, &stmts, true, NULL_TREE);
1207 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1210 gsi = gsi_last_bb (loop->latch);
1211 create_iv (build_int_cst_type (type, 0), build_int_cst (type, 1), NULL_TREE,
1212 loop, &gsi, true, &var_before, NULL);
1214 rewrite_all_phi_nodes_with_iv (loop, var_before);
1216 stmt = last_stmt (exit->src);
1217 /* Make the loop exit if the control condition is not satisfied. */
1218 if (exit->flags & EDGE_TRUE_VALUE)
1222 extract_true_false_edges_from_block (exit->src, &te, &fe);
1223 te->flags = EDGE_FALSE_VALUE;
1224 fe->flags = EDGE_TRUE_VALUE;
1226 gimple_cond_set_code (stmt, LT_EXPR);
1227 gimple_cond_set_lhs (stmt, var_before);
1228 gimple_cond_set_rhs (stmt, *nit);