2012-12-01 Alessandro Fanfarillo <alessandro.fanfarillo@gmail.com>
[official-gcc.git] / gcc / tree-ssa-loop-ivcanon.c
blobdbf643b65a8f059c673950a432b5f3eb25ed1120
1 /* Induction variable canonicalization.
2 Copyright (C) 2004, 2005, 2007, 2008, 2010
3 Free Software Foundation, Inc.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* This pass detects the loops that iterate a constant number of times,
22 adds a canonical induction variable (step -1, tested against 0)
23 and replaces the exit test. This enables the less powerful rtl
24 level analysis to use this information.
26 This might spoil the code in some cases (by increasing register pressure).
27 Note that in the case the new variable is not needed, ivopts will get rid
28 of it, so it might only be a problem when there are no other linear induction
29 variables. In that case the created optimization possibilities are likely
30 to pay up.
32 Additionally in case we detect that it is beneficial to unroll the
33 loop completely, we do it right here to expose the optimization
34 possibilities to the following passes. */
36 #include "config.h"
37 #include "system.h"
38 #include "coretypes.h"
39 #include "tm.h"
40 #include "tree.h"
41 #include "tm_p.h"
42 #include "basic-block.h"
43 #include "gimple-pretty-print.h"
44 #include "tree-flow.h"
45 #include "cfgloop.h"
46 #include "tree-pass.h"
47 #include "tree-chrec.h"
48 #include "tree-scalar-evolution.h"
49 #include "params.h"
50 #include "flags.h"
51 #include "tree-inline.h"
52 #include "target.h"
54 /* Specifies types of loops that may be unrolled. */
56 enum unroll_level
58 UL_SINGLE_ITER, /* Only loops that exit immediately in the first
59 iteration. */
60 UL_NO_GROWTH, /* Only loops whose unrolling will not cause increase
61 of code size. */
62 UL_ALL /* All suitable loops. */
65 /* Adds a canonical induction variable to LOOP iterating NITER times. EXIT
66 is the exit edge whose condition is replaced. */
68 static void
69 create_canonical_iv (struct loop *loop, edge exit, tree niter)
71 edge in;
72 tree type, var;
73 gimple cond;
74 gimple_stmt_iterator incr_at;
75 enum tree_code cmp;
77 if (dump_file && (dump_flags & TDF_DETAILS))
79 fprintf (dump_file, "Added canonical iv to loop %d, ", loop->num);
80 print_generic_expr (dump_file, niter, TDF_SLIM);
81 fprintf (dump_file, " iterations.\n");
84 cond = last_stmt (exit->src);
85 in = EDGE_SUCC (exit->src, 0);
86 if (in == exit)
87 in = EDGE_SUCC (exit->src, 1);
89 /* Note that we do not need to worry about overflows, since
90 type of niter is always unsigned and all comparisons are
91 just for equality/nonequality -- i.e. everything works
92 with a modulo arithmetics. */
94 type = TREE_TYPE (niter);
95 niter = fold_build2 (PLUS_EXPR, type,
96 niter,
97 build_int_cst (type, 1));
98 incr_at = gsi_last_bb (in->src);
99 create_iv (niter,
100 build_int_cst (type, -1),
101 NULL_TREE, loop,
102 &incr_at, false, NULL, &var);
104 cmp = (exit->flags & EDGE_TRUE_VALUE) ? EQ_EXPR : NE_EXPR;
105 gimple_cond_set_code (cond, cmp);
106 gimple_cond_set_lhs (cond, var);
107 gimple_cond_set_rhs (cond, build_int_cst (type, 0));
108 update_stmt (cond);
111 /* Computes an estimated number of insns in LOOP, weighted by WEIGHTS. */
113 unsigned
114 tree_num_loop_insns (struct loop *loop, eni_weights *weights)
116 basic_block *body = get_loop_body (loop);
117 gimple_stmt_iterator gsi;
118 unsigned size = 0, i;
120 for (i = 0; i < loop->num_nodes; i++)
121 for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi))
122 size += estimate_num_insns (gsi_stmt (gsi), weights);
123 free (body);
125 return size;
128 /* Describe size of loop as detected by tree_estimate_loop_size. */
129 struct loop_size
131 /* Number of instructions in the loop. */
132 int overall;
134 /* Number of instructions that will be likely optimized out in
135 peeled iterations of loop (i.e. computation based on induction
136 variable where induction variable starts at known constant.) */
137 int eliminated_by_peeling;
139 /* Same statistics for last iteration of loop: it is smaller because
140 instructions after exit are not executed. */
141 int last_iteration;
142 int last_iteration_eliminated_by_peeling;
144 /* If some IV computation will become constant. */
145 bool constant_iv;
147 /* Number of call stmts that are not a builtin and are pure or const
148 present on the hot path. */
149 int num_pure_calls_on_hot_path;
150 /* Number of call stmts that are not a builtin and are not pure nor const
151 present on the hot path. */
152 int num_non_pure_calls_on_hot_path;
153 /* Number of statements other than calls in the loop. */
154 int non_call_stmts_on_hot_path;
155 /* Number of branches seen on the hot path. */
156 int num_branches_on_hot_path;
159 /* Return true if OP in STMT will be constant after peeling LOOP. */
161 static bool
162 constant_after_peeling (tree op, gimple stmt, struct loop *loop)
164 affine_iv iv;
166 if (is_gimple_min_invariant (op))
167 return true;
169 /* We can still fold accesses to constant arrays when index is known. */
170 if (TREE_CODE (op) != SSA_NAME)
172 tree base = op;
174 /* First make fast look if we see constant array inside. */
175 while (handled_component_p (base))
176 base = TREE_OPERAND (base, 0);
177 if ((DECL_P (base)
178 && const_value_known_p (base))
179 || CONSTANT_CLASS_P (base))
181 /* If so, see if we understand all the indices. */
182 base = op;
183 while (handled_component_p (base))
185 if (TREE_CODE (base) == ARRAY_REF
186 && !constant_after_peeling (TREE_OPERAND (base, 1), stmt, loop))
187 return false;
188 base = TREE_OPERAND (base, 0);
190 return true;
192 return false;
195 /* Induction variables are constants. */
196 if (!simple_iv (loop, loop_containing_stmt (stmt), op, &iv, false))
197 return false;
198 if (!is_gimple_min_invariant (iv.base))
199 return false;
200 if (!is_gimple_min_invariant (iv.step))
201 return false;
202 return true;
205 /* Computes an estimated number of insns in LOOP.
206 EXIT (if non-NULL) is an exite edge that will be eliminated in all but last
207 iteration of the loop.
208 EDGE_TO_CANCEL (if non-NULL) is an non-exit edge eliminated in the last iteration
209 of loop.
210 Return results in SIZE, estimate benefits for complete unrolling exiting by EXIT. */
212 static void
213 tree_estimate_loop_size (struct loop *loop, edge exit, edge edge_to_cancel, struct loop_size *size)
215 basic_block *body = get_loop_body (loop);
216 gimple_stmt_iterator gsi;
217 unsigned int i;
218 bool after_exit;
219 vec<basic_block> path = get_loop_hot_path (loop);
221 size->overall = 0;
222 size->eliminated_by_peeling = 0;
223 size->last_iteration = 0;
224 size->last_iteration_eliminated_by_peeling = 0;
225 size->num_pure_calls_on_hot_path = 0;
226 size->num_non_pure_calls_on_hot_path = 0;
227 size->non_call_stmts_on_hot_path = 0;
228 size->num_branches_on_hot_path = 0;
229 size->constant_iv = 0;
231 if (dump_file && (dump_flags & TDF_DETAILS))
232 fprintf (dump_file, "Estimating sizes for loop %i\n", loop->num);
233 for (i = 0; i < loop->num_nodes; i++)
235 if (edge_to_cancel && body[i] != edge_to_cancel->src
236 && dominated_by_p (CDI_DOMINATORS, body[i], edge_to_cancel->src))
237 after_exit = true;
238 else
239 after_exit = false;
240 if (dump_file && (dump_flags & TDF_DETAILS))
241 fprintf (dump_file, " BB: %i, after_exit: %i\n", body[i]->index, after_exit);
243 for (gsi = gsi_start_bb (body[i]); !gsi_end_p (gsi); gsi_next (&gsi))
245 gimple stmt = gsi_stmt (gsi);
246 int num = estimate_num_insns (stmt, &eni_size_weights);
247 bool likely_eliminated = false;
248 bool likely_eliminated_last = false;
249 bool likely_eliminated_peeled = false;
251 if (dump_file && (dump_flags & TDF_DETAILS))
253 fprintf (dump_file, " size: %3i ", num);
254 print_gimple_stmt (dump_file, gsi_stmt (gsi), 0, 0);
257 /* Look for reasons why we might optimize this stmt away. */
259 /* Exit conditional. */
260 if (exit && body[i] == exit->src
261 && stmt == last_stmt (exit->src))
263 if (dump_file && (dump_flags & TDF_DETAILS))
264 fprintf (dump_file, " Exit condition will be eliminated "
265 "in peeled copies.\n");
266 likely_eliminated_peeled = true;
268 else if (edge_to_cancel && body[i] == edge_to_cancel->src
269 && stmt == last_stmt (edge_to_cancel->src))
271 if (dump_file && (dump_flags & TDF_DETAILS))
272 fprintf (dump_file, " Exit condition will be eliminated "
273 "in last copy.\n");
274 likely_eliminated_last = true;
276 /* Sets of IV variables */
277 else if (gimple_code (stmt) == GIMPLE_ASSIGN
278 && constant_after_peeling (gimple_assign_lhs (stmt), stmt, loop))
280 if (dump_file && (dump_flags & TDF_DETAILS))
281 fprintf (dump_file, " Induction variable computation will"
282 " be folded away.\n");
283 likely_eliminated = true;
285 /* Assignments of IV variables. */
286 else if (gimple_code (stmt) == GIMPLE_ASSIGN
287 && TREE_CODE (gimple_assign_lhs (stmt)) == SSA_NAME
288 && constant_after_peeling (gimple_assign_rhs1 (stmt), stmt, loop)
289 && (gimple_assign_rhs_class (stmt) != GIMPLE_BINARY_RHS
290 || constant_after_peeling (gimple_assign_rhs2 (stmt),
291 stmt, loop)))
293 size->constant_iv = true;
294 if (dump_file && (dump_flags & TDF_DETAILS))
295 fprintf (dump_file, " Constant expression will be folded away.\n");
296 likely_eliminated = true;
298 /* Conditionals. */
299 else if ((gimple_code (stmt) == GIMPLE_COND
300 && constant_after_peeling (gimple_cond_lhs (stmt), stmt, loop)
301 && constant_after_peeling (gimple_cond_rhs (stmt), stmt, loop))
302 || (gimple_code (stmt) == GIMPLE_SWITCH
303 && constant_after_peeling (gimple_switch_index (stmt), stmt, loop)))
305 if (dump_file && (dump_flags & TDF_DETAILS))
306 fprintf (dump_file, " Constant conditional.\n");
307 likely_eliminated = true;
310 size->overall += num;
311 if (likely_eliminated || likely_eliminated_peeled)
312 size->eliminated_by_peeling += num;
313 if (!after_exit)
315 size->last_iteration += num;
316 if (likely_eliminated || likely_eliminated_last)
317 size->last_iteration_eliminated_by_peeling += num;
321 while (path.length ())
323 basic_block bb = path.pop ();
324 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
326 gimple stmt = gsi_stmt (gsi);
327 if (gimple_code (stmt) == GIMPLE_CALL)
329 int flags = gimple_call_flags (stmt);
330 tree decl = gimple_call_fndecl (stmt);
332 if (decl && DECL_IS_BUILTIN (decl)
333 && is_inexpensive_builtin (decl))
335 else if (flags & (ECF_PURE | ECF_CONST))
336 size->num_pure_calls_on_hot_path++;
337 else
338 size->num_non_pure_calls_on_hot_path++;
339 size->num_branches_on_hot_path ++;
341 else if (gimple_code (stmt) != GIMPLE_CALL
342 && gimple_code (stmt) != GIMPLE_DEBUG)
343 size->non_call_stmts_on_hot_path++;
344 if (((gimple_code (stmt) == GIMPLE_COND
345 && (!constant_after_peeling (gimple_cond_lhs (stmt), stmt, loop)
346 || constant_after_peeling (gimple_cond_rhs (stmt), stmt, loop)))
347 || (gimple_code (stmt) == GIMPLE_SWITCH
348 && !constant_after_peeling (gimple_switch_index (stmt), stmt, loop)))
349 && (!exit || bb != exit->src))
350 size->num_branches_on_hot_path++;
353 path.release ();
354 if (dump_file && (dump_flags & TDF_DETAILS))
355 fprintf (dump_file, "size: %i-%i, last_iteration: %i-%i\n", size->overall,
356 size->eliminated_by_peeling, size->last_iteration,
357 size->last_iteration_eliminated_by_peeling);
359 free (body);
362 /* Estimate number of insns of completely unrolled loop.
363 It is (NUNROLL + 1) * size of loop body with taking into account
364 the fact that in last copy everything after exit conditional
365 is dead and that some instructions will be eliminated after
366 peeling.
368 Loop body is likely going to simplify futher, this is difficult
369 to guess, we just decrease the result by 1/3. */
371 static unsigned HOST_WIDE_INT
372 estimated_unrolled_size (struct loop_size *size,
373 unsigned HOST_WIDE_INT nunroll)
375 HOST_WIDE_INT unr_insns = ((nunroll)
376 * (HOST_WIDE_INT) (size->overall
377 - size->eliminated_by_peeling));
378 if (!nunroll)
379 unr_insns = 0;
380 unr_insns += size->last_iteration - size->last_iteration_eliminated_by_peeling;
382 unr_insns = unr_insns * 2 / 3;
383 if (unr_insns <= 0)
384 unr_insns = 1;
386 return unr_insns;
389 /* Loop LOOP is known to not loop. See if there is an edge in the loop
390 body that can be remove to make the loop to always exit and at
391 the same time it does not make any code potentially executed
392 during the last iteration dead.
394 After complette unrolling we still may get rid of the conditional
395 on the exit in the last copy even if we have no idea what it does.
396 This is quite common case for loops of form
398 int a[5];
399 for (i=0;i<b;i++)
400 a[i]=0;
402 Here we prove the loop to iterate 5 times but we do not know
403 it from induction variable.
405 For now we handle only simple case where there is exit condition
406 just before the latch block and the latch block contains no statements
407 with side effect that may otherwise terminate the execution of loop
408 (such as by EH or by terminating the program or longjmp).
410 In the general case we may want to cancel the paths leading to statements
411 loop-niter identified as having undefined effect in the last iteration.
412 The other cases are hopefully rare and will be cleaned up later. */
414 edge
415 loop_edge_to_cancel (struct loop *loop)
417 vec<edge> exits;
418 unsigned i;
419 edge edge_to_cancel;
420 gimple_stmt_iterator gsi;
422 /* We want only one predecestor of the loop. */
423 if (EDGE_COUNT (loop->latch->preds) > 1)
424 return NULL;
426 exits = get_loop_exit_edges (loop);
428 FOR_EACH_VEC_ELT (exits, i, edge_to_cancel)
430 /* Find the other edge than the loop exit
431 leaving the conditoinal. */
432 if (EDGE_COUNT (edge_to_cancel->src->succs) != 2)
433 continue;
434 if (EDGE_SUCC (edge_to_cancel->src, 0) == edge_to_cancel)
435 edge_to_cancel = EDGE_SUCC (edge_to_cancel->src, 1);
436 else
437 edge_to_cancel = EDGE_SUCC (edge_to_cancel->src, 0);
439 /* We only can handle conditionals. */
440 if (!(edge_to_cancel->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
441 continue;
443 /* We should never have conditionals in the loop latch. */
444 gcc_assert (edge_to_cancel->dest != loop->header);
446 /* Check that it leads to loop latch. */
447 if (edge_to_cancel->dest != loop->latch)
448 continue;
450 exits.release ();
452 /* Verify that the code in loop latch does nothing that may end program
453 execution without really reaching the exit. This may include
454 non-pure/const function calls, EH statements, volatile ASMs etc. */
455 for (gsi = gsi_start_bb (loop->latch); !gsi_end_p (gsi); gsi_next (&gsi))
456 if (gimple_has_side_effects (gsi_stmt (gsi)))
457 return NULL;
458 return edge_to_cancel;
460 exits.release ();
461 return NULL;
464 /* Remove all tests for exits that are known to be taken after LOOP was
465 peeled NPEELED times. Put gcc_unreachable before every statement
466 known to not be executed. */
468 static bool
469 remove_exits_and_undefined_stmts (struct loop *loop, unsigned int npeeled)
471 struct nb_iter_bound *elt;
472 bool changed = false;
474 for (elt = loop->bounds; elt; elt = elt->next)
476 /* If statement is known to be undefined after peeling, turn it
477 into unreachable (or trap when debugging experience is supposed
478 to be good). */
479 if (!elt->is_exit
480 && elt->bound.ult (double_int::from_uhwi (npeeled)))
482 gimple_stmt_iterator gsi = gsi_for_stmt (elt->stmt);
483 gimple stmt = gimple_build_call
484 (builtin_decl_implicit (BUILT_IN_UNREACHABLE), 0);
486 gimple_set_location (stmt, gimple_location (elt->stmt));
487 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
488 changed = true;
489 if (dump_file && (dump_flags & TDF_DETAILS))
491 fprintf (dump_file, "Forced statement unreachable: ");
492 print_gimple_stmt (dump_file, elt->stmt, 0, 0);
495 /* If we know the exit will be taken after peeling, update. */
496 else if (elt->is_exit
497 && elt->bound.ule (double_int::from_uhwi (npeeled)))
499 basic_block bb = gimple_bb (elt->stmt);
500 edge exit_edge = EDGE_SUCC (bb, 0);
502 if (dump_file && (dump_flags & TDF_DETAILS))
504 fprintf (dump_file, "Forced exit to be taken: ");
505 print_gimple_stmt (dump_file, elt->stmt, 0, 0);
507 if (!loop_exit_edge_p (loop, exit_edge))
508 exit_edge = EDGE_SUCC (bb, 1);
509 gcc_checking_assert (loop_exit_edge_p (loop, exit_edge));
510 if (exit_edge->flags & EDGE_TRUE_VALUE)
511 gimple_cond_make_true (elt->stmt);
512 else
513 gimple_cond_make_false (elt->stmt);
514 update_stmt (elt->stmt);
515 changed = true;
518 return changed;
521 /* Remove all exits that are known to be never taken because of the loop bound
522 discovered. */
524 static bool
525 remove_redundant_iv_tests (struct loop *loop)
527 struct nb_iter_bound *elt;
528 bool changed = false;
530 if (!loop->any_upper_bound)
531 return false;
532 for (elt = loop->bounds; elt; elt = elt->next)
534 /* Exit is pointless if it won't be taken before loop reaches
535 upper bound. */
536 if (elt->is_exit && loop->any_upper_bound
537 && loop->nb_iterations_upper_bound.ult (elt->bound))
539 basic_block bb = gimple_bb (elt->stmt);
540 edge exit_edge = EDGE_SUCC (bb, 0);
541 struct tree_niter_desc niter;
543 if (!loop_exit_edge_p (loop, exit_edge))
544 exit_edge = EDGE_SUCC (bb, 1);
546 /* Only when we know the actual number of iterations, not
547 just a bound, we can remove the exit. */
548 if (!number_of_iterations_exit (loop, exit_edge,
549 &niter, false, false))
550 gcc_unreachable ();
551 if (!integer_onep (niter.assumptions)
552 || !integer_zerop (niter.may_be_zero)
553 || !niter.niter
554 || TREE_CODE (niter.niter) != INTEGER_CST
555 || !loop->nb_iterations_upper_bound.ult
556 (tree_to_double_int (niter.niter)))
557 continue;
559 if (dump_file && (dump_flags & TDF_DETAILS))
561 fprintf (dump_file, "Removed pointless exit: ");
562 print_gimple_stmt (dump_file, elt->stmt, 0, 0);
564 if (exit_edge->flags & EDGE_TRUE_VALUE)
565 gimple_cond_make_false (elt->stmt);
566 else
567 gimple_cond_make_true (elt->stmt);
568 update_stmt (elt->stmt);
569 changed = true;
572 return changed;
575 /* Stores loops that will be unlooped after we process whole loop tree. */
576 static vec<loop_p> loops_to_unloop;
577 static vec<int> loops_to_unloop_nunroll;
579 /* Cancel all fully unrolled loops by putting __builtin_unreachable
580 on the latch edge.
581 We do it after all unrolling since unlooping moves basic blocks
582 across loop boundaries trashing loop closed SSA form as well
583 as SCEV info needed to be intact during unrolling.
585 IRRED_INVALIDATED is used to bookkeep if information about
586 irreducible regions may become invalid as a result
587 of the transformation.
588 LOOP_CLOSED_SSA_INVALIDATED is used to bookkepp the case
589 when we need to go into loop closed SSA form. */
591 void
592 unloop_loops (bitmap loop_closed_ssa_invalidated,
593 bool *irred_invalidated)
595 while (loops_to_unloop.length ())
597 struct loop *loop = loops_to_unloop.pop ();
598 int n_unroll = loops_to_unloop_nunroll.pop ();
599 basic_block latch = loop->latch;
600 edge latch_edge = loop_latch_edge (loop);
601 int flags = latch_edge->flags;
602 location_t locus = latch_edge->goto_locus;
603 gimple stmt;
604 gimple_stmt_iterator gsi;
606 remove_exits_and_undefined_stmts (loop, n_unroll);
608 /* Unloop destroys the latch edge. */
609 unloop (loop, irred_invalidated, loop_closed_ssa_invalidated);
611 /* Create new basic block for the latch edge destination and wire
612 it in. */
613 stmt = gimple_build_call (builtin_decl_implicit (BUILT_IN_UNREACHABLE), 0);
614 latch_edge = make_edge (latch, create_basic_block (NULL, NULL, latch), flags);
615 latch_edge->probability = 0;
616 latch_edge->count = 0;
617 latch_edge->flags |= flags;
618 latch_edge->goto_locus = locus;
620 latch_edge->dest->loop_father = current_loops->tree_root;
621 latch_edge->dest->count = 0;
622 latch_edge->dest->frequency = 0;
623 set_immediate_dominator (CDI_DOMINATORS, latch_edge->dest, latch_edge->src);
625 gsi = gsi_start_bb (latch_edge->dest);
626 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
628 loops_to_unloop.release ();
629 loops_to_unloop_nunroll.release ();
632 /* Tries to unroll LOOP completely, i.e. NITER times.
633 UL determines which loops we are allowed to unroll.
634 EXIT is the exit of the loop that should be eliminated.
635 MAXITER specfy bound on number of iterations, -1 if it is
636 not known or too large for HOST_WIDE_INT. */
638 static bool
639 try_unroll_loop_completely (struct loop *loop,
640 edge exit, tree niter,
641 enum unroll_level ul,
642 HOST_WIDE_INT maxiter)
644 unsigned HOST_WIDE_INT n_unroll, ninsns, max_unroll, unr_insns;
645 gimple cond;
646 struct loop_size size;
647 bool n_unroll_found = false;
648 edge edge_to_cancel = NULL;
649 int num = loop->num;
651 /* See if we proved number of iterations to be low constant.
653 EXIT is an edge that will be removed in all but last iteration of
654 the loop.
656 EDGE_TO_CACNEL is an edge that will be removed from the last iteration
657 of the unrolled sequence and is expected to make the final loop not
658 rolling.
660 If the number of execution of loop is determined by standard induction
661 variable test, then EXIT and EDGE_TO_CANCEL are the two edges leaving
662 from the iv test. */
663 if (host_integerp (niter, 1))
665 n_unroll = tree_low_cst (niter, 1);
666 n_unroll_found = true;
667 edge_to_cancel = EDGE_SUCC (exit->src, 0);
668 if (edge_to_cancel == exit)
669 edge_to_cancel = EDGE_SUCC (exit->src, 1);
671 /* We do not know the number of iterations and thus we can not eliminate
672 the EXIT edge. */
673 else
674 exit = NULL;
676 /* See if we can improve our estimate by using recorded loop bounds. */
677 if (maxiter >= 0
678 && (!n_unroll_found || (unsigned HOST_WIDE_INT)maxiter < n_unroll))
680 n_unroll = maxiter;
681 n_unroll_found = true;
682 /* Loop terminates before the IV variable test, so we can not
683 remove it in the last iteration. */
684 edge_to_cancel = NULL;
687 if (!n_unroll_found)
688 return false;
690 max_unroll = PARAM_VALUE (PARAM_MAX_COMPLETELY_PEEL_TIMES);
691 if (n_unroll > max_unroll)
692 return false;
694 if (!edge_to_cancel)
695 edge_to_cancel = loop_edge_to_cancel (loop);
697 if (n_unroll)
699 sbitmap wont_exit;
700 edge e;
701 unsigned i;
702 vec<edge> to_remove = vNULL;
703 if (ul == UL_SINGLE_ITER)
704 return false;
706 tree_estimate_loop_size (loop, exit, edge_to_cancel, &size);
707 ninsns = size.overall;
709 unr_insns = estimated_unrolled_size (&size, n_unroll);
710 if (dump_file && (dump_flags & TDF_DETAILS))
712 fprintf (dump_file, " Loop size: %d\n", (int) ninsns);
713 fprintf (dump_file, " Estimated size after unrolling: %d\n",
714 (int) unr_insns);
717 /* If the code is going to shrink, we don't need to be extra cautious
718 on guessing if the unrolling is going to be profitable. */
719 if (unr_insns
720 /* If there is IV variable that will become constant, we save
721 one instruction in the loop prologue we do not account
722 otherwise. */
723 <= ninsns + (size.constant_iv != false))
725 /* We unroll only inner loops, because we do not consider it profitable
726 otheriwse. We still can cancel loopback edge of not rolling loop;
727 this is always a good idea. */
728 else if (ul == UL_NO_GROWTH)
730 if (dump_file && (dump_flags & TDF_DETAILS))
731 fprintf (dump_file, "Not unrolling loop %d: size would grow.\n",
732 loop->num);
733 return false;
735 /* Outer loops tend to be less interesting candidates for complette
736 unrolling unless we can do a lot of propagation into the inner loop
737 body. For now we disable outer loop unrolling when the code would
738 grow. */
739 else if (loop->inner)
741 if (dump_file && (dump_flags & TDF_DETAILS))
742 fprintf (dump_file, "Not unrolling loop %d: "
743 "it is not innermost and code would grow.\n",
744 loop->num);
745 return false;
747 /* If there is call on a hot path through the loop, then
748 there is most probably not much to optimize. */
749 else if (size.num_non_pure_calls_on_hot_path)
751 if (dump_file && (dump_flags & TDF_DETAILS))
752 fprintf (dump_file, "Not unrolling loop %d: "
753 "contains call and code would grow.\n",
754 loop->num);
755 return false;
757 /* If there is pure/const call in the function, then we
758 can still optimize the unrolled loop body if it contains
759 some other interesting code than the calls and code
760 storing or cumulating the return value. */
761 else if (size.num_pure_calls_on_hot_path
762 /* One IV increment, one test, one ivtmp store
763 and one usefull stmt. That is about minimal loop
764 doing pure call. */
765 && (size.non_call_stmts_on_hot_path
766 <= 3 + size.num_pure_calls_on_hot_path))
768 if (dump_file && (dump_flags & TDF_DETAILS))
769 fprintf (dump_file, "Not unrolling loop %d: "
770 "contains just pure calls and code would grow.\n",
771 loop->num);
772 return false;
774 /* Complette unrolling is major win when control flow is removed and
775 one big basic block is created. If the loop contains control flow
776 the optimization may still be a win because of eliminating the loop
777 overhead but it also may blow the branch predictor tables.
778 Limit number of branches on the hot path through the peeled
779 sequence. */
780 else if (size.num_branches_on_hot_path * (int)n_unroll
781 > PARAM_VALUE (PARAM_MAX_PEEL_BRANCHES))
783 if (dump_file && (dump_flags & TDF_DETAILS))
784 fprintf (dump_file, "Not unrolling loop %d: "
785 " number of branches on hot path in the unrolled sequence"
786 " reach --param max-peel-branches limit.\n",
787 loop->num);
788 return false;
790 else if (unr_insns
791 > (unsigned) PARAM_VALUE (PARAM_MAX_COMPLETELY_PEELED_INSNS))
793 if (dump_file && (dump_flags & TDF_DETAILS))
794 fprintf (dump_file, "Not unrolling loop %d: "
795 "(--param max-completely-peeled-insns limit reached).\n",
796 loop->num);
797 return false;
800 initialize_original_copy_tables ();
801 wont_exit = sbitmap_alloc (n_unroll + 1);
802 bitmap_ones (wont_exit);
803 bitmap_clear_bit (wont_exit, 0);
805 if (!gimple_duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
806 n_unroll, wont_exit,
807 exit, &to_remove,
808 DLTHE_FLAG_UPDATE_FREQ
809 | DLTHE_FLAG_COMPLETTE_PEEL))
811 free_original_copy_tables ();
812 free (wont_exit);
813 if (dump_file && (dump_flags & TDF_DETAILS))
814 fprintf (dump_file, "Failed to duplicate the loop\n");
815 return false;
818 FOR_EACH_VEC_ELT (to_remove, i, e)
820 bool ok = remove_path (e);
821 gcc_assert (ok);
824 to_remove.release ();
825 free (wont_exit);
826 free_original_copy_tables ();
830 /* Remove the conditional from the last copy of the loop. */
831 if (edge_to_cancel)
833 cond = last_stmt (edge_to_cancel->src);
834 if (edge_to_cancel->flags & EDGE_TRUE_VALUE)
835 gimple_cond_make_false (cond);
836 else
837 gimple_cond_make_true (cond);
838 update_stmt (cond);
839 /* Do not remove the path. Doing so may remove outer loop
840 and confuse bookkeeping code in tree_unroll_loops_completelly. */
843 /* Store the loop for later unlooping and exit removal. */
844 loops_to_unloop.safe_push (loop);
845 loops_to_unloop_nunroll.safe_push (n_unroll);
847 if (dump_file && (dump_flags & TDF_DETAILS))
849 if (!n_unroll)
850 fprintf (dump_file, "Turned loop %d to non-loop; it never loops.\n",
851 num);
852 else
853 fprintf (dump_file, "Unrolled loop %d completely "
854 "(duplicated %i times).\n", num, (int)n_unroll);
855 if (exit)
856 fprintf (dump_file, "Exit condition of peeled iterations was "
857 "eliminated.\n");
858 if (edge_to_cancel)
859 fprintf (dump_file, "Last iteration exit edge was proved true.\n");
860 else
861 fprintf (dump_file, "Latch of last iteration was marked by "
862 "__builtin_unreachable ().\n");
865 return true;
868 /* Adds a canonical induction variable to LOOP if suitable.
869 CREATE_IV is true if we may create a new iv. UL determines
870 which loops we are allowed to completely unroll. If TRY_EVAL is true, we try
871 to determine the number of iterations of a loop by direct evaluation.
872 Returns true if cfg is changed. */
874 static bool
875 canonicalize_loop_induction_variables (struct loop *loop,
876 bool create_iv, enum unroll_level ul,
877 bool try_eval)
879 edge exit = NULL;
880 tree niter;
881 HOST_WIDE_INT maxiter;
882 bool modified = false;
884 niter = number_of_latch_executions (loop);
885 if (TREE_CODE (niter) == INTEGER_CST)
886 exit = single_exit (loop);
887 else
889 /* If the loop has more than one exit, try checking all of them
890 for # of iterations determinable through scev. */
891 if (!single_exit (loop))
892 niter = find_loop_niter (loop, &exit);
894 /* Finally if everything else fails, try brute force evaluation. */
895 if (try_eval
896 && (chrec_contains_undetermined (niter)
897 || TREE_CODE (niter) != INTEGER_CST))
898 niter = find_loop_niter_by_eval (loop, &exit);
900 if (TREE_CODE (niter) != INTEGER_CST)
901 exit = NULL;
904 /* We work exceptionally hard here to estimate the bound
905 by find_loop_niter_by_eval. Be sure to keep it for future. */
906 if (niter && TREE_CODE (niter) == INTEGER_CST)
908 record_niter_bound (loop, tree_to_double_int (niter),
909 exit == single_likely_exit (loop), true);
912 /* Force re-computation of loop bounds so we can remove redundant exits. */
913 maxiter = max_loop_iterations_int (loop);
915 if (dump_file && (dump_flags & TDF_DETAILS)
916 && TREE_CODE (niter) == INTEGER_CST)
918 fprintf (dump_file, "Loop %d iterates ", loop->num);
919 print_generic_expr (dump_file, niter, TDF_SLIM);
920 fprintf (dump_file, " times.\n");
922 if (dump_file && (dump_flags & TDF_DETAILS)
923 && maxiter >= 0)
925 fprintf (dump_file, "Loop %d iterates at most %i times.\n", loop->num,
926 (int)maxiter);
929 /* Remove exits that are known to be never taken based on loop bound.
930 Needs to be called after compilation of max_loop_iterations_int that
931 populates the loop bounds. */
932 modified |= remove_redundant_iv_tests (loop);
934 if (try_unroll_loop_completely (loop, exit, niter, ul, maxiter))
935 return true;
937 if (create_iv
938 && niter && !chrec_contains_undetermined (niter)
939 && exit && just_once_each_iteration_p (loop, exit->src))
940 create_canonical_iv (loop, exit, niter);
942 return modified;
945 /* The main entry point of the pass. Adds canonical induction variables
946 to the suitable loops. */
948 unsigned int
949 canonicalize_induction_variables (void)
951 loop_iterator li;
952 struct loop *loop;
953 bool changed = false;
954 bool irred_invalidated = false;
955 bitmap loop_closed_ssa_invalidated = BITMAP_ALLOC (NULL);
957 free_numbers_of_iterations_estimates ();
958 estimate_numbers_of_iterations ();
960 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
962 changed |= canonicalize_loop_induction_variables (loop,
963 true, UL_SINGLE_ITER,
964 true);
966 gcc_assert (!need_ssa_update_p (cfun));
968 unloop_loops (loop_closed_ssa_invalidated, &irred_invalidated);
969 if (irred_invalidated
970 && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS))
971 mark_irreducible_loops ();
973 /* Clean up the information about numbers of iterations, since brute force
974 evaluation could reveal new information. */
975 scev_reset ();
977 if (!bitmap_empty_p (loop_closed_ssa_invalidated))
979 gcc_checking_assert (loops_state_satisfies_p (LOOP_CLOSED_SSA));
980 rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
982 BITMAP_FREE (loop_closed_ssa_invalidated);
984 if (changed)
985 return TODO_cleanup_cfg;
986 return 0;
989 /* Propagate VAL into all uses of SSA_NAME. */
991 static void
992 propagate_into_all_uses (tree ssa_name, tree val)
994 imm_use_iterator iter;
995 gimple use_stmt;
997 FOR_EACH_IMM_USE_STMT (use_stmt, iter, ssa_name)
999 gimple_stmt_iterator use_stmt_gsi = gsi_for_stmt (use_stmt);
1000 use_operand_p use;
1002 FOR_EACH_IMM_USE_ON_STMT (use, iter)
1003 SET_USE (use, val);
1005 if (is_gimple_assign (use_stmt)
1006 && get_gimple_rhs_class (gimple_assign_rhs_code (use_stmt))
1007 == GIMPLE_SINGLE_RHS)
1009 tree rhs = gimple_assign_rhs1 (use_stmt);
1011 if (TREE_CODE (rhs) == ADDR_EXPR)
1012 recompute_tree_invariant_for_addr_expr (rhs);
1015 fold_stmt_inplace (&use_stmt_gsi);
1016 update_stmt (use_stmt);
1017 maybe_clean_or_replace_eh_stmt (use_stmt, use_stmt);
1021 /* Propagate constant SSA_NAMEs defined in basic block BB. */
1023 static void
1024 propagate_constants_for_unrolling (basic_block bb)
1026 gimple_stmt_iterator gsi;
1028 /* Look for degenerate PHI nodes with constant argument. */
1029 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); )
1031 gimple phi = gsi_stmt (gsi);
1032 tree result = gimple_phi_result (phi);
1033 tree arg = gimple_phi_arg_def (phi, 0);
1035 if (gimple_phi_num_args (phi) == 1 && TREE_CODE (arg) == INTEGER_CST)
1037 propagate_into_all_uses (result, arg);
1038 gsi_remove (&gsi, true);
1039 release_ssa_name (result);
1041 else
1042 gsi_next (&gsi);
1045 /* Look for assignments to SSA names with constant RHS. */
1046 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
1048 gimple stmt = gsi_stmt (gsi);
1049 tree lhs;
1051 if (is_gimple_assign (stmt)
1052 && (lhs = gimple_assign_lhs (stmt), TREE_CODE (lhs) == SSA_NAME)
1053 && gimple_assign_rhs_code (stmt) == INTEGER_CST)
1055 propagate_into_all_uses (lhs, gimple_assign_rhs1 (stmt));
1056 gsi_remove (&gsi, true);
1057 release_ssa_name (lhs);
1059 else
1060 gsi_next (&gsi);
1064 /* Unroll LOOPS completely if they iterate just few times. Unless
1065 MAY_INCREASE_SIZE is true, perform the unrolling only if the
1066 size of the code does not increase. */
1068 unsigned int
1069 tree_unroll_loops_completely (bool may_increase_size, bool unroll_outer)
1071 vec<loop_p, va_stack> father_stack;
1072 loop_iterator li;
1073 struct loop *loop;
1074 bool changed;
1075 enum unroll_level ul;
1076 int iteration = 0;
1077 bool irred_invalidated = false;
1079 vec_stack_alloc (loop_p, father_stack, 16);
1082 changed = false;
1083 bitmap loop_closed_ssa_invalidated = NULL;
1085 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
1086 loop_closed_ssa_invalidated = BITMAP_ALLOC (NULL);
1088 free_numbers_of_iterations_estimates ();
1089 estimate_numbers_of_iterations ();
1091 FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1093 struct loop *loop_father = loop_outer (loop);
1095 if (may_increase_size && optimize_loop_nest_for_speed_p (loop)
1096 /* Unroll outermost loops only if asked to do so or they do
1097 not cause code growth. */
1098 && (unroll_outer || loop_outer (loop_father)))
1099 ul = UL_ALL;
1100 else
1101 ul = UL_NO_GROWTH;
1103 if (canonicalize_loop_induction_variables
1104 (loop, false, ul, !flag_tree_loop_ivcanon))
1106 changed = true;
1107 /* If we'll continue unrolling, we need to propagate constants
1108 within the new basic blocks to fold away induction variable
1109 computations; otherwise, the size might blow up before the
1110 iteration is complete and the IR eventually cleaned up. */
1111 if (loop_outer (loop_father) && !loop_father->aux)
1113 father_stack.safe_push (loop_father);
1114 loop_father->aux = loop_father;
1119 if (changed)
1121 struct loop **iter;
1122 unsigned i;
1124 /* Be sure to skip unlooped loops while procesing father_stack
1125 array. */
1126 FOR_EACH_VEC_ELT (loops_to_unloop, i, iter)
1127 (*iter)->aux = NULL;
1128 FOR_EACH_VEC_ELT (father_stack, i, iter)
1129 if (!(*iter)->aux)
1130 *iter = NULL;
1131 unloop_loops (loop_closed_ssa_invalidated, &irred_invalidated);
1133 /* We can not use TODO_update_ssa_no_phi because VOPS gets confused. */
1134 if (loop_closed_ssa_invalidated
1135 && !bitmap_empty_p (loop_closed_ssa_invalidated))
1136 rewrite_into_loop_closed_ssa (loop_closed_ssa_invalidated,
1137 TODO_update_ssa);
1138 else
1139 update_ssa (TODO_update_ssa);
1141 /* Propagate the constants within the new basic blocks. */
1142 FOR_EACH_VEC_ELT (father_stack, i, iter)
1143 if (*iter)
1145 unsigned j;
1146 basic_block *body = get_loop_body_in_dom_order (*iter);
1147 for (j = 0; j < (*iter)->num_nodes; j++)
1148 propagate_constants_for_unrolling (body[j]);
1149 free (body);
1150 (*iter)->aux = NULL;
1152 father_stack.truncate (0);
1154 /* This will take care of removing completely unrolled loops
1155 from the loop structures so we can continue unrolling now
1156 innermost loops. */
1157 if (cleanup_tree_cfg ())
1158 update_ssa (TODO_update_ssa_only_virtuals);
1160 /* Clean up the information about numbers of iterations, since
1161 complete unrolling might have invalidated it. */
1162 scev_reset ();
1163 #ifdef ENABLE_CHECKING
1164 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
1165 verify_loop_closed_ssa (true);
1166 #endif
1168 if (loop_closed_ssa_invalidated)
1169 BITMAP_FREE (loop_closed_ssa_invalidated);
1171 while (changed
1172 && ++iteration <= PARAM_VALUE (PARAM_MAX_UNROLL_ITERATIONS));
1174 father_stack.release ();
1176 if (irred_invalidated
1177 && loops_state_satisfies_p (LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS))
1178 mark_irreducible_loops ();
1180 return 0;