]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-ssa-loop-ivcanon.c
* doc/loop.texi: Document number_of_latch_executions and
[thirdparty/gcc.git] / gcc / tree-ssa-loop-ivcanon.c
1 /* Induction variable canonicalization.
2 Copyright (C) 2004, 2005 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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 2, or (at your option) any
9 later version.
10
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.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING. If not, write to the Free
18 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301, USA. */
20
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.
25
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.
31
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. */
35
36 #include "config.h"
37 #include "system.h"
38 #include "coretypes.h"
39 #include "tm.h"
40 #include "tree.h"
41 #include "rtl.h"
42 #include "tm_p.h"
43 #include "hard-reg-set.h"
44 #include "basic-block.h"
45 #include "output.h"
46 #include "diagnostic.h"
47 #include "tree-flow.h"
48 #include "tree-dump.h"
49 #include "cfgloop.h"
50 #include "tree-pass.h"
51 #include "ggc.h"
52 #include "tree-chrec.h"
53 #include "tree-scalar-evolution.h"
54 #include "params.h"
55 #include "flags.h"
56 #include "tree-inline.h"
57
58 /* Specifies types of loops that may be unrolled. */
59
60 enum unroll_level
61 {
62 UL_SINGLE_ITER, /* Only loops that exit immediately in the first
63 iteration. */
64 UL_NO_GROWTH, /* Only loops whose unrolling will not cause increase
65 of code size. */
66 UL_ALL /* All suitable loops. */
67 };
68
69 /* Adds a canonical induction variable to LOOP iterating NITER times. EXIT
70 is the exit edge whose condition is replaced. */
71
72 static void
73 create_canonical_iv (struct loop *loop, edge exit, tree niter)
74 {
75 edge in;
76 tree cond, type, var;
77 block_stmt_iterator incr_at;
78 enum tree_code cmp;
79
80 if (dump_file && (dump_flags & TDF_DETAILS))
81 {
82 fprintf (dump_file, "Added canonical iv to loop %d, ", loop->num);
83 print_generic_expr (dump_file, niter, TDF_SLIM);
84 fprintf (dump_file, " iterations.\n");
85 }
86
87 cond = last_stmt (exit->src);
88 in = EDGE_SUCC (exit->src, 0);
89 if (in == exit)
90 in = EDGE_SUCC (exit->src, 1);
91
92 /* Note that we do not need to worry about overflows, since
93 type of niter is always unsigned and all comparisons are
94 just for equality/nonequality -- i.e. everything works
95 with a modulo arithmetics. */
96
97 type = TREE_TYPE (niter);
98 niter = fold_build2 (PLUS_EXPR, type,
99 niter,
100 build_int_cst (type, 1));
101 incr_at = bsi_last (in->src);
102 create_iv (niter,
103 build_int_cst (type, -1),
104 NULL_TREE, loop,
105 &incr_at, false, NULL, &var);
106
107 cmp = (exit->flags & EDGE_TRUE_VALUE) ? EQ_EXPR : NE_EXPR;
108 COND_EXPR_COND (cond) = build2 (cmp, boolean_type_node,
109 var,
110 build_int_cst (type, 0));
111 update_stmt (cond);
112 }
113
114 /* Computes an estimated number of insns in LOOP. */
115
116 unsigned
117 tree_num_loop_insns (struct loop *loop)
118 {
119 basic_block *body = get_loop_body (loop);
120 block_stmt_iterator bsi;
121 unsigned size = 1, i;
122
123 for (i = 0; i < loop->num_nodes; i++)
124 for (bsi = bsi_start (body[i]); !bsi_end_p (bsi); bsi_next (&bsi))
125 size += estimate_num_insns (bsi_stmt (bsi));
126 free (body);
127
128 return size;
129 }
130
131 /* Estimate number of insns of completely unrolled loop. We assume
132 that the size of the unrolled loop is decreased in the
133 following way (the numbers of insns are based on what
134 estimate_num_insns returns for appropriate statements):
135
136 1) exit condition gets removed (2 insns)
137 2) increment of the control variable gets removed (2 insns)
138 3) All remaining statements are likely to get simplified
139 due to constant propagation. Hard to estimate; just
140 as a heuristics we decrease the rest by 1/3.
141
142 NINSNS is the number of insns in the loop before unrolling.
143 NUNROLL is the number of times the loop is unrolled. */
144
145 static unsigned HOST_WIDE_INT
146 estimated_unrolled_size (unsigned HOST_WIDE_INT ninsns,
147 unsigned HOST_WIDE_INT nunroll)
148 {
149 HOST_WIDE_INT unr_insns = 2 * ((HOST_WIDE_INT) ninsns - 4) / 3;
150 if (unr_insns <= 0)
151 unr_insns = 1;
152 unr_insns *= (nunroll + 1);
153
154 return unr_insns;
155 }
156
157 /* Tries to unroll LOOP completely, i.e. NITER times.
158 UL determines which loops we are allowed to unroll.
159 EXIT is the exit of the loop that should be eliminated. */
160
161 static bool
162 try_unroll_loop_completely (struct loop *loop,
163 edge exit, tree niter,
164 enum unroll_level ul)
165 {
166 unsigned HOST_WIDE_INT n_unroll, ninsns, max_unroll, unr_insns;
167 tree old_cond, cond, dont_exit, do_exit;
168
169 if (loop->inner)
170 return false;
171
172 if (!host_integerp (niter, 1))
173 return false;
174 n_unroll = tree_low_cst (niter, 1);
175
176 max_unroll = PARAM_VALUE (PARAM_MAX_COMPLETELY_PEEL_TIMES);
177 if (n_unroll > max_unroll)
178 return false;
179
180 if (n_unroll)
181 {
182 if (ul == UL_SINGLE_ITER)
183 return false;
184
185 ninsns = tree_num_loop_insns (loop);
186
187 if (n_unroll * ninsns
188 > (unsigned) PARAM_VALUE (PARAM_MAX_COMPLETELY_PEELED_INSNS))
189 return false;
190
191 if (ul == UL_NO_GROWTH)
192 {
193 unr_insns = estimated_unrolled_size (ninsns, n_unroll);
194
195 if (dump_file && (dump_flags & TDF_DETAILS))
196 {
197 fprintf (dump_file, " Loop size: %d\n", (int) ninsns);
198 fprintf (dump_file, " Estimated size after unrolling: %d\n",
199 (int) unr_insns);
200 }
201
202 if (unr_insns > ninsns)
203 {
204 if (dump_file && (dump_flags & TDF_DETAILS))
205 fprintf (dump_file, "Not unrolling loop %d:\n", loop->num);
206 return false;
207 }
208 }
209 }
210
211 if (exit->flags & EDGE_TRUE_VALUE)
212 {
213 dont_exit = boolean_false_node;
214 do_exit = boolean_true_node;
215 }
216 else
217 {
218 dont_exit = boolean_true_node;
219 do_exit = boolean_false_node;
220 }
221 cond = last_stmt (exit->src);
222
223 if (n_unroll)
224 {
225 sbitmap wont_exit;
226 edge *edges_to_remove = XNEWVEC (edge, n_unroll);
227 unsigned int n_to_remove = 0;
228
229 old_cond = COND_EXPR_COND (cond);
230 COND_EXPR_COND (cond) = dont_exit;
231 update_stmt (cond);
232 initialize_original_copy_tables ();
233
234 wont_exit = sbitmap_alloc (n_unroll + 1);
235 sbitmap_ones (wont_exit);
236 RESET_BIT (wont_exit, 0);
237
238 if (!tree_duplicate_loop_to_header_edge (loop, loop_preheader_edge (loop),
239 n_unroll, wont_exit,
240 exit, edges_to_remove,
241 &n_to_remove,
242 DLTHE_FLAG_UPDATE_FREQ
243 | DLTHE_FLAG_COMPLETTE_PEEL))
244 {
245 COND_EXPR_COND (cond) = old_cond;
246 update_stmt (cond);
247 free_original_copy_tables ();
248 free (wont_exit);
249 free (edges_to_remove);
250 return false;
251 }
252 free (wont_exit);
253 free (edges_to_remove);
254 free_original_copy_tables ();
255 }
256
257 COND_EXPR_COND (cond) = do_exit;
258 update_stmt (cond);
259
260 update_ssa (TODO_update_ssa);
261
262 if (dump_file && (dump_flags & TDF_DETAILS))
263 fprintf (dump_file, "Unrolled loop %d completely.\n", loop->num);
264
265 return true;
266 }
267
268 /* Adds a canonical induction variable to LOOP if suitable.
269 CREATE_IV is true if we may create a new iv. UL determines
270 which loops we are allowed to completely unroll. If TRY_EVAL is true, we try
271 to determine the number of iterations of a loop by direct evaluation.
272 Returns true if cfg is changed. */
273
274 static bool
275 canonicalize_loop_induction_variables (struct loop *loop,
276 bool create_iv, enum unroll_level ul,
277 bool try_eval)
278 {
279 edge exit = NULL;
280 tree niter;
281
282 niter = number_of_latch_executions (loop);
283 if (TREE_CODE (niter) == INTEGER_CST)
284 {
285 exit = single_exit (loop);
286 if (!just_once_each_iteration_p (loop, exit->src))
287 return false;
288 }
289 else
290 {
291 /* If the loop has more than one exit, try checking all of them
292 for # of iterations determinable through scev. */
293 if (!single_exit (loop))
294 niter = find_loop_niter (loop, &exit);
295
296 /* Finally if everything else fails, try brute force evaluation. */
297 if (try_eval
298 && (chrec_contains_undetermined (niter)
299 || TREE_CODE (niter) != INTEGER_CST))
300 niter = find_loop_niter_by_eval (loop, &exit);
301
302 if (chrec_contains_undetermined (niter)
303 || TREE_CODE (niter) != INTEGER_CST)
304 return false;
305 }
306
307 if (dump_file && (dump_flags & TDF_DETAILS))
308 {
309 fprintf (dump_file, "Loop %d iterates ", loop->num);
310 print_generic_expr (dump_file, niter, TDF_SLIM);
311 fprintf (dump_file, " times.\n");
312 }
313
314 if (try_unroll_loop_completely (loop, exit, niter, ul))
315 return true;
316
317 if (create_iv)
318 create_canonical_iv (loop, exit, niter);
319
320 return false;
321 }
322
323 /* The main entry point of the pass. Adds canonical induction variables
324 to the suitable loops. */
325
326 unsigned int
327 canonicalize_induction_variables (void)
328 {
329 loop_iterator li;
330 struct loop *loop;
331 bool changed = false;
332
333 FOR_EACH_LOOP (li, loop, 0)
334 {
335 changed |= canonicalize_loop_induction_variables (loop,
336 true, UL_SINGLE_ITER,
337 true);
338 }
339
340 /* Clean up the information about numbers of iterations, since brute force
341 evaluation could reveal new information. */
342 scev_reset ();
343
344 if (changed)
345 return TODO_cleanup_cfg;
346 return 0;
347 }
348
349 /* Unroll LOOPS completely if they iterate just few times. Unless
350 MAY_INCREASE_SIZE is true, perform the unrolling only if the
351 size of the code does not increase. */
352
353 unsigned int
354 tree_unroll_loops_completely (bool may_increase_size)
355 {
356 loop_iterator li;
357 struct loop *loop;
358 bool changed = false;
359 enum unroll_level ul;
360
361 FOR_EACH_LOOP (li, loop, 0)
362 {
363 if (may_increase_size && maybe_hot_bb_p (loop->header))
364 ul = UL_ALL;
365 else
366 ul = UL_NO_GROWTH;
367 changed |= canonicalize_loop_induction_variables (loop,
368 false, ul,
369 !flag_tree_loop_ivcanon);
370 }
371
372 /* Clean up the information about numbers of iterations, since complete
373 unrolling might have invalidated it. */
374 scev_reset ();
375
376 if (changed)
377 return TODO_cleanup_cfg;
378 return 0;
379 }
380
381 /* Checks whether LOOP is empty. */
382
383 static bool
384 empty_loop_p (struct loop *loop)
385 {
386 edge exit;
387 struct tree_niter_desc niter;
388 tree phi, def;
389 basic_block *body;
390 block_stmt_iterator bsi;
391 unsigned i;
392 tree stmt;
393
394 /* If the loop has multiple exits, it is too hard for us to handle.
395 Similarly, if the exit is not dominating, we cannot determine
396 whether the loop is not infinite. */
397 exit = single_dom_exit (loop);
398 if (!exit)
399 return false;
400
401 /* The loop must be finite. */
402 if (!number_of_iterations_exit (loop, exit, &niter, false))
403 return false;
404
405 /* Values of all loop exit phi nodes must be invariants. */
406 for (phi = phi_nodes (exit->dest); phi; phi = PHI_CHAIN (phi))
407 {
408 if (!is_gimple_reg (PHI_RESULT (phi)))
409 continue;
410
411 def = PHI_ARG_DEF_FROM_EDGE (phi, exit);
412
413 if (!expr_invariant_in_loop_p (loop, def))
414 return false;
415 }
416
417 /* And there should be no memory modifying or from other reasons
418 unremovable statements. */
419 body = get_loop_body (loop);
420 for (i = 0; i < loop->num_nodes; i++)
421 {
422 /* Irreducible region might be infinite. */
423 if (body[i]->flags & BB_IRREDUCIBLE_LOOP)
424 {
425 free (body);
426 return false;
427 }
428
429 for (bsi = bsi_start (body[i]); !bsi_end_p (bsi); bsi_next (&bsi))
430 {
431 stmt = bsi_stmt (bsi);
432 if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_VIRTUAL_DEFS)
433 || stmt_ann (stmt)->has_volatile_ops)
434 {
435 free (body);
436 return false;
437 }
438
439 /* Also, asm statements and calls may have side effects and we
440 cannot change the number of times they are executed. */
441 switch (TREE_CODE (stmt))
442 {
443 case RETURN_EXPR:
444 case GIMPLE_MODIFY_STMT:
445 stmt = get_call_expr_in (stmt);
446 if (!stmt)
447 break;
448
449 case CALL_EXPR:
450 if (TREE_SIDE_EFFECTS (stmt))
451 {
452 free (body);
453 return false;
454 }
455 break;
456
457 case ASM_EXPR:
458 /* We cannot remove volatile assembler. */
459 if (ASM_VOLATILE_P (stmt))
460 {
461 free (body);
462 return false;
463 }
464 break;
465
466 default:
467 break;
468 }
469 }
470 }
471 free (body);
472
473 return true;
474 }
475
476 /* Remove LOOP by making it exit in the first iteration. */
477
478 static void
479 remove_empty_loop (struct loop *loop)
480 {
481 edge exit = single_dom_exit (loop), non_exit;
482 tree cond_stmt = last_stmt (exit->src);
483 tree do_exit;
484 basic_block *body;
485 unsigned n_before, freq_in, freq_h;
486 gcov_type exit_count = exit->count;
487
488 non_exit = EDGE_SUCC (exit->src, 0);
489 if (non_exit == exit)
490 non_exit = EDGE_SUCC (exit->src, 1);
491
492 if (exit->flags & EDGE_TRUE_VALUE)
493 do_exit = boolean_true_node;
494 else
495 do_exit = boolean_false_node;
496
497 COND_EXPR_COND (cond_stmt) = do_exit;
498 update_stmt (cond_stmt);
499
500 /* Let us set the probabilities of the edges coming from the exit block. */
501 exit->probability = REG_BR_PROB_BASE;
502 non_exit->probability = 0;
503 non_exit->count = 0;
504
505 /* Update frequencies and counts. Everything before
506 the exit needs to be scaled FREQ_IN/FREQ_H times,
507 where FREQ_IN is the frequency of the entry edge
508 and FREQ_H is the frequency of the loop header.
509 Everything after the exit has zero frequency. */
510 freq_h = loop->header->frequency;
511 freq_in = EDGE_FREQUENCY (loop_preheader_edge (loop));
512 if (freq_h != 0)
513 {
514 body = get_loop_body_in_dom_order (loop);
515 for (n_before = 1; n_before <= loop->num_nodes; n_before++)
516 if (body[n_before - 1] == exit->src)
517 break;
518 scale_bbs_frequencies_int (body, n_before, freq_in, freq_h);
519 scale_bbs_frequencies_int (body + n_before, loop->num_nodes - n_before,
520 0, 1);
521 free (body);
522 }
523
524 /* Number of executions of exit is not changed, thus we need to restore
525 the original value. */
526 exit->count = exit_count;
527 }
528
529 /* Removes LOOP if it is empty. Returns true if LOOP is removed. CHANGED
530 is set to true if LOOP or any of its subloops is removed. */
531
532 static bool
533 try_remove_empty_loop (struct loop *loop, bool *changed)
534 {
535 bool nonempty_subloop = false;
536 struct loop *sub;
537
538 /* First, all subloops must be removed. */
539 for (sub = loop->inner; sub; sub = sub->next)
540 nonempty_subloop |= !try_remove_empty_loop (sub, changed);
541
542 if (nonempty_subloop || !empty_loop_p (loop))
543 return false;
544
545 remove_empty_loop (loop);
546 *changed = true;
547 return true;
548 }
549
550 /* Remove the empty loops. */
551
552 unsigned int
553 remove_empty_loops (void)
554 {
555 bool changed = false;
556 struct loop *loop;
557
558 for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
559 try_remove_empty_loop (loop, &changed);
560
561 if (changed)
562 {
563 scev_reset ();
564 return TODO_cleanup_cfg;
565 }
566 return 0;
567 }