New vectorizer messages; message format change.
[official-gcc.git] / gcc / tree-ssa-loop-ivcanon.c
blobf2acc4c15f1c949db53b53b2caeb02da1eda30e4
1 /* Induction variable canonicalization and loop peeling.
2 Copyright (C) 2004-2013 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
9 later version.
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
14 for more details.
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/>. */
20 /* This pass detects the loops that iterate a constant number of times,
21 adds a canonical induction variable (step -1, tested against 0)
22 and replaces the exit test. This enables the less powerful rtl
23 level analysis to use this information.
25 This might spoil the code in some cases (by increasing register pressure).
26 Note that in the case the new variable is not needed, ivopts will get rid
27 of it, so it might only be a problem when there are no other linear induction
28 variables. In that case the created optimization possibilities are likely
29 to pay up.
31 Additionally in case we detect that it is beneficial to unroll the
32 loop completely, we do it right here to expose the optimization
33 possibilities to the following passes. */
35 #include "config.h"
36 #include "system.h"
37 #include "coretypes.h"
38 #include "tm.h"
39 #include "tree.h"
40 #include "tm_p.h"
41 #include "basic-block.h"
42 #include "gimple-pretty-print.h"
43 #include "tree-flow.h"
44 #include "cfgloop.h"
45 #include "tree-pass.h"
46 #include "tree-chrec.h"
47 #include "tree-scalar-evolution.h"
48 #include "params.h"
49 #include "flags.h"
50 #include "tree-inline.h"
51 #include "target.h"
53 /* Specifies types of loops that may be unrolled. */
55 enum unroll_level
57 UL_SINGLE_ITER, /* Only loops that exit immediately in the first
58 iteration. */
59 UL_NO_GROWTH, /* Only loops whose unrolling will not cause increase
60 of code size. */
61 UL_ALL /* All suitable loops. */
64 /* Adds a canonical induction variable to LOOP iterating NITER times. EXIT
65 is the exit edge whose condition is replaced. */
67 static void
68 create_canonical_iv (struct loop *loop, edge exit, tree niter)
70 edge in;
71 tree type, var;
72 gimple cond;
73 gimple_stmt_iterator incr_at;
74 enum tree_code cmp;
76 if (dump_file && (dump_flags & TDF_DETAILS))
78 fprintf (dump_file, "Added canonical iv to loop %d, ", loop->num);
79 print_generic_expr (dump_file, niter, TDF_SLIM);
80 fprintf (dump_file, " iterations.\n");
83 cond = last_stmt (exit->src);
84 in = EDGE_SUCC (exit->src, 0);
85 if (in == exit)
86 in = EDGE_SUCC (exit->src, 1);
88 /* Note that we do not need to worry about overflows, since
89 type of niter is always unsigned and all comparisons are
90 just for equality/nonequality -- i.e. everything works
91 with a modulo arithmetics. */
93 type = TREE_TYPE (niter);
94 niter = fold_build2 (PLUS_EXPR, type,
95 niter,
96 build_int_cst (type, 1));
97 incr_at = gsi_last_bb (in->src);
98 create_iv (niter,
99 build_int_cst (type, -1),
100 NULL_TREE, loop,
101 &incr_at, false, NULL, &var);
103 cmp = (exit->flags & EDGE_TRUE_VALUE) ? EQ_EXPR : NE_EXPR;
104 gimple_cond_set_code (cond, cmp);
105 gimple_cond_set_lhs (cond, var);
106 gimple_cond_set_rhs (cond, build_int_cst (type, 0));
107 update_stmt (cond);
110 /* Computes an estimated number of insns in LOOP, weighted by WEIGHTS. */
112 unsigned
113 tree_num_loop_insns (struct loop *loop, eni_weights *weights)
115 basic_block *body = get_loop_body (loop);
116 gimple_stmt_iterator gsi;
117 unsigned size = 0, i;
119 for (i = 0; i < loop->num_nodes; i++)
120 for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi))
121 size += estimate_num_insns (gsi_stmt (gsi), weights);
122 free (body);
124 return size;
127 /* Describe size of loop as detected by tree_estimate_loop_size. */
128 struct loop_size
130 /* Number of instructions in the loop. */
131 int overall;
133 /* Number of instructions that will be likely optimized out in
134 peeled iterations of loop (i.e. computation based on induction
135 variable where induction variable starts at known constant.) */
136 int eliminated_by_peeling;
138 /* Same statistics for last iteration of loop: it is smaller because
139 instructions after exit are not executed. */
140 int last_iteration;
141 int last_iteration_eliminated_by_peeling;
143 /* If some IV computation will become constant. */
144 bool constant_iv;
146 /* Number of call stmts that are not a builtin and are pure or const
147 present on the hot path. */
148 int num_pure_calls_on_hot_path;
149 /* Number of call stmts that are not a builtin and are not pure nor const
150 present on the hot path. */
151 int num_non_pure_calls_on_hot_path;
152 /* Number of statements other than calls in the loop. */
153 int non_call_stmts_on_hot_path;
154 /* Number of branches seen on the hot path. */
155 int num_branches_on_hot_path;
158 /* Return true if OP in STMT will be constant after peeling LOOP. */
160 static bool
161 constant_after_peeling (tree op, gimple stmt, struct loop *loop)
163 affine_iv iv;
165 if (is_gimple_min_invariant (op))
166 return true;
168 /* We can still fold accesses to constant arrays when index is known. */
169 if (TREE_CODE (op) != SSA_NAME)
171 tree base = op;
173 /* First make fast look if we see constant array inside. */
174 while (handled_component_p (base))
175 base = TREE_OPERAND (base, 0);
176 if ((DECL_P (base)
177 && ctor_for_folding (base) != error_mark_node)
178 || CONSTANT_CLASS_P (base))
180 /* If so, see if we understand all the indices. */
181 base = op;
182 while (handled_component_p (base))
184 if (TREE_CODE (base) == ARRAY_REF
185 && !constant_after_peeling (TREE_OPERAND (base, 1), stmt, loop))
186 return false;
187 base = TREE_OPERAND (base, 0);
189 return true;
191 return false;
194 /* Induction variables are constants. */
195 if (!simple_iv (loop, loop_containing_stmt (stmt), op, &iv, false))
196 return false;
197 if (!is_gimple_min_invariant (iv.base))
198 return false;
199 if (!is_gimple_min_invariant (iv.step))
200 return false;
201 return true;
204 /* Computes an estimated number of insns in LOOP.
205 EXIT (if non-NULL) is an exite edge that will be eliminated in all but last
206 iteration of the loop.
207 EDGE_TO_CANCEL (if non-NULL) is an non-exit edge eliminated in the last iteration
208 of loop.
209 Return results in SIZE, estimate benefits for complete unrolling exiting by EXIT.
210 Stop estimating after UPPER_BOUND is met. Return true in this case. */
212 static bool
213 tree_estimate_loop_size (struct loop *loop, edge exit, edge edge_to_cancel, struct loop_size *size,
214 int upper_bound)
216 basic_block *body = get_loop_body (loop);
217 gimple_stmt_iterator gsi;
218 unsigned int i;
219 bool after_exit;
220 vec<basic_block> path = get_loop_hot_path (loop);
222 size->overall = 0;
223 size->eliminated_by_peeling = 0;
224 size->last_iteration = 0;
225 size->last_iteration_eliminated_by_peeling = 0;
226 size->num_pure_calls_on_hot_path = 0;
227 size->num_non_pure_calls_on_hot_path = 0;
228 size->non_call_stmts_on_hot_path = 0;
229 size->num_branches_on_hot_path = 0;
230 size->constant_iv = 0;
232 if (dump_file && (dump_flags & TDF_DETAILS))
233 fprintf (dump_file, "Estimating sizes for loop %i\n", loop->num);
234 for (i = 0; i < loop->num_nodes; i++)
236 if (edge_to_cancel && body[i] != edge_to_cancel->src
237 && dominated_by_p (CDI_DOMINATORS, body[i], edge_to_cancel->src))
238 after_exit = true;
239 else
240 after_exit = false;
241 if (dump_file && (dump_flags & TDF_DETAILS))
242 fprintf (dump_file, " BB: %i, after_exit: %i\n", body[i]->index, after_exit);
244 for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi))
246 gimple stmt = gsi_stmt (gsi);
247 int num = estimate_num_insns (stmt, &eni_size_weights);
248 bool likely_eliminated = false;
249 bool likely_eliminated_last = false;
250 bool likely_eliminated_peeled = false;
252 if (dump_file && (dump_flags & TDF_DETAILS))
254 fprintf (dump_file, " size: %3i ", num);
255 print_gimple_stmt (dump_file, gsi_stmt (gsi), 0, 0);
258 /* Look for reasons why we might optimize this stmt away. */
260 if (gimple_has_side_effects (stmt))
262 /* Exit conditional. */
263 else if (exit && body[i] == exit->src
264 && stmt == last_stmt (exit->src))
266 if (dump_file && (dump_flags & TDF_DETAILS))
267 fprintf (dump_file, " Exit condition will be eliminated "
268 "in peeled copies.\n");
269 likely_eliminated_peeled = true;
271 else if (edge_to_cancel && body[i] == edge_to_cancel->src
272 && stmt == last_stmt (edge_to_cancel->src))
274 if (dump_file && (dump_flags & TDF_DETAILS))
275 fprintf (dump_file, " Exit condition will be eliminated "
276 "in last copy.\n");
277 likely_eliminated_last = true;
279 /* Sets of IV variables */
280 else if (gimple_code (stmt) == GIMPLE_ASSIGN
281 && constant_after_peeling (gimple_assign_lhs (stmt), stmt, loop))
283 if (dump_file && (dump_flags & TDF_DETAILS))
284 fprintf (dump_file, " Induction variable computation will"
285 " be folded away.\n");
286 likely_eliminated = true;
288 /* Assignments of IV variables. */
289 else if (gimple_code (stmt) == GIMPLE_ASSIGN
290 && TREE_CODE (gimple_assign_lhs (stmt)) == SSA_NAME
291 && constant_after_peeling (gimple_assign_rhs1 (stmt), stmt, loop)
292 && (gimple_assign_rhs_class (stmt) != GIMPLE_BINARY_RHS
293 || constant_after_peeling (gimple_assign_rhs2 (stmt),
294 stmt, loop)))
296 size->constant_iv = true;
297 if (dump_file && (dump_flags & TDF_DETAILS))
298 fprintf (dump_file, " Constant expression will be folded away.\n");
299 likely_eliminated = true;
301 /* Conditionals. */
302 else if ((gimple_code (stmt) == GIMPLE_COND
303 && constant_after_peeling (gimple_cond_lhs (stmt), stmt, loop)
304 && constant_after_peeling (gimple_cond_rhs (stmt), stmt, loop))
305 || (gimple_code (stmt) == GIMPLE_SWITCH
306 && constant_after_peeling (gimple_switch_index (stmt), stmt, loop)))
308 if (dump_file && (dump_flags & TDF_DETAILS))
309 fprintf (dump_file, " Constant conditional.\n");
310 likely_eliminated = true;
313 size->overall += num;
314 if (likely_eliminated || likely_eliminated_peeled)
315 size->eliminated_by_peeling += num;
316 if (!after_exit)
318 size->last_iteration += num;
319 if (likely_eliminated || likely_eliminated_last)
320 size->last_iteration_eliminated_by_peeling += num;
322 if ((size->overall * 3 / 2 - size->eliminated_by_peeling
323 - size->last_iteration_eliminated_by_peeling) > upper_bound)
325 free (body);
326 path.release ();
327 return true;
331 while (path.length ())
333 basic_block bb = path.pop ();
334 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
336 gimple stmt = gsi_stmt (gsi);
337 if (gimple_code (stmt) == GIMPLE_CALL)
339 int flags = gimple_call_flags (stmt);
340 tree decl = gimple_call_fndecl (stmt);
342 if (decl && DECL_IS_BUILTIN (decl)
343 && is_inexpensive_builtin (decl))
345 else if (flags & (ECF_PURE | ECF_CONST))
346 size->num_pure_calls_on_hot_path++;
347 else
348 size->num_non_pure_calls_on_hot_path++;
349 size->num_branches_on_hot_path ++;
351 else if (gimple_code (stmt) != GIMPLE_CALL
352 && gimple_code (stmt) != GIMPLE_DEBUG)
353 size->non_call_stmts_on_hot_path++;
354 if (((gimple_code (stmt) == GIMPLE_COND
355 && (!constant_after_peeling (gimple_cond_lhs (stmt), stmt, loop)
356 || constant_after_peeling (gimple_cond_rhs (stmt), stmt, loop)))
357 || (gimple_code (stmt) == GIMPLE_SWITCH
358 && !constant_after_peeling (gimple_switch_index (stmt), stmt, loop)))
359 && (!exit || bb != exit->src))
360 size->num_branches_on_hot_path++;
363 path.release ();
364 if (dump_file && (dump_flags & TDF_DETAILS))
365 fprintf (dump_file, "size: %i-%i, last_iteration: %i-%i\n", size->overall,
366 size->eliminated_by_peeling, size->last_iteration,
367 size->last_iteration_eliminated_by_peeling);
369 free (body);
370 return false;
373 /* Estimate number of insns of completely unrolled loop.
374 It is (NUNROLL + 1) * size of loop body with taking into account
375 the fact that in last copy everything after exit conditional
376 is dead and that some instructions will be eliminated after
377 peeling.
379 Loop body is likely going to simplify further, this is difficult
380 to guess, we just decrease the result by 1/3. */
382 static unsigned HOST_WIDE_INT
383 estimated_unrolled_size (struct loop_size *size,
384 unsigned HOST_WIDE_INT nunroll)
386 HOST_WIDE_INT unr_insns = ((nunroll)
387 * (HOST_WIDE_INT) (size->overall
388 - size->eliminated_by_peeling));
389 if (!nunroll)
390 unr_insns = 0;
391 unr_insns += size->last_iteration - size->last_iteration_eliminated_by_peeling;
393 unr_insns = unr_insns * 2 / 3;
394 if (unr_insns <= 0)
395 unr_insns = 1;
397 return unr_insns;
400 /* Loop LOOP is known to not loop. See if there is an edge in the loop
401 body that can be remove to make the loop to always exit and at
402 the same time it does not make any code potentially executed
403 during the last iteration dead.
405 After complette unrolling we still may get rid of the conditional
406 on the exit in the last copy even if we have no idea what it does.
407 This is quite common case for loops of form
409 int a[5];
410 for (i=0;i<b;i++)
411 a[i]=0;
413 Here we prove the loop to iterate 5 times but we do not know
414 it from induction variable.
416 For now we handle only simple case where there is exit condition
417 just before the latch block and the latch block contains no statements
418 with side effect that may otherwise terminate the execution of loop
419 (such as by EH or by terminating the program or longjmp).
421 In the general case we may want to cancel the paths leading to statements
422 loop-niter identified as having undefined effect in the last iteration.
423 The other cases are hopefully rare and will be cleaned up later. */
425 edge
426 loop_edge_to_cancel (struct loop *loop)
428 vec<edge> exits;
429 unsigned i;
430 edge edge_to_cancel;
431 gimple_stmt_iterator gsi;
433 /* We want only one predecestor of the loop. */
434 if (EDGE_COUNT (loop->latch->preds) > 1)
435 return NULL;
437 exits = get_loop_exit_edges (loop);
439 FOR_EACH_VEC_ELT (exits, i, edge_to_cancel)
441 /* Find the other edge than the loop exit
442 leaving the conditoinal. */
443 if (EDGE_COUNT (edge_to_cancel->src->succs) != 2)
444 continue;
445 if (EDGE_SUCC (edge_to_cancel->src, 0) == edge_to_cancel)
446 edge_to_cancel = EDGE_SUCC (edge_to_cancel->src, 1);
447 else
448 edge_to_cancel = EDGE_SUCC (edge_to_cancel->src, 0);
450 /* We only can handle conditionals. */
451 if (!(edge_to_cancel->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
452 continue;
454 /* We should never have conditionals in the loop latch. */
455 gcc_assert (edge_to_cancel->dest != loop->header);
457 /* Check that it leads to loop latch. */
458 if (edge_to_cancel->dest != loop->latch)
459 continue;
461 exits.release ();
463 /* Verify that the code in loop latch does nothing that may end program
464 execution without really reaching the exit. This may include
465 non-pure/const function calls, EH statements, volatile ASMs etc. */
466 for (gsi = gsi_start_bb (loop->latch); !gsi_end_p (gsi); gsi_next (&gsi))
467 if (gimple_has_side_effects (gsi_stmt (gsi)))
468 return NULL;
469 return edge_to_cancel;
471 exits.release ();
472 return NULL;
475 /* Remove all tests for exits that are known to be taken after LOOP was
476 peeled NPEELED times. Put gcc_unreachable before every statement
477 known to not be executed. */
479 static bool
480 remove_exits_and_undefined_stmts (struct loop *loop, unsigned int npeeled)
482 struct nb_iter_bound *elt;
483 bool changed = false;
485 for (elt = loop->bounds; elt; elt = elt->next)
487 /* If statement is known to be undefined after peeling, turn it
488 into unreachable (or trap when debugging experience is supposed
489 to be good). */
490 if (!elt->is_exit
491 && elt->bound.ult (double_int::from_uhwi (npeeled)))
493 gimple_stmt_iterator gsi = gsi_for_stmt (elt->stmt);
494 gimple stmt = gimple_build_call
495 (builtin_decl_implicit (BUILT_IN_UNREACHABLE), 0);
497 gimple_set_location (stmt, gimple_location (elt->stmt));
498 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
499 changed = true;
500 if (dump_file && (dump_flags & TDF_DETAILS))
502 fprintf (dump_file, "Forced statement unreachable: ");
503 print_gimple_stmt (dump_file, elt->stmt, 0, 0);
506 /* If we know the exit will be taken after peeling, update. */
507 else if (elt->is_exit
508 && elt->bound.ule (double_int::from_uhwi (npeeled)))
510 basic_block bb = gimple_bb (elt->stmt);
511 edge exit_edge = EDGE_SUCC (bb, 0);
513 if (dump_file && (dump_flags & TDF_DETAILS))
515 fprintf (dump_file, "Forced exit to be taken: ");
516 print_gimple_stmt (dump_file, elt->stmt, 0, 0);
518 if (!loop_exit_edge_p (loop, exit_edge))
519 exit_edge = EDGE_SUCC (bb, 1);
520 gcc_checking_assert (loop_exit_edge_p (loop, exit_edge));
521 if (exit_edge->flags & EDGE_TRUE_VALUE)
522 gimple_cond_make_true (elt->stmt);
523 else
524 gimple_cond_make_false (elt->stmt);
525 update_stmt (elt->stmt);
526 changed = true;
529 return changed;
532 /* Remove all exits that are known to be never taken because of the loop bound
533 discovered. */
535 static bool
536 remove_redundant_iv_tests (struct loop *loop)
538 struct nb_iter_bound *elt;
539 bool changed = false;
541 if (!loop->any_upper_bound)
542 return false;
543 for (elt = loop->bounds; elt; elt = elt->next)
545 /* Exit is pointless if it won't be taken before loop reaches
546 upper bound. */
547 if (elt->is_exit && loop->any_upper_bound
548 && loop->nb_iterations_upper_bound.ult (elt->bound))
550 basic_block bb = gimple_bb (elt->stmt);
551 edge exit_edge = EDGE_SUCC (bb, 0);
552 struct tree_niter_desc niter;
554 if (!loop_exit_edge_p (loop, exit_edge))
555 exit_edge = EDGE_SUCC (bb, 1);
557 /* Only when we know the actual number of iterations, not
558 just a bound, we can remove the exit. */
559 if (!number_of_iterations_exit (loop, exit_edge,
560 &niter, false, false)
561 || !integer_onep (niter.assumptions)
562 || !integer_zerop (niter.may_be_zero)
563 || !niter.niter
564 || TREE_CODE (niter.niter) != INTEGER_CST
565 || !loop->nb_iterations_upper_bound.ult
566 (tree_to_double_int (niter.niter)))
567 continue;
569 if (dump_file && (dump_flags & TDF_DETAILS))
571 fprintf (dump_file, "Removed pointless exit: ");
572 print_gimple_stmt (dump_file, elt->stmt, 0, 0);
574 if (exit_edge->flags & EDGE_TRUE_VALUE)
575 gimple_cond_make_false (elt->stmt);
576 else
577 gimple_cond_make_true (elt->stmt);
578 update_stmt (elt->stmt);
579 changed = true;
582 return changed;
585 /* Stores loops that will be unlooped after we process whole loop tree. */
586 static vec<loop_p> loops_to_unloop;
587 static vec<int> loops_to_unloop_nunroll;
589 /* Cancel all fully unrolled loops by putting __builtin_unreachable
590 on the latch edge.
591 We do it after all unrolling since unlooping moves basic blocks
592 across loop boundaries trashing loop closed SSA form as well
593 as SCEV info needed to be intact during unrolling.
595 IRRED_INVALIDATED is used to bookkeep if information about
596 irreducible regions may become invalid as a result
597 of the transformation.
598 LOOP_CLOSED_SSA_INVALIDATED is used to bookkepp the case
599 when we need to go into loop closed SSA form. */
601 void
602 unloop_loops (bitmap loop_closed_ssa_invalidated,
603 bool *irred_invalidated)
605 while (loops_to_unloop.length ())
607 struct loop *loop = loops_to_unloop.pop ();
608 int n_unroll = loops_to_unloop_nunroll.pop ();
609 basic_block latch = loop->latch;
610 edge latch_edge = loop_latch_edge (loop);
611 int flags = latch_edge->flags;
612 location_t locus = latch_edge->goto_locus;
613 gimple stmt;
614 gimple_stmt_iterator gsi;
616 remove_exits_and_undefined_stmts (loop, n_unroll);
618 /* Unloop destroys the latch edge. */
619 unloop (loop, irred_invalidated, loop_closed_ssa_invalidated);
621 /* Create new basic block for the latch edge destination and wire
622 it in. */
623 stmt = gimple_build_call (builtin_decl_implicit (BUILT_IN_UNREACHABLE), 0);
624 latch_edge = make_edge (latch, create_basic_block (NULL, NULL, latch), flags);
625 latch_edge->probability = 0;
626 latch_edge->count = 0;
627 latch_edge->flags |= flags;
628 latch_edge->goto_locus = locus;
630 latch_edge->dest->loop_father = current_loops->tree_root;
631 latch_edge->dest->count = 0;
632 latch_edge->dest->frequency = 0;
633 set_immediate_dominator (CDI_DOMINATORS, latch_edge->dest, latch_edge->src);
635 gsi = gsi_start_bb (latch_edge->dest);
636 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
638 loops_to_unloop.release ();
639 loops_to_unloop_nunroll.release ();
642 /* Tries to unroll LOOP completely, i.e. NITER times.
643 UL determines which loops we are allowed to unroll.
644 EXIT is the exit of the loop that should be eliminated.
645 MAXITER specfy bound on number of iterations, -1 if it is
646 not known or too large for HOST_WIDE_INT. The location
647 LOCUS corresponding to the loop is used when emitting
648 a summary of the unroll to the dump file. */
650 static bool
651 try_unroll_loop_completely (struct loop *loop,
652 edge exit, tree niter,
653 enum unroll_level ul,
654 HOST_WIDE_INT maxiter,
655 location_t locus)
657 unsigned HOST_WIDE_INT n_unroll, ninsns, max_unroll, unr_insns;
658 gimple cond;
659 struct loop_size size;
660 bool n_unroll_found = false;
661 edge edge_to_cancel = NULL;
663 /* See if we proved number of iterations to be low constant.
665 EXIT is an edge that will be removed in all but last iteration of
666 the loop.
668 EDGE_TO_CACNEL is an edge that will be removed from the last iteration
669 of the unrolled sequence and is expected to make the final loop not
670 rolling.
672 If the number of execution of loop is determined by standard induction
673 variable test, then EXIT and EDGE_TO_CANCEL are the two edges leaving
674 from the iv test. */
675 if (host_integerp (niter, 1))
677 n_unroll = tree_low_cst (niter, 1);
678 n_unroll_found = true;
679 edge_to_cancel = EDGE_SUCC (exit->src, 0);
680 if (edge_to_cancel == exit)
681 edge_to_cancel = EDGE_SUCC (exit->src, 1);
683 /* We do not know the number of iterations and thus we can not eliminate
684 the EXIT edge. */
685 else
686 exit = NULL;
688 /* See if we can improve our estimate by using recorded loop bounds. */
689 if (maxiter >= 0
690 && (!n_unroll_found || (unsigned HOST_WIDE_INT)maxiter < n_unroll))
692 n_unroll = maxiter;
693 n_unroll_found = true;
694 /* Loop terminates before the IV variable test, so we can not
695 remove it in the last iteration. */
696 edge_to_cancel = NULL;
699 if (!n_unroll_found)
700 return false;
702 max_unroll = PARAM_VALUE (PARAM_MAX_COMPLETELY_PEEL_TIMES);
703 if (n_unroll > max_unroll)
704 return false;
706 if (!edge_to_cancel)
707 edge_to_cancel = loop_edge_to_cancel (loop);
709 if (n_unroll)
711 sbitmap wont_exit;
712 edge e;
713 unsigned i;
714 bool large;
715 vec<edge> to_remove = vNULL;
716 if (ul == UL_SINGLE_ITER)
717 return false;
719 large = tree_estimate_loop_size
720 (loop, exit, edge_to_cancel, &size,
721 PARAM_VALUE (PARAM_MAX_COMPLETELY_PEELED_INSNS));
722 ninsns = size.overall;
723 if (large)
725 if (dump_file && (dump_flags & TDF_DETAILS))
726 fprintf (dump_file, "Not unrolling loop %d: it is too large.\n",
727 loop->num);
728 return false;
731 unr_insns = estimated_unrolled_size (&size, n_unroll);
732 if (dump_file && (dump_flags & TDF_DETAILS))
734 fprintf (dump_file, " Loop size: %d\n", (int) ninsns);
735 fprintf (dump_file, " Estimated size after unrolling: %d\n",
736 (int) unr_insns);
739 /* If the code is going to shrink, we don't need to be extra cautious
740 on guessing if the unrolling is going to be profitable. */
741 if (unr_insns
742 /* If there is IV variable that will become constant, we save
743 one instruction in the loop prologue we do not account
744 otherwise. */
745 <= ninsns + (size.constant_iv != false))
747 /* We unroll only inner loops, because we do not consider it profitable
748 otheriwse. We still can cancel loopback edge of not rolling loop;
749 this is always a good idea. */
750 else if (ul == UL_NO_GROWTH)
752 if (dump_file && (dump_flags & TDF_DETAILS))
753 fprintf (dump_file, "Not unrolling loop %d: size would grow.\n",
754 loop->num);
755 return false;
757 /* Outer loops tend to be less interesting candidates for complette
758 unrolling unless we can do a lot of propagation into the inner loop
759 body. For now we disable outer loop unrolling when the code would
760 grow. */
761 else if (loop->inner)
763 if (dump_file && (dump_flags & TDF_DETAILS))
764 fprintf (dump_file, "Not unrolling loop %d: "
765 "it is not innermost and code would grow.\n",
766 loop->num);
767 return false;
769 /* If there is call on a hot path through the loop, then
770 there is most probably not much to optimize. */
771 else if (size.num_non_pure_calls_on_hot_path)
773 if (dump_file && (dump_flags & TDF_DETAILS))
774 fprintf (dump_file, "Not unrolling loop %d: "
775 "contains call and code would grow.\n",
776 loop->num);
777 return false;
779 /* If there is pure/const call in the function, then we
780 can still optimize the unrolled loop body if it contains
781 some other interesting code than the calls and code
782 storing or cumulating the return value. */
783 else if (size.num_pure_calls_on_hot_path
784 /* One IV increment, one test, one ivtmp store
785 and one useful stmt. That is about minimal loop
786 doing pure call. */
787 && (size.non_call_stmts_on_hot_path
788 <= 3 + size.num_pure_calls_on_hot_path))
790 if (dump_file && (dump_flags & TDF_DETAILS))
791 fprintf (dump_file, "Not unrolling loop %d: "
792 "contains just pure calls and code would grow.\n",
793 loop->num);
794 return false;
796 /* Complette unrolling is major win when control flow is removed and
797 one big basic block is created. If the loop contains control flow
798 the optimization may still be a win because of eliminating the loop
799 overhead but it also may blow the branch predictor tables.
800 Limit number of branches on the hot path through the peeled
801 sequence. */
802 else if (size.num_branches_on_hot_path * (int)n_unroll
803 > PARAM_VALUE (PARAM_MAX_PEEL_BRANCHES))
805 if (dump_file && (dump_flags & TDF_DETAILS))
806 fprintf (dump_file, "Not unrolling loop %d: "
807 " number of branches on hot path in the unrolled sequence"
808 " reach --param max-peel-branches limit.\n",
809 loop->num);
810 return false;
812 else if (unr_insns
813 > (unsigned) PARAM_VALUE (PARAM_MAX_COMPLETELY_PEELED_INSNS))
815 if (dump_file && (dump_flags & TDF_DETAILS))
816 fprintf (dump_file, "Not unrolling loop %d: "
817 "(--param max-completely-peeled-insns limit reached).\n",
818 loop->num);
819 return false;
822 initialize_original_copy_tables ();
823 wont_exit = sbitmap_alloc (n_unroll + 1);
824 bitmap_ones (wont_exit);
825 bitmap_clear_bit (wont_exit, 0);
827 if (!gimple_duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
828 n_unroll, wont_exit,
829 exit, &to_remove,
830 DLTHE_FLAG_UPDATE_FREQ
831 | DLTHE_FLAG_COMPLETTE_PEEL))
833 free_original_copy_tables ();
834 free (wont_exit);
835 if (dump_file && (dump_flags & TDF_DETAILS))
836 fprintf (dump_file, "Failed to duplicate the loop\n");
837 return false;
840 FOR_EACH_VEC_ELT (to_remove, i, e)
842 bool ok = remove_path (e);
843 gcc_assert (ok);
846 to_remove.release ();
847 free (wont_exit);
848 free_original_copy_tables ();
852 /* Remove the conditional from the last copy of the loop. */
853 if (edge_to_cancel)
855 cond = last_stmt (edge_to_cancel->src);
856 if (edge_to_cancel->flags & EDGE_TRUE_VALUE)
857 gimple_cond_make_false (cond);
858 else
859 gimple_cond_make_true (cond);
860 update_stmt (cond);
861 /* Do not remove the path. Doing so may remove outer loop
862 and confuse bookkeeping code in tree_unroll_loops_completelly. */
865 /* Store the loop for later unlooping and exit removal. */
866 loops_to_unloop.safe_push (loop);
867 loops_to_unloop_nunroll.safe_push (n_unroll);
869 if (dump_enabled_p ())
871 if (!n_unroll)
872 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, locus,
873 "loop turned into non-loop; it never loops\n");
874 else
876 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, locus,
877 "loop with %d iterations completely unrolled",
878 (int) (n_unroll + 1));
879 if (profile_info)
880 dump_printf (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS,
881 " (header execution count %d)",
882 (int)loop->header->count);
883 dump_printf (MSG_OPTIMIZED_LOCATIONS | TDF_DETAILS, "\n");
887 if (dump_file && (dump_flags & TDF_DETAILS))
889 if (exit)
890 fprintf (dump_file, "Exit condition of peeled iterations was "
891 "eliminated.\n");
892 if (edge_to_cancel)
893 fprintf (dump_file, "Last iteration exit edge was proved true.\n");
894 else
895 fprintf (dump_file, "Latch of last iteration was marked by "
896 "__builtin_unreachable ().\n");
899 return true;
902 /* Adds a canonical induction variable to LOOP if suitable.
903 CREATE_IV is true if we may create a new iv. UL determines
904 which loops we are allowed to completely unroll. If TRY_EVAL is true, we try
905 to determine the number of iterations of a loop by direct evaluation.
906 Returns true if cfg is changed. */
908 static bool
909 canonicalize_loop_induction_variables (struct loop *loop,
910 bool create_iv, enum unroll_level ul,
911 bool try_eval)
913 edge exit = NULL;
914 tree niter;
915 HOST_WIDE_INT maxiter;
916 bool modified = false;
917 location_t locus = UNKNOWN_LOCATION;
919 niter = number_of_latch_executions (loop);
920 exit = single_exit (loop);
921 if (TREE_CODE (niter) == INTEGER_CST)
922 locus = gimple_location (last_stmt (exit->src));
923 else
925 /* If the loop has more than one exit, try checking all of them
926 for # of iterations determinable through scev. */
927 if (!exit)
928 niter = find_loop_niter (loop, &exit);
930 /* Finally if everything else fails, try brute force evaluation. */
931 if (try_eval
932 && (chrec_contains_undetermined (niter)
933 || TREE_CODE (niter) != INTEGER_CST))
934 niter = find_loop_niter_by_eval (loop, &exit);
936 if (exit)
937 locus = gimple_location (last_stmt (exit->src));
939 if (TREE_CODE (niter) != INTEGER_CST)
940 exit = NULL;
943 /* We work exceptionally hard here to estimate the bound
944 by find_loop_niter_by_eval. Be sure to keep it for future. */
945 if (niter && TREE_CODE (niter) == INTEGER_CST)
947 record_niter_bound (loop, tree_to_double_int (niter),
948 exit == single_likely_exit (loop), true);
951 /* Force re-computation of loop bounds so we can remove redundant exits. */
952 maxiter = max_loop_iterations_int (loop);
954 if (dump_file && (dump_flags & TDF_DETAILS)
955 && TREE_CODE (niter) == INTEGER_CST)
957 fprintf (dump_file, "Loop %d iterates ", loop->num);
958 print_generic_expr (dump_file, niter, TDF_SLIM);
959 fprintf (dump_file, " times.\n");
961 if (dump_file && (dump_flags & TDF_DETAILS)
962 && maxiter >= 0)
964 fprintf (dump_file, "Loop %d iterates at most %i times.\n", loop->num,
965 (int)maxiter);
968 /* Remove exits that are known to be never taken based on loop bound.
969 Needs to be called after compilation of max_loop_iterations_int that
970 populates the loop bounds. */
971 modified |= remove_redundant_iv_tests (loop);
973 if (try_unroll_loop_completely (loop, exit, niter, ul, maxiter, locus))
974 return true;
976 if (create_iv
977 && niter && !chrec_contains_undetermined (niter)
978 && exit && just_once_each_iteration_p (loop, exit->src))
979 create_canonical_iv (loop, exit, niter);
981 return modified;
984 /* The main entry point of the pass. Adds canonical induction variables
985 to the suitable loops. */
987 unsigned int
988 canonicalize_induction_variables (void)
990 loop_iterator li;
991 struct loop *loop;
992 bool changed = false;
993 bool irred_invalidated = false;
994 bitmap loop_closed_ssa_invalidated = BITMAP_ALLOC (NULL);
996 free_numbers_of_iterations_estimates ();
997 estimate_numbers_of_iterations ();
999 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1001 changed |= canonicalize_loop_induction_variables (loop,
1002 true, UL_SINGLE_ITER,
1003 true);
1005 gcc_assert (!need_ssa_update_p (cfun));
1007 unloop_loops (loop_closed_ssa_invalidated, &irred_invalidated);
1008 if (irred_invalidated
1009 && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS))
1010 mark_irreducible_loops ();
1012 /* Clean up the information about numbers of iterations, since brute force
1013 evaluation could reveal new information. */
1014 scev_reset ();
1016 if (!bitmap_empty_p (loop_closed_ssa_invalidated))
1018 gcc_checking_assert (loops_state_satisfies_p (LOOP_CLOSED_SSA));
1019 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1021 BITMAP_FREE (loop_closed_ssa_invalidated);
1023 if (changed)
1024 return TODO_cleanup_cfg;
1025 return 0;
1028 /* Propagate VAL into all uses of SSA_NAME. */
1030 static void
1031 propagate_into_all_uses (tree ssa_name, tree val)
1033 imm_use_iterator iter;
1034 gimple use_stmt;
1036 FOR_EACH_IMM_USE_STMT (use_stmt, iter, ssa_name)
1038 gimple_stmt_iterator use_stmt_gsi = gsi_for_stmt (use_stmt);
1039 use_operand_p use;
1041 FOR_EACH_IMM_USE_ON_STMT (use, iter)
1042 SET_USE (use, val);
1044 if (is_gimple_assign (use_stmt)
1045 && get_gimple_rhs_class (gimple_assign_rhs_code (use_stmt))
1046 == GIMPLE_SINGLE_RHS)
1048 tree rhs = gimple_assign_rhs1 (use_stmt);
1050 if (TREE_CODE (rhs) == ADDR_EXPR)
1051 recompute_tree_invariant_for_addr_expr (rhs);
1054 fold_stmt_inplace (&use_stmt_gsi);
1055 update_stmt (use_stmt);
1056 maybe_clean_or_replace_eh_stmt (use_stmt, use_stmt);
1060 /* Propagate constant SSA_NAMEs defined in basic block BB. */
1062 static void
1063 propagate_constants_for_unrolling (basic_block bb)
1065 gimple_stmt_iterator gsi;
1067 /* Look for degenerate PHI nodes with constant argument. */
1068 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); )
1070 gimple phi = gsi_stmt (gsi);
1071 tree result = gimple_phi_result (phi);
1072 tree arg = gimple_phi_arg_def (phi, 0);
1074 if (gimple_phi_num_args (phi) == 1 && TREE_CODE (arg) == INTEGER_CST)
1076 propagate_into_all_uses (result, arg);
1077 gsi_remove (&gsi, true);
1078 release_ssa_name (result);
1080 else
1081 gsi_next (&gsi);
1084 /* Look for assignments to SSA names with constant RHS. */
1085 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
1087 gimple stmt = gsi_stmt (gsi);
1088 tree lhs;
1090 if (is_gimple_assign (stmt)
1091 && gimple_assign_rhs_code (stmt) == INTEGER_CST
1092 && (lhs = gimple_assign_lhs (stmt), TREE_CODE (lhs) == SSA_NAME)
1093 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
1095 propagate_into_all_uses (lhs, gimple_assign_rhs1 (stmt));
1096 gsi_remove (&gsi, true);
1097 release_ssa_name (lhs);
1099 else
1100 gsi_next (&gsi);
1104 /* Process loops from innermost to outer, stopping at the innermost
1105 loop we unrolled. */
1107 static bool
1108 tree_unroll_loops_completely_1 (bool may_increase_size, bool unroll_outer,
1109 vec<loop_p, va_stack>& father_stack,
1110 struct loop *loop)
1112 struct loop *loop_father;
1113 bool changed = false;
1114 struct loop *inner;
1115 enum unroll_level ul;
1117 /* Process inner loops first. */
1118 for (inner = loop->inner; inner != NULL; inner = inner->next)
1119 changed |= tree_unroll_loops_completely_1 (may_increase_size,
1120 unroll_outer, father_stack,
1121 inner);
1123 /* If we changed an inner loop we cannot process outer loops in this
1124 iteration because SSA form is not up-to-date. Continue with
1125 siblings of outer loops instead. */
1126 if (changed)
1127 return true;
1129 /* Don't unroll #pragma omp simd loops until the vectorizer
1130 attempts to vectorize those. */
1131 if (loop->force_vect)
1132 return false;
1134 /* Try to unroll this loop. */
1135 loop_father = loop_outer (loop);
1136 if (!loop_father)
1137 return false;
1139 if (may_increase_size && optimize_loop_nest_for_speed_p (loop)
1140 /* Unroll outermost loops only if asked to do so or they do
1141 not cause code growth. */
1142 && (unroll_outer || loop_outer (loop_father)))
1143 ul = UL_ALL;
1144 else
1145 ul = UL_NO_GROWTH;
1147 if (canonicalize_loop_induction_variables
1148 (loop, false, ul, !flag_tree_loop_ivcanon))
1150 /* If we'll continue unrolling, we need to propagate constants
1151 within the new basic blocks to fold away induction variable
1152 computations; otherwise, the size might blow up before the
1153 iteration is complete and the IR eventually cleaned up. */
1154 if (loop_outer (loop_father) && !loop_father->aux)
1156 father_stack.safe_push (loop_father);
1157 loop_father->aux = loop_father;
1160 return true;
1163 return false;
1166 /* Unroll LOOPS completely if they iterate just few times. Unless
1167 MAY_INCREASE_SIZE is true, perform the unrolling only if the
1168 size of the code does not increase. */
1170 unsigned int
1171 tree_unroll_loops_completely (bool may_increase_size, bool unroll_outer)
1173 vec<loop_p, va_stack> father_stack;
1174 bool changed;
1175 int iteration = 0;
1176 bool irred_invalidated = false;
1178 vec_stack_alloc (loop_p, father_stack, 16);
1181 changed = false;
1182 bitmap loop_closed_ssa_invalidated = NULL;
1184 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
1185 loop_closed_ssa_invalidated = BITMAP_ALLOC (NULL);
1187 free_numbers_of_iterations_estimates ();
1188 estimate_numbers_of_iterations ();
1190 changed = tree_unroll_loops_completely_1 (may_increase_size,
1191 unroll_outer, father_stack,
1192 current_loops->tree_root);
1193 if (changed)
1195 struct loop **iter;
1196 unsigned i;
1198 /* Be sure to skip unlooped loops while procesing father_stack
1199 array. */
1200 FOR_EACH_VEC_ELT (loops_to_unloop, i, iter)
1201 (*iter)->aux = NULL;
1202 FOR_EACH_VEC_ELT (father_stack, i, iter)
1203 if (!(*iter)->aux)
1204 *iter = NULL;
1205 unloop_loops (loop_closed_ssa_invalidated, &irred_invalidated);
1207 /* We can not use TODO_update_ssa_no_phi because VOPS gets confused. */
1208 if (loop_closed_ssa_invalidated
1209 && !bitmap_empty_p (loop_closed_ssa_invalidated))
1210 rewrite_into_loop_closed_ssa (loop_closed_ssa_invalidated,
1211 TODO_update_ssa);
1212 else
1213 update_ssa (TODO_update_ssa);
1215 /* Propagate the constants within the new basic blocks. */
1216 FOR_EACH_VEC_ELT (father_stack, i, iter)
1217 if (*iter)
1219 unsigned j;
1220 basic_block *body = get_loop_body_in_dom_order (*iter);
1221 for (j = 0; j < (*iter)->num_nodes; j++)
1222 propagate_constants_for_unrolling (body[j]);
1223 free (body);
1224 (*iter)->aux = NULL;
1226 father_stack.truncate (0);
1228 /* This will take care of removing completely unrolled loops
1229 from the loop structures so we can continue unrolling now
1230 innermost loops. */
1231 if (cleanup_tree_cfg ())
1232 update_ssa (TODO_update_ssa_only_virtuals);
1234 /* Clean up the information about numbers of iterations, since
1235 complete unrolling might have invalidated it. */
1236 scev_reset ();
1237 #ifdef ENABLE_CHECKING
1238 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
1239 verify_loop_closed_ssa (true);
1240 #endif
1242 if (loop_closed_ssa_invalidated)
1243 BITMAP_FREE (loop_closed_ssa_invalidated);
1245 while (changed
1246 && ++iteration <= PARAM_VALUE (PARAM_MAX_UNROLL_ITERATIONS));
1248 father_stack.release ();
1250 if (irred_invalidated
1251 && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS))
1252 mark_irreducible_loops ();
1254 return 0;