gcc/
[official-gcc.git] / gcc / tree-ssa-loop-niter.c
blobfd32d2808a38b031f13408d6b6a025707a5266e3
1 /* Functions to determine/estimate number of iterations of a loop.
2 Copyright (C) 2004-2014 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 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "calls.h"
26 #include "expr.h"
27 #include "tm_p.h"
28 #include "predict.h"
29 #include "vec.h"
30 #include "hashtab.h"
31 #include "hash-set.h"
32 #include "machmode.h"
33 #include "hard-reg-set.h"
34 #include "input.h"
35 #include "function.h"
36 #include "dominance.h"
37 #include "cfg.h"
38 #include "basic-block.h"
39 #include "gimple-pretty-print.h"
40 #include "intl.h"
41 #include "tree-ssa-alias.h"
42 #include "internal-fn.h"
43 #include "gimple-expr.h"
44 #include "is-a.h"
45 #include "gimple.h"
46 #include "gimplify.h"
47 #include "gimple-iterator.h"
48 #include "gimple-ssa.h"
49 #include "tree-cfg.h"
50 #include "tree-phinodes.h"
51 #include "ssa-iterators.h"
52 #include "tree-ssa-loop-ivopts.h"
53 #include "tree-ssa-loop-niter.h"
54 #include "tree-ssa-loop.h"
55 #include "dumpfile.h"
56 #include "cfgloop.h"
57 #include "tree-chrec.h"
58 #include "tree-scalar-evolution.h"
59 #include "tree-data-ref.h"
60 #include "params.h"
61 #include "flags.h"
62 #include "diagnostic-core.h"
63 #include "tree-inline.h"
64 #include "tree-pass.h"
65 #include "stringpool.h"
66 #include "tree-ssanames.h"
67 #include "wide-int-print.h"
70 #define SWAP(X, Y) do { affine_iv *tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
72 /* The maximum number of dominator BBs we search for conditions
73 of loop header copies we use for simplifying a conditional
74 expression. */
75 #define MAX_DOMINATORS_TO_WALK 8
79 Analysis of number of iterations of an affine exit test.
83 /* Bounds on some value, BELOW <= X <= UP. */
85 typedef struct
87 mpz_t below, up;
88 } bounds;
91 /* Splits expression EXPR to a variable part VAR and constant OFFSET. */
93 static void
94 split_to_var_and_offset (tree expr, tree *var, mpz_t offset)
96 tree type = TREE_TYPE (expr);
97 tree op0, op1;
98 bool negate = false;
100 *var = expr;
101 mpz_set_ui (offset, 0);
103 switch (TREE_CODE (expr))
105 case MINUS_EXPR:
106 negate = true;
107 /* Fallthru. */
109 case PLUS_EXPR:
110 case POINTER_PLUS_EXPR:
111 op0 = TREE_OPERAND (expr, 0);
112 op1 = TREE_OPERAND (expr, 1);
114 if (TREE_CODE (op1) != INTEGER_CST)
115 break;
117 *var = op0;
118 /* Always sign extend the offset. */
119 wi::to_mpz (op1, offset, SIGNED);
120 if (negate)
121 mpz_neg (offset, offset);
122 break;
124 case INTEGER_CST:
125 *var = build_int_cst_type (type, 0);
126 wi::to_mpz (expr, offset, TYPE_SIGN (type));
127 break;
129 default:
130 break;
134 /* Stores estimate on the minimum/maximum value of the expression VAR + OFF
135 in TYPE to MIN and MAX. */
137 static void
138 determine_value_range (struct loop *loop, tree type, tree var, mpz_t off,
139 mpz_t min, mpz_t max)
141 wide_int minv, maxv;
142 enum value_range_type rtype = VR_VARYING;
144 /* If the expression is a constant, we know its value exactly. */
145 if (integer_zerop (var))
147 mpz_set (min, off);
148 mpz_set (max, off);
149 return;
152 get_type_static_bounds (type, min, max);
154 /* See if we have some range info from VRP. */
155 if (TREE_CODE (var) == SSA_NAME && INTEGRAL_TYPE_P (type))
157 edge e = loop_preheader_edge (loop);
158 signop sgn = TYPE_SIGN (type);
159 gimple_stmt_iterator gsi;
161 /* Either for VAR itself... */
162 rtype = get_range_info (var, &minv, &maxv);
163 /* Or for PHI results in loop->header where VAR is used as
164 PHI argument from the loop preheader edge. */
165 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
167 gimple phi = gsi_stmt (gsi);
168 wide_int minc, maxc;
169 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var
170 && (get_range_info (gimple_phi_result (phi), &minc, &maxc)
171 == VR_RANGE))
173 if (rtype != VR_RANGE)
175 rtype = VR_RANGE;
176 minv = minc;
177 maxv = maxc;
179 else
181 minv = wi::max (minv, minc, sgn);
182 maxv = wi::min (maxv, maxc, sgn);
183 /* If the PHI result range are inconsistent with
184 the VAR range, give up on looking at the PHI
185 results. This can happen if VR_UNDEFINED is
186 involved. */
187 if (wi::gt_p (minv, maxv, sgn))
189 rtype = get_range_info (var, &minv, &maxv);
190 break;
195 if (rtype == VR_RANGE)
197 mpz_t minm, maxm;
198 gcc_assert (wi::le_p (minv, maxv, sgn));
199 mpz_init (minm);
200 mpz_init (maxm);
201 wi::to_mpz (minv, minm, sgn);
202 wi::to_mpz (maxv, maxm, sgn);
203 mpz_add (minm, minm, off);
204 mpz_add (maxm, maxm, off);
205 /* If the computation may not wrap or off is zero, then this
206 is always fine. If off is negative and minv + off isn't
207 smaller than type's minimum, or off is positive and
208 maxv + off isn't bigger than type's maximum, use the more
209 precise range too. */
210 if (nowrap_type_p (type)
211 || mpz_sgn (off) == 0
212 || (mpz_sgn (off) < 0 && mpz_cmp (minm, min) >= 0)
213 || (mpz_sgn (off) > 0 && mpz_cmp (maxm, max) <= 0))
215 mpz_set (min, minm);
216 mpz_set (max, maxm);
217 mpz_clear (minm);
218 mpz_clear (maxm);
219 return;
221 mpz_clear (minm);
222 mpz_clear (maxm);
226 /* If the computation may wrap, we know nothing about the value, except for
227 the range of the type. */
228 if (!nowrap_type_p (type))
229 return;
231 /* Since the addition of OFF does not wrap, if OFF is positive, then we may
232 add it to MIN, otherwise to MAX. */
233 if (mpz_sgn (off) < 0)
234 mpz_add (max, max, off);
235 else
236 mpz_add (min, min, off);
239 /* Stores the bounds on the difference of the values of the expressions
240 (var + X) and (var + Y), computed in TYPE, to BNDS. */
242 static void
243 bound_difference_of_offsetted_base (tree type, mpz_t x, mpz_t y,
244 bounds *bnds)
246 int rel = mpz_cmp (x, y);
247 bool may_wrap = !nowrap_type_p (type);
248 mpz_t m;
250 /* If X == Y, then the expressions are always equal.
251 If X > Y, there are the following possibilities:
252 a) neither of var + X and var + Y overflow or underflow, or both of
253 them do. Then their difference is X - Y.
254 b) var + X overflows, and var + Y does not. Then the values of the
255 expressions are var + X - M and var + Y, where M is the range of
256 the type, and their difference is X - Y - M.
257 c) var + Y underflows and var + X does not. Their difference again
258 is M - X + Y.
259 Therefore, if the arithmetics in type does not overflow, then the
260 bounds are (X - Y, X - Y), otherwise they are (X - Y - M, X - Y)
261 Similarly, if X < Y, the bounds are either (X - Y, X - Y) or
262 (X - Y, X - Y + M). */
264 if (rel == 0)
266 mpz_set_ui (bnds->below, 0);
267 mpz_set_ui (bnds->up, 0);
268 return;
271 mpz_init (m);
272 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), m, UNSIGNED);
273 mpz_add_ui (m, m, 1);
274 mpz_sub (bnds->up, x, y);
275 mpz_set (bnds->below, bnds->up);
277 if (may_wrap)
279 if (rel > 0)
280 mpz_sub (bnds->below, bnds->below, m);
281 else
282 mpz_add (bnds->up, bnds->up, m);
285 mpz_clear (m);
288 /* From condition C0 CMP C1 derives information regarding the
289 difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
290 and stores it to BNDS. */
292 static void
293 refine_bounds_using_guard (tree type, tree varx, mpz_t offx,
294 tree vary, mpz_t offy,
295 tree c0, enum tree_code cmp, tree c1,
296 bounds *bnds)
298 tree varc0, varc1, tmp, ctype;
299 mpz_t offc0, offc1, loffx, loffy, bnd;
300 bool lbound = false;
301 bool no_wrap = nowrap_type_p (type);
302 bool x_ok, y_ok;
304 switch (cmp)
306 case LT_EXPR:
307 case LE_EXPR:
308 case GT_EXPR:
309 case GE_EXPR:
310 STRIP_SIGN_NOPS (c0);
311 STRIP_SIGN_NOPS (c1);
312 ctype = TREE_TYPE (c0);
313 if (!useless_type_conversion_p (ctype, type))
314 return;
316 break;
318 case EQ_EXPR:
319 /* We could derive quite precise information from EQ_EXPR, however, such
320 a guard is unlikely to appear, so we do not bother with handling
321 it. */
322 return;
324 case NE_EXPR:
325 /* NE_EXPR comparisons do not contain much of useful information, except for
326 special case of comparing with the bounds of the type. */
327 if (TREE_CODE (c1) != INTEGER_CST
328 || !INTEGRAL_TYPE_P (type))
329 return;
331 /* Ensure that the condition speaks about an expression in the same type
332 as X and Y. */
333 ctype = TREE_TYPE (c0);
334 if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
335 return;
336 c0 = fold_convert (type, c0);
337 c1 = fold_convert (type, c1);
339 if (TYPE_MIN_VALUE (type)
340 && operand_equal_p (c1, TYPE_MIN_VALUE (type), 0))
342 cmp = GT_EXPR;
343 break;
345 if (TYPE_MAX_VALUE (type)
346 && operand_equal_p (c1, TYPE_MAX_VALUE (type), 0))
348 cmp = LT_EXPR;
349 break;
352 return;
353 default:
354 return;
357 mpz_init (offc0);
358 mpz_init (offc1);
359 split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
360 split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
362 /* We are only interested in comparisons of expressions based on VARX and
363 VARY. TODO -- we might also be able to derive some bounds from
364 expressions containing just one of the variables. */
366 if (operand_equal_p (varx, varc1, 0))
368 tmp = varc0; varc0 = varc1; varc1 = tmp;
369 mpz_swap (offc0, offc1);
370 cmp = swap_tree_comparison (cmp);
373 if (!operand_equal_p (varx, varc0, 0)
374 || !operand_equal_p (vary, varc1, 0))
375 goto end;
377 mpz_init_set (loffx, offx);
378 mpz_init_set (loffy, offy);
380 if (cmp == GT_EXPR || cmp == GE_EXPR)
382 tmp = varx; varx = vary; vary = tmp;
383 mpz_swap (offc0, offc1);
384 mpz_swap (loffx, loffy);
385 cmp = swap_tree_comparison (cmp);
386 lbound = true;
389 /* If there is no overflow, the condition implies that
391 (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
393 The overflows and underflows may complicate things a bit; each
394 overflow decreases the appropriate offset by M, and underflow
395 increases it by M. The above inequality would not necessarily be
396 true if
398 -- VARX + OFFX underflows and VARX + OFFC0 does not, or
399 VARX + OFFC0 overflows, but VARX + OFFX does not.
400 This may only happen if OFFX < OFFC0.
401 -- VARY + OFFY overflows and VARY + OFFC1 does not, or
402 VARY + OFFC1 underflows and VARY + OFFY does not.
403 This may only happen if OFFY > OFFC1. */
405 if (no_wrap)
407 x_ok = true;
408 y_ok = true;
410 else
412 x_ok = (integer_zerop (varx)
413 || mpz_cmp (loffx, offc0) >= 0);
414 y_ok = (integer_zerop (vary)
415 || mpz_cmp (loffy, offc1) <= 0);
418 if (x_ok && y_ok)
420 mpz_init (bnd);
421 mpz_sub (bnd, loffx, loffy);
422 mpz_add (bnd, bnd, offc1);
423 mpz_sub (bnd, bnd, offc0);
425 if (cmp == LT_EXPR)
426 mpz_sub_ui (bnd, bnd, 1);
428 if (lbound)
430 mpz_neg (bnd, bnd);
431 if (mpz_cmp (bnds->below, bnd) < 0)
432 mpz_set (bnds->below, bnd);
434 else
436 if (mpz_cmp (bnd, bnds->up) < 0)
437 mpz_set (bnds->up, bnd);
439 mpz_clear (bnd);
442 mpz_clear (loffx);
443 mpz_clear (loffy);
444 end:
445 mpz_clear (offc0);
446 mpz_clear (offc1);
449 /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
450 The subtraction is considered to be performed in arbitrary precision,
451 without overflows.
453 We do not attempt to be too clever regarding the value ranges of X and
454 Y; most of the time, they are just integers or ssa names offsetted by
455 integer. However, we try to use the information contained in the
456 comparisons before the loop (usually created by loop header copying). */
458 static void
459 bound_difference (struct loop *loop, tree x, tree y, bounds *bnds)
461 tree type = TREE_TYPE (x);
462 tree varx, vary;
463 mpz_t offx, offy;
464 mpz_t minx, maxx, miny, maxy;
465 int cnt = 0;
466 edge e;
467 basic_block bb;
468 tree c0, c1;
469 gimple cond;
470 enum tree_code cmp;
472 /* Get rid of unnecessary casts, but preserve the value of
473 the expressions. */
474 STRIP_SIGN_NOPS (x);
475 STRIP_SIGN_NOPS (y);
477 mpz_init (bnds->below);
478 mpz_init (bnds->up);
479 mpz_init (offx);
480 mpz_init (offy);
481 split_to_var_and_offset (x, &varx, offx);
482 split_to_var_and_offset (y, &vary, offy);
484 if (!integer_zerop (varx)
485 && operand_equal_p (varx, vary, 0))
487 /* Special case VARX == VARY -- we just need to compare the
488 offsets. The matters are a bit more complicated in the
489 case addition of offsets may wrap. */
490 bound_difference_of_offsetted_base (type, offx, offy, bnds);
492 else
494 /* Otherwise, use the value ranges to determine the initial
495 estimates on below and up. */
496 mpz_init (minx);
497 mpz_init (maxx);
498 mpz_init (miny);
499 mpz_init (maxy);
500 determine_value_range (loop, type, varx, offx, minx, maxx);
501 determine_value_range (loop, type, vary, offy, miny, maxy);
503 mpz_sub (bnds->below, minx, maxy);
504 mpz_sub (bnds->up, maxx, miny);
505 mpz_clear (minx);
506 mpz_clear (maxx);
507 mpz_clear (miny);
508 mpz_clear (maxy);
511 /* If both X and Y are constants, we cannot get any more precise. */
512 if (integer_zerop (varx) && integer_zerop (vary))
513 goto end;
515 /* Now walk the dominators of the loop header and use the entry
516 guards to refine the estimates. */
517 for (bb = loop->header;
518 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
519 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
521 if (!single_pred_p (bb))
522 continue;
523 e = single_pred_edge (bb);
525 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
526 continue;
528 cond = last_stmt (e->src);
529 c0 = gimple_cond_lhs (cond);
530 cmp = gimple_cond_code (cond);
531 c1 = gimple_cond_rhs (cond);
533 if (e->flags & EDGE_FALSE_VALUE)
534 cmp = invert_tree_comparison (cmp, false);
536 refine_bounds_using_guard (type, varx, offx, vary, offy,
537 c0, cmp, c1, bnds);
538 ++cnt;
541 end:
542 mpz_clear (offx);
543 mpz_clear (offy);
546 /* Update the bounds in BNDS that restrict the value of X to the bounds
547 that restrict the value of X + DELTA. X can be obtained as a
548 difference of two values in TYPE. */
550 static void
551 bounds_add (bounds *bnds, const widest_int &delta, tree type)
553 mpz_t mdelta, max;
555 mpz_init (mdelta);
556 wi::to_mpz (delta, mdelta, SIGNED);
558 mpz_init (max);
559 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
561 mpz_add (bnds->up, bnds->up, mdelta);
562 mpz_add (bnds->below, bnds->below, mdelta);
564 if (mpz_cmp (bnds->up, max) > 0)
565 mpz_set (bnds->up, max);
567 mpz_neg (max, max);
568 if (mpz_cmp (bnds->below, max) < 0)
569 mpz_set (bnds->below, max);
571 mpz_clear (mdelta);
572 mpz_clear (max);
575 /* Update the bounds in BNDS that restrict the value of X to the bounds
576 that restrict the value of -X. */
578 static void
579 bounds_negate (bounds *bnds)
581 mpz_t tmp;
583 mpz_init_set (tmp, bnds->up);
584 mpz_neg (bnds->up, bnds->below);
585 mpz_neg (bnds->below, tmp);
586 mpz_clear (tmp);
589 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
591 static tree
592 inverse (tree x, tree mask)
594 tree type = TREE_TYPE (x);
595 tree rslt;
596 unsigned ctr = tree_floor_log2 (mask);
598 if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
600 unsigned HOST_WIDE_INT ix;
601 unsigned HOST_WIDE_INT imask;
602 unsigned HOST_WIDE_INT irslt = 1;
604 gcc_assert (cst_and_fits_in_hwi (x));
605 gcc_assert (cst_and_fits_in_hwi (mask));
607 ix = int_cst_value (x);
608 imask = int_cst_value (mask);
610 for (; ctr; ctr--)
612 irslt *= ix;
613 ix *= ix;
615 irslt &= imask;
617 rslt = build_int_cst_type (type, irslt);
619 else
621 rslt = build_int_cst (type, 1);
622 for (; ctr; ctr--)
624 rslt = int_const_binop (MULT_EXPR, rslt, x);
625 x = int_const_binop (MULT_EXPR, x, x);
627 rslt = int_const_binop (BIT_AND_EXPR, rslt, mask);
630 return rslt;
633 /* Derives the upper bound BND on the number of executions of loop with exit
634 condition S * i <> C. If NO_OVERFLOW is true, then the control variable of
635 the loop does not overflow. EXIT_MUST_BE_TAKEN is true if we are guaranteed
636 that the loop ends through this exit, i.e., the induction variable ever
637 reaches the value of C.
639 The value C is equal to final - base, where final and base are the final and
640 initial value of the actual induction variable in the analysed loop. BNDS
641 bounds the value of this difference when computed in signed type with
642 unbounded range, while the computation of C is performed in an unsigned
643 type with the range matching the range of the type of the induction variable.
644 In particular, BNDS.up contains an upper bound on C in the following cases:
645 -- if the iv must reach its final value without overflow, i.e., if
646 NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
647 -- if final >= base, which we know to hold when BNDS.below >= 0. */
649 static void
650 number_of_iterations_ne_max (mpz_t bnd, bool no_overflow, tree c, tree s,
651 bounds *bnds, bool exit_must_be_taken)
653 widest_int max;
654 mpz_t d;
655 tree type = TREE_TYPE (c);
656 bool bnds_u_valid = ((no_overflow && exit_must_be_taken)
657 || mpz_sgn (bnds->below) >= 0);
659 if (integer_onep (s)
660 || (TREE_CODE (c) == INTEGER_CST
661 && TREE_CODE (s) == INTEGER_CST
662 && wi::mod_trunc (c, s, TYPE_SIGN (type)) == 0)
663 || (TYPE_OVERFLOW_UNDEFINED (type)
664 && multiple_of_p (type, c, s)))
666 /* If C is an exact multiple of S, then its value will be reached before
667 the induction variable overflows (unless the loop is exited in some
668 other way before). Note that the actual induction variable in the
669 loop (which ranges from base to final instead of from 0 to C) may
670 overflow, in which case BNDS.up will not be giving a correct upper
671 bound on C; thus, BNDS_U_VALID had to be computed in advance. */
672 no_overflow = true;
673 exit_must_be_taken = true;
676 /* If the induction variable can overflow, the number of iterations is at
677 most the period of the control variable (or infinite, but in that case
678 the whole # of iterations analysis will fail). */
679 if (!no_overflow)
681 max = wi::mask <widest_int> (TYPE_PRECISION (type) - wi::ctz (s), false);
682 wi::to_mpz (max, bnd, UNSIGNED);
683 return;
686 /* Now we know that the induction variable does not overflow, so the loop
687 iterates at most (range of type / S) times. */
688 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), bnd, UNSIGNED);
690 /* If the induction variable is guaranteed to reach the value of C before
691 overflow, ... */
692 if (exit_must_be_taken)
694 /* ... then we can strengthen this to C / S, and possibly we can use
695 the upper bound on C given by BNDS. */
696 if (TREE_CODE (c) == INTEGER_CST)
697 wi::to_mpz (c, bnd, UNSIGNED);
698 else if (bnds_u_valid)
699 mpz_set (bnd, bnds->up);
702 mpz_init (d);
703 wi::to_mpz (s, d, UNSIGNED);
704 mpz_fdiv_q (bnd, bnd, d);
705 mpz_clear (d);
708 /* Determines number of iterations of loop whose ending condition
709 is IV <> FINAL. TYPE is the type of the iv. The number of
710 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
711 we know that the exit must be taken eventually, i.e., that the IV
712 ever reaches the value FINAL (we derived this earlier, and possibly set
713 NITER->assumptions to make sure this is the case). BNDS contains the
714 bounds on the difference FINAL - IV->base. */
716 static bool
717 number_of_iterations_ne (tree type, affine_iv *iv, tree final,
718 struct tree_niter_desc *niter, bool exit_must_be_taken,
719 bounds *bnds)
721 tree niter_type = unsigned_type_for (type);
722 tree s, c, d, bits, assumption, tmp, bound;
723 mpz_t max;
725 niter->control = *iv;
726 niter->bound = final;
727 niter->cmp = NE_EXPR;
729 /* Rearrange the terms so that we get inequality S * i <> C, with S
730 positive. Also cast everything to the unsigned type. If IV does
731 not overflow, BNDS bounds the value of C. Also, this is the
732 case if the computation |FINAL - IV->base| does not overflow, i.e.,
733 if BNDS->below in the result is nonnegative. */
734 if (tree_int_cst_sign_bit (iv->step))
736 s = fold_convert (niter_type,
737 fold_build1 (NEGATE_EXPR, type, iv->step));
738 c = fold_build2 (MINUS_EXPR, niter_type,
739 fold_convert (niter_type, iv->base),
740 fold_convert (niter_type, final));
741 bounds_negate (bnds);
743 else
745 s = fold_convert (niter_type, iv->step);
746 c = fold_build2 (MINUS_EXPR, niter_type,
747 fold_convert (niter_type, final),
748 fold_convert (niter_type, iv->base));
751 mpz_init (max);
752 number_of_iterations_ne_max (max, iv->no_overflow, c, s, bnds,
753 exit_must_be_taken);
754 niter->max = widest_int::from (wi::from_mpz (niter_type, max, false),
755 TYPE_SIGN (niter_type));
756 mpz_clear (max);
758 /* First the trivial cases -- when the step is 1. */
759 if (integer_onep (s))
761 niter->niter = c;
762 return true;
765 /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
766 is infinite. Otherwise, the number of iterations is
767 (inverse(s/d) * (c/d)) mod (size of mode/d). */
768 bits = num_ending_zeros (s);
769 bound = build_low_bits_mask (niter_type,
770 (TYPE_PRECISION (niter_type)
771 - tree_to_uhwi (bits)));
773 d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
774 build_int_cst (niter_type, 1), bits);
775 s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
777 if (!exit_must_be_taken)
779 /* If we cannot assume that the exit is taken eventually, record the
780 assumptions for divisibility of c. */
781 assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
782 assumption = fold_build2 (EQ_EXPR, boolean_type_node,
783 assumption, build_int_cst (niter_type, 0));
784 if (!integer_nonzerop (assumption))
785 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
786 niter->assumptions, assumption);
789 c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
790 tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
791 niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
792 return true;
795 /* Checks whether we can determine the final value of the control variable
796 of the loop with ending condition IV0 < IV1 (computed in TYPE).
797 DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
798 of the step. The assumptions necessary to ensure that the computation
799 of the final value does not overflow are recorded in NITER. If we
800 find the final value, we adjust DELTA and return TRUE. Otherwise
801 we return false. BNDS bounds the value of IV1->base - IV0->base,
802 and will be updated by the same amount as DELTA. EXIT_MUST_BE_TAKEN is
803 true if we know that the exit must be taken eventually. */
805 static bool
806 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
807 struct tree_niter_desc *niter,
808 tree *delta, tree step,
809 bool exit_must_be_taken, bounds *bnds)
811 tree niter_type = TREE_TYPE (step);
812 tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
813 tree tmod;
814 mpz_t mmod;
815 tree assumption = boolean_true_node, bound, noloop;
816 bool ret = false, fv_comp_no_overflow;
817 tree type1 = type;
818 if (POINTER_TYPE_P (type))
819 type1 = sizetype;
821 if (TREE_CODE (mod) != INTEGER_CST)
822 return false;
823 if (integer_nonzerop (mod))
824 mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
825 tmod = fold_convert (type1, mod);
827 mpz_init (mmod);
828 wi::to_mpz (mod, mmod, UNSIGNED);
829 mpz_neg (mmod, mmod);
831 /* If the induction variable does not overflow and the exit is taken,
832 then the computation of the final value does not overflow. This is
833 also obviously the case if the new final value is equal to the
834 current one. Finally, we postulate this for pointer type variables,
835 as the code cannot rely on the object to that the pointer points being
836 placed at the end of the address space (and more pragmatically,
837 TYPE_{MIN,MAX}_VALUE is not defined for pointers). */
838 if (integer_zerop (mod) || POINTER_TYPE_P (type))
839 fv_comp_no_overflow = true;
840 else if (!exit_must_be_taken)
841 fv_comp_no_overflow = false;
842 else
843 fv_comp_no_overflow =
844 (iv0->no_overflow && integer_nonzerop (iv0->step))
845 || (iv1->no_overflow && integer_nonzerop (iv1->step));
847 if (integer_nonzerop (iv0->step))
849 /* The final value of the iv is iv1->base + MOD, assuming that this
850 computation does not overflow, and that
851 iv0->base <= iv1->base + MOD. */
852 if (!fv_comp_no_overflow)
854 bound = fold_build2 (MINUS_EXPR, type1,
855 TYPE_MAX_VALUE (type1), tmod);
856 assumption = fold_build2 (LE_EXPR, boolean_type_node,
857 iv1->base, bound);
858 if (integer_zerop (assumption))
859 goto end;
861 if (mpz_cmp (mmod, bnds->below) < 0)
862 noloop = boolean_false_node;
863 else if (POINTER_TYPE_P (type))
864 noloop = fold_build2 (GT_EXPR, boolean_type_node,
865 iv0->base,
866 fold_build_pointer_plus (iv1->base, tmod));
867 else
868 noloop = fold_build2 (GT_EXPR, boolean_type_node,
869 iv0->base,
870 fold_build2 (PLUS_EXPR, type1,
871 iv1->base, tmod));
873 else
875 /* The final value of the iv is iv0->base - MOD, assuming that this
876 computation does not overflow, and that
877 iv0->base - MOD <= iv1->base. */
878 if (!fv_comp_no_overflow)
880 bound = fold_build2 (PLUS_EXPR, type1,
881 TYPE_MIN_VALUE (type1), tmod);
882 assumption = fold_build2 (GE_EXPR, boolean_type_node,
883 iv0->base, bound);
884 if (integer_zerop (assumption))
885 goto end;
887 if (mpz_cmp (mmod, bnds->below) < 0)
888 noloop = boolean_false_node;
889 else if (POINTER_TYPE_P (type))
890 noloop = fold_build2 (GT_EXPR, boolean_type_node,
891 fold_build_pointer_plus (iv0->base,
892 fold_build1 (NEGATE_EXPR,
893 type1, tmod)),
894 iv1->base);
895 else
896 noloop = fold_build2 (GT_EXPR, boolean_type_node,
897 fold_build2 (MINUS_EXPR, type1,
898 iv0->base, tmod),
899 iv1->base);
902 if (!integer_nonzerop (assumption))
903 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
904 niter->assumptions,
905 assumption);
906 if (!integer_zerop (noloop))
907 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
908 niter->may_be_zero,
909 noloop);
910 bounds_add (bnds, wi::to_widest (mod), type);
911 *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
913 ret = true;
914 end:
915 mpz_clear (mmod);
916 return ret;
919 /* Add assertions to NITER that ensure that the control variable of the loop
920 with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
921 are TYPE. Returns false if we can prove that there is an overflow, true
922 otherwise. STEP is the absolute value of the step. */
924 static bool
925 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
926 struct tree_niter_desc *niter, tree step)
928 tree bound, d, assumption, diff;
929 tree niter_type = TREE_TYPE (step);
931 if (integer_nonzerop (iv0->step))
933 /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
934 if (iv0->no_overflow)
935 return true;
937 /* If iv0->base is a constant, we can determine the last value before
938 overflow precisely; otherwise we conservatively assume
939 MAX - STEP + 1. */
941 if (TREE_CODE (iv0->base) == INTEGER_CST)
943 d = fold_build2 (MINUS_EXPR, niter_type,
944 fold_convert (niter_type, TYPE_MAX_VALUE (type)),
945 fold_convert (niter_type, iv0->base));
946 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
948 else
949 diff = fold_build2 (MINUS_EXPR, niter_type, step,
950 build_int_cst (niter_type, 1));
951 bound = fold_build2 (MINUS_EXPR, type,
952 TYPE_MAX_VALUE (type), fold_convert (type, diff));
953 assumption = fold_build2 (LE_EXPR, boolean_type_node,
954 iv1->base, bound);
956 else
958 /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
959 if (iv1->no_overflow)
960 return true;
962 if (TREE_CODE (iv1->base) == INTEGER_CST)
964 d = fold_build2 (MINUS_EXPR, niter_type,
965 fold_convert (niter_type, iv1->base),
966 fold_convert (niter_type, TYPE_MIN_VALUE (type)));
967 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
969 else
970 diff = fold_build2 (MINUS_EXPR, niter_type, step,
971 build_int_cst (niter_type, 1));
972 bound = fold_build2 (PLUS_EXPR, type,
973 TYPE_MIN_VALUE (type), fold_convert (type, diff));
974 assumption = fold_build2 (GE_EXPR, boolean_type_node,
975 iv0->base, bound);
978 if (integer_zerop (assumption))
979 return false;
980 if (!integer_nonzerop (assumption))
981 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
982 niter->assumptions, assumption);
984 iv0->no_overflow = true;
985 iv1->no_overflow = true;
986 return true;
989 /* Add an assumption to NITER that a loop whose ending condition
990 is IV0 < IV1 rolls. TYPE is the type of the control iv. BNDS
991 bounds the value of IV1->base - IV0->base. */
993 static void
994 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
995 struct tree_niter_desc *niter, bounds *bnds)
997 tree assumption = boolean_true_node, bound, diff;
998 tree mbz, mbzl, mbzr, type1;
999 bool rolls_p, no_overflow_p;
1000 widest_int dstep;
1001 mpz_t mstep, max;
1003 /* We are going to compute the number of iterations as
1004 (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1005 variant of TYPE. This formula only works if
1007 -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1009 (where MAX is the maximum value of the unsigned variant of TYPE, and
1010 the computations in this formula are performed in full precision,
1011 i.e., without overflows).
1013 Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1014 we have a condition of the form iv0->base - step < iv1->base before the loop,
1015 and for loops iv0->base < iv1->base - step * i the condition
1016 iv0->base < iv1->base + step, due to loop header copying, which enable us
1017 to prove the lower bound.
1019 The upper bound is more complicated. Unless the expressions for initial
1020 and final value themselves contain enough information, we usually cannot
1021 derive it from the context. */
1023 /* First check whether the answer does not follow from the bounds we gathered
1024 before. */
1025 if (integer_nonzerop (iv0->step))
1026 dstep = wi::to_widest (iv0->step);
1027 else
1029 dstep = wi::sext (wi::to_widest (iv1->step), TYPE_PRECISION (type));
1030 dstep = -dstep;
1033 mpz_init (mstep);
1034 wi::to_mpz (dstep, mstep, UNSIGNED);
1035 mpz_neg (mstep, mstep);
1036 mpz_add_ui (mstep, mstep, 1);
1038 rolls_p = mpz_cmp (mstep, bnds->below) <= 0;
1040 mpz_init (max);
1041 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
1042 mpz_add (max, max, mstep);
1043 no_overflow_p = (mpz_cmp (bnds->up, max) <= 0
1044 /* For pointers, only values lying inside a single object
1045 can be compared or manipulated by pointer arithmetics.
1046 Gcc in general does not allow or handle objects larger
1047 than half of the address space, hence the upper bound
1048 is satisfied for pointers. */
1049 || POINTER_TYPE_P (type));
1050 mpz_clear (mstep);
1051 mpz_clear (max);
1053 if (rolls_p && no_overflow_p)
1054 return;
1056 type1 = type;
1057 if (POINTER_TYPE_P (type))
1058 type1 = sizetype;
1060 /* Now the hard part; we must formulate the assumption(s) as expressions, and
1061 we must be careful not to introduce overflow. */
1063 if (integer_nonzerop (iv0->step))
1065 diff = fold_build2 (MINUS_EXPR, type1,
1066 iv0->step, build_int_cst (type1, 1));
1068 /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
1069 0 address never belongs to any object, we can assume this for
1070 pointers. */
1071 if (!POINTER_TYPE_P (type))
1073 bound = fold_build2 (PLUS_EXPR, type1,
1074 TYPE_MIN_VALUE (type), diff);
1075 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1076 iv0->base, bound);
1079 /* And then we can compute iv0->base - diff, and compare it with
1080 iv1->base. */
1081 mbzl = fold_build2 (MINUS_EXPR, type1,
1082 fold_convert (type1, iv0->base), diff);
1083 mbzr = fold_convert (type1, iv1->base);
1085 else
1087 diff = fold_build2 (PLUS_EXPR, type1,
1088 iv1->step, build_int_cst (type1, 1));
1090 if (!POINTER_TYPE_P (type))
1092 bound = fold_build2 (PLUS_EXPR, type1,
1093 TYPE_MAX_VALUE (type), diff);
1094 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1095 iv1->base, bound);
1098 mbzl = fold_convert (type1, iv0->base);
1099 mbzr = fold_build2 (MINUS_EXPR, type1,
1100 fold_convert (type1, iv1->base), diff);
1103 if (!integer_nonzerop (assumption))
1104 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1105 niter->assumptions, assumption);
1106 if (!rolls_p)
1108 mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
1109 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1110 niter->may_be_zero, mbz);
1114 /* Determines number of iterations of loop whose ending condition
1115 is IV0 < IV1. TYPE is the type of the iv. The number of
1116 iterations is stored to NITER. BNDS bounds the difference
1117 IV1->base - IV0->base. EXIT_MUST_BE_TAKEN is true if we know
1118 that the exit must be taken eventually. */
1120 static bool
1121 number_of_iterations_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1122 struct tree_niter_desc *niter,
1123 bool exit_must_be_taken, bounds *bnds)
1125 tree niter_type = unsigned_type_for (type);
1126 tree delta, step, s;
1127 mpz_t mstep, tmp;
1129 if (integer_nonzerop (iv0->step))
1131 niter->control = *iv0;
1132 niter->cmp = LT_EXPR;
1133 niter->bound = iv1->base;
1135 else
1137 niter->control = *iv1;
1138 niter->cmp = GT_EXPR;
1139 niter->bound = iv0->base;
1142 delta = fold_build2 (MINUS_EXPR, niter_type,
1143 fold_convert (niter_type, iv1->base),
1144 fold_convert (niter_type, iv0->base));
1146 /* First handle the special case that the step is +-1. */
1147 if ((integer_onep (iv0->step) && integer_zerop (iv1->step))
1148 || (integer_all_onesp (iv1->step) && integer_zerop (iv0->step)))
1150 /* for (i = iv0->base; i < iv1->base; i++)
1154 for (i = iv1->base; i > iv0->base; i--).
1156 In both cases # of iterations is iv1->base - iv0->base, assuming that
1157 iv1->base >= iv0->base.
1159 First try to derive a lower bound on the value of
1160 iv1->base - iv0->base, computed in full precision. If the difference
1161 is nonnegative, we are done, otherwise we must record the
1162 condition. */
1164 if (mpz_sgn (bnds->below) < 0)
1165 niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
1166 iv1->base, iv0->base);
1167 niter->niter = delta;
1168 niter->max = widest_int::from (wi::from_mpz (niter_type, bnds->up, false),
1169 TYPE_SIGN (niter_type));
1170 return true;
1173 if (integer_nonzerop (iv0->step))
1174 step = fold_convert (niter_type, iv0->step);
1175 else
1176 step = fold_convert (niter_type,
1177 fold_build1 (NEGATE_EXPR, type, iv1->step));
1179 /* If we can determine the final value of the control iv exactly, we can
1180 transform the condition to != comparison. In particular, this will be
1181 the case if DELTA is constant. */
1182 if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step,
1183 exit_must_be_taken, bnds))
1185 affine_iv zps;
1187 zps.base = build_int_cst (niter_type, 0);
1188 zps.step = step;
1189 /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1190 zps does not overflow. */
1191 zps.no_overflow = true;
1193 return number_of_iterations_ne (type, &zps, delta, niter, true, bnds);
1196 /* Make sure that the control iv does not overflow. */
1197 if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
1198 return false;
1200 /* We determine the number of iterations as (delta + step - 1) / step. For
1201 this to work, we must know that iv1->base >= iv0->base - step + 1,
1202 otherwise the loop does not roll. */
1203 assert_loop_rolls_lt (type, iv0, iv1, niter, bnds);
1205 s = fold_build2 (MINUS_EXPR, niter_type,
1206 step, build_int_cst (niter_type, 1));
1207 delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
1208 niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
1210 mpz_init (mstep);
1211 mpz_init (tmp);
1212 wi::to_mpz (step, mstep, UNSIGNED);
1213 mpz_add (tmp, bnds->up, mstep);
1214 mpz_sub_ui (tmp, tmp, 1);
1215 mpz_fdiv_q (tmp, tmp, mstep);
1216 niter->max = widest_int::from (wi::from_mpz (niter_type, tmp, false),
1217 TYPE_SIGN (niter_type));
1218 mpz_clear (mstep);
1219 mpz_clear (tmp);
1221 return true;
1224 /* Determines number of iterations of loop whose ending condition
1225 is IV0 <= IV1. TYPE is the type of the iv. The number of
1226 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
1227 we know that this condition must eventually become false (we derived this
1228 earlier, and possibly set NITER->assumptions to make sure this
1229 is the case). BNDS bounds the difference IV1->base - IV0->base. */
1231 static bool
1232 number_of_iterations_le (tree type, affine_iv *iv0, affine_iv *iv1,
1233 struct tree_niter_desc *niter, bool exit_must_be_taken,
1234 bounds *bnds)
1236 tree assumption;
1237 tree type1 = type;
1238 if (POINTER_TYPE_P (type))
1239 type1 = sizetype;
1241 /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
1242 IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1243 value of the type. This we must know anyway, since if it is
1244 equal to this value, the loop rolls forever. We do not check
1245 this condition for pointer type ivs, as the code cannot rely on
1246 the object to that the pointer points being placed at the end of
1247 the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1248 not defined for pointers). */
1250 if (!exit_must_be_taken && !POINTER_TYPE_P (type))
1252 if (integer_nonzerop (iv0->step))
1253 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1254 iv1->base, TYPE_MAX_VALUE (type));
1255 else
1256 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1257 iv0->base, TYPE_MIN_VALUE (type));
1259 if (integer_zerop (assumption))
1260 return false;
1261 if (!integer_nonzerop (assumption))
1262 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1263 niter->assumptions, assumption);
1266 if (integer_nonzerop (iv0->step))
1268 if (POINTER_TYPE_P (type))
1269 iv1->base = fold_build_pointer_plus_hwi (iv1->base, 1);
1270 else
1271 iv1->base = fold_build2 (PLUS_EXPR, type1, iv1->base,
1272 build_int_cst (type1, 1));
1274 else if (POINTER_TYPE_P (type))
1275 iv0->base = fold_build_pointer_plus_hwi (iv0->base, -1);
1276 else
1277 iv0->base = fold_build2 (MINUS_EXPR, type1,
1278 iv0->base, build_int_cst (type1, 1));
1280 bounds_add (bnds, 1, type1);
1282 return number_of_iterations_lt (type, iv0, iv1, niter, exit_must_be_taken,
1283 bnds);
1286 /* Dumps description of affine induction variable IV to FILE. */
1288 static void
1289 dump_affine_iv (FILE *file, affine_iv *iv)
1291 if (!integer_zerop (iv->step))
1292 fprintf (file, "[");
1294 print_generic_expr (dump_file, iv->base, TDF_SLIM);
1296 if (!integer_zerop (iv->step))
1298 fprintf (file, ", + , ");
1299 print_generic_expr (dump_file, iv->step, TDF_SLIM);
1300 fprintf (file, "]%s", iv->no_overflow ? "(no_overflow)" : "");
1304 /* Determine the number of iterations according to condition (for staying
1305 inside loop) which compares two induction variables using comparison
1306 operator CODE. The induction variable on left side of the comparison
1307 is IV0, the right-hand side is IV1. Both induction variables must have
1308 type TYPE, which must be an integer or pointer type. The steps of the
1309 ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1311 LOOP is the loop whose number of iterations we are determining.
1313 ONLY_EXIT is true if we are sure this is the only way the loop could be
1314 exited (including possibly non-returning function calls, exceptions, etc.)
1315 -- in this case we can use the information whether the control induction
1316 variables can overflow or not in a more efficient way.
1318 if EVERY_ITERATION is true, we know the test is executed on every iteration.
1320 The results (number of iterations and assumptions as described in
1321 comments at struct tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1322 Returns false if it fails to determine number of iterations, true if it
1323 was determined (possibly with some assumptions). */
1325 static bool
1326 number_of_iterations_cond (struct loop *loop,
1327 tree type, affine_iv *iv0, enum tree_code code,
1328 affine_iv *iv1, struct tree_niter_desc *niter,
1329 bool only_exit, bool every_iteration)
1331 bool exit_must_be_taken = false, ret;
1332 bounds bnds;
1334 /* If the test is not executed every iteration, wrapping may make the test
1335 to pass again.
1336 TODO: the overflow case can be still used as unreliable estimate of upper
1337 bound. But we have no API to pass it down to number of iterations code
1338 and, at present, it will not use it anyway. */
1339 if (!every_iteration
1340 && (!iv0->no_overflow || !iv1->no_overflow
1341 || code == NE_EXPR || code == EQ_EXPR))
1342 return false;
1344 /* The meaning of these assumptions is this:
1345 if !assumptions
1346 then the rest of information does not have to be valid
1347 if may_be_zero then the loop does not roll, even if
1348 niter != 0. */
1349 niter->assumptions = boolean_true_node;
1350 niter->may_be_zero = boolean_false_node;
1351 niter->niter = NULL_TREE;
1352 niter->max = 0;
1353 niter->bound = NULL_TREE;
1354 niter->cmp = ERROR_MARK;
1356 /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1357 the control variable is on lhs. */
1358 if (code == GE_EXPR || code == GT_EXPR
1359 || (code == NE_EXPR && integer_zerop (iv0->step)))
1361 SWAP (iv0, iv1);
1362 code = swap_tree_comparison (code);
1365 if (POINTER_TYPE_P (type))
1367 /* Comparison of pointers is undefined unless both iv0 and iv1 point
1368 to the same object. If they do, the control variable cannot wrap
1369 (as wrap around the bounds of memory will never return a pointer
1370 that would be guaranteed to point to the same object, even if we
1371 avoid undefined behavior by casting to size_t and back). */
1372 iv0->no_overflow = true;
1373 iv1->no_overflow = true;
1376 /* If the control induction variable does not overflow and the only exit
1377 from the loop is the one that we analyze, we know it must be taken
1378 eventually. */
1379 if (only_exit)
1381 if (!integer_zerop (iv0->step) && iv0->no_overflow)
1382 exit_must_be_taken = true;
1383 else if (!integer_zerop (iv1->step) && iv1->no_overflow)
1384 exit_must_be_taken = true;
1387 /* We can handle the case when neither of the sides of the comparison is
1388 invariant, provided that the test is NE_EXPR. This rarely occurs in
1389 practice, but it is simple enough to manage. */
1390 if (!integer_zerop (iv0->step) && !integer_zerop (iv1->step))
1392 tree step_type = POINTER_TYPE_P (type) ? sizetype : type;
1393 if (code != NE_EXPR)
1394 return false;
1396 iv0->step = fold_binary_to_constant (MINUS_EXPR, step_type,
1397 iv0->step, iv1->step);
1398 iv0->no_overflow = false;
1399 iv1->step = build_int_cst (step_type, 0);
1400 iv1->no_overflow = true;
1403 /* If the result of the comparison is a constant, the loop is weird. More
1404 precise handling would be possible, but the situation is not common enough
1405 to waste time on it. */
1406 if (integer_zerop (iv0->step) && integer_zerop (iv1->step))
1407 return false;
1409 /* Ignore loops of while (i-- < 10) type. */
1410 if (code != NE_EXPR)
1412 if (iv0->step && tree_int_cst_sign_bit (iv0->step))
1413 return false;
1415 if (!integer_zerop (iv1->step) && !tree_int_cst_sign_bit (iv1->step))
1416 return false;
1419 /* If the loop exits immediately, there is nothing to do. */
1420 tree tem = fold_binary (code, boolean_type_node, iv0->base, iv1->base);
1421 if (tem && integer_zerop (tem))
1423 niter->niter = build_int_cst (unsigned_type_for (type), 0);
1424 niter->max = 0;
1425 return true;
1428 /* OK, now we know we have a senseful loop. Handle several cases, depending
1429 on what comparison operator is used. */
1430 bound_difference (loop, iv1->base, iv0->base, &bnds);
1432 if (dump_file && (dump_flags & TDF_DETAILS))
1434 fprintf (dump_file,
1435 "Analyzing # of iterations of loop %d\n", loop->num);
1437 fprintf (dump_file, " exit condition ");
1438 dump_affine_iv (dump_file, iv0);
1439 fprintf (dump_file, " %s ",
1440 code == NE_EXPR ? "!="
1441 : code == LT_EXPR ? "<"
1442 : "<=");
1443 dump_affine_iv (dump_file, iv1);
1444 fprintf (dump_file, "\n");
1446 fprintf (dump_file, " bounds on difference of bases: ");
1447 mpz_out_str (dump_file, 10, bnds.below);
1448 fprintf (dump_file, " ... ");
1449 mpz_out_str (dump_file, 10, bnds.up);
1450 fprintf (dump_file, "\n");
1453 switch (code)
1455 case NE_EXPR:
1456 gcc_assert (integer_zerop (iv1->step));
1457 ret = number_of_iterations_ne (type, iv0, iv1->base, niter,
1458 exit_must_be_taken, &bnds);
1459 break;
1461 case LT_EXPR:
1462 ret = number_of_iterations_lt (type, iv0, iv1, niter, exit_must_be_taken,
1463 &bnds);
1464 break;
1466 case LE_EXPR:
1467 ret = number_of_iterations_le (type, iv0, iv1, niter, exit_must_be_taken,
1468 &bnds);
1469 break;
1471 default:
1472 gcc_unreachable ();
1475 mpz_clear (bnds.up);
1476 mpz_clear (bnds.below);
1478 if (dump_file && (dump_flags & TDF_DETAILS))
1480 if (ret)
1482 fprintf (dump_file, " result:\n");
1483 if (!integer_nonzerop (niter->assumptions))
1485 fprintf (dump_file, " under assumptions ");
1486 print_generic_expr (dump_file, niter->assumptions, TDF_SLIM);
1487 fprintf (dump_file, "\n");
1490 if (!integer_zerop (niter->may_be_zero))
1492 fprintf (dump_file, " zero if ");
1493 print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
1494 fprintf (dump_file, "\n");
1497 fprintf (dump_file, " # of iterations ");
1498 print_generic_expr (dump_file, niter->niter, TDF_SLIM);
1499 fprintf (dump_file, ", bounded by ");
1500 print_decu (niter->max, dump_file);
1501 fprintf (dump_file, "\n");
1503 else
1504 fprintf (dump_file, " failed\n\n");
1506 return ret;
1509 /* Substitute NEW for OLD in EXPR and fold the result. */
1511 static tree
1512 simplify_replace_tree (tree expr, tree old, tree new_tree)
1514 unsigned i, n;
1515 tree ret = NULL_TREE, e, se;
1517 if (!expr)
1518 return NULL_TREE;
1520 /* Do not bother to replace constants. */
1521 if (CONSTANT_CLASS_P (old))
1522 return expr;
1524 if (expr == old
1525 || operand_equal_p (expr, old, 0))
1526 return unshare_expr (new_tree);
1528 if (!EXPR_P (expr))
1529 return expr;
1531 n = TREE_OPERAND_LENGTH (expr);
1532 for (i = 0; i < n; i++)
1534 e = TREE_OPERAND (expr, i);
1535 se = simplify_replace_tree (e, old, new_tree);
1536 if (e == se)
1537 continue;
1539 if (!ret)
1540 ret = copy_node (expr);
1542 TREE_OPERAND (ret, i) = se;
1545 return (ret ? fold (ret) : expr);
1548 /* Expand definitions of ssa names in EXPR as long as they are simple
1549 enough, and return the new expression. */
1551 tree
1552 expand_simple_operations (tree expr)
1554 unsigned i, n;
1555 tree ret = NULL_TREE, e, ee, e1;
1556 enum tree_code code;
1557 gimple stmt;
1559 if (expr == NULL_TREE)
1560 return expr;
1562 if (is_gimple_min_invariant (expr))
1563 return expr;
1565 code = TREE_CODE (expr);
1566 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
1568 n = TREE_OPERAND_LENGTH (expr);
1569 for (i = 0; i < n; i++)
1571 e = TREE_OPERAND (expr, i);
1572 ee = expand_simple_operations (e);
1573 if (e == ee)
1574 continue;
1576 if (!ret)
1577 ret = copy_node (expr);
1579 TREE_OPERAND (ret, i) = ee;
1582 if (!ret)
1583 return expr;
1585 fold_defer_overflow_warnings ();
1586 ret = fold (ret);
1587 fold_undefer_and_ignore_overflow_warnings ();
1588 return ret;
1591 if (TREE_CODE (expr) != SSA_NAME)
1592 return expr;
1594 stmt = SSA_NAME_DEF_STMT (expr);
1595 if (gimple_code (stmt) == GIMPLE_PHI)
1597 basic_block src, dest;
1599 if (gimple_phi_num_args (stmt) != 1)
1600 return expr;
1601 e = PHI_ARG_DEF (stmt, 0);
1603 /* Avoid propagating through loop exit phi nodes, which
1604 could break loop-closed SSA form restrictions. */
1605 dest = gimple_bb (stmt);
1606 src = single_pred (dest);
1607 if (TREE_CODE (e) == SSA_NAME
1608 && src->loop_father != dest->loop_father)
1609 return expr;
1611 return expand_simple_operations (e);
1613 if (gimple_code (stmt) != GIMPLE_ASSIGN)
1614 return expr;
1616 /* Avoid expanding to expressions that contain SSA names that need
1617 to take part in abnormal coalescing. */
1618 ssa_op_iter iter;
1619 FOR_EACH_SSA_TREE_OPERAND (e, stmt, iter, SSA_OP_USE)
1620 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e))
1621 return expr;
1623 e = gimple_assign_rhs1 (stmt);
1624 code = gimple_assign_rhs_code (stmt);
1625 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1627 if (is_gimple_min_invariant (e))
1628 return e;
1630 if (code == SSA_NAME)
1631 return expand_simple_operations (e);
1633 return expr;
1636 switch (code)
1638 CASE_CONVERT:
1639 /* Casts are simple. */
1640 ee = expand_simple_operations (e);
1641 return fold_build1 (code, TREE_TYPE (expr), ee);
1643 case PLUS_EXPR:
1644 case MINUS_EXPR:
1645 if (TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr)))
1646 return expr;
1647 /* Fallthru. */
1648 case POINTER_PLUS_EXPR:
1649 /* And increments and decrements by a constant are simple. */
1650 e1 = gimple_assign_rhs2 (stmt);
1651 if (!is_gimple_min_invariant (e1))
1652 return expr;
1654 ee = expand_simple_operations (e);
1655 return fold_build2 (code, TREE_TYPE (expr), ee, e1);
1657 default:
1658 return expr;
1662 /* Tries to simplify EXPR using the condition COND. Returns the simplified
1663 expression (or EXPR unchanged, if no simplification was possible). */
1665 static tree
1666 tree_simplify_using_condition_1 (tree cond, tree expr)
1668 bool changed;
1669 tree e, te, e0, e1, e2, notcond;
1670 enum tree_code code = TREE_CODE (expr);
1672 if (code == INTEGER_CST)
1673 return expr;
1675 if (code == TRUTH_OR_EXPR
1676 || code == TRUTH_AND_EXPR
1677 || code == COND_EXPR)
1679 changed = false;
1681 e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
1682 if (TREE_OPERAND (expr, 0) != e0)
1683 changed = true;
1685 e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
1686 if (TREE_OPERAND (expr, 1) != e1)
1687 changed = true;
1689 if (code == COND_EXPR)
1691 e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
1692 if (TREE_OPERAND (expr, 2) != e2)
1693 changed = true;
1695 else
1696 e2 = NULL_TREE;
1698 if (changed)
1700 if (code == COND_EXPR)
1701 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
1702 else
1703 expr = fold_build2 (code, boolean_type_node, e0, e1);
1706 return expr;
1709 /* In case COND is equality, we may be able to simplify EXPR by copy/constant
1710 propagation, and vice versa. Fold does not handle this, since it is
1711 considered too expensive. */
1712 if (TREE_CODE (cond) == EQ_EXPR)
1714 e0 = TREE_OPERAND (cond, 0);
1715 e1 = TREE_OPERAND (cond, 1);
1717 /* We know that e0 == e1. Check whether we cannot simplify expr
1718 using this fact. */
1719 e = simplify_replace_tree (expr, e0, e1);
1720 if (integer_zerop (e) || integer_nonzerop (e))
1721 return e;
1723 e = simplify_replace_tree (expr, e1, e0);
1724 if (integer_zerop (e) || integer_nonzerop (e))
1725 return e;
1727 if (TREE_CODE (expr) == EQ_EXPR)
1729 e0 = TREE_OPERAND (expr, 0);
1730 e1 = TREE_OPERAND (expr, 1);
1732 /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
1733 e = simplify_replace_tree (cond, e0, e1);
1734 if (integer_zerop (e))
1735 return e;
1736 e = simplify_replace_tree (cond, e1, e0);
1737 if (integer_zerop (e))
1738 return e;
1740 if (TREE_CODE (expr) == NE_EXPR)
1742 e0 = TREE_OPERAND (expr, 0);
1743 e1 = TREE_OPERAND (expr, 1);
1745 /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
1746 e = simplify_replace_tree (cond, e0, e1);
1747 if (integer_zerop (e))
1748 return boolean_true_node;
1749 e = simplify_replace_tree (cond, e1, e0);
1750 if (integer_zerop (e))
1751 return boolean_true_node;
1754 te = expand_simple_operations (expr);
1756 /* Check whether COND ==> EXPR. */
1757 notcond = invert_truthvalue (cond);
1758 e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, te);
1759 if (e && integer_nonzerop (e))
1760 return e;
1762 /* Check whether COND ==> not EXPR. */
1763 e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, te);
1764 if (e && integer_zerop (e))
1765 return e;
1767 return expr;
1770 /* Tries to simplify EXPR using the condition COND. Returns the simplified
1771 expression (or EXPR unchanged, if no simplification was possible).
1772 Wrapper around tree_simplify_using_condition_1 that ensures that chains
1773 of simple operations in definitions of ssa names in COND are expanded,
1774 so that things like casts or incrementing the value of the bound before
1775 the loop do not cause us to fail. */
1777 static tree
1778 tree_simplify_using_condition (tree cond, tree expr)
1780 cond = expand_simple_operations (cond);
1782 return tree_simplify_using_condition_1 (cond, expr);
1785 /* Tries to simplify EXPR using the conditions on entry to LOOP.
1786 Returns the simplified expression (or EXPR unchanged, if no
1787 simplification was possible).*/
1789 static tree
1790 simplify_using_initial_conditions (struct loop *loop, tree expr)
1792 edge e;
1793 basic_block bb;
1794 gimple stmt;
1795 tree cond;
1796 int cnt = 0;
1798 if (TREE_CODE (expr) == INTEGER_CST)
1799 return expr;
1801 /* Limit walking the dominators to avoid quadraticness in
1802 the number of BBs times the number of loops in degenerate
1803 cases. */
1804 for (bb = loop->header;
1805 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
1806 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
1808 if (!single_pred_p (bb))
1809 continue;
1810 e = single_pred_edge (bb);
1812 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
1813 continue;
1815 stmt = last_stmt (e->src);
1816 cond = fold_build2 (gimple_cond_code (stmt),
1817 boolean_type_node,
1818 gimple_cond_lhs (stmt),
1819 gimple_cond_rhs (stmt));
1820 if (e->flags & EDGE_FALSE_VALUE)
1821 cond = invert_truthvalue (cond);
1822 expr = tree_simplify_using_condition (cond, expr);
1823 ++cnt;
1826 return expr;
1829 /* Tries to simplify EXPR using the evolutions of the loop invariants
1830 in the superloops of LOOP. Returns the simplified expression
1831 (or EXPR unchanged, if no simplification was possible). */
1833 static tree
1834 simplify_using_outer_evolutions (struct loop *loop, tree expr)
1836 enum tree_code code = TREE_CODE (expr);
1837 bool changed;
1838 tree e, e0, e1, e2;
1840 if (is_gimple_min_invariant (expr))
1841 return expr;
1843 if (code == TRUTH_OR_EXPR
1844 || code == TRUTH_AND_EXPR
1845 || code == COND_EXPR)
1847 changed = false;
1849 e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
1850 if (TREE_OPERAND (expr, 0) != e0)
1851 changed = true;
1853 e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
1854 if (TREE_OPERAND (expr, 1) != e1)
1855 changed = true;
1857 if (code == COND_EXPR)
1859 e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
1860 if (TREE_OPERAND (expr, 2) != e2)
1861 changed = true;
1863 else
1864 e2 = NULL_TREE;
1866 if (changed)
1868 if (code == COND_EXPR)
1869 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
1870 else
1871 expr = fold_build2 (code, boolean_type_node, e0, e1);
1874 return expr;
1877 e = instantiate_parameters (loop, expr);
1878 if (is_gimple_min_invariant (e))
1879 return e;
1881 return expr;
1884 /* Returns true if EXIT is the only possible exit from LOOP. */
1886 bool
1887 loop_only_exit_p (const struct loop *loop, const_edge exit)
1889 basic_block *body;
1890 gimple_stmt_iterator bsi;
1891 unsigned i;
1892 gimple call;
1894 if (exit != single_exit (loop))
1895 return false;
1897 body = get_loop_body (loop);
1898 for (i = 0; i < loop->num_nodes; i++)
1900 for (bsi = gsi_start_bb (body[i]); !gsi_end_p (bsi); gsi_next (&bsi))
1902 call = gsi_stmt (bsi);
1903 if (gimple_code (call) != GIMPLE_CALL)
1904 continue;
1906 if (gimple_has_side_effects (call))
1908 free (body);
1909 return false;
1914 free (body);
1915 return true;
1918 /* Stores description of number of iterations of LOOP derived from
1919 EXIT (an exit edge of the LOOP) in NITER. Returns true if some
1920 useful information could be derived (and fields of NITER has
1921 meaning described in comments at struct tree_niter_desc
1922 declaration), false otherwise. If WARN is true and
1923 -Wunsafe-loop-optimizations was given, warn if the optimizer is going to use
1924 potentially unsafe assumptions.
1925 When EVERY_ITERATION is true, only tests that are known to be executed
1926 every iteration are considered (i.e. only test that alone bounds the loop).
1929 bool
1930 number_of_iterations_exit (struct loop *loop, edge exit,
1931 struct tree_niter_desc *niter,
1932 bool warn, bool every_iteration)
1934 gimple stmt;
1935 tree type;
1936 tree op0, op1;
1937 enum tree_code code;
1938 affine_iv iv0, iv1;
1939 bool safe;
1941 safe = dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src);
1943 if (every_iteration && !safe)
1944 return false;
1946 niter->assumptions = boolean_false_node;
1947 stmt = last_stmt (exit->src);
1948 if (!stmt || gimple_code (stmt) != GIMPLE_COND)
1949 return false;
1951 /* We want the condition for staying inside loop. */
1952 code = gimple_cond_code (stmt);
1953 if (exit->flags & EDGE_TRUE_VALUE)
1954 code = invert_tree_comparison (code, false);
1956 switch (code)
1958 case GT_EXPR:
1959 case GE_EXPR:
1960 case LT_EXPR:
1961 case LE_EXPR:
1962 case NE_EXPR:
1963 break;
1965 default:
1966 return false;
1969 op0 = gimple_cond_lhs (stmt);
1970 op1 = gimple_cond_rhs (stmt);
1971 type = TREE_TYPE (op0);
1973 if (TREE_CODE (type) != INTEGER_TYPE
1974 && !POINTER_TYPE_P (type))
1975 return false;
1977 if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, false))
1978 return false;
1979 if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, false))
1980 return false;
1982 /* We don't want to see undefined signed overflow warnings while
1983 computing the number of iterations. */
1984 fold_defer_overflow_warnings ();
1986 iv0.base = expand_simple_operations (iv0.base);
1987 iv1.base = expand_simple_operations (iv1.base);
1988 if (!number_of_iterations_cond (loop, type, &iv0, code, &iv1, niter,
1989 loop_only_exit_p (loop, exit), safe))
1991 fold_undefer_and_ignore_overflow_warnings ();
1992 return false;
1995 if (optimize >= 3)
1997 niter->assumptions = simplify_using_outer_evolutions (loop,
1998 niter->assumptions);
1999 niter->may_be_zero = simplify_using_outer_evolutions (loop,
2000 niter->may_be_zero);
2001 niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
2004 niter->assumptions
2005 = simplify_using_initial_conditions (loop,
2006 niter->assumptions);
2007 niter->may_be_zero
2008 = simplify_using_initial_conditions (loop,
2009 niter->may_be_zero);
2011 fold_undefer_and_ignore_overflow_warnings ();
2013 /* If NITER has simplified into a constant, update MAX. */
2014 if (TREE_CODE (niter->niter) == INTEGER_CST)
2015 niter->max = wi::to_widest (niter->niter);
2017 if (integer_onep (niter->assumptions))
2018 return true;
2020 /* With -funsafe-loop-optimizations we assume that nothing bad can happen.
2021 But if we can prove that there is overflow or some other source of weird
2022 behavior, ignore the loop even with -funsafe-loop-optimizations. */
2023 if (integer_zerop (niter->assumptions) || !single_exit (loop))
2024 return false;
2026 if (flag_unsafe_loop_optimizations)
2027 niter->assumptions = boolean_true_node;
2029 if (warn)
2031 const char *wording;
2032 location_t loc = gimple_location (stmt);
2034 /* We can provide a more specific warning if one of the operator is
2035 constant and the other advances by +1 or -1. */
2036 if (!integer_zerop (iv1.step)
2037 ? (integer_zerop (iv0.step)
2038 && (integer_onep (iv1.step) || integer_all_onesp (iv1.step)))
2039 : (integer_onep (iv0.step) || integer_all_onesp (iv0.step)))
2040 wording =
2041 flag_unsafe_loop_optimizations
2042 ? N_("assuming that the loop is not infinite")
2043 : N_("cannot optimize possibly infinite loops");
2044 else
2045 wording =
2046 flag_unsafe_loop_optimizations
2047 ? N_("assuming that the loop counter does not overflow")
2048 : N_("cannot optimize loop, the loop counter may overflow");
2050 warning_at ((LOCATION_LINE (loc) > 0) ? loc : input_location,
2051 OPT_Wunsafe_loop_optimizations, "%s", gettext (wording));
2054 return flag_unsafe_loop_optimizations;
2057 /* Try to determine the number of iterations of LOOP. If we succeed,
2058 expression giving number of iterations is returned and *EXIT is
2059 set to the edge from that the information is obtained. Otherwise
2060 chrec_dont_know is returned. */
2062 tree
2063 find_loop_niter (struct loop *loop, edge *exit)
2065 unsigned i;
2066 vec<edge> exits = get_loop_exit_edges (loop);
2067 edge ex;
2068 tree niter = NULL_TREE, aniter;
2069 struct tree_niter_desc desc;
2071 *exit = NULL;
2072 FOR_EACH_VEC_ELT (exits, i, ex)
2074 if (!number_of_iterations_exit (loop, ex, &desc, false))
2075 continue;
2077 if (integer_nonzerop (desc.may_be_zero))
2079 /* We exit in the first iteration through this exit.
2080 We won't find anything better. */
2081 niter = build_int_cst (unsigned_type_node, 0);
2082 *exit = ex;
2083 break;
2086 if (!integer_zerop (desc.may_be_zero))
2087 continue;
2089 aniter = desc.niter;
2091 if (!niter)
2093 /* Nothing recorded yet. */
2094 niter = aniter;
2095 *exit = ex;
2096 continue;
2099 /* Prefer constants, the lower the better. */
2100 if (TREE_CODE (aniter) != INTEGER_CST)
2101 continue;
2103 if (TREE_CODE (niter) != INTEGER_CST)
2105 niter = aniter;
2106 *exit = ex;
2107 continue;
2110 if (tree_int_cst_lt (aniter, niter))
2112 niter = aniter;
2113 *exit = ex;
2114 continue;
2117 exits.release ();
2119 return niter ? niter : chrec_dont_know;
2122 /* Return true if loop is known to have bounded number of iterations. */
2124 bool
2125 finite_loop_p (struct loop *loop)
2127 widest_int nit;
2128 int flags;
2130 if (flag_unsafe_loop_optimizations)
2131 return true;
2132 flags = flags_from_decl_or_type (current_function_decl);
2133 if ((flags & (ECF_CONST|ECF_PURE)) && !(flags & ECF_LOOPING_CONST_OR_PURE))
2135 if (dump_file && (dump_flags & TDF_DETAILS))
2136 fprintf (dump_file, "Found loop %i to be finite: it is within pure or const function.\n",
2137 loop->num);
2138 return true;
2141 if (loop->any_upper_bound
2142 || max_loop_iterations (loop, &nit))
2144 if (dump_file && (dump_flags & TDF_DETAILS))
2145 fprintf (dump_file, "Found loop %i to be finite: upper bound found.\n",
2146 loop->num);
2147 return true;
2149 return false;
2154 Analysis of a number of iterations of a loop by a brute-force evaluation.
2158 /* Bound on the number of iterations we try to evaluate. */
2160 #define MAX_ITERATIONS_TO_TRACK \
2161 ((unsigned) PARAM_VALUE (PARAM_MAX_ITERATIONS_TO_TRACK))
2163 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
2164 result by a chain of operations such that all but exactly one of their
2165 operands are constants. */
2167 static gimple
2168 chain_of_csts_start (struct loop *loop, tree x)
2170 gimple stmt = SSA_NAME_DEF_STMT (x);
2171 tree use;
2172 basic_block bb = gimple_bb (stmt);
2173 enum tree_code code;
2175 if (!bb
2176 || !flow_bb_inside_loop_p (loop, bb))
2177 return NULL;
2179 if (gimple_code (stmt) == GIMPLE_PHI)
2181 if (bb == loop->header)
2182 return stmt;
2184 return NULL;
2187 if (gimple_code (stmt) != GIMPLE_ASSIGN
2188 || gimple_assign_rhs_class (stmt) == GIMPLE_TERNARY_RHS)
2189 return NULL;
2191 code = gimple_assign_rhs_code (stmt);
2192 if (gimple_references_memory_p (stmt)
2193 || TREE_CODE_CLASS (code) == tcc_reference
2194 || (code == ADDR_EXPR
2195 && !is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
2196 return NULL;
2198 use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
2199 if (use == NULL_TREE)
2200 return NULL;
2202 return chain_of_csts_start (loop, use);
2205 /* Determines whether the expression X is derived from a result of a phi node
2206 in header of LOOP such that
2208 * the derivation of X consists only from operations with constants
2209 * the initial value of the phi node is constant
2210 * the value of the phi node in the next iteration can be derived from the
2211 value in the current iteration by a chain of operations with constants.
2213 If such phi node exists, it is returned, otherwise NULL is returned. */
2215 static gimple
2216 get_base_for (struct loop *loop, tree x)
2218 gimple phi;
2219 tree init, next;
2221 if (is_gimple_min_invariant (x))
2222 return NULL;
2224 phi = chain_of_csts_start (loop, x);
2225 if (!phi)
2226 return NULL;
2228 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2229 next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2231 if (TREE_CODE (next) != SSA_NAME)
2232 return NULL;
2234 if (!is_gimple_min_invariant (init))
2235 return NULL;
2237 if (chain_of_csts_start (loop, next) != phi)
2238 return NULL;
2240 return phi;
2243 /* Given an expression X, then
2245 * if X is NULL_TREE, we return the constant BASE.
2246 * otherwise X is a SSA name, whose value in the considered loop is derived
2247 by a chain of operations with constant from a result of a phi node in
2248 the header of the loop. Then we return value of X when the value of the
2249 result of this phi node is given by the constant BASE. */
2251 static tree
2252 get_val_for (tree x, tree base)
2254 gimple stmt;
2256 gcc_checking_assert (is_gimple_min_invariant (base));
2258 if (!x)
2259 return base;
2261 stmt = SSA_NAME_DEF_STMT (x);
2262 if (gimple_code (stmt) == GIMPLE_PHI)
2263 return base;
2265 gcc_checking_assert (is_gimple_assign (stmt));
2267 /* STMT must be either an assignment of a single SSA name or an
2268 expression involving an SSA name and a constant. Try to fold that
2269 expression using the value for the SSA name. */
2270 if (gimple_assign_ssa_name_copy_p (stmt))
2271 return get_val_for (gimple_assign_rhs1 (stmt), base);
2272 else if (gimple_assign_rhs_class (stmt) == GIMPLE_UNARY_RHS
2273 && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
2275 return fold_build1 (gimple_assign_rhs_code (stmt),
2276 gimple_expr_type (stmt),
2277 get_val_for (gimple_assign_rhs1 (stmt), base));
2279 else if (gimple_assign_rhs_class (stmt) == GIMPLE_BINARY_RHS)
2281 tree rhs1 = gimple_assign_rhs1 (stmt);
2282 tree rhs2 = gimple_assign_rhs2 (stmt);
2283 if (TREE_CODE (rhs1) == SSA_NAME)
2284 rhs1 = get_val_for (rhs1, base);
2285 else if (TREE_CODE (rhs2) == SSA_NAME)
2286 rhs2 = get_val_for (rhs2, base);
2287 else
2288 gcc_unreachable ();
2289 return fold_build2 (gimple_assign_rhs_code (stmt),
2290 gimple_expr_type (stmt), rhs1, rhs2);
2292 else
2293 gcc_unreachable ();
2297 /* Tries to count the number of iterations of LOOP till it exits by EXIT
2298 by brute force -- i.e. by determining the value of the operands of the
2299 condition at EXIT in first few iterations of the loop (assuming that
2300 these values are constant) and determining the first one in that the
2301 condition is not satisfied. Returns the constant giving the number
2302 of the iterations of LOOP if successful, chrec_dont_know otherwise. */
2304 tree
2305 loop_niter_by_eval (struct loop *loop, edge exit)
2307 tree acnd;
2308 tree op[2], val[2], next[2], aval[2];
2309 gimple phi, cond;
2310 unsigned i, j;
2311 enum tree_code cmp;
2313 cond = last_stmt (exit->src);
2314 if (!cond || gimple_code (cond) != GIMPLE_COND)
2315 return chrec_dont_know;
2317 cmp = gimple_cond_code (cond);
2318 if (exit->flags & EDGE_TRUE_VALUE)
2319 cmp = invert_tree_comparison (cmp, false);
2321 switch (cmp)
2323 case EQ_EXPR:
2324 case NE_EXPR:
2325 case GT_EXPR:
2326 case GE_EXPR:
2327 case LT_EXPR:
2328 case LE_EXPR:
2329 op[0] = gimple_cond_lhs (cond);
2330 op[1] = gimple_cond_rhs (cond);
2331 break;
2333 default:
2334 return chrec_dont_know;
2337 for (j = 0; j < 2; j++)
2339 if (is_gimple_min_invariant (op[j]))
2341 val[j] = op[j];
2342 next[j] = NULL_TREE;
2343 op[j] = NULL_TREE;
2345 else
2347 phi = get_base_for (loop, op[j]);
2348 if (!phi)
2349 return chrec_dont_know;
2350 val[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2351 next[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2355 /* Don't issue signed overflow warnings. */
2356 fold_defer_overflow_warnings ();
2358 for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
2360 for (j = 0; j < 2; j++)
2361 aval[j] = get_val_for (op[j], val[j]);
2363 acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
2364 if (acnd && integer_zerop (acnd))
2366 fold_undefer_and_ignore_overflow_warnings ();
2367 if (dump_file && (dump_flags & TDF_DETAILS))
2368 fprintf (dump_file,
2369 "Proved that loop %d iterates %d times using brute force.\n",
2370 loop->num, i);
2371 return build_int_cst (unsigned_type_node, i);
2374 for (j = 0; j < 2; j++)
2376 val[j] = get_val_for (next[j], val[j]);
2377 if (!is_gimple_min_invariant (val[j]))
2379 fold_undefer_and_ignore_overflow_warnings ();
2380 return chrec_dont_know;
2385 fold_undefer_and_ignore_overflow_warnings ();
2387 return chrec_dont_know;
2390 /* Finds the exit of the LOOP by that the loop exits after a constant
2391 number of iterations and stores the exit edge to *EXIT. The constant
2392 giving the number of iterations of LOOP is returned. The number of
2393 iterations is determined using loop_niter_by_eval (i.e. by brute force
2394 evaluation). If we are unable to find the exit for that loop_niter_by_eval
2395 determines the number of iterations, chrec_dont_know is returned. */
2397 tree
2398 find_loop_niter_by_eval (struct loop *loop, edge *exit)
2400 unsigned i;
2401 vec<edge> exits = get_loop_exit_edges (loop);
2402 edge ex;
2403 tree niter = NULL_TREE, aniter;
2405 *exit = NULL;
2407 /* Loops with multiple exits are expensive to handle and less important. */
2408 if (!flag_expensive_optimizations
2409 && exits.length () > 1)
2411 exits.release ();
2412 return chrec_dont_know;
2415 FOR_EACH_VEC_ELT (exits, i, ex)
2417 if (!just_once_each_iteration_p (loop, ex->src))
2418 continue;
2420 aniter = loop_niter_by_eval (loop, ex);
2421 if (chrec_contains_undetermined (aniter))
2422 continue;
2424 if (niter
2425 && !tree_int_cst_lt (aniter, niter))
2426 continue;
2428 niter = aniter;
2429 *exit = ex;
2431 exits.release ();
2433 return niter ? niter : chrec_dont_know;
2438 Analysis of upper bounds on number of iterations of a loop.
2442 static widest_int derive_constant_upper_bound_ops (tree, tree,
2443 enum tree_code, tree);
2445 /* Returns a constant upper bound on the value of the right-hand side of
2446 an assignment statement STMT. */
2448 static widest_int
2449 derive_constant_upper_bound_assign (gimple stmt)
2451 enum tree_code code = gimple_assign_rhs_code (stmt);
2452 tree op0 = gimple_assign_rhs1 (stmt);
2453 tree op1 = gimple_assign_rhs2 (stmt);
2455 return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt)),
2456 op0, code, op1);
2459 /* Returns a constant upper bound on the value of expression VAL. VAL
2460 is considered to be unsigned. If its type is signed, its value must
2461 be nonnegative. */
2463 static widest_int
2464 derive_constant_upper_bound (tree val)
2466 enum tree_code code;
2467 tree op0, op1;
2469 extract_ops_from_tree (val, &code, &op0, &op1);
2470 return derive_constant_upper_bound_ops (TREE_TYPE (val), op0, code, op1);
2473 /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
2474 whose type is TYPE. The expression is considered to be unsigned. If
2475 its type is signed, its value must be nonnegative. */
2477 static widest_int
2478 derive_constant_upper_bound_ops (tree type, tree op0,
2479 enum tree_code code, tree op1)
2481 tree subtype, maxt;
2482 widest_int bnd, max, mmax, cst;
2483 gimple stmt;
2485 if (INTEGRAL_TYPE_P (type))
2486 maxt = TYPE_MAX_VALUE (type);
2487 else
2488 maxt = upper_bound_in_type (type, type);
2490 max = wi::to_widest (maxt);
2492 switch (code)
2494 case INTEGER_CST:
2495 return wi::to_widest (op0);
2497 CASE_CONVERT:
2498 subtype = TREE_TYPE (op0);
2499 if (!TYPE_UNSIGNED (subtype)
2500 /* If TYPE is also signed, the fact that VAL is nonnegative implies
2501 that OP0 is nonnegative. */
2502 && TYPE_UNSIGNED (type)
2503 && !tree_expr_nonnegative_p (op0))
2505 /* If we cannot prove that the casted expression is nonnegative,
2506 we cannot establish more useful upper bound than the precision
2507 of the type gives us. */
2508 return max;
2511 /* We now know that op0 is an nonnegative value. Try deriving an upper
2512 bound for it. */
2513 bnd = derive_constant_upper_bound (op0);
2515 /* If the bound does not fit in TYPE, max. value of TYPE could be
2516 attained. */
2517 if (wi::ltu_p (max, bnd))
2518 return max;
2520 return bnd;
2522 case PLUS_EXPR:
2523 case POINTER_PLUS_EXPR:
2524 case MINUS_EXPR:
2525 if (TREE_CODE (op1) != INTEGER_CST
2526 || !tree_expr_nonnegative_p (op0))
2527 return max;
2529 /* Canonicalize to OP0 - CST. Consider CST to be signed, in order to
2530 choose the most logical way how to treat this constant regardless
2531 of the signedness of the type. */
2532 cst = wi::sext (wi::to_widest (op1), TYPE_PRECISION (type));
2533 if (code != MINUS_EXPR)
2534 cst = -cst;
2536 bnd = derive_constant_upper_bound (op0);
2538 if (wi::neg_p (cst))
2540 cst = -cst;
2541 /* Avoid CST == 0x80000... */
2542 if (wi::neg_p (cst))
2543 return max;;
2545 /* OP0 + CST. We need to check that
2546 BND <= MAX (type) - CST. */
2548 mmax -= cst;
2549 if (wi::ltu_p (bnd, max))
2550 return max;
2552 return bnd + cst;
2554 else
2556 /* OP0 - CST, where CST >= 0.
2558 If TYPE is signed, we have already verified that OP0 >= 0, and we
2559 know that the result is nonnegative. This implies that
2560 VAL <= BND - CST.
2562 If TYPE is unsigned, we must additionally know that OP0 >= CST,
2563 otherwise the operation underflows.
2566 /* This should only happen if the type is unsigned; however, for
2567 buggy programs that use overflowing signed arithmetics even with
2568 -fno-wrapv, this condition may also be true for signed values. */
2569 if (wi::ltu_p (bnd, cst))
2570 return max;
2572 if (TYPE_UNSIGNED (type))
2574 tree tem = fold_binary (GE_EXPR, boolean_type_node, op0,
2575 wide_int_to_tree (type, cst));
2576 if (!tem || integer_nonzerop (tem))
2577 return max;
2580 bnd -= cst;
2583 return bnd;
2585 case FLOOR_DIV_EXPR:
2586 case EXACT_DIV_EXPR:
2587 if (TREE_CODE (op1) != INTEGER_CST
2588 || tree_int_cst_sign_bit (op1))
2589 return max;
2591 bnd = derive_constant_upper_bound (op0);
2592 return wi::udiv_floor (bnd, wi::to_widest (op1));
2594 case BIT_AND_EXPR:
2595 if (TREE_CODE (op1) != INTEGER_CST
2596 || tree_int_cst_sign_bit (op1))
2597 return max;
2598 return wi::to_widest (op1);
2600 case SSA_NAME:
2601 stmt = SSA_NAME_DEF_STMT (op0);
2602 if (gimple_code (stmt) != GIMPLE_ASSIGN
2603 || gimple_assign_lhs (stmt) != op0)
2604 return max;
2605 return derive_constant_upper_bound_assign (stmt);
2607 default:
2608 return max;
2612 /* Emit a -Waggressive-loop-optimizations warning if needed. */
2614 static void
2615 do_warn_aggressive_loop_optimizations (struct loop *loop,
2616 widest_int i_bound, gimple stmt)
2618 /* Don't warn if the loop doesn't have known constant bound. */
2619 if (!loop->nb_iterations
2620 || TREE_CODE (loop->nb_iterations) != INTEGER_CST
2621 || !warn_aggressive_loop_optimizations
2622 /* To avoid warning multiple times for the same loop,
2623 only start warning when we preserve loops. */
2624 || (cfun->curr_properties & PROP_loops) == 0
2625 /* Only warn once per loop. */
2626 || loop->warned_aggressive_loop_optimizations
2627 /* Only warn if undefined behavior gives us lower estimate than the
2628 known constant bound. */
2629 || wi::cmpu (i_bound, wi::to_widest (loop->nb_iterations)) >= 0
2630 /* And undefined behavior happens unconditionally. */
2631 || !dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (stmt)))
2632 return;
2634 edge e = single_exit (loop);
2635 if (e == NULL)
2636 return;
2638 gimple estmt = last_stmt (e->src);
2639 if (warning_at (gimple_location (stmt), OPT_Waggressive_loop_optimizations,
2640 "iteration %E invokes undefined behavior",
2641 wide_int_to_tree (TREE_TYPE (loop->nb_iterations),
2642 i_bound)))
2643 inform (gimple_location (estmt), "containing loop");
2644 loop->warned_aggressive_loop_optimizations = true;
2647 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP. IS_EXIT
2648 is true if the loop is exited immediately after STMT, and this exit
2649 is taken at last when the STMT is executed BOUND + 1 times.
2650 REALISTIC is true if BOUND is expected to be close to the real number
2651 of iterations. UPPER is true if we are sure the loop iterates at most
2652 BOUND times. I_BOUND is a widest_int upper estimate on BOUND. */
2654 static void
2655 record_estimate (struct loop *loop, tree bound, const widest_int &i_bound,
2656 gimple at_stmt, bool is_exit, bool realistic, bool upper)
2658 widest_int delta;
2660 if (dump_file && (dump_flags & TDF_DETAILS))
2662 fprintf (dump_file, "Statement %s", is_exit ? "(exit)" : "");
2663 print_gimple_stmt (dump_file, at_stmt, 0, TDF_SLIM);
2664 fprintf (dump_file, " is %sexecuted at most ",
2665 upper ? "" : "probably ");
2666 print_generic_expr (dump_file, bound, TDF_SLIM);
2667 fprintf (dump_file, " (bounded by ");
2668 print_decu (i_bound, dump_file);
2669 fprintf (dump_file, ") + 1 times in loop %d.\n", loop->num);
2672 /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
2673 real number of iterations. */
2674 if (TREE_CODE (bound) != INTEGER_CST)
2675 realistic = false;
2676 else
2677 gcc_checking_assert (i_bound == wi::to_widest (bound));
2678 if (!upper && !realistic)
2679 return;
2681 /* If we have a guaranteed upper bound, record it in the appropriate
2682 list, unless this is an !is_exit bound (i.e. undefined behavior in
2683 at_stmt) in a loop with known constant number of iterations. */
2684 if (upper
2685 && (is_exit
2686 || loop->nb_iterations == NULL_TREE
2687 || TREE_CODE (loop->nb_iterations) != INTEGER_CST))
2689 struct nb_iter_bound *elt = ggc_alloc<nb_iter_bound> ();
2691 elt->bound = i_bound;
2692 elt->stmt = at_stmt;
2693 elt->is_exit = is_exit;
2694 elt->next = loop->bounds;
2695 loop->bounds = elt;
2698 /* If statement is executed on every path to the loop latch, we can directly
2699 infer the upper bound on the # of iterations of the loop. */
2700 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (at_stmt)))
2701 return;
2703 /* Update the number of iteration estimates according to the bound.
2704 If at_stmt is an exit then the loop latch is executed at most BOUND times,
2705 otherwise it can be executed BOUND + 1 times. We will lower the estimate
2706 later if such statement must be executed on last iteration */
2707 if (is_exit)
2708 delta = 0;
2709 else
2710 delta = 1;
2711 widest_int new_i_bound = i_bound + delta;
2713 /* If an overflow occurred, ignore the result. */
2714 if (wi::ltu_p (new_i_bound, delta))
2715 return;
2717 if (upper && !is_exit)
2718 do_warn_aggressive_loop_optimizations (loop, new_i_bound, at_stmt);
2719 record_niter_bound (loop, new_i_bound, realistic, upper);
2722 /* Record the estimate on number of iterations of LOOP based on the fact that
2723 the induction variable BASE + STEP * i evaluated in STMT does not wrap and
2724 its values belong to the range <LOW, HIGH>. REALISTIC is true if the
2725 estimated number of iterations is expected to be close to the real one.
2726 UPPER is true if we are sure the induction variable does not wrap. */
2728 static void
2729 record_nonwrapping_iv (struct loop *loop, tree base, tree step, gimple stmt,
2730 tree low, tree high, bool realistic, bool upper)
2732 tree niter_bound, extreme, delta;
2733 tree type = TREE_TYPE (base), unsigned_type;
2735 if (TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
2736 return;
2738 if (dump_file && (dump_flags & TDF_DETAILS))
2740 fprintf (dump_file, "Induction variable (");
2741 print_generic_expr (dump_file, TREE_TYPE (base), TDF_SLIM);
2742 fprintf (dump_file, ") ");
2743 print_generic_expr (dump_file, base, TDF_SLIM);
2744 fprintf (dump_file, " + ");
2745 print_generic_expr (dump_file, step, TDF_SLIM);
2746 fprintf (dump_file, " * iteration does not wrap in statement ");
2747 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2748 fprintf (dump_file, " in loop %d.\n", loop->num);
2751 unsigned_type = unsigned_type_for (type);
2752 base = fold_convert (unsigned_type, base);
2753 step = fold_convert (unsigned_type, step);
2755 if (tree_int_cst_sign_bit (step))
2757 extreme = fold_convert (unsigned_type, low);
2758 if (TREE_CODE (base) != INTEGER_CST)
2759 base = fold_convert (unsigned_type, high);
2760 delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
2761 step = fold_build1 (NEGATE_EXPR, unsigned_type, step);
2763 else
2765 extreme = fold_convert (unsigned_type, high);
2766 if (TREE_CODE (base) != INTEGER_CST)
2767 base = fold_convert (unsigned_type, low);
2768 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
2771 /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
2772 would get out of the range. */
2773 niter_bound = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step);
2774 widest_int max = derive_constant_upper_bound (niter_bound);
2775 record_estimate (loop, niter_bound, max, stmt, false, realistic, upper);
2778 /* Determine information about number of iterations a LOOP from the index
2779 IDX of a data reference accessed in STMT. RELIABLE is true if STMT is
2780 guaranteed to be executed in every iteration of LOOP. Callback for
2781 for_each_index. */
2783 struct ilb_data
2785 struct loop *loop;
2786 gimple stmt;
2789 static bool
2790 idx_infer_loop_bounds (tree base, tree *idx, void *dta)
2792 struct ilb_data *data = (struct ilb_data *) dta;
2793 tree ev, init, step;
2794 tree low, high, type, next;
2795 bool sign, upper = true, at_end = false;
2796 struct loop *loop = data->loop;
2797 bool reliable = true;
2799 if (TREE_CODE (base) != ARRAY_REF)
2800 return true;
2802 /* For arrays at the end of the structure, we are not guaranteed that they
2803 do not really extend over their declared size. However, for arrays of
2804 size greater than one, this is unlikely to be intended. */
2805 if (array_at_struct_end_p (base))
2807 at_end = true;
2808 upper = false;
2811 struct loop *dloop = loop_containing_stmt (data->stmt);
2812 if (!dloop)
2813 return true;
2815 ev = analyze_scalar_evolution (dloop, *idx);
2816 ev = instantiate_parameters (loop, ev);
2817 init = initial_condition (ev);
2818 step = evolution_part_in_loop_num (ev, loop->num);
2820 if (!init
2821 || !step
2822 || TREE_CODE (step) != INTEGER_CST
2823 || integer_zerop (step)
2824 || tree_contains_chrecs (init, NULL)
2825 || chrec_contains_symbols_defined_in_loop (init, loop->num))
2826 return true;
2828 low = array_ref_low_bound (base);
2829 high = array_ref_up_bound (base);
2831 /* The case of nonconstant bounds could be handled, but it would be
2832 complicated. */
2833 if (TREE_CODE (low) != INTEGER_CST
2834 || !high
2835 || TREE_CODE (high) != INTEGER_CST)
2836 return true;
2837 sign = tree_int_cst_sign_bit (step);
2838 type = TREE_TYPE (step);
2840 /* The array of length 1 at the end of a structure most likely extends
2841 beyond its bounds. */
2842 if (at_end
2843 && operand_equal_p (low, high, 0))
2844 return true;
2846 /* In case the relevant bound of the array does not fit in type, or
2847 it does, but bound + step (in type) still belongs into the range of the
2848 array, the index may wrap and still stay within the range of the array
2849 (consider e.g. if the array is indexed by the full range of
2850 unsigned char).
2852 To make things simpler, we require both bounds to fit into type, although
2853 there are cases where this would not be strictly necessary. */
2854 if (!int_fits_type_p (high, type)
2855 || !int_fits_type_p (low, type))
2856 return true;
2857 low = fold_convert (type, low);
2858 high = fold_convert (type, high);
2860 if (sign)
2861 next = fold_binary (PLUS_EXPR, type, low, step);
2862 else
2863 next = fold_binary (PLUS_EXPR, type, high, step);
2865 if (tree_int_cst_compare (low, next) <= 0
2866 && tree_int_cst_compare (next, high) <= 0)
2867 return true;
2869 /* If access is not executed on every iteration, we must ensure that overlow may
2870 not make the access valid later. */
2871 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (data->stmt))
2872 && scev_probably_wraps_p (initial_condition_in_loop_num (ev, loop->num),
2873 step, data->stmt, loop, true))
2874 reliable = false;
2876 record_nonwrapping_iv (loop, init, step, data->stmt, low, high, reliable, upper);
2877 return true;
2880 /* Determine information about number of iterations a LOOP from the bounds
2881 of arrays in the data reference REF accessed in STMT. RELIABLE is true if
2882 STMT is guaranteed to be executed in every iteration of LOOP.*/
2884 static void
2885 infer_loop_bounds_from_ref (struct loop *loop, gimple stmt, tree ref)
2887 struct ilb_data data;
2889 data.loop = loop;
2890 data.stmt = stmt;
2891 for_each_index (&ref, idx_infer_loop_bounds, &data);
2894 /* Determine information about number of iterations of a LOOP from the way
2895 arrays are used in STMT. RELIABLE is true if STMT is guaranteed to be
2896 executed in every iteration of LOOP. */
2898 static void
2899 infer_loop_bounds_from_array (struct loop *loop, gimple stmt)
2901 if (is_gimple_assign (stmt))
2903 tree op0 = gimple_assign_lhs (stmt);
2904 tree op1 = gimple_assign_rhs1 (stmt);
2906 /* For each memory access, analyze its access function
2907 and record a bound on the loop iteration domain. */
2908 if (REFERENCE_CLASS_P (op0))
2909 infer_loop_bounds_from_ref (loop, stmt, op0);
2911 if (REFERENCE_CLASS_P (op1))
2912 infer_loop_bounds_from_ref (loop, stmt, op1);
2914 else if (is_gimple_call (stmt))
2916 tree arg, lhs;
2917 unsigned i, n = gimple_call_num_args (stmt);
2919 lhs = gimple_call_lhs (stmt);
2920 if (lhs && REFERENCE_CLASS_P (lhs))
2921 infer_loop_bounds_from_ref (loop, stmt, lhs);
2923 for (i = 0; i < n; i++)
2925 arg = gimple_call_arg (stmt, i);
2926 if (REFERENCE_CLASS_P (arg))
2927 infer_loop_bounds_from_ref (loop, stmt, arg);
2932 /* Determine information about number of iterations of a LOOP from the fact
2933 that pointer arithmetics in STMT does not overflow. */
2935 static void
2936 infer_loop_bounds_from_pointer_arith (struct loop *loop, gimple stmt)
2938 tree def, base, step, scev, type, low, high;
2939 tree var, ptr;
2941 if (!is_gimple_assign (stmt)
2942 || gimple_assign_rhs_code (stmt) != POINTER_PLUS_EXPR)
2943 return;
2945 def = gimple_assign_lhs (stmt);
2946 if (TREE_CODE (def) != SSA_NAME)
2947 return;
2949 type = TREE_TYPE (def);
2950 if (!nowrap_type_p (type))
2951 return;
2953 ptr = gimple_assign_rhs1 (stmt);
2954 if (!expr_invariant_in_loop_p (loop, ptr))
2955 return;
2957 var = gimple_assign_rhs2 (stmt);
2958 if (TYPE_PRECISION (type) != TYPE_PRECISION (TREE_TYPE (var)))
2959 return;
2961 scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
2962 if (chrec_contains_undetermined (scev))
2963 return;
2965 base = initial_condition_in_loop_num (scev, loop->num);
2966 step = evolution_part_in_loop_num (scev, loop->num);
2968 if (!base || !step
2969 || TREE_CODE (step) != INTEGER_CST
2970 || tree_contains_chrecs (base, NULL)
2971 || chrec_contains_symbols_defined_in_loop (base, loop->num))
2972 return;
2974 low = lower_bound_in_type (type, type);
2975 high = upper_bound_in_type (type, type);
2977 /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
2978 produce a NULL pointer. The contrary would mean NULL points to an object,
2979 while NULL is supposed to compare unequal with the address of all objects.
2980 Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
2981 NULL pointer since that would mean wrapping, which we assume here not to
2982 happen. So, we can exclude NULL from the valid range of pointer
2983 arithmetic. */
2984 if (flag_delete_null_pointer_checks && int_cst_value (low) == 0)
2985 low = build_int_cstu (TREE_TYPE (low), TYPE_ALIGN_UNIT (TREE_TYPE (type)));
2987 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
2990 /* Determine information about number of iterations of a LOOP from the fact
2991 that signed arithmetics in STMT does not overflow. */
2993 static void
2994 infer_loop_bounds_from_signedness (struct loop *loop, gimple stmt)
2996 tree def, base, step, scev, type, low, high;
2998 if (gimple_code (stmt) != GIMPLE_ASSIGN)
2999 return;
3001 def = gimple_assign_lhs (stmt);
3003 if (TREE_CODE (def) != SSA_NAME)
3004 return;
3006 type = TREE_TYPE (def);
3007 if (!INTEGRAL_TYPE_P (type)
3008 || !TYPE_OVERFLOW_UNDEFINED (type))
3009 return;
3011 scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
3012 if (chrec_contains_undetermined (scev))
3013 return;
3015 base = initial_condition_in_loop_num (scev, loop->num);
3016 step = evolution_part_in_loop_num (scev, loop->num);
3018 if (!base || !step
3019 || TREE_CODE (step) != INTEGER_CST
3020 || tree_contains_chrecs (base, NULL)
3021 || chrec_contains_symbols_defined_in_loop (base, loop->num))
3022 return;
3024 low = lower_bound_in_type (type, type);
3025 high = upper_bound_in_type (type, type);
3027 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
3030 /* The following analyzers are extracting informations on the bounds
3031 of LOOP from the following undefined behaviors:
3033 - data references should not access elements over the statically
3034 allocated size,
3036 - signed variables should not overflow when flag_wrapv is not set.
3039 static void
3040 infer_loop_bounds_from_undefined (struct loop *loop)
3042 unsigned i;
3043 basic_block *bbs;
3044 gimple_stmt_iterator bsi;
3045 basic_block bb;
3046 bool reliable;
3048 bbs = get_loop_body (loop);
3050 for (i = 0; i < loop->num_nodes; i++)
3052 bb = bbs[i];
3054 /* If BB is not executed in each iteration of the loop, we cannot
3055 use the operations in it to infer reliable upper bound on the
3056 # of iterations of the loop. However, we can use it as a guess.
3057 Reliable guesses come only from array bounds. */
3058 reliable = dominated_by_p (CDI_DOMINATORS, loop->latch, bb);
3060 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
3062 gimple stmt = gsi_stmt (bsi);
3064 infer_loop_bounds_from_array (loop, stmt);
3066 if (reliable)
3068 infer_loop_bounds_from_signedness (loop, stmt);
3069 infer_loop_bounds_from_pointer_arith (loop, stmt);
3075 free (bbs);
3078 /* Compare wide ints, callback for qsort. */
3080 static int
3081 wide_int_cmp (const void *p1, const void *p2)
3083 const widest_int *d1 = (const widest_int *) p1;
3084 const widest_int *d2 = (const widest_int *) p2;
3085 return wi::cmpu (*d1, *d2);
3088 /* Return index of BOUND in BOUNDS array sorted in increasing order.
3089 Lookup by binary search. */
3091 static int
3092 bound_index (vec<widest_int> bounds, const widest_int &bound)
3094 unsigned int end = bounds.length ();
3095 unsigned int begin = 0;
3097 /* Find a matching index by means of a binary search. */
3098 while (begin != end)
3100 unsigned int middle = (begin + end) / 2;
3101 widest_int index = bounds[middle];
3103 if (index == bound)
3104 return middle;
3105 else if (wi::ltu_p (index, bound))
3106 begin = middle + 1;
3107 else
3108 end = middle;
3110 gcc_unreachable ();
3113 /* We recorded loop bounds only for statements dominating loop latch (and thus
3114 executed each loop iteration). If there are any bounds on statements not
3115 dominating the loop latch we can improve the estimate by walking the loop
3116 body and seeing if every path from loop header to loop latch contains
3117 some bounded statement. */
3119 static void
3120 discover_iteration_bound_by_body_walk (struct loop *loop)
3122 struct nb_iter_bound *elt;
3123 vec<widest_int> bounds = vNULL;
3124 vec<vec<basic_block> > queues = vNULL;
3125 vec<basic_block> queue = vNULL;
3126 ptrdiff_t queue_index;
3127 ptrdiff_t latch_index = 0;
3129 /* Discover what bounds may interest us. */
3130 for (elt = loop->bounds; elt; elt = elt->next)
3132 widest_int bound = elt->bound;
3134 /* Exit terminates loop at given iteration, while non-exits produce undefined
3135 effect on the next iteration. */
3136 if (!elt->is_exit)
3138 bound += 1;
3139 /* If an overflow occurred, ignore the result. */
3140 if (bound == 0)
3141 continue;
3144 if (!loop->any_upper_bound
3145 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
3146 bounds.safe_push (bound);
3149 /* Exit early if there is nothing to do. */
3150 if (!bounds.exists ())
3151 return;
3153 if (dump_file && (dump_flags & TDF_DETAILS))
3154 fprintf (dump_file, " Trying to walk loop body to reduce the bound.\n");
3156 /* Sort the bounds in decreasing order. */
3157 bounds.qsort (wide_int_cmp);
3159 /* For every basic block record the lowest bound that is guaranteed to
3160 terminate the loop. */
3162 hash_map<basic_block, ptrdiff_t> bb_bounds;
3163 for (elt = loop->bounds; elt; elt = elt->next)
3165 widest_int bound = elt->bound;
3166 if (!elt->is_exit)
3168 bound += 1;
3169 /* If an overflow occurred, ignore the result. */
3170 if (bound == 0)
3171 continue;
3174 if (!loop->any_upper_bound
3175 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
3177 ptrdiff_t index = bound_index (bounds, bound);
3178 ptrdiff_t *entry = bb_bounds.get (gimple_bb (elt->stmt));
3179 if (!entry)
3180 bb_bounds.put (gimple_bb (elt->stmt), index);
3181 else if ((ptrdiff_t)*entry > index)
3182 *entry = index;
3186 hash_map<basic_block, ptrdiff_t> block_priority;
3188 /* Perform shortest path discovery loop->header ... loop->latch.
3190 The "distance" is given by the smallest loop bound of basic block
3191 present in the path and we look for path with largest smallest bound
3192 on it.
3194 To avoid the need for fibonacci heap on double ints we simply compress
3195 double ints into indexes to BOUNDS array and then represent the queue
3196 as arrays of queues for every index.
3197 Index of BOUNDS.length() means that the execution of given BB has
3198 no bounds determined.
3200 VISITED is a pointer map translating basic block into smallest index
3201 it was inserted into the priority queue with. */
3202 latch_index = -1;
3204 /* Start walk in loop header with index set to infinite bound. */
3205 queue_index = bounds.length ();
3206 queues.safe_grow_cleared (queue_index + 1);
3207 queue.safe_push (loop->header);
3208 queues[queue_index] = queue;
3209 block_priority.put (loop->header, queue_index);
3211 for (; queue_index >= 0; queue_index--)
3213 if (latch_index < queue_index)
3215 while (queues[queue_index].length ())
3217 basic_block bb;
3218 ptrdiff_t bound_index = queue_index;
3219 edge e;
3220 edge_iterator ei;
3222 queue = queues[queue_index];
3223 bb = queue.pop ();
3225 /* OK, we later inserted the BB with lower priority, skip it. */
3226 if (*block_priority.get (bb) > queue_index)
3227 continue;
3229 /* See if we can improve the bound. */
3230 ptrdiff_t *entry = bb_bounds.get (bb);
3231 if (entry && *entry < bound_index)
3232 bound_index = *entry;
3234 /* Insert succesors into the queue, watch for latch edge
3235 and record greatest index we saw. */
3236 FOR_EACH_EDGE (e, ei, bb->succs)
3238 bool insert = false;
3240 if (loop_exit_edge_p (loop, e))
3241 continue;
3243 if (e == loop_latch_edge (loop)
3244 && latch_index < bound_index)
3245 latch_index = bound_index;
3246 else if (!(entry = block_priority.get (e->dest)))
3248 insert = true;
3249 block_priority.put (e->dest, bound_index);
3251 else if (*entry < bound_index)
3253 insert = true;
3254 *entry = bound_index;
3257 if (insert)
3258 queues[bound_index].safe_push (e->dest);
3262 queues[queue_index].release ();
3265 gcc_assert (latch_index >= 0);
3266 if ((unsigned)latch_index < bounds.length ())
3268 if (dump_file && (dump_flags & TDF_DETAILS))
3270 fprintf (dump_file, "Found better loop bound ");
3271 print_decu (bounds[latch_index], dump_file);
3272 fprintf (dump_file, "\n");
3274 record_niter_bound (loop, bounds[latch_index], false, true);
3277 queues.release ();
3278 bounds.release ();
3281 /* See if every path cross the loop goes through a statement that is known
3282 to not execute at the last iteration. In that case we can decrese iteration
3283 count by 1. */
3285 static void
3286 maybe_lower_iteration_bound (struct loop *loop)
3288 hash_set<gimple> *not_executed_last_iteration = NULL;
3289 struct nb_iter_bound *elt;
3290 bool found_exit = false;
3291 vec<basic_block> queue = vNULL;
3292 bitmap visited;
3294 /* Collect all statements with interesting (i.e. lower than
3295 nb_iterations_upper_bound) bound on them.
3297 TODO: Due to the way record_estimate choose estimates to store, the bounds
3298 will be always nb_iterations_upper_bound-1. We can change this to record
3299 also statements not dominating the loop latch and update the walk bellow
3300 to the shortest path algorthm. */
3301 for (elt = loop->bounds; elt; elt = elt->next)
3303 if (!elt->is_exit
3304 && wi::ltu_p (elt->bound, loop->nb_iterations_upper_bound))
3306 if (!not_executed_last_iteration)
3307 not_executed_last_iteration = new hash_set<gimple>;
3308 not_executed_last_iteration->add (elt->stmt);
3311 if (!not_executed_last_iteration)
3312 return;
3314 /* Start DFS walk in the loop header and see if we can reach the
3315 loop latch or any of the exits (including statements with side
3316 effects that may terminate the loop otherwise) without visiting
3317 any of the statements known to have undefined effect on the last
3318 iteration. */
3319 queue.safe_push (loop->header);
3320 visited = BITMAP_ALLOC (NULL);
3321 bitmap_set_bit (visited, loop->header->index);
3322 found_exit = false;
3326 basic_block bb = queue.pop ();
3327 gimple_stmt_iterator gsi;
3328 bool stmt_found = false;
3330 /* Loop for possible exits and statements bounding the execution. */
3331 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3333 gimple stmt = gsi_stmt (gsi);
3334 if (not_executed_last_iteration->contains (stmt))
3336 stmt_found = true;
3337 break;
3339 if (gimple_has_side_effects (stmt))
3341 found_exit = true;
3342 break;
3345 if (found_exit)
3346 break;
3348 /* If no bounding statement is found, continue the walk. */
3349 if (!stmt_found)
3351 edge e;
3352 edge_iterator ei;
3354 FOR_EACH_EDGE (e, ei, bb->succs)
3356 if (loop_exit_edge_p (loop, e)
3357 || e == loop_latch_edge (loop))
3359 found_exit = true;
3360 break;
3362 if (bitmap_set_bit (visited, e->dest->index))
3363 queue.safe_push (e->dest);
3367 while (queue.length () && !found_exit);
3369 /* If every path through the loop reach bounding statement before exit,
3370 then we know the last iteration of the loop will have undefined effect
3371 and we can decrease number of iterations. */
3373 if (!found_exit)
3375 if (dump_file && (dump_flags & TDF_DETAILS))
3376 fprintf (dump_file, "Reducing loop iteration estimate by 1; "
3377 "undefined statement must be executed at the last iteration.\n");
3378 record_niter_bound (loop, loop->nb_iterations_upper_bound - 1,
3379 false, true);
3381 BITMAP_FREE (visited);
3382 queue.release ();
3383 delete not_executed_last_iteration;
3386 /* Records estimates on numbers of iterations of LOOP. If USE_UNDEFINED_P
3387 is true also use estimates derived from undefined behavior. */
3389 static void
3390 estimate_numbers_of_iterations_loop (struct loop *loop)
3392 vec<edge> exits;
3393 tree niter, type;
3394 unsigned i;
3395 struct tree_niter_desc niter_desc;
3396 edge ex;
3397 widest_int bound;
3398 edge likely_exit;
3400 /* Give up if we already have tried to compute an estimation. */
3401 if (loop->estimate_state != EST_NOT_COMPUTED)
3402 return;
3404 loop->estimate_state = EST_AVAILABLE;
3405 /* Force estimate compuation but leave any existing upper bound in place. */
3406 loop->any_estimate = false;
3408 /* Ensure that loop->nb_iterations is computed if possible. If it turns out
3409 to be constant, we avoid undefined behavior implied bounds and instead
3410 diagnose those loops with -Waggressive-loop-optimizations. */
3411 number_of_latch_executions (loop);
3413 exits = get_loop_exit_edges (loop);
3414 likely_exit = single_likely_exit (loop);
3415 FOR_EACH_VEC_ELT (exits, i, ex)
3417 if (!number_of_iterations_exit (loop, ex, &niter_desc, false, false))
3418 continue;
3420 niter = niter_desc.niter;
3421 type = TREE_TYPE (niter);
3422 if (TREE_CODE (niter_desc.may_be_zero) != INTEGER_CST)
3423 niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
3424 build_int_cst (type, 0),
3425 niter);
3426 record_estimate (loop, niter, niter_desc.max,
3427 last_stmt (ex->src),
3428 true, ex == likely_exit, true);
3430 exits.release ();
3432 if (flag_aggressive_loop_optimizations)
3433 infer_loop_bounds_from_undefined (loop);
3435 discover_iteration_bound_by_body_walk (loop);
3437 maybe_lower_iteration_bound (loop);
3439 /* If we have a measured profile, use it to estimate the number of
3440 iterations. */
3441 if (loop->header->count != 0)
3443 gcov_type nit = expected_loop_iterations_unbounded (loop) + 1;
3444 bound = gcov_type_to_wide_int (nit);
3445 record_niter_bound (loop, bound, true, false);
3448 /* If we know the exact number of iterations of this loop, try to
3449 not break code with undefined behavior by not recording smaller
3450 maximum number of iterations. */
3451 if (loop->nb_iterations
3452 && TREE_CODE (loop->nb_iterations) == INTEGER_CST)
3454 loop->any_upper_bound = true;
3455 loop->nb_iterations_upper_bound = wi::to_widest (loop->nb_iterations);
3459 /* Sets NIT to the estimated number of executions of the latch of the
3460 LOOP. If CONSERVATIVE is true, we must be sure that NIT is at least as
3461 large as the number of iterations. If we have no reliable estimate,
3462 the function returns false, otherwise returns true. */
3464 bool
3465 estimated_loop_iterations (struct loop *loop, widest_int *nit)
3467 /* When SCEV information is available, try to update loop iterations
3468 estimate. Otherwise just return whatever we recorded earlier. */
3469 if (scev_initialized_p ())
3470 estimate_numbers_of_iterations_loop (loop);
3472 return (get_estimated_loop_iterations (loop, nit));
3475 /* Similar to estimated_loop_iterations, but returns the estimate only
3476 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
3477 on the number of iterations of LOOP could not be derived, returns -1. */
3479 HOST_WIDE_INT
3480 estimated_loop_iterations_int (struct loop *loop)
3482 widest_int nit;
3483 HOST_WIDE_INT hwi_nit;
3485 if (!estimated_loop_iterations (loop, &nit))
3486 return -1;
3488 if (!wi::fits_shwi_p (nit))
3489 return -1;
3490 hwi_nit = nit.to_shwi ();
3492 return hwi_nit < 0 ? -1 : hwi_nit;
3496 /* Sets NIT to an upper bound for the maximum number of executions of the
3497 latch of the LOOP. If we have no reliable estimate, the function returns
3498 false, otherwise returns true. */
3500 bool
3501 max_loop_iterations (struct loop *loop, widest_int *nit)
3503 /* When SCEV information is available, try to update loop iterations
3504 estimate. Otherwise just return whatever we recorded earlier. */
3505 if (scev_initialized_p ())
3506 estimate_numbers_of_iterations_loop (loop);
3508 return get_max_loop_iterations (loop, nit);
3511 /* Similar to max_loop_iterations, but returns the estimate only
3512 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
3513 on the number of iterations of LOOP could not be derived, returns -1. */
3515 HOST_WIDE_INT
3516 max_loop_iterations_int (struct loop *loop)
3518 widest_int nit;
3519 HOST_WIDE_INT hwi_nit;
3521 if (!max_loop_iterations (loop, &nit))
3522 return -1;
3524 if (!wi::fits_shwi_p (nit))
3525 return -1;
3526 hwi_nit = nit.to_shwi ();
3528 return hwi_nit < 0 ? -1 : hwi_nit;
3531 /* Returns an estimate for the number of executions of statements
3532 in the LOOP. For statements before the loop exit, this exceeds
3533 the number of execution of the latch by one. */
3535 HOST_WIDE_INT
3536 estimated_stmt_executions_int (struct loop *loop)
3538 HOST_WIDE_INT nit = estimated_loop_iterations_int (loop);
3539 HOST_WIDE_INT snit;
3541 if (nit == -1)
3542 return -1;
3544 snit = (HOST_WIDE_INT) ((unsigned HOST_WIDE_INT) nit + 1);
3546 /* If the computation overflows, return -1. */
3547 return snit < 0 ? -1 : snit;
3550 /* Sets NIT to the estimated maximum number of executions of the latch of the
3551 LOOP, plus one. If we have no reliable estimate, the function returns
3552 false, otherwise returns true. */
3554 bool
3555 max_stmt_executions (struct loop *loop, widest_int *nit)
3557 widest_int nit_minus_one;
3559 if (!max_loop_iterations (loop, nit))
3560 return false;
3562 nit_minus_one = *nit;
3564 *nit += 1;
3566 return wi::gtu_p (*nit, nit_minus_one);
3569 /* Sets NIT to the estimated number of executions of the latch of the
3570 LOOP, plus one. If we have no reliable estimate, the function returns
3571 false, otherwise returns true. */
3573 bool
3574 estimated_stmt_executions (struct loop *loop, widest_int *nit)
3576 widest_int nit_minus_one;
3578 if (!estimated_loop_iterations (loop, nit))
3579 return false;
3581 nit_minus_one = *nit;
3583 *nit += 1;
3585 return wi::gtu_p (*nit, nit_minus_one);
3588 /* Records estimates on numbers of iterations of loops. */
3590 void
3591 estimate_numbers_of_iterations (void)
3593 struct loop *loop;
3595 /* We don't want to issue signed overflow warnings while getting
3596 loop iteration estimates. */
3597 fold_defer_overflow_warnings ();
3599 FOR_EACH_LOOP (loop, 0)
3601 estimate_numbers_of_iterations_loop (loop);
3604 fold_undefer_and_ignore_overflow_warnings ();
3607 /* Returns true if statement S1 dominates statement S2. */
3609 bool
3610 stmt_dominates_stmt_p (gimple s1, gimple s2)
3612 basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
3614 if (!bb1
3615 || s1 == s2)
3616 return true;
3618 if (bb1 == bb2)
3620 gimple_stmt_iterator bsi;
3622 if (gimple_code (s2) == GIMPLE_PHI)
3623 return false;
3625 if (gimple_code (s1) == GIMPLE_PHI)
3626 return true;
3628 for (bsi = gsi_start_bb (bb1); gsi_stmt (bsi) != s2; gsi_next (&bsi))
3629 if (gsi_stmt (bsi) == s1)
3630 return true;
3632 return false;
3635 return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
3638 /* Returns true when we can prove that the number of executions of
3639 STMT in the loop is at most NITER, according to the bound on
3640 the number of executions of the statement NITER_BOUND->stmt recorded in
3641 NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
3643 ??? This code can become quite a CPU hog - we can have many bounds,
3644 and large basic block forcing stmt_dominates_stmt_p to be queried
3645 many times on a large basic blocks, so the whole thing is O(n^2)
3646 for scev_probably_wraps_p invocation (that can be done n times).
3648 It would make more sense (and give better answers) to remember BB
3649 bounds computed by discover_iteration_bound_by_body_walk. */
3651 static bool
3652 n_of_executions_at_most (gimple stmt,
3653 struct nb_iter_bound *niter_bound,
3654 tree niter)
3656 widest_int bound = niter_bound->bound;
3657 tree nit_type = TREE_TYPE (niter), e;
3658 enum tree_code cmp;
3660 gcc_assert (TYPE_UNSIGNED (nit_type));
3662 /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
3663 the number of iterations is small. */
3664 if (!wi::fits_to_tree_p (bound, nit_type))
3665 return false;
3667 /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
3668 times. This means that:
3670 -- if NITER_BOUND->is_exit is true, then everything after
3671 it at most NITER_BOUND->bound times.
3673 -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
3674 is executed, then NITER_BOUND->stmt is executed as well in the same
3675 iteration then STMT is executed at most NITER_BOUND->bound + 1 times.
3677 If we can determine that NITER_BOUND->stmt is always executed
3678 after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
3679 We conclude that if both statements belong to the same
3680 basic block and STMT is before NITER_BOUND->stmt and there are no
3681 statements with side effects in between. */
3683 if (niter_bound->is_exit)
3685 if (stmt == niter_bound->stmt
3686 || !stmt_dominates_stmt_p (niter_bound->stmt, stmt))
3687 return false;
3688 cmp = GE_EXPR;
3690 else
3692 if (!stmt_dominates_stmt_p (niter_bound->stmt, stmt))
3694 gimple_stmt_iterator bsi;
3695 if (gimple_bb (stmt) != gimple_bb (niter_bound->stmt)
3696 || gimple_code (stmt) == GIMPLE_PHI
3697 || gimple_code (niter_bound->stmt) == GIMPLE_PHI)
3698 return false;
3700 /* By stmt_dominates_stmt_p we already know that STMT appears
3701 before NITER_BOUND->STMT. Still need to test that the loop
3702 can not be terinated by a side effect in between. */
3703 for (bsi = gsi_for_stmt (stmt); gsi_stmt (bsi) != niter_bound->stmt;
3704 gsi_next (&bsi))
3705 if (gimple_has_side_effects (gsi_stmt (bsi)))
3706 return false;
3707 bound += 1;
3708 if (bound == 0
3709 || !wi::fits_to_tree_p (bound, nit_type))
3710 return false;
3712 cmp = GT_EXPR;
3715 e = fold_binary (cmp, boolean_type_node,
3716 niter, wide_int_to_tree (nit_type, bound));
3717 return e && integer_nonzerop (e);
3720 /* Returns true if the arithmetics in TYPE can be assumed not to wrap. */
3722 bool
3723 nowrap_type_p (tree type)
3725 if (INTEGRAL_TYPE_P (type)
3726 && TYPE_OVERFLOW_UNDEFINED (type))
3727 return true;
3729 if (POINTER_TYPE_P (type))
3730 return true;
3732 return false;
3735 /* Return false only when the induction variable BASE + STEP * I is
3736 known to not overflow: i.e. when the number of iterations is small
3737 enough with respect to the step and initial condition in order to
3738 keep the evolution confined in TYPEs bounds. Return true when the
3739 iv is known to overflow or when the property is not computable.
3741 USE_OVERFLOW_SEMANTICS is true if this function should assume that
3742 the rules for overflow of the given language apply (e.g., that signed
3743 arithmetics in C does not overflow). */
3745 bool
3746 scev_probably_wraps_p (tree base, tree step,
3747 gimple at_stmt, struct loop *loop,
3748 bool use_overflow_semantics)
3750 tree delta, step_abs;
3751 tree unsigned_type, valid_niter;
3752 tree type = TREE_TYPE (step);
3753 tree e;
3754 widest_int niter;
3755 struct nb_iter_bound *bound;
3757 /* FIXME: We really need something like
3758 http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
3760 We used to test for the following situation that frequently appears
3761 during address arithmetics:
3763 D.1621_13 = (long unsigned intD.4) D.1620_12;
3764 D.1622_14 = D.1621_13 * 8;
3765 D.1623_15 = (doubleD.29 *) D.1622_14;
3767 And derived that the sequence corresponding to D_14
3768 can be proved to not wrap because it is used for computing a
3769 memory access; however, this is not really the case -- for example,
3770 if D_12 = (unsigned char) [254,+,1], then D_14 has values
3771 2032, 2040, 0, 8, ..., but the code is still legal. */
3773 if (chrec_contains_undetermined (base)
3774 || chrec_contains_undetermined (step))
3775 return true;
3777 if (integer_zerop (step))
3778 return false;
3780 /* If we can use the fact that signed and pointer arithmetics does not
3781 wrap, we are done. */
3782 if (use_overflow_semantics && nowrap_type_p (TREE_TYPE (base)))
3783 return false;
3785 /* To be able to use estimates on number of iterations of the loop,
3786 we must have an upper bound on the absolute value of the step. */
3787 if (TREE_CODE (step) != INTEGER_CST)
3788 return true;
3790 /* Don't issue signed overflow warnings. */
3791 fold_defer_overflow_warnings ();
3793 /* Otherwise, compute the number of iterations before we reach the
3794 bound of the type, and verify that the loop is exited before this
3795 occurs. */
3796 unsigned_type = unsigned_type_for (type);
3797 base = fold_convert (unsigned_type, base);
3799 if (tree_int_cst_sign_bit (step))
3801 tree extreme = fold_convert (unsigned_type,
3802 lower_bound_in_type (type, type));
3803 delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
3804 step_abs = fold_build1 (NEGATE_EXPR, unsigned_type,
3805 fold_convert (unsigned_type, step));
3807 else
3809 tree extreme = fold_convert (unsigned_type,
3810 upper_bound_in_type (type, type));
3811 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
3812 step_abs = fold_convert (unsigned_type, step);
3815 valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
3817 estimate_numbers_of_iterations_loop (loop);
3819 if (max_loop_iterations (loop, &niter)
3820 && wi::fits_to_tree_p (niter, TREE_TYPE (valid_niter))
3821 && (e = fold_binary (GT_EXPR, boolean_type_node, valid_niter,
3822 wide_int_to_tree (TREE_TYPE (valid_niter),
3823 niter))) != NULL
3824 && integer_nonzerop (e))
3826 fold_undefer_and_ignore_overflow_warnings ();
3827 return false;
3829 if (at_stmt)
3830 for (bound = loop->bounds; bound; bound = bound->next)
3832 if (n_of_executions_at_most (at_stmt, bound, valid_niter))
3834 fold_undefer_and_ignore_overflow_warnings ();
3835 return false;
3839 fold_undefer_and_ignore_overflow_warnings ();
3841 /* At this point we still don't have a proof that the iv does not
3842 overflow: give up. */
3843 return true;
3846 /* Frees the information on upper bounds on numbers of iterations of LOOP. */
3848 void
3849 free_numbers_of_iterations_estimates_loop (struct loop *loop)
3851 struct nb_iter_bound *bound, *next;
3853 loop->nb_iterations = NULL;
3854 loop->estimate_state = EST_NOT_COMPUTED;
3855 for (bound = loop->bounds; bound; bound = next)
3857 next = bound->next;
3858 ggc_free (bound);
3861 loop->bounds = NULL;
3864 /* Frees the information on upper bounds on numbers of iterations of loops. */
3866 void
3867 free_numbers_of_iterations_estimates (void)
3869 struct loop *loop;
3871 FOR_EACH_LOOP (loop, 0)
3873 free_numbers_of_iterations_estimates_loop (loop);
3877 /* Substitute value VAL for ssa name NAME inside expressions held
3878 at LOOP. */
3880 void
3881 substitute_in_loop_info (struct loop *loop, tree name, tree val)
3883 loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);