warn-access: wrong -Wdangling-pointer with labels [PR106080]
[official-gcc.git] / gcc / tree-ssa-loop-niter.cc
blob581bf5d067b58c3a41755bcf1c92c6cb105f853f
1 /* Functions to determine/estimate number of iterations of a loop.
2 Copyright (C) 2004-2023 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 "backend.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "tree-pass.h"
28 #include "ssa.h"
29 #include "gimple-pretty-print.h"
30 #include "diagnostic-core.h"
31 #include "stor-layout.h"
32 #include "fold-const.h"
33 #include "calls.h"
34 #include "intl.h"
35 #include "gimplify.h"
36 #include "gimple-iterator.h"
37 #include "tree-cfg.h"
38 #include "tree-ssa-loop-ivopts.h"
39 #include "tree-ssa-loop-niter.h"
40 #include "tree-ssa-loop.h"
41 #include "cfgloop.h"
42 #include "tree-chrec.h"
43 #include "tree-scalar-evolution.h"
44 #include "tree-dfa.h"
45 #include "internal-fn.h"
46 #include "gimple-range.h"
49 /* The maximum number of dominator BBs we search for conditions
50 of loop header copies we use for simplifying a conditional
51 expression. */
52 #define MAX_DOMINATORS_TO_WALK 8
56 Analysis of number of iterations of an affine exit test.
60 /* Bounds on some value, BELOW <= X <= UP. */
62 struct bounds
64 mpz_t below, up;
67 /* Splits expression EXPR to a variable part VAR and constant OFFSET. */
69 static void
70 split_to_var_and_offset (tree expr, tree *var, mpz_t offset)
72 tree type = TREE_TYPE (expr);
73 tree op0, op1;
74 bool negate = false;
76 *var = expr;
77 mpz_set_ui (offset, 0);
79 switch (TREE_CODE (expr))
81 case MINUS_EXPR:
82 negate = true;
83 /* Fallthru. */
85 case PLUS_EXPR:
86 case POINTER_PLUS_EXPR:
87 op0 = TREE_OPERAND (expr, 0);
88 op1 = TREE_OPERAND (expr, 1);
90 if (TREE_CODE (op1) != INTEGER_CST)
91 break;
93 *var = op0;
94 /* Always sign extend the offset. */
95 wi::to_mpz (wi::to_wide (op1), offset, SIGNED);
96 if (negate)
97 mpz_neg (offset, offset);
98 break;
100 case INTEGER_CST:
101 *var = build_int_cst_type (type, 0);
102 wi::to_mpz (wi::to_wide (expr), offset, TYPE_SIGN (type));
103 break;
105 default:
106 break;
110 /* From condition C0 CMP C1 derives information regarding the value range
111 of VAR, which is of TYPE. Results are stored in to BELOW and UP. */
113 static void
114 refine_value_range_using_guard (tree type, tree var,
115 tree c0, enum tree_code cmp, tree c1,
116 mpz_t below, mpz_t up)
118 tree varc0, varc1, ctype;
119 mpz_t offc0, offc1;
120 mpz_t mint, maxt, minc1, maxc1;
121 bool no_wrap = nowrap_type_p (type);
122 bool c0_ok, c1_ok;
123 signop sgn = TYPE_SIGN (type);
125 switch (cmp)
127 case LT_EXPR:
128 case LE_EXPR:
129 case GT_EXPR:
130 case GE_EXPR:
131 STRIP_SIGN_NOPS (c0);
132 STRIP_SIGN_NOPS (c1);
133 ctype = TREE_TYPE (c0);
134 if (!useless_type_conversion_p (ctype, type))
135 return;
137 break;
139 case EQ_EXPR:
140 /* We could derive quite precise information from EQ_EXPR, however,
141 such a guard is unlikely to appear, so we do not bother with
142 handling it. */
143 return;
145 case NE_EXPR:
146 /* NE_EXPR comparisons do not contain much of useful information,
147 except for cases of comparing with bounds. */
148 if (TREE_CODE (c1) != INTEGER_CST
149 || !INTEGRAL_TYPE_P (type))
150 return;
152 /* Ensure that the condition speaks about an expression in the same
153 type as X and Y. */
154 ctype = TREE_TYPE (c0);
155 if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
156 return;
157 c0 = fold_convert (type, c0);
158 c1 = fold_convert (type, c1);
160 if (operand_equal_p (var, c0, 0))
162 mpz_t valc1;
164 /* Case of comparing VAR with its below/up bounds. */
165 mpz_init (valc1);
166 wi::to_mpz (wi::to_wide (c1), valc1, TYPE_SIGN (type));
167 if (mpz_cmp (valc1, below) == 0)
168 cmp = GT_EXPR;
169 if (mpz_cmp (valc1, up) == 0)
170 cmp = LT_EXPR;
172 mpz_clear (valc1);
174 else
176 /* Case of comparing with the bounds of the type. */
177 wide_int min = wi::min_value (type);
178 wide_int max = wi::max_value (type);
180 if (wi::to_wide (c1) == min)
181 cmp = GT_EXPR;
182 if (wi::to_wide (c1) == max)
183 cmp = LT_EXPR;
186 /* Quick return if no useful information. */
187 if (cmp == NE_EXPR)
188 return;
190 break;
192 default:
193 return;
196 mpz_init (offc0);
197 mpz_init (offc1);
198 split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
199 split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
201 /* We are only interested in comparisons of expressions based on VAR. */
202 if (operand_equal_p (var, varc1, 0))
204 std::swap (varc0, varc1);
205 mpz_swap (offc0, offc1);
206 cmp = swap_tree_comparison (cmp);
208 else if (!operand_equal_p (var, varc0, 0))
210 mpz_clear (offc0);
211 mpz_clear (offc1);
212 return;
215 mpz_init (mint);
216 mpz_init (maxt);
217 get_type_static_bounds (type, mint, maxt);
218 mpz_init (minc1);
219 mpz_init (maxc1);
220 Value_Range r (TREE_TYPE (varc1));
221 /* Setup range information for varc1. */
222 if (integer_zerop (varc1))
224 wi::to_mpz (0, minc1, TYPE_SIGN (type));
225 wi::to_mpz (0, maxc1, TYPE_SIGN (type));
227 else if (TREE_CODE (varc1) == SSA_NAME
228 && INTEGRAL_TYPE_P (type)
229 && get_range_query (cfun)->range_of_expr (r, varc1)
230 && r.kind () == VR_RANGE)
232 gcc_assert (wi::le_p (r.lower_bound (), r.upper_bound (), sgn));
233 wi::to_mpz (r.lower_bound (), minc1, sgn);
234 wi::to_mpz (r.upper_bound (), maxc1, sgn);
236 else
238 mpz_set (minc1, mint);
239 mpz_set (maxc1, maxt);
242 /* Compute valid range information for varc1 + offc1. Note nothing
243 useful can be derived if it overflows or underflows. Overflow or
244 underflow could happen when:
246 offc1 > 0 && varc1 + offc1 > MAX_VAL (type)
247 offc1 < 0 && varc1 + offc1 < MIN_VAL (type). */
248 mpz_add (minc1, minc1, offc1);
249 mpz_add (maxc1, maxc1, offc1);
250 c1_ok = (no_wrap
251 || mpz_sgn (offc1) == 0
252 || (mpz_sgn (offc1) < 0 && mpz_cmp (minc1, mint) >= 0)
253 || (mpz_sgn (offc1) > 0 && mpz_cmp (maxc1, maxt) <= 0));
254 if (!c1_ok)
255 goto end;
257 if (mpz_cmp (minc1, mint) < 0)
258 mpz_set (minc1, mint);
259 if (mpz_cmp (maxc1, maxt) > 0)
260 mpz_set (maxc1, maxt);
262 if (cmp == LT_EXPR)
264 cmp = LE_EXPR;
265 mpz_sub_ui (maxc1, maxc1, 1);
267 if (cmp == GT_EXPR)
269 cmp = GE_EXPR;
270 mpz_add_ui (minc1, minc1, 1);
273 /* Compute range information for varc0. If there is no overflow,
274 the condition implied that
276 (varc0) cmp (varc1 + offc1 - offc0)
278 We can possibly improve the upper bound of varc0 if cmp is LE_EXPR,
279 or the below bound if cmp is GE_EXPR.
281 To prove there is no overflow/underflow, we need to check below
282 four cases:
283 1) cmp == LE_EXPR && offc0 > 0
285 (varc0 + offc0) doesn't overflow
286 && (varc1 + offc1 - offc0) doesn't underflow
288 2) cmp == LE_EXPR && offc0 < 0
290 (varc0 + offc0) doesn't underflow
291 && (varc1 + offc1 - offc0) doesn't overfloe
293 In this case, (varc0 + offc0) will never underflow if we can
294 prove (varc1 + offc1 - offc0) doesn't overflow.
296 3) cmp == GE_EXPR && offc0 < 0
298 (varc0 + offc0) doesn't underflow
299 && (varc1 + offc1 - offc0) doesn't overflow
301 4) cmp == GE_EXPR && offc0 > 0
303 (varc0 + offc0) doesn't overflow
304 && (varc1 + offc1 - offc0) doesn't underflow
306 In this case, (varc0 + offc0) will never overflow if we can
307 prove (varc1 + offc1 - offc0) doesn't underflow.
309 Note we only handle case 2 and 4 in below code. */
311 mpz_sub (minc1, minc1, offc0);
312 mpz_sub (maxc1, maxc1, offc0);
313 c0_ok = (no_wrap
314 || mpz_sgn (offc0) == 0
315 || (cmp == LE_EXPR
316 && mpz_sgn (offc0) < 0 && mpz_cmp (maxc1, maxt) <= 0)
317 || (cmp == GE_EXPR
318 && mpz_sgn (offc0) > 0 && mpz_cmp (minc1, mint) >= 0));
319 if (!c0_ok)
320 goto end;
322 if (cmp == LE_EXPR)
324 if (mpz_cmp (up, maxc1) > 0)
325 mpz_set (up, maxc1);
327 else
329 if (mpz_cmp (below, minc1) < 0)
330 mpz_set (below, minc1);
333 end:
334 mpz_clear (mint);
335 mpz_clear (maxt);
336 mpz_clear (minc1);
337 mpz_clear (maxc1);
338 mpz_clear (offc0);
339 mpz_clear (offc1);
342 /* Stores estimate on the minimum/maximum value of the expression VAR + OFF
343 in TYPE to MIN and MAX. */
345 static void
346 determine_value_range (class loop *loop, tree type, tree var, mpz_t off,
347 mpz_t min, mpz_t max)
349 int cnt = 0;
350 mpz_t minm, maxm;
351 basic_block bb;
352 wide_int minv, maxv;
353 enum value_range_kind rtype = VR_VARYING;
355 /* If the expression is a constant, we know its value exactly. */
356 if (integer_zerop (var))
358 mpz_set (min, off);
359 mpz_set (max, off);
360 return;
363 get_type_static_bounds (type, min, max);
365 /* See if we have some range info from VRP. */
366 if (TREE_CODE (var) == SSA_NAME && INTEGRAL_TYPE_P (type))
368 edge e = loop_preheader_edge (loop);
369 signop sgn = TYPE_SIGN (type);
370 gphi_iterator gsi;
372 /* Either for VAR itself... */
373 Value_Range var_range (TREE_TYPE (var));
374 get_range_query (cfun)->range_of_expr (var_range, var);
375 rtype = var_range.kind ();
376 if (!var_range.undefined_p ())
378 minv = var_range.lower_bound ();
379 maxv = var_range.upper_bound ();
382 /* Or for PHI results in loop->header where VAR is used as
383 PHI argument from the loop preheader edge. */
384 Value_Range phi_range (TREE_TYPE (var));
385 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
387 gphi *phi = gsi.phi ();
388 if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var
389 && get_range_query (cfun)->range_of_expr (phi_range,
390 gimple_phi_result (phi))
391 && phi_range.kind () == VR_RANGE)
393 if (rtype != VR_RANGE)
395 rtype = VR_RANGE;
396 minv = phi_range.lower_bound ();
397 maxv = phi_range.upper_bound ();
399 else
401 minv = wi::max (minv, phi_range.lower_bound (), sgn);
402 maxv = wi::min (maxv, phi_range.upper_bound (), sgn);
403 /* If the PHI result range are inconsistent with
404 the VAR range, give up on looking at the PHI
405 results. This can happen if VR_UNDEFINED is
406 involved. */
407 if (wi::gt_p (minv, maxv, sgn))
409 Value_Range vr (TREE_TYPE (var));
410 get_range_query (cfun)->range_of_expr (vr, var);
411 rtype = vr.kind ();
412 if (!vr.undefined_p ())
414 minv = vr.lower_bound ();
415 maxv = vr.upper_bound ();
417 break;
422 mpz_init (minm);
423 mpz_init (maxm);
424 if (rtype != VR_RANGE)
426 mpz_set (minm, min);
427 mpz_set (maxm, max);
429 else
431 gcc_assert (wi::le_p (minv, maxv, sgn));
432 wi::to_mpz (minv, minm, sgn);
433 wi::to_mpz (maxv, maxm, sgn);
435 /* Now walk the dominators of the loop header and use the entry
436 guards to refine the estimates. */
437 for (bb = loop->header;
438 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
439 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
441 edge e;
442 tree c0, c1;
443 gimple *cond;
444 enum tree_code cmp;
446 if (!single_pred_p (bb))
447 continue;
448 e = single_pred_edge (bb);
450 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
451 continue;
453 cond = last_stmt (e->src);
454 c0 = gimple_cond_lhs (cond);
455 cmp = gimple_cond_code (cond);
456 c1 = gimple_cond_rhs (cond);
458 if (e->flags & EDGE_FALSE_VALUE)
459 cmp = invert_tree_comparison (cmp, false);
461 refine_value_range_using_guard (type, var, c0, cmp, c1, minm, maxm);
462 ++cnt;
465 mpz_add (minm, minm, off);
466 mpz_add (maxm, maxm, off);
467 /* If the computation may not wrap or off is zero, then this
468 is always fine. If off is negative and minv + off isn't
469 smaller than type's minimum, or off is positive and
470 maxv + off isn't bigger than type's maximum, use the more
471 precise range too. */
472 if (nowrap_type_p (type)
473 || mpz_sgn (off) == 0
474 || (mpz_sgn (off) < 0 && mpz_cmp (minm, min) >= 0)
475 || (mpz_sgn (off) > 0 && mpz_cmp (maxm, max) <= 0))
477 mpz_set (min, minm);
478 mpz_set (max, maxm);
479 mpz_clear (minm);
480 mpz_clear (maxm);
481 return;
483 mpz_clear (minm);
484 mpz_clear (maxm);
487 /* If the computation may wrap, we know nothing about the value, except for
488 the range of the type. */
489 if (!nowrap_type_p (type))
490 return;
492 /* Since the addition of OFF does not wrap, if OFF is positive, then we may
493 add it to MIN, otherwise to MAX. */
494 if (mpz_sgn (off) < 0)
495 mpz_add (max, max, off);
496 else
497 mpz_add (min, min, off);
500 /* Stores the bounds on the difference of the values of the expressions
501 (var + X) and (var + Y), computed in TYPE, to BNDS. */
503 static void
504 bound_difference_of_offsetted_base (tree type, mpz_t x, mpz_t y,
505 bounds *bnds)
507 int rel = mpz_cmp (x, y);
508 bool may_wrap = !nowrap_type_p (type);
509 mpz_t m;
511 /* If X == Y, then the expressions are always equal.
512 If X > Y, there are the following possibilities:
513 a) neither of var + X and var + Y overflow or underflow, or both of
514 them do. Then their difference is X - Y.
515 b) var + X overflows, and var + Y does not. Then the values of the
516 expressions are var + X - M and var + Y, where M is the range of
517 the type, and their difference is X - Y - M.
518 c) var + Y underflows and var + X does not. Their difference again
519 is M - X + Y.
520 Therefore, if the arithmetics in type does not overflow, then the
521 bounds are (X - Y, X - Y), otherwise they are (X - Y - M, X - Y)
522 Similarly, if X < Y, the bounds are either (X - Y, X - Y) or
523 (X - Y, X - Y + M). */
525 if (rel == 0)
527 mpz_set_ui (bnds->below, 0);
528 mpz_set_ui (bnds->up, 0);
529 return;
532 mpz_init (m);
533 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), m, UNSIGNED);
534 mpz_add_ui (m, m, 1);
535 mpz_sub (bnds->up, x, y);
536 mpz_set (bnds->below, bnds->up);
538 if (may_wrap)
540 if (rel > 0)
541 mpz_sub (bnds->below, bnds->below, m);
542 else
543 mpz_add (bnds->up, bnds->up, m);
546 mpz_clear (m);
549 /* From condition C0 CMP C1 derives information regarding the
550 difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
551 and stores it to BNDS. */
553 static void
554 refine_bounds_using_guard (tree type, tree varx, mpz_t offx,
555 tree vary, mpz_t offy,
556 tree c0, enum tree_code cmp, tree c1,
557 bounds *bnds)
559 tree varc0, varc1, ctype;
560 mpz_t offc0, offc1, loffx, loffy, bnd;
561 bool lbound = false;
562 bool no_wrap = nowrap_type_p (type);
563 bool x_ok, y_ok;
565 switch (cmp)
567 case LT_EXPR:
568 case LE_EXPR:
569 case GT_EXPR:
570 case GE_EXPR:
571 STRIP_SIGN_NOPS (c0);
572 STRIP_SIGN_NOPS (c1);
573 ctype = TREE_TYPE (c0);
574 if (!useless_type_conversion_p (ctype, type))
575 return;
577 break;
579 case EQ_EXPR:
580 /* We could derive quite precise information from EQ_EXPR, however, such
581 a guard is unlikely to appear, so we do not bother with handling
582 it. */
583 return;
585 case NE_EXPR:
586 /* NE_EXPR comparisons do not contain much of useful information, except for
587 special case of comparing with the bounds of the type. */
588 if (TREE_CODE (c1) != INTEGER_CST
589 || !INTEGRAL_TYPE_P (type))
590 return;
592 /* Ensure that the condition speaks about an expression in the same type
593 as X and Y. */
594 ctype = TREE_TYPE (c0);
595 if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
596 return;
597 c0 = fold_convert (type, c0);
598 c1 = fold_convert (type, c1);
600 if (TYPE_MIN_VALUE (type)
601 && operand_equal_p (c1, TYPE_MIN_VALUE (type), 0))
603 cmp = GT_EXPR;
604 break;
606 if (TYPE_MAX_VALUE (type)
607 && operand_equal_p (c1, TYPE_MAX_VALUE (type), 0))
609 cmp = LT_EXPR;
610 break;
613 return;
614 default:
615 return;
618 mpz_init (offc0);
619 mpz_init (offc1);
620 split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
621 split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
623 /* We are only interested in comparisons of expressions based on VARX and
624 VARY. TODO -- we might also be able to derive some bounds from
625 expressions containing just one of the variables. */
627 if (operand_equal_p (varx, varc1, 0))
629 std::swap (varc0, varc1);
630 mpz_swap (offc0, offc1);
631 cmp = swap_tree_comparison (cmp);
634 if (!operand_equal_p (varx, varc0, 0)
635 || !operand_equal_p (vary, varc1, 0))
636 goto end;
638 mpz_init_set (loffx, offx);
639 mpz_init_set (loffy, offy);
641 if (cmp == GT_EXPR || cmp == GE_EXPR)
643 std::swap (varx, vary);
644 mpz_swap (offc0, offc1);
645 mpz_swap (loffx, loffy);
646 cmp = swap_tree_comparison (cmp);
647 lbound = true;
650 /* If there is no overflow, the condition implies that
652 (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
654 The overflows and underflows may complicate things a bit; each
655 overflow decreases the appropriate offset by M, and underflow
656 increases it by M. The above inequality would not necessarily be
657 true if
659 -- VARX + OFFX underflows and VARX + OFFC0 does not, or
660 VARX + OFFC0 overflows, but VARX + OFFX does not.
661 This may only happen if OFFX < OFFC0.
662 -- VARY + OFFY overflows and VARY + OFFC1 does not, or
663 VARY + OFFC1 underflows and VARY + OFFY does not.
664 This may only happen if OFFY > OFFC1. */
666 if (no_wrap)
668 x_ok = true;
669 y_ok = true;
671 else
673 x_ok = (integer_zerop (varx)
674 || mpz_cmp (loffx, offc0) >= 0);
675 y_ok = (integer_zerop (vary)
676 || mpz_cmp (loffy, offc1) <= 0);
679 if (x_ok && y_ok)
681 mpz_init (bnd);
682 mpz_sub (bnd, loffx, loffy);
683 mpz_add (bnd, bnd, offc1);
684 mpz_sub (bnd, bnd, offc0);
686 if (cmp == LT_EXPR)
687 mpz_sub_ui (bnd, bnd, 1);
689 if (lbound)
691 mpz_neg (bnd, bnd);
692 if (mpz_cmp (bnds->below, bnd) < 0)
693 mpz_set (bnds->below, bnd);
695 else
697 if (mpz_cmp (bnd, bnds->up) < 0)
698 mpz_set (bnds->up, bnd);
700 mpz_clear (bnd);
703 mpz_clear (loffx);
704 mpz_clear (loffy);
705 end:
706 mpz_clear (offc0);
707 mpz_clear (offc1);
710 /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
711 The subtraction is considered to be performed in arbitrary precision,
712 without overflows.
714 We do not attempt to be too clever regarding the value ranges of X and
715 Y; most of the time, they are just integers or ssa names offsetted by
716 integer. However, we try to use the information contained in the
717 comparisons before the loop (usually created by loop header copying). */
719 static void
720 bound_difference (class loop *loop, tree x, tree y, bounds *bnds)
722 tree type = TREE_TYPE (x);
723 tree varx, vary;
724 mpz_t offx, offy;
725 mpz_t minx, maxx, miny, maxy;
726 int cnt = 0;
727 edge e;
728 basic_block bb;
729 tree c0, c1;
730 gimple *cond;
731 enum tree_code cmp;
733 /* Get rid of unnecessary casts, but preserve the value of
734 the expressions. */
735 STRIP_SIGN_NOPS (x);
736 STRIP_SIGN_NOPS (y);
738 mpz_init (bnds->below);
739 mpz_init (bnds->up);
740 mpz_init (offx);
741 mpz_init (offy);
742 split_to_var_and_offset (x, &varx, offx);
743 split_to_var_and_offset (y, &vary, offy);
745 if (!integer_zerop (varx)
746 && operand_equal_p (varx, vary, 0))
748 /* Special case VARX == VARY -- we just need to compare the
749 offsets. The matters are a bit more complicated in the
750 case addition of offsets may wrap. */
751 bound_difference_of_offsetted_base (type, offx, offy, bnds);
753 else
755 /* Otherwise, use the value ranges to determine the initial
756 estimates on below and up. */
757 mpz_init (minx);
758 mpz_init (maxx);
759 mpz_init (miny);
760 mpz_init (maxy);
761 determine_value_range (loop, type, varx, offx, minx, maxx);
762 determine_value_range (loop, type, vary, offy, miny, maxy);
764 mpz_sub (bnds->below, minx, maxy);
765 mpz_sub (bnds->up, maxx, miny);
766 mpz_clear (minx);
767 mpz_clear (maxx);
768 mpz_clear (miny);
769 mpz_clear (maxy);
772 /* If both X and Y are constants, we cannot get any more precise. */
773 if (integer_zerop (varx) && integer_zerop (vary))
774 goto end;
776 /* Now walk the dominators of the loop header and use the entry
777 guards to refine the estimates. */
778 for (bb = loop->header;
779 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
780 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
782 if (!single_pred_p (bb))
783 continue;
784 e = single_pred_edge (bb);
786 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
787 continue;
789 cond = last_stmt (e->src);
790 c0 = gimple_cond_lhs (cond);
791 cmp = gimple_cond_code (cond);
792 c1 = gimple_cond_rhs (cond);
794 if (e->flags & EDGE_FALSE_VALUE)
795 cmp = invert_tree_comparison (cmp, false);
797 refine_bounds_using_guard (type, varx, offx, vary, offy,
798 c0, cmp, c1, bnds);
799 ++cnt;
802 end:
803 mpz_clear (offx);
804 mpz_clear (offy);
807 /* Update the bounds in BNDS that restrict the value of X to the bounds
808 that restrict the value of X + DELTA. X can be obtained as a
809 difference of two values in TYPE. */
811 static void
812 bounds_add (bounds *bnds, const widest_int &delta, tree type)
814 mpz_t mdelta, max;
816 mpz_init (mdelta);
817 wi::to_mpz (delta, mdelta, SIGNED);
819 mpz_init (max);
820 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
822 mpz_add (bnds->up, bnds->up, mdelta);
823 mpz_add (bnds->below, bnds->below, mdelta);
825 if (mpz_cmp (bnds->up, max) > 0)
826 mpz_set (bnds->up, max);
828 mpz_neg (max, max);
829 if (mpz_cmp (bnds->below, max) < 0)
830 mpz_set (bnds->below, max);
832 mpz_clear (mdelta);
833 mpz_clear (max);
836 /* Update the bounds in BNDS that restrict the value of X to the bounds
837 that restrict the value of -X. */
839 static void
840 bounds_negate (bounds *bnds)
842 mpz_t tmp;
844 mpz_init_set (tmp, bnds->up);
845 mpz_neg (bnds->up, bnds->below);
846 mpz_neg (bnds->below, tmp);
847 mpz_clear (tmp);
850 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
852 static tree
853 inverse (tree x, tree mask)
855 tree type = TREE_TYPE (x);
856 tree rslt;
857 unsigned ctr = tree_floor_log2 (mask);
859 if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
861 unsigned HOST_WIDE_INT ix;
862 unsigned HOST_WIDE_INT imask;
863 unsigned HOST_WIDE_INT irslt = 1;
865 gcc_assert (cst_and_fits_in_hwi (x));
866 gcc_assert (cst_and_fits_in_hwi (mask));
868 ix = int_cst_value (x);
869 imask = int_cst_value (mask);
871 for (; ctr; ctr--)
873 irslt *= ix;
874 ix *= ix;
876 irslt &= imask;
878 rslt = build_int_cst_type (type, irslt);
880 else
882 rslt = build_int_cst (type, 1);
883 for (; ctr; ctr--)
885 rslt = int_const_binop (MULT_EXPR, rslt, x);
886 x = int_const_binop (MULT_EXPR, x, x);
888 rslt = int_const_binop (BIT_AND_EXPR, rslt, mask);
891 return rslt;
894 /* Derives the upper bound BND on the number of executions of loop with exit
895 condition S * i <> C. If NO_OVERFLOW is true, then the control variable of
896 the loop does not overflow. EXIT_MUST_BE_TAKEN is true if we are guaranteed
897 that the loop ends through this exit, i.e., the induction variable ever
898 reaches the value of C.
900 The value C is equal to final - base, where final and base are the final and
901 initial value of the actual induction variable in the analysed loop. BNDS
902 bounds the value of this difference when computed in signed type with
903 unbounded range, while the computation of C is performed in an unsigned
904 type with the range matching the range of the type of the induction variable.
905 In particular, BNDS.up contains an upper bound on C in the following cases:
906 -- if the iv must reach its final value without overflow, i.e., if
907 NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
908 -- if final >= base, which we know to hold when BNDS.below >= 0. */
910 static void
911 number_of_iterations_ne_max (mpz_t bnd, bool no_overflow, tree c, tree s,
912 bounds *bnds, bool exit_must_be_taken)
914 widest_int max;
915 mpz_t d;
916 tree type = TREE_TYPE (c);
917 bool bnds_u_valid = ((no_overflow && exit_must_be_taken)
918 || mpz_sgn (bnds->below) >= 0);
920 if (integer_onep (s)
921 || (TREE_CODE (c) == INTEGER_CST
922 && TREE_CODE (s) == INTEGER_CST
923 && wi::mod_trunc (wi::to_wide (c), wi::to_wide (s),
924 TYPE_SIGN (type)) == 0)
925 || (TYPE_OVERFLOW_UNDEFINED (type)
926 && multiple_of_p (type, c, s)))
928 /* If C is an exact multiple of S, then its value will be reached before
929 the induction variable overflows (unless the loop is exited in some
930 other way before). Note that the actual induction variable in the
931 loop (which ranges from base to final instead of from 0 to C) may
932 overflow, in which case BNDS.up will not be giving a correct upper
933 bound on C; thus, BNDS_U_VALID had to be computed in advance. */
934 no_overflow = true;
935 exit_must_be_taken = true;
938 /* If the induction variable can overflow, the number of iterations is at
939 most the period of the control variable (or infinite, but in that case
940 the whole # of iterations analysis will fail). */
941 if (!no_overflow)
943 max = wi::mask <widest_int> (TYPE_PRECISION (type)
944 - wi::ctz (wi::to_wide (s)), false);
945 wi::to_mpz (max, bnd, UNSIGNED);
946 return;
949 /* Now we know that the induction variable does not overflow, so the loop
950 iterates at most (range of type / S) times. */
951 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), bnd, UNSIGNED);
953 /* If the induction variable is guaranteed to reach the value of C before
954 overflow, ... */
955 if (exit_must_be_taken)
957 /* ... then we can strengthen this to C / S, and possibly we can use
958 the upper bound on C given by BNDS. */
959 if (TREE_CODE (c) == INTEGER_CST)
960 wi::to_mpz (wi::to_wide (c), bnd, UNSIGNED);
961 else if (bnds_u_valid)
962 mpz_set (bnd, bnds->up);
965 mpz_init (d);
966 wi::to_mpz (wi::to_wide (s), d, UNSIGNED);
967 mpz_fdiv_q (bnd, bnd, d);
968 mpz_clear (d);
971 /* Determines number of iterations of loop whose ending condition
972 is IV <> FINAL. TYPE is the type of the iv. The number of
973 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
974 we know that the exit must be taken eventually, i.e., that the IV
975 ever reaches the value FINAL (we derived this earlier, and possibly set
976 NITER->assumptions to make sure this is the case). BNDS contains the
977 bounds on the difference FINAL - IV->base. */
979 static bool
980 number_of_iterations_ne (class loop *loop, tree type, affine_iv *iv,
981 tree final, class tree_niter_desc *niter,
982 bool exit_must_be_taken, bounds *bnds)
984 tree niter_type = unsigned_type_for (type);
985 tree s, c, d, bits, assumption, tmp, bound;
986 mpz_t max;
988 niter->control = *iv;
989 niter->bound = final;
990 niter->cmp = NE_EXPR;
992 /* Rearrange the terms so that we get inequality S * i <> C, with S
993 positive. Also cast everything to the unsigned type. If IV does
994 not overflow, BNDS bounds the value of C. Also, this is the
995 case if the computation |FINAL - IV->base| does not overflow, i.e.,
996 if BNDS->below in the result is nonnegative. */
997 if (tree_int_cst_sign_bit (iv->step))
999 s = fold_convert (niter_type,
1000 fold_build1 (NEGATE_EXPR, type, iv->step));
1001 c = fold_build2 (MINUS_EXPR, niter_type,
1002 fold_convert (niter_type, iv->base),
1003 fold_convert (niter_type, final));
1004 bounds_negate (bnds);
1006 else
1008 s = fold_convert (niter_type, iv->step);
1009 c = fold_build2 (MINUS_EXPR, niter_type,
1010 fold_convert (niter_type, final),
1011 fold_convert (niter_type, iv->base));
1014 mpz_init (max);
1015 number_of_iterations_ne_max (max, iv->no_overflow, c, s, bnds,
1016 exit_must_be_taken);
1017 niter->max = widest_int::from (wi::from_mpz (niter_type, max, false),
1018 TYPE_SIGN (niter_type));
1019 mpz_clear (max);
1021 /* Compute no-overflow information for the control iv. This can be
1022 proven when below two conditions are satisfied:
1024 1) IV evaluates toward FINAL at beginning, i.e:
1025 base <= FINAL ; step > 0
1026 base >= FINAL ; step < 0
1028 2) |FINAL - base| is an exact multiple of step.
1030 Unfortunately, it's hard to prove above conditions after pass loop-ch
1031 because loop with exit condition (IV != FINAL) usually will be guarded
1032 by initial-condition (IV.base - IV.step != FINAL). In this case, we
1033 can alternatively try to prove below conditions:
1035 1') IV evaluates toward FINAL at beginning, i.e:
1036 new_base = base - step < FINAL ; step > 0
1037 && base - step doesn't underflow
1038 new_base = base - step > FINAL ; step < 0
1039 && base - step doesn't overflow
1041 Please refer to PR34114 as an example of loop-ch's impact.
1043 Note, for NE_EXPR, base equals to FINAL is a special case, in
1044 which the loop exits immediately, and the iv does not overflow.
1046 Also note, we prove condition 2) by checking base and final seperately
1047 along with condition 1) or 1'). Since we ensure the difference
1048 computation of c does not wrap with cond below and the adjusted s
1049 will fit a signed type as well as an unsigned we can safely do
1050 this using the type of the IV if it is not pointer typed. */
1051 tree mtype = type;
1052 if (POINTER_TYPE_P (type))
1053 mtype = niter_type;
1054 if (!niter->control.no_overflow
1055 && (integer_onep (s)
1056 || (multiple_of_p (mtype, fold_convert (mtype, iv->base),
1057 fold_convert (mtype, s), false)
1058 && multiple_of_p (mtype, fold_convert (mtype, final),
1059 fold_convert (mtype, s), false))))
1061 tree t, cond, relaxed_cond = boolean_false_node;
1063 if (tree_int_cst_sign_bit (iv->step))
1065 cond = fold_build2 (GE_EXPR, boolean_type_node, iv->base, final);
1066 if (TREE_CODE (type) == INTEGER_TYPE)
1068 /* Only when base - step doesn't overflow. */
1069 t = TYPE_MAX_VALUE (type);
1070 t = fold_build2 (PLUS_EXPR, type, t, iv->step);
1071 t = fold_build2 (GE_EXPR, boolean_type_node, t, iv->base);
1072 if (integer_nonzerop (t))
1074 t = fold_build2 (MINUS_EXPR, type, iv->base, iv->step);
1075 relaxed_cond = fold_build2 (GT_EXPR, boolean_type_node, t,
1076 final);
1080 else
1082 cond = fold_build2 (LE_EXPR, boolean_type_node, iv->base, final);
1083 if (TREE_CODE (type) == INTEGER_TYPE)
1085 /* Only when base - step doesn't underflow. */
1086 t = TYPE_MIN_VALUE (type);
1087 t = fold_build2 (PLUS_EXPR, type, t, iv->step);
1088 t = fold_build2 (LE_EXPR, boolean_type_node, t, iv->base);
1089 if (integer_nonzerop (t))
1091 t = fold_build2 (MINUS_EXPR, type, iv->base, iv->step);
1092 relaxed_cond = fold_build2 (LT_EXPR, boolean_type_node, t,
1093 final);
1098 t = simplify_using_initial_conditions (loop, cond);
1099 if (!t || !integer_onep (t))
1100 t = simplify_using_initial_conditions (loop, relaxed_cond);
1102 if (t && integer_onep (t))
1104 niter->control.no_overflow = true;
1105 niter->niter = fold_build2 (EXACT_DIV_EXPR, niter_type, c, s);
1106 return true;
1110 /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
1111 is infinite. Otherwise, the number of iterations is
1112 (inverse(s/d) * (c/d)) mod (size of mode/d). */
1113 bits = num_ending_zeros (s);
1114 bound = build_low_bits_mask (niter_type,
1115 (TYPE_PRECISION (niter_type)
1116 - tree_to_uhwi (bits)));
1118 d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
1119 build_int_cst (niter_type, 1), bits);
1120 s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
1122 if (!exit_must_be_taken)
1124 /* If we cannot assume that the exit is taken eventually, record the
1125 assumptions for divisibility of c. */
1126 assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
1127 assumption = fold_build2 (EQ_EXPR, boolean_type_node,
1128 assumption, build_int_cst (niter_type, 0));
1129 if (!integer_nonzerop (assumption))
1130 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1131 niter->assumptions, assumption);
1134 c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
1135 if (integer_onep (s))
1137 niter->niter = c;
1139 else
1141 tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
1142 niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
1144 return true;
1147 /* Checks whether we can determine the final value of the control variable
1148 of the loop with ending condition IV0 < IV1 (computed in TYPE).
1149 DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
1150 of the step. The assumptions necessary to ensure that the computation
1151 of the final value does not overflow are recorded in NITER. If we
1152 find the final value, we adjust DELTA and return TRUE. Otherwise
1153 we return false. BNDS bounds the value of IV1->base - IV0->base,
1154 and will be updated by the same amount as DELTA. EXIT_MUST_BE_TAKEN is
1155 true if we know that the exit must be taken eventually. */
1157 static bool
1158 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
1159 class tree_niter_desc *niter,
1160 tree *delta, tree step,
1161 bool exit_must_be_taken, bounds *bnds)
1163 tree niter_type = TREE_TYPE (step);
1164 tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
1165 tree tmod;
1166 mpz_t mmod;
1167 tree assumption = boolean_true_node, bound, noloop;
1168 bool ret = false, fv_comp_no_overflow;
1169 tree type1 = type;
1170 if (POINTER_TYPE_P (type))
1171 type1 = sizetype;
1173 if (TREE_CODE (mod) != INTEGER_CST)
1174 return false;
1175 if (integer_nonzerop (mod))
1176 mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
1177 tmod = fold_convert (type1, mod);
1179 mpz_init (mmod);
1180 wi::to_mpz (wi::to_wide (mod), mmod, UNSIGNED);
1181 mpz_neg (mmod, mmod);
1183 /* If the induction variable does not overflow and the exit is taken,
1184 then the computation of the final value does not overflow. This is
1185 also obviously the case if the new final value is equal to the
1186 current one. Finally, we postulate this for pointer type variables,
1187 as the code cannot rely on the object to that the pointer points being
1188 placed at the end of the address space (and more pragmatically,
1189 TYPE_{MIN,MAX}_VALUE is not defined for pointers). */
1190 if (integer_zerop (mod) || POINTER_TYPE_P (type))
1191 fv_comp_no_overflow = true;
1192 else if (!exit_must_be_taken)
1193 fv_comp_no_overflow = false;
1194 else
1195 fv_comp_no_overflow =
1196 (iv0->no_overflow && integer_nonzerop (iv0->step))
1197 || (iv1->no_overflow && integer_nonzerop (iv1->step));
1199 if (integer_nonzerop (iv0->step))
1201 /* The final value of the iv is iv1->base + MOD, assuming that this
1202 computation does not overflow, and that
1203 iv0->base <= iv1->base + MOD. */
1204 if (!fv_comp_no_overflow)
1206 bound = fold_build2 (MINUS_EXPR, type1,
1207 TYPE_MAX_VALUE (type1), tmod);
1208 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1209 iv1->base, bound);
1210 if (integer_zerop (assumption))
1211 goto end;
1213 if (mpz_cmp (mmod, bnds->below) < 0)
1214 noloop = boolean_false_node;
1215 else if (POINTER_TYPE_P (type))
1216 noloop = fold_build2 (GT_EXPR, boolean_type_node,
1217 iv0->base,
1218 fold_build_pointer_plus (iv1->base, tmod));
1219 else
1220 noloop = fold_build2 (GT_EXPR, boolean_type_node,
1221 iv0->base,
1222 fold_build2 (PLUS_EXPR, type1,
1223 iv1->base, tmod));
1225 else
1227 /* The final value of the iv is iv0->base - MOD, assuming that this
1228 computation does not overflow, and that
1229 iv0->base - MOD <= iv1->base. */
1230 if (!fv_comp_no_overflow)
1232 bound = fold_build2 (PLUS_EXPR, type1,
1233 TYPE_MIN_VALUE (type1), tmod);
1234 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1235 iv0->base, bound);
1236 if (integer_zerop (assumption))
1237 goto end;
1239 if (mpz_cmp (mmod, bnds->below) < 0)
1240 noloop = boolean_false_node;
1241 else if (POINTER_TYPE_P (type))
1242 noloop = fold_build2 (GT_EXPR, boolean_type_node,
1243 fold_build_pointer_plus (iv0->base,
1244 fold_build1 (NEGATE_EXPR,
1245 type1, tmod)),
1246 iv1->base);
1247 else
1248 noloop = fold_build2 (GT_EXPR, boolean_type_node,
1249 fold_build2 (MINUS_EXPR, type1,
1250 iv0->base, tmod),
1251 iv1->base);
1254 if (!integer_nonzerop (assumption))
1255 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1256 niter->assumptions,
1257 assumption);
1258 if (!integer_zerop (noloop))
1259 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1260 niter->may_be_zero,
1261 noloop);
1262 bounds_add (bnds, wi::to_widest (mod), type);
1263 *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
1265 ret = true;
1266 end:
1267 mpz_clear (mmod);
1268 return ret;
1271 /* Add assertions to NITER that ensure that the control variable of the loop
1272 with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
1273 are TYPE. Returns false if we can prove that there is an overflow, true
1274 otherwise. STEP is the absolute value of the step. */
1276 static bool
1277 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1278 class tree_niter_desc *niter, tree step)
1280 tree bound, d, assumption, diff;
1281 tree niter_type = TREE_TYPE (step);
1283 if (integer_nonzerop (iv0->step))
1285 /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
1286 if (iv0->no_overflow)
1287 return true;
1289 /* If iv0->base is a constant, we can determine the last value before
1290 overflow precisely; otherwise we conservatively assume
1291 MAX - STEP + 1. */
1293 if (TREE_CODE (iv0->base) == INTEGER_CST)
1295 d = fold_build2 (MINUS_EXPR, niter_type,
1296 fold_convert (niter_type, TYPE_MAX_VALUE (type)),
1297 fold_convert (niter_type, iv0->base));
1298 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
1300 else
1301 diff = fold_build2 (MINUS_EXPR, niter_type, step,
1302 build_int_cst (niter_type, 1));
1303 bound = fold_build2 (MINUS_EXPR, type,
1304 TYPE_MAX_VALUE (type), fold_convert (type, diff));
1305 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1306 iv1->base, bound);
1308 else
1310 /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
1311 if (iv1->no_overflow)
1312 return true;
1314 if (TREE_CODE (iv1->base) == INTEGER_CST)
1316 d = fold_build2 (MINUS_EXPR, niter_type,
1317 fold_convert (niter_type, iv1->base),
1318 fold_convert (niter_type, TYPE_MIN_VALUE (type)));
1319 diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
1321 else
1322 diff = fold_build2 (MINUS_EXPR, niter_type, step,
1323 build_int_cst (niter_type, 1));
1324 bound = fold_build2 (PLUS_EXPR, type,
1325 TYPE_MIN_VALUE (type), fold_convert (type, diff));
1326 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1327 iv0->base, bound);
1330 if (integer_zerop (assumption))
1331 return false;
1332 if (!integer_nonzerop (assumption))
1333 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1334 niter->assumptions, assumption);
1336 iv0->no_overflow = true;
1337 iv1->no_overflow = true;
1338 return true;
1341 /* Add an assumption to NITER that a loop whose ending condition
1342 is IV0 < IV1 rolls. TYPE is the type of the control iv. BNDS
1343 bounds the value of IV1->base - IV0->base. */
1345 static void
1346 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1347 class tree_niter_desc *niter, bounds *bnds)
1349 tree assumption = boolean_true_node, bound, diff;
1350 tree mbz, mbzl, mbzr, type1;
1351 bool rolls_p, no_overflow_p;
1352 widest_int dstep;
1353 mpz_t mstep, max;
1355 /* We are going to compute the number of iterations as
1356 (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1357 variant of TYPE. This formula only works if
1359 -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1361 (where MAX is the maximum value of the unsigned variant of TYPE, and
1362 the computations in this formula are performed in full precision,
1363 i.e., without overflows).
1365 Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1366 we have a condition of the form iv0->base - step < iv1->base before the loop,
1367 and for loops iv0->base < iv1->base - step * i the condition
1368 iv0->base < iv1->base + step, due to loop header copying, which enable us
1369 to prove the lower bound.
1371 The upper bound is more complicated. Unless the expressions for initial
1372 and final value themselves contain enough information, we usually cannot
1373 derive it from the context. */
1375 /* First check whether the answer does not follow from the bounds we gathered
1376 before. */
1377 if (integer_nonzerop (iv0->step))
1378 dstep = wi::to_widest (iv0->step);
1379 else
1381 dstep = wi::sext (wi::to_widest (iv1->step), TYPE_PRECISION (type));
1382 dstep = -dstep;
1385 mpz_init (mstep);
1386 wi::to_mpz (dstep, mstep, UNSIGNED);
1387 mpz_neg (mstep, mstep);
1388 mpz_add_ui (mstep, mstep, 1);
1390 rolls_p = mpz_cmp (mstep, bnds->below) <= 0;
1392 mpz_init (max);
1393 wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
1394 mpz_add (max, max, mstep);
1395 no_overflow_p = (mpz_cmp (bnds->up, max) <= 0
1396 /* For pointers, only values lying inside a single object
1397 can be compared or manipulated by pointer arithmetics.
1398 Gcc in general does not allow or handle objects larger
1399 than half of the address space, hence the upper bound
1400 is satisfied for pointers. */
1401 || POINTER_TYPE_P (type));
1402 mpz_clear (mstep);
1403 mpz_clear (max);
1405 if (rolls_p && no_overflow_p)
1406 return;
1408 type1 = type;
1409 if (POINTER_TYPE_P (type))
1410 type1 = sizetype;
1412 /* Now the hard part; we must formulate the assumption(s) as expressions, and
1413 we must be careful not to introduce overflow. */
1415 if (integer_nonzerop (iv0->step))
1417 diff = fold_build2 (MINUS_EXPR, type1,
1418 iv0->step, build_int_cst (type1, 1));
1420 /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
1421 0 address never belongs to any object, we can assume this for
1422 pointers. */
1423 if (!POINTER_TYPE_P (type))
1425 bound = fold_build2 (PLUS_EXPR, type1,
1426 TYPE_MIN_VALUE (type), diff);
1427 assumption = fold_build2 (GE_EXPR, boolean_type_node,
1428 iv0->base, bound);
1431 /* And then we can compute iv0->base - diff, and compare it with
1432 iv1->base. */
1433 mbzl = fold_build2 (MINUS_EXPR, type1,
1434 fold_convert (type1, iv0->base), diff);
1435 mbzr = fold_convert (type1, iv1->base);
1437 else
1439 diff = fold_build2 (PLUS_EXPR, type1,
1440 iv1->step, build_int_cst (type1, 1));
1442 if (!POINTER_TYPE_P (type))
1444 bound = fold_build2 (PLUS_EXPR, type1,
1445 TYPE_MAX_VALUE (type), diff);
1446 assumption = fold_build2 (LE_EXPR, boolean_type_node,
1447 iv1->base, bound);
1450 mbzl = fold_convert (type1, iv0->base);
1451 mbzr = fold_build2 (MINUS_EXPR, type1,
1452 fold_convert (type1, iv1->base), diff);
1455 if (!integer_nonzerop (assumption))
1456 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1457 niter->assumptions, assumption);
1458 if (!rolls_p)
1460 mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
1461 niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1462 niter->may_be_zero, mbz);
1466 /* Determines number of iterations of loop whose ending condition
1467 is IV0 < IV1 which likes: {base, -C} < n, or n < {base, C}.
1468 The number of iterations is stored to NITER. */
1470 static bool
1471 number_of_iterations_until_wrap (class loop *loop, tree type, affine_iv *iv0,
1472 affine_iv *iv1, class tree_niter_desc *niter)
1474 tree niter_type = unsigned_type_for (type);
1475 tree step, num, assumptions, may_be_zero, span;
1476 wide_int high, low, max, min;
1478 may_be_zero = fold_build2 (LE_EXPR, boolean_type_node, iv1->base, iv0->base);
1479 if (integer_onep (may_be_zero))
1480 return false;
1482 int prec = TYPE_PRECISION (type);
1483 signop sgn = TYPE_SIGN (type);
1484 min = wi::min_value (prec, sgn);
1485 max = wi::max_value (prec, sgn);
1487 /* n < {base, C}. */
1488 if (integer_zerop (iv0->step) && !tree_int_cst_sign_bit (iv1->step))
1490 step = iv1->step;
1491 /* MIN + C - 1 <= n. */
1492 tree last = wide_int_to_tree (type, min + wi::to_wide (step) - 1);
1493 assumptions = fold_build2 (LE_EXPR, boolean_type_node, last, iv0->base);
1494 if (integer_zerop (assumptions))
1495 return false;
1497 num = fold_build2 (MINUS_EXPR, niter_type, wide_int_to_tree (type, max),
1498 iv1->base);
1500 /* When base has the form iv + 1, if we know iv >= n, then iv + 1 < n
1501 only when iv + 1 overflows, i.e. when iv == TYPE_VALUE_MAX. */
1502 if (sgn == UNSIGNED
1503 && integer_onep (step)
1504 && TREE_CODE (iv1->base) == PLUS_EXPR
1505 && integer_onep (TREE_OPERAND (iv1->base, 1)))
1507 tree cond = fold_build2 (GE_EXPR, boolean_type_node,
1508 TREE_OPERAND (iv1->base, 0), iv0->base);
1509 cond = simplify_using_initial_conditions (loop, cond);
1510 if (integer_onep (cond))
1511 may_be_zero = fold_build2 (EQ_EXPR, boolean_type_node,
1512 TREE_OPERAND (iv1->base, 0),
1513 TYPE_MAX_VALUE (type));
1516 high = max;
1517 if (TREE_CODE (iv1->base) == INTEGER_CST)
1518 low = wi::to_wide (iv1->base) - 1;
1519 else if (TREE_CODE (iv0->base) == INTEGER_CST)
1520 low = wi::to_wide (iv0->base);
1521 else
1522 low = min;
1524 /* {base, -C} < n. */
1525 else if (tree_int_cst_sign_bit (iv0->step) && integer_zerop (iv1->step))
1527 step = fold_build1 (NEGATE_EXPR, TREE_TYPE (iv0->step), iv0->step);
1528 /* MAX - C + 1 >= n. */
1529 tree last = wide_int_to_tree (type, max - wi::to_wide (step) + 1);
1530 assumptions = fold_build2 (GE_EXPR, boolean_type_node, last, iv1->base);
1531 if (integer_zerop (assumptions))
1532 return false;
1534 num = fold_build2 (MINUS_EXPR, niter_type, iv0->base,
1535 wide_int_to_tree (type, min));
1536 low = min;
1537 if (TREE_CODE (iv0->base) == INTEGER_CST)
1538 high = wi::to_wide (iv0->base) + 1;
1539 else if (TREE_CODE (iv1->base) == INTEGER_CST)
1540 high = wi::to_wide (iv1->base);
1541 else
1542 high = max;
1544 else
1545 return false;
1547 /* (delta + step - 1) / step */
1548 step = fold_convert (niter_type, step);
1549 num = fold_convert (niter_type, num);
1550 num = fold_build2 (PLUS_EXPR, niter_type, num, step);
1551 niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, num, step);
1553 widest_int delta, s;
1554 delta = widest_int::from (high, sgn) - widest_int::from (low, sgn);
1555 s = wi::to_widest (step);
1556 delta = delta + s - 1;
1557 niter->max = wi::udiv_floor (delta, s);
1559 niter->may_be_zero = may_be_zero;
1561 if (!integer_nonzerop (assumptions))
1562 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1563 niter->assumptions, assumptions);
1565 niter->control.no_overflow = false;
1567 /* Update bound and exit condition as:
1568 bound = niter * STEP + (IVbase - STEP).
1569 { IVbase - STEP, +, STEP } != bound
1570 Here, biasing IVbase by 1 step makes 'bound' be the value before wrap.
1572 tree base_type = TREE_TYPE (niter->control.base);
1573 if (POINTER_TYPE_P (base_type))
1575 tree utype = unsigned_type_for (base_type);
1576 niter->control.base
1577 = fold_build2 (MINUS_EXPR, utype,
1578 fold_convert (utype, niter->control.base),
1579 fold_convert (utype, niter->control.step));
1580 niter->control.base = fold_convert (base_type, niter->control.base);
1582 else
1583 niter->control.base
1584 = fold_build2 (MINUS_EXPR, base_type, niter->control.base,
1585 niter->control.step);
1587 span = fold_build2 (MULT_EXPR, niter_type, niter->niter,
1588 fold_convert (niter_type, niter->control.step));
1589 niter->bound = fold_build2 (PLUS_EXPR, niter_type, span,
1590 fold_convert (niter_type, niter->control.base));
1591 niter->bound = fold_convert (type, niter->bound);
1592 niter->cmp = NE_EXPR;
1594 return true;
1597 /* Determines number of iterations of loop whose ending condition
1598 is IV0 < IV1. TYPE is the type of the iv. The number of
1599 iterations is stored to NITER. BNDS bounds the difference
1600 IV1->base - IV0->base. EXIT_MUST_BE_TAKEN is true if we know
1601 that the exit must be taken eventually. */
1603 static bool
1604 number_of_iterations_lt (class loop *loop, tree type, affine_iv *iv0,
1605 affine_iv *iv1, class tree_niter_desc *niter,
1606 bool exit_must_be_taken, bounds *bnds)
1608 tree niter_type = unsigned_type_for (type);
1609 tree delta, step, s;
1610 mpz_t mstep, tmp;
1612 if (integer_nonzerop (iv0->step))
1614 niter->control = *iv0;
1615 niter->cmp = LT_EXPR;
1616 niter->bound = iv1->base;
1618 else
1620 niter->control = *iv1;
1621 niter->cmp = GT_EXPR;
1622 niter->bound = iv0->base;
1625 /* {base, -C} < n, or n < {base, C} */
1626 if (tree_int_cst_sign_bit (iv0->step)
1627 || (!integer_zerop (iv1->step) && !tree_int_cst_sign_bit (iv1->step)))
1628 return number_of_iterations_until_wrap (loop, type, iv0, iv1, niter);
1630 delta = fold_build2 (MINUS_EXPR, niter_type,
1631 fold_convert (niter_type, iv1->base),
1632 fold_convert (niter_type, iv0->base));
1634 /* First handle the special case that the step is +-1. */
1635 if ((integer_onep (iv0->step) && integer_zerop (iv1->step))
1636 || (integer_all_onesp (iv1->step) && integer_zerop (iv0->step)))
1638 /* for (i = iv0->base; i < iv1->base; i++)
1642 for (i = iv1->base; i > iv0->base; i--).
1644 In both cases # of iterations is iv1->base - iv0->base, assuming that
1645 iv1->base >= iv0->base.
1647 First try to derive a lower bound on the value of
1648 iv1->base - iv0->base, computed in full precision. If the difference
1649 is nonnegative, we are done, otherwise we must record the
1650 condition. */
1652 if (mpz_sgn (bnds->below) < 0)
1653 niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
1654 iv1->base, iv0->base);
1655 niter->niter = delta;
1656 niter->max = widest_int::from (wi::from_mpz (niter_type, bnds->up, false),
1657 TYPE_SIGN (niter_type));
1658 niter->control.no_overflow = true;
1659 return true;
1662 if (integer_nonzerop (iv0->step))
1663 step = fold_convert (niter_type, iv0->step);
1664 else
1665 step = fold_convert (niter_type,
1666 fold_build1 (NEGATE_EXPR, type, iv1->step));
1668 /* If we can determine the final value of the control iv exactly, we can
1669 transform the condition to != comparison. In particular, this will be
1670 the case if DELTA is constant. */
1671 if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step,
1672 exit_must_be_taken, bnds))
1674 affine_iv zps;
1676 zps.base = build_int_cst (niter_type, 0);
1677 zps.step = step;
1678 /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1679 zps does not overflow. */
1680 zps.no_overflow = true;
1682 return number_of_iterations_ne (loop, type, &zps,
1683 delta, niter, true, bnds);
1686 /* Make sure that the control iv does not overflow. */
1687 if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
1688 return false;
1690 /* We determine the number of iterations as (delta + step - 1) / step. For
1691 this to work, we must know that iv1->base >= iv0->base - step + 1,
1692 otherwise the loop does not roll. */
1693 assert_loop_rolls_lt (type, iv0, iv1, niter, bnds);
1695 s = fold_build2 (MINUS_EXPR, niter_type,
1696 step, build_int_cst (niter_type, 1));
1697 delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
1698 niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
1700 mpz_init (mstep);
1701 mpz_init (tmp);
1702 wi::to_mpz (wi::to_wide (step), mstep, UNSIGNED);
1703 mpz_add (tmp, bnds->up, mstep);
1704 mpz_sub_ui (tmp, tmp, 1);
1705 mpz_fdiv_q (tmp, tmp, mstep);
1706 niter->max = widest_int::from (wi::from_mpz (niter_type, tmp, false),
1707 TYPE_SIGN (niter_type));
1708 mpz_clear (mstep);
1709 mpz_clear (tmp);
1711 return true;
1714 /* Determines number of iterations of loop whose ending condition
1715 is IV0 <= IV1. TYPE is the type of the iv. The number of
1716 iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
1717 we know that this condition must eventually become false (we derived this
1718 earlier, and possibly set NITER->assumptions to make sure this
1719 is the case). BNDS bounds the difference IV1->base - IV0->base. */
1721 static bool
1722 number_of_iterations_le (class loop *loop, tree type, affine_iv *iv0,
1723 affine_iv *iv1, class tree_niter_desc *niter,
1724 bool exit_must_be_taken, bounds *bnds)
1726 tree assumption;
1727 tree type1 = type;
1728 if (POINTER_TYPE_P (type))
1729 type1 = sizetype;
1731 /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
1732 IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1733 value of the type. This we must know anyway, since if it is
1734 equal to this value, the loop rolls forever. We do not check
1735 this condition for pointer type ivs, as the code cannot rely on
1736 the object to that the pointer points being placed at the end of
1737 the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1738 not defined for pointers). */
1740 if (!exit_must_be_taken && !POINTER_TYPE_P (type))
1742 if (integer_nonzerop (iv0->step))
1743 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1744 iv1->base, TYPE_MAX_VALUE (type));
1745 else
1746 assumption = fold_build2 (NE_EXPR, boolean_type_node,
1747 iv0->base, TYPE_MIN_VALUE (type));
1749 if (integer_zerop (assumption))
1750 return false;
1751 if (!integer_nonzerop (assumption))
1752 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1753 niter->assumptions, assumption);
1756 if (integer_nonzerop (iv0->step))
1758 if (POINTER_TYPE_P (type))
1759 iv1->base = fold_build_pointer_plus_hwi (iv1->base, 1);
1760 else
1761 iv1->base = fold_build2 (PLUS_EXPR, type1, iv1->base,
1762 build_int_cst (type1, 1));
1764 else if (POINTER_TYPE_P (type))
1765 iv0->base = fold_build_pointer_plus_hwi (iv0->base, -1);
1766 else
1767 iv0->base = fold_build2 (MINUS_EXPR, type1,
1768 iv0->base, build_int_cst (type1, 1));
1770 bounds_add (bnds, 1, type1);
1772 return number_of_iterations_lt (loop, type, iv0, iv1, niter, exit_must_be_taken,
1773 bnds);
1776 /* Dumps description of affine induction variable IV to FILE. */
1778 static void
1779 dump_affine_iv (FILE *file, affine_iv *iv)
1781 if (!integer_zerop (iv->step))
1782 fprintf (file, "[");
1784 print_generic_expr (dump_file, iv->base, TDF_SLIM);
1786 if (!integer_zerop (iv->step))
1788 fprintf (file, ", + , ");
1789 print_generic_expr (dump_file, iv->step, TDF_SLIM);
1790 fprintf (file, "]%s", iv->no_overflow ? "(no_overflow)" : "");
1794 /* Determine the number of iterations according to condition (for staying
1795 inside loop) which compares two induction variables using comparison
1796 operator CODE. The induction variable on left side of the comparison
1797 is IV0, the right-hand side is IV1. Both induction variables must have
1798 type TYPE, which must be an integer or pointer type. The steps of the
1799 ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1801 LOOP is the loop whose number of iterations we are determining.
1803 ONLY_EXIT is true if we are sure this is the only way the loop could be
1804 exited (including possibly non-returning function calls, exceptions, etc.)
1805 -- in this case we can use the information whether the control induction
1806 variables can overflow or not in a more efficient way.
1808 if EVERY_ITERATION is true, we know the test is executed on every iteration.
1810 The results (number of iterations and assumptions as described in
1811 comments at class tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1812 Returns false if it fails to determine number of iterations, true if it
1813 was determined (possibly with some assumptions). */
1815 static bool
1816 number_of_iterations_cond (class loop *loop,
1817 tree type, affine_iv *iv0, enum tree_code code,
1818 affine_iv *iv1, class tree_niter_desc *niter,
1819 bool only_exit, bool every_iteration)
1821 bool exit_must_be_taken = false, ret;
1822 bounds bnds;
1824 /* If the test is not executed every iteration, wrapping may make the test
1825 to pass again.
1826 TODO: the overflow case can be still used as unreliable estimate of upper
1827 bound. But we have no API to pass it down to number of iterations code
1828 and, at present, it will not use it anyway. */
1829 if (!every_iteration
1830 && (!iv0->no_overflow || !iv1->no_overflow
1831 || code == NE_EXPR || code == EQ_EXPR))
1832 return false;
1834 /* The meaning of these assumptions is this:
1835 if !assumptions
1836 then the rest of information does not have to be valid
1837 if may_be_zero then the loop does not roll, even if
1838 niter != 0. */
1839 niter->assumptions = boolean_true_node;
1840 niter->may_be_zero = boolean_false_node;
1841 niter->niter = NULL_TREE;
1842 niter->max = 0;
1843 niter->bound = NULL_TREE;
1844 niter->cmp = ERROR_MARK;
1846 /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1847 the control variable is on lhs. */
1848 if (code == GE_EXPR || code == GT_EXPR
1849 || (code == NE_EXPR && integer_zerop (iv0->step)))
1851 std::swap (iv0, iv1);
1852 code = swap_tree_comparison (code);
1855 if (POINTER_TYPE_P (type))
1857 /* Comparison of pointers is undefined unless both iv0 and iv1 point
1858 to the same object. If they do, the control variable cannot wrap
1859 (as wrap around the bounds of memory will never return a pointer
1860 that would be guaranteed to point to the same object, even if we
1861 avoid undefined behavior by casting to size_t and back). */
1862 iv0->no_overflow = true;
1863 iv1->no_overflow = true;
1866 /* If the control induction variable does not overflow and the only exit
1867 from the loop is the one that we analyze, we know it must be taken
1868 eventually. */
1869 if (only_exit)
1871 if (!integer_zerop (iv0->step) && iv0->no_overflow)
1872 exit_must_be_taken = true;
1873 else if (!integer_zerop (iv1->step) && iv1->no_overflow)
1874 exit_must_be_taken = true;
1877 /* We can handle cases which neither of the sides of the comparison is
1878 invariant:
1880 {iv0.base, iv0.step} cmp_code {iv1.base, iv1.step}
1881 as if:
1882 {iv0.base, iv0.step - iv1.step} cmp_code {iv1.base, 0}
1884 provided that either below condition is satisfied:
1886 a) the test is NE_EXPR;
1887 b) iv0 and iv1 do not overflow and iv0.step - iv1.step is of
1888 the same sign and of less or equal magnitude than iv0.step
1890 This rarely occurs in practice, but it is simple enough to manage. */
1891 if (!integer_zerop (iv0->step) && !integer_zerop (iv1->step))
1893 tree step_type = POINTER_TYPE_P (type) ? sizetype : type;
1894 tree step = fold_binary_to_constant (MINUS_EXPR, step_type,
1895 iv0->step, iv1->step);
1897 /* For code other than NE_EXPR we have to ensure moving the evolution
1898 of IV1 to that of IV0 does not introduce overflow. */
1899 if (TREE_CODE (step) != INTEGER_CST
1900 || !iv0->no_overflow || !iv1->no_overflow)
1902 if (code != NE_EXPR)
1903 return false;
1904 iv0->no_overflow = false;
1906 /* If the new step of IV0 has changed sign or is of greater
1907 magnitude then we do not know whether IV0 does overflow
1908 and thus the transform is not valid for code other than NE_EXPR. */
1909 else if (tree_int_cst_sign_bit (step) != tree_int_cst_sign_bit (iv0->step)
1910 || wi::gtu_p (wi::abs (wi::to_widest (step)),
1911 wi::abs (wi::to_widest (iv0->step))))
1913 if (POINTER_TYPE_P (type) && code != NE_EXPR)
1914 /* For relational pointer compares we have further guarantees
1915 that the pointers always point to the same object (or one
1916 after it) and that objects do not cross the zero page. So
1917 not only is the transform always valid for relational
1918 pointer compares, we also know the resulting IV does not
1919 overflow. */
1921 else if (code != NE_EXPR)
1922 return false;
1923 else
1924 iv0->no_overflow = false;
1927 iv0->step = step;
1928 iv1->step = build_int_cst (step_type, 0);
1929 iv1->no_overflow = true;
1932 /* If the result of the comparison is a constant, the loop is weird. More
1933 precise handling would be possible, but the situation is not common enough
1934 to waste time on it. */
1935 if (integer_zerop (iv0->step) && integer_zerop (iv1->step))
1936 return false;
1938 /* If the loop exits immediately, there is nothing to do. */
1939 tree tem = fold_binary (code, boolean_type_node, iv0->base, iv1->base);
1940 if (tem && integer_zerop (tem))
1942 if (!every_iteration)
1943 return false;
1944 niter->niter = build_int_cst (unsigned_type_for (type), 0);
1945 niter->max = 0;
1946 return true;
1949 /* OK, now we know we have a senseful loop. Handle several cases, depending
1950 on what comparison operator is used. */
1951 bound_difference (loop, iv1->base, iv0->base, &bnds);
1953 if (dump_file && (dump_flags & TDF_DETAILS))
1955 fprintf (dump_file,
1956 "Analyzing # of iterations of loop %d\n", loop->num);
1958 fprintf (dump_file, " exit condition ");
1959 dump_affine_iv (dump_file, iv0);
1960 fprintf (dump_file, " %s ",
1961 code == NE_EXPR ? "!="
1962 : code == LT_EXPR ? "<"
1963 : "<=");
1964 dump_affine_iv (dump_file, iv1);
1965 fprintf (dump_file, "\n");
1967 fprintf (dump_file, " bounds on difference of bases: ");
1968 mpz_out_str (dump_file, 10, bnds.below);
1969 fprintf (dump_file, " ... ");
1970 mpz_out_str (dump_file, 10, bnds.up);
1971 fprintf (dump_file, "\n");
1974 switch (code)
1976 case NE_EXPR:
1977 gcc_assert (integer_zerop (iv1->step));
1978 ret = number_of_iterations_ne (loop, type, iv0, iv1->base, niter,
1979 exit_must_be_taken, &bnds);
1980 break;
1982 case LT_EXPR:
1983 ret = number_of_iterations_lt (loop, type, iv0, iv1, niter,
1984 exit_must_be_taken, &bnds);
1985 break;
1987 case LE_EXPR:
1988 ret = number_of_iterations_le (loop, type, iv0, iv1, niter,
1989 exit_must_be_taken, &bnds);
1990 break;
1992 default:
1993 gcc_unreachable ();
1996 mpz_clear (bnds.up);
1997 mpz_clear (bnds.below);
1999 if (dump_file && (dump_flags & TDF_DETAILS))
2001 if (ret)
2003 fprintf (dump_file, " result:\n");
2004 if (!integer_nonzerop (niter->assumptions))
2006 fprintf (dump_file, " under assumptions ");
2007 print_generic_expr (dump_file, niter->assumptions, TDF_SLIM);
2008 fprintf (dump_file, "\n");
2011 if (!integer_zerop (niter->may_be_zero))
2013 fprintf (dump_file, " zero if ");
2014 print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
2015 fprintf (dump_file, "\n");
2018 fprintf (dump_file, " # of iterations ");
2019 print_generic_expr (dump_file, niter->niter, TDF_SLIM);
2020 fprintf (dump_file, ", bounded by ");
2021 print_decu (niter->max, dump_file);
2022 fprintf (dump_file, "\n");
2024 else
2025 fprintf (dump_file, " failed\n\n");
2027 return ret;
2030 /* Return an expression that computes the popcount of src. */
2032 static tree
2033 build_popcount_expr (tree src)
2035 tree fn;
2036 bool use_ifn = false;
2037 int prec = TYPE_PRECISION (TREE_TYPE (src));
2038 int i_prec = TYPE_PRECISION (integer_type_node);
2039 int li_prec = TYPE_PRECISION (long_integer_type_node);
2040 int lli_prec = TYPE_PRECISION (long_long_integer_type_node);
2042 tree utype = unsigned_type_for (TREE_TYPE (src));
2043 src = fold_convert (utype, src);
2045 if (direct_internal_fn_supported_p (IFN_POPCOUNT, utype, OPTIMIZE_FOR_BOTH))
2046 use_ifn = true;
2047 else if (prec <= i_prec)
2048 fn = builtin_decl_implicit (BUILT_IN_POPCOUNT);
2049 else if (prec == li_prec)
2050 fn = builtin_decl_implicit (BUILT_IN_POPCOUNTL);
2051 else if (prec == lli_prec || prec == 2 * lli_prec)
2052 fn = builtin_decl_implicit (BUILT_IN_POPCOUNTLL);
2053 else
2054 return NULL_TREE;
2056 tree call;
2057 if (use_ifn)
2058 call = build_call_expr_internal_loc (UNKNOWN_LOCATION, IFN_POPCOUNT,
2059 integer_type_node, 1, src);
2060 else if (prec == 2 * lli_prec)
2062 tree src1 = fold_convert (long_long_unsigned_type_node,
2063 fold_build2 (RSHIFT_EXPR, TREE_TYPE (src),
2064 unshare_expr (src),
2065 build_int_cst (integer_type_node,
2066 lli_prec)));
2067 tree src2 = fold_convert (long_long_unsigned_type_node, src);
2068 tree call1 = build_call_expr (fn, 1, src1);
2069 tree call2 = build_call_expr (fn, 1, src2);
2070 call = fold_build2 (PLUS_EXPR, integer_type_node, call1, call2);
2072 else
2074 if (prec < i_prec)
2075 src = fold_convert (unsigned_type_node, src);
2077 call = build_call_expr (fn, 1, src);
2080 return call;
2083 /* Utility function to check if OP is defined by a stmt
2084 that is a val - 1. */
2086 static bool
2087 ssa_defined_by_minus_one_stmt_p (tree op, tree val)
2089 gimple *stmt;
2090 return (TREE_CODE (op) == SSA_NAME
2091 && (stmt = SSA_NAME_DEF_STMT (op))
2092 && is_gimple_assign (stmt)
2093 && (gimple_assign_rhs_code (stmt) == PLUS_EXPR)
2094 && val == gimple_assign_rhs1 (stmt)
2095 && integer_minus_onep (gimple_assign_rhs2 (stmt)));
2098 /* See comment below for number_of_iterations_bitcount.
2099 For popcount, we have:
2101 modify:
2102 _1 = iv_1 + -1
2103 iv_2 = iv_1 & _1
2105 test:
2106 if (iv != 0)
2108 modification count:
2109 popcount (src)
2113 static bool
2114 number_of_iterations_popcount (loop_p loop, edge exit,
2115 enum tree_code code,
2116 class tree_niter_desc *niter)
2118 bool modify_before_test = true;
2119 HOST_WIDE_INT max;
2121 /* Check that condition for staying inside the loop is like
2122 if (iv != 0). */
2123 gimple *cond_stmt = last_stmt (exit->src);
2124 if (!cond_stmt
2125 || gimple_code (cond_stmt) != GIMPLE_COND
2126 || code != NE_EXPR
2127 || !integer_zerop (gimple_cond_rhs (cond_stmt))
2128 || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2129 return false;
2131 tree iv_2 = gimple_cond_lhs (cond_stmt);
2132 gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2134 /* If the test comes before the iv modification, then these will actually be
2135 iv_1 and a phi node. */
2136 if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2137 && gimple_bb (iv_2_stmt) == loop->header
2138 && gimple_phi_num_args (iv_2_stmt) == 2
2139 && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2140 loop_latch_edge (loop)->dest_idx))
2141 == SSA_NAME))
2143 /* iv_2 is actually one of the inputs to the phi. */
2144 iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2145 iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2146 modify_before_test = false;
2149 /* Make sure iv_2_stmt is an and stmt (iv_2 = _1 & iv_1). */
2150 if (!is_gimple_assign (iv_2_stmt)
2151 || gimple_assign_rhs_code (iv_2_stmt) != BIT_AND_EXPR)
2152 return false;
2154 tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2155 tree _1 = gimple_assign_rhs2 (iv_2_stmt);
2157 /* Check that _1 is defined by (_1 = iv_1 + -1).
2158 Also make sure that _1 is the same in and_stmt and _1 defining stmt.
2159 Also canonicalize if _1 and _b11 are revrsed. */
2160 if (ssa_defined_by_minus_one_stmt_p (iv_1, _1))
2161 std::swap (iv_1, _1);
2162 else if (ssa_defined_by_minus_one_stmt_p (_1, iv_1))
2164 else
2165 return false;
2167 /* Check the recurrence. */
2168 gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2169 if (gimple_code (phi) != GIMPLE_PHI
2170 || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2171 || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx)))
2172 return false;
2174 /* We found a match. */
2175 tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2176 int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2178 /* Get the corresponding popcount builtin. */
2179 tree expr = build_popcount_expr (src);
2181 if (!expr)
2182 return false;
2184 max = src_precision;
2186 tree may_be_zero = boolean_false_node;
2188 if (modify_before_test)
2190 expr = fold_build2 (MINUS_EXPR, integer_type_node, expr,
2191 integer_one_node);
2192 max = max - 1;
2193 may_be_zero = fold_build2 (EQ_EXPR, boolean_type_node, src,
2194 build_zero_cst (TREE_TYPE (src)));
2197 expr = fold_convert (unsigned_type_node, expr);
2199 niter->assumptions = boolean_true_node;
2200 niter->may_be_zero = simplify_using_initial_conditions (loop, may_be_zero);
2201 niter->niter = simplify_using_initial_conditions(loop, expr);
2203 if (TREE_CODE (niter->niter) == INTEGER_CST)
2204 niter->max = tree_to_uhwi (niter->niter);
2205 else
2206 niter->max = max;
2208 niter->bound = NULL_TREE;
2209 niter->cmp = ERROR_MARK;
2210 return true;
2213 /* Return an expression that counts the leading/trailing zeroes of src.
2215 If define_at_zero is true, then the built expression will be defined to
2216 return the precision of src when src == 0 (using either a conditional
2217 expression or a suitable internal function).
2218 Otherwise, we can elide the conditional expression and let src = 0 invoke
2219 undefined behaviour. */
2221 static tree
2222 build_cltz_expr (tree src, bool leading, bool define_at_zero)
2224 tree fn;
2225 internal_fn ifn = leading ? IFN_CLZ : IFN_CTZ;
2226 bool use_ifn = false;
2227 int prec = TYPE_PRECISION (TREE_TYPE (src));
2228 int i_prec = TYPE_PRECISION (integer_type_node);
2229 int li_prec = TYPE_PRECISION (long_integer_type_node);
2230 int lli_prec = TYPE_PRECISION (long_long_integer_type_node);
2232 tree utype = unsigned_type_for (TREE_TYPE (src));
2233 src = fold_convert (utype, src);
2235 if (direct_internal_fn_supported_p (ifn, utype, OPTIMIZE_FOR_BOTH))
2236 use_ifn = true;
2237 else if (prec <= i_prec)
2238 fn = leading ? builtin_decl_implicit (BUILT_IN_CLZ)
2239 : builtin_decl_implicit (BUILT_IN_CTZ);
2240 else if (prec == li_prec)
2241 fn = leading ? builtin_decl_implicit (BUILT_IN_CLZL)
2242 : builtin_decl_implicit (BUILT_IN_CTZL);
2243 else if (prec == lli_prec || prec == 2 * lli_prec)
2244 fn = leading ? builtin_decl_implicit (BUILT_IN_CLZLL)
2245 : builtin_decl_implicit (BUILT_IN_CTZLL);
2246 else
2247 return NULL_TREE;
2249 tree call;
2250 if (use_ifn)
2252 call = build_call_expr_internal_loc (UNKNOWN_LOCATION, ifn,
2253 integer_type_node, 1, src);
2254 int val;
2255 int optab_defined_at_zero
2256 = (leading
2257 ? CLZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (utype), val)
2258 : CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (utype), val));
2259 if (define_at_zero && !(optab_defined_at_zero == 2 && val == prec))
2261 tree is_zero = fold_build2 (NE_EXPR, boolean_type_node, src,
2262 build_zero_cst (TREE_TYPE (src)));
2263 call = fold_build3 (COND_EXPR, integer_type_node, is_zero, call,
2264 build_int_cst (integer_type_node, prec));
2267 else if (prec == 2 * lli_prec)
2269 tree src1 = fold_convert (long_long_unsigned_type_node,
2270 fold_build2 (RSHIFT_EXPR, TREE_TYPE (src),
2271 unshare_expr (src),
2272 build_int_cst (integer_type_node,
2273 lli_prec)));
2274 tree src2 = fold_convert (long_long_unsigned_type_node, src);
2275 /* We count the zeroes in src1, and add the number in src2 when src1
2276 is 0. */
2277 if (!leading)
2278 std::swap (src1, src2);
2279 tree call1 = build_call_expr (fn, 1, src1);
2280 tree call2 = build_call_expr (fn, 1, src2);
2281 if (define_at_zero)
2283 tree is_zero2 = fold_build2 (NE_EXPR, boolean_type_node, src2,
2284 build_zero_cst (TREE_TYPE (src2)));
2285 call2 = fold_build3 (COND_EXPR, integer_type_node, is_zero2, call2,
2286 build_int_cst (integer_type_node, lli_prec));
2288 tree is_zero1 = fold_build2 (NE_EXPR, boolean_type_node, src1,
2289 build_zero_cst (TREE_TYPE (src1)));
2290 call = fold_build3 (COND_EXPR, integer_type_node, is_zero1, call1,
2291 fold_build2 (PLUS_EXPR, integer_type_node, call2,
2292 build_int_cst (integer_type_node,
2293 lli_prec)));
2295 else
2297 if (prec < i_prec)
2298 src = fold_convert (unsigned_type_node, src);
2300 call = build_call_expr (fn, 1, src);
2301 if (define_at_zero)
2303 tree is_zero = fold_build2 (NE_EXPR, boolean_type_node, src,
2304 build_zero_cst (TREE_TYPE (src)));
2305 call = fold_build3 (COND_EXPR, integer_type_node, is_zero, call,
2306 build_int_cst (integer_type_node, prec));
2309 if (leading && prec < i_prec)
2310 call = fold_build2 (MINUS_EXPR, integer_type_node, call,
2311 build_int_cst (integer_type_node, i_prec - prec));
2314 return call;
2317 /* See comment below for number_of_iterations_bitcount.
2318 For c[lt]z, we have:
2320 modify:
2321 iv_2 = iv_1 << 1 OR iv_1 >> 1
2323 test:
2324 if (iv & 1 << (prec-1)) OR (iv & 1)
2326 modification count:
2327 src precision - c[lt]z (src)
2331 static bool
2332 number_of_iterations_cltz (loop_p loop, edge exit,
2333 enum tree_code code,
2334 class tree_niter_desc *niter)
2336 bool modify_before_test = true;
2337 HOST_WIDE_INT max;
2338 int checked_bit;
2339 tree iv_2;
2341 /* Check that condition for staying inside the loop is like
2342 if (iv == 0). */
2343 gimple *cond_stmt = last_stmt (exit->src);
2344 if (!cond_stmt
2345 || gimple_code (cond_stmt) != GIMPLE_COND
2346 || (code != EQ_EXPR && code != GE_EXPR)
2347 || !integer_zerop (gimple_cond_rhs (cond_stmt))
2348 || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2349 return false;
2351 if (code == EQ_EXPR)
2353 /* Make sure we check a bitwise and with a suitable constant */
2354 gimple *and_stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (cond_stmt));
2355 if (!is_gimple_assign (and_stmt)
2356 || gimple_assign_rhs_code (and_stmt) != BIT_AND_EXPR
2357 || !integer_pow2p (gimple_assign_rhs2 (and_stmt)))
2358 return false;
2360 checked_bit = tree_log2 (gimple_assign_rhs2 (and_stmt));
2362 iv_2 = gimple_assign_rhs1 (and_stmt);
2364 else
2366 /* We have a GE_EXPR - a signed comparison with zero is equivalent to
2367 testing the leading bit, so check for this pattern too. */
2369 iv_2 = gimple_cond_lhs (cond_stmt);
2370 tree test_value_type = TREE_TYPE (iv_2);
2372 if (TYPE_UNSIGNED (test_value_type))
2373 return false;
2375 gimple *test_value_stmt = SSA_NAME_DEF_STMT (iv_2);
2377 if (is_gimple_assign (test_value_stmt)
2378 && gimple_assign_rhs_code (test_value_stmt) == NOP_EXPR)
2380 /* If the test value comes from a NOP_EXPR, then we need to unwrap
2381 this. We conservatively require that both types have the same
2382 precision. */
2383 iv_2 = gimple_assign_rhs1 (test_value_stmt);
2384 tree rhs_type = TREE_TYPE (iv_2);
2385 if (TREE_CODE (rhs_type) != INTEGER_TYPE
2386 || (TYPE_PRECISION (rhs_type)
2387 != TYPE_PRECISION (test_value_type)))
2388 return false;
2391 checked_bit = TYPE_PRECISION (test_value_type) - 1;
2394 gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2396 /* If the test comes before the iv modification, then these will actually be
2397 iv_1 and a phi node. */
2398 if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2399 && gimple_bb (iv_2_stmt) == loop->header
2400 && gimple_phi_num_args (iv_2_stmt) == 2
2401 && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2402 loop_latch_edge (loop)->dest_idx))
2403 == SSA_NAME))
2405 /* iv_2 is actually one of the inputs to the phi. */
2406 iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2407 iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2408 modify_before_test = false;
2411 /* Make sure iv_2_stmt is a logical shift by one stmt:
2412 iv_2 = iv_1 {<<|>>} 1 */
2413 if (!is_gimple_assign (iv_2_stmt)
2414 || (gimple_assign_rhs_code (iv_2_stmt) != LSHIFT_EXPR
2415 && (gimple_assign_rhs_code (iv_2_stmt) != RSHIFT_EXPR
2416 || !TYPE_UNSIGNED (TREE_TYPE (gimple_assign_lhs (iv_2_stmt)))))
2417 || !integer_onep (gimple_assign_rhs2 (iv_2_stmt)))
2418 return false;
2420 bool left_shift = (gimple_assign_rhs_code (iv_2_stmt) == LSHIFT_EXPR);
2422 tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2424 /* Check the recurrence. */
2425 gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2426 if (gimple_code (phi) != GIMPLE_PHI
2427 || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2428 || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx)))
2429 return false;
2431 /* We found a match. */
2432 tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2433 int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2435 /* Apply any needed preprocessing to src. */
2436 int num_ignored_bits;
2437 if (left_shift)
2438 num_ignored_bits = src_precision - checked_bit - 1;
2439 else
2440 num_ignored_bits = checked_bit;
2442 if (modify_before_test)
2443 num_ignored_bits++;
2445 if (num_ignored_bits != 0)
2446 src = fold_build2 (left_shift ? LSHIFT_EXPR : RSHIFT_EXPR,
2447 TREE_TYPE (src), src,
2448 build_int_cst (integer_type_node, num_ignored_bits));
2450 /* Get the corresponding c[lt]z builtin. */
2451 tree expr = build_cltz_expr (src, left_shift, false);
2453 if (!expr)
2454 return false;
2456 max = src_precision - num_ignored_bits - 1;
2458 expr = fold_convert (unsigned_type_node, expr);
2460 tree assumptions = fold_build2 (NE_EXPR, boolean_type_node, src,
2461 build_zero_cst (TREE_TYPE (src)));
2463 niter->assumptions = simplify_using_initial_conditions (loop, assumptions);
2464 niter->may_be_zero = boolean_false_node;
2465 niter->niter = simplify_using_initial_conditions (loop, expr);
2467 if (TREE_CODE (niter->niter) == INTEGER_CST)
2468 niter->max = tree_to_uhwi (niter->niter);
2469 else
2470 niter->max = max;
2472 niter->bound = NULL_TREE;
2473 niter->cmp = ERROR_MARK;
2475 return true;
2478 /* See comment below for number_of_iterations_bitcount.
2479 For c[lt]z complement, we have:
2481 modify:
2482 iv_2 = iv_1 >> 1 OR iv_1 << 1
2484 test:
2485 if (iv != 0)
2487 modification count:
2488 src precision - c[lt]z (src)
2492 static bool
2493 number_of_iterations_cltz_complement (loop_p loop, edge exit,
2494 enum tree_code code,
2495 class tree_niter_desc *niter)
2497 bool modify_before_test = true;
2498 HOST_WIDE_INT max;
2500 /* Check that condition for staying inside the loop is like
2501 if (iv != 0). */
2502 gimple *cond_stmt = last_stmt (exit->src);
2503 if (!cond_stmt
2504 || gimple_code (cond_stmt) != GIMPLE_COND
2505 || code != NE_EXPR
2506 || !integer_zerop (gimple_cond_rhs (cond_stmt))
2507 || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2508 return false;
2510 tree iv_2 = gimple_cond_lhs (cond_stmt);
2511 gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2513 /* If the test comes before the iv modification, then these will actually be
2514 iv_1 and a phi node. */
2515 if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2516 && gimple_bb (iv_2_stmt) == loop->header
2517 && gimple_phi_num_args (iv_2_stmt) == 2
2518 && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2519 loop_latch_edge (loop)->dest_idx))
2520 == SSA_NAME))
2522 /* iv_2 is actually one of the inputs to the phi. */
2523 iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2524 iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2525 modify_before_test = false;
2528 /* Make sure iv_2_stmt is a logical shift by one stmt:
2529 iv_2 = iv_1 {>>|<<} 1 */
2530 if (!is_gimple_assign (iv_2_stmt)
2531 || (gimple_assign_rhs_code (iv_2_stmt) != LSHIFT_EXPR
2532 && (gimple_assign_rhs_code (iv_2_stmt) != RSHIFT_EXPR
2533 || !TYPE_UNSIGNED (TREE_TYPE (gimple_assign_lhs (iv_2_stmt)))))
2534 || !integer_onep (gimple_assign_rhs2 (iv_2_stmt)))
2535 return false;
2537 bool left_shift = (gimple_assign_rhs_code (iv_2_stmt) == LSHIFT_EXPR);
2539 tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2541 /* Check the recurrence. */
2542 gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2543 if (gimple_code (phi) != GIMPLE_PHI
2544 || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2545 || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx)))
2546 return false;
2548 /* We found a match. */
2549 tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2550 int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2552 /* Get the corresponding c[lt]z builtin. */
2553 tree expr = build_cltz_expr (src, !left_shift, true);
2555 if (!expr)
2556 return false;
2558 expr = fold_build2 (MINUS_EXPR, integer_type_node,
2559 build_int_cst (integer_type_node, src_precision),
2560 expr);
2562 max = src_precision;
2564 tree may_be_zero = boolean_false_node;
2566 if (modify_before_test)
2568 expr = fold_build2 (MINUS_EXPR, integer_type_node, expr,
2569 integer_one_node);
2570 max = max - 1;
2571 may_be_zero = fold_build2 (EQ_EXPR, boolean_type_node, src,
2572 build_zero_cst (TREE_TYPE (src)));
2575 expr = fold_convert (unsigned_type_node, expr);
2577 niter->assumptions = boolean_true_node;
2578 niter->may_be_zero = simplify_using_initial_conditions (loop, may_be_zero);
2579 niter->niter = simplify_using_initial_conditions (loop, expr);
2581 if (TREE_CODE (niter->niter) == INTEGER_CST)
2582 niter->max = tree_to_uhwi (niter->niter);
2583 else
2584 niter->max = max;
2586 niter->bound = NULL_TREE;
2587 niter->cmp = ERROR_MARK;
2588 return true;
2591 /* See if LOOP contains a bit counting idiom. The idiom consists of two parts:
2592 1. A modification to the induction variabler;.
2593 2. A test to determine whether or not to exit the loop.
2595 These can come in either order - i.e.:
2597 <bb 3>
2598 iv_1 = PHI <src(2), iv_2(4)>
2599 if (test (iv_1))
2600 goto <bb 4>
2601 else
2602 goto <bb 5>
2604 <bb 4>
2605 iv_2 = modify (iv_1)
2606 goto <bb 3>
2610 <bb 3>
2611 iv_1 = PHI <src(2), iv_2(4)>
2612 iv_2 = modify (iv_1)
2614 <bb 4>
2615 if (test (iv_2))
2616 goto <bb 3>
2617 else
2618 goto <bb 5>
2620 The second form can be generated by copying the loop header out of the loop.
2622 In the first case, the number of latch executions will be equal to the
2623 number of induction variable modifications required before the test fails.
2625 In the second case (modify_before_test), if we assume that the number of
2626 modifications required before the test fails is nonzero, then the number of
2627 latch executions will be one less than this number.
2629 If we recognise the pattern, then we update niter accordingly, and return
2630 true. */
2632 static bool
2633 number_of_iterations_bitcount (loop_p loop, edge exit,
2634 enum tree_code code,
2635 class tree_niter_desc *niter)
2637 return (number_of_iterations_popcount (loop, exit, code, niter)
2638 || number_of_iterations_cltz (loop, exit, code, niter)
2639 || number_of_iterations_cltz_complement (loop, exit, code, niter));
2642 /* Substitute NEW_TREE for OLD in EXPR and fold the result.
2643 If VALUEIZE is non-NULL then OLD and NEW_TREE are ignored and instead
2644 all SSA names are replaced with the result of calling the VALUEIZE
2645 function with the SSA name as argument. */
2647 tree
2648 simplify_replace_tree (tree expr, tree old, tree new_tree,
2649 tree (*valueize) (tree, void*), void *context,
2650 bool do_fold)
2652 unsigned i, n;
2653 tree ret = NULL_TREE, e, se;
2655 if (!expr)
2656 return NULL_TREE;
2658 /* Do not bother to replace constants. */
2659 if (CONSTANT_CLASS_P (expr))
2660 return expr;
2662 if (valueize)
2664 if (TREE_CODE (expr) == SSA_NAME)
2666 new_tree = valueize (expr, context);
2667 if (new_tree != expr)
2668 return new_tree;
2671 else if (expr == old
2672 || operand_equal_p (expr, old, 0))
2673 return unshare_expr (new_tree);
2675 if (!EXPR_P (expr))
2676 return expr;
2678 n = TREE_OPERAND_LENGTH (expr);
2679 for (i = 0; i < n; i++)
2681 e = TREE_OPERAND (expr, i);
2682 se = simplify_replace_tree (e, old, new_tree, valueize, context, do_fold);
2683 if (e == se)
2684 continue;
2686 if (!ret)
2687 ret = copy_node (expr);
2689 TREE_OPERAND (ret, i) = se;
2692 return (ret ? (do_fold ? fold (ret) : ret) : expr);
2695 /* Expand definitions of ssa names in EXPR as long as they are simple
2696 enough, and return the new expression. If STOP is specified, stop
2697 expanding if EXPR equals to it. */
2699 static tree
2700 expand_simple_operations (tree expr, tree stop, hash_map<tree, tree> &cache)
2702 unsigned i, n;
2703 tree ret = NULL_TREE, e, ee, e1;
2704 enum tree_code code;
2705 gimple *stmt;
2707 if (expr == NULL_TREE)
2708 return expr;
2710 if (is_gimple_min_invariant (expr))
2711 return expr;
2713 code = TREE_CODE (expr);
2714 if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
2716 n = TREE_OPERAND_LENGTH (expr);
2717 for (i = 0; i < n; i++)
2719 e = TREE_OPERAND (expr, i);
2720 if (!e)
2721 continue;
2722 /* SCEV analysis feeds us with a proper expression
2723 graph matching the SSA graph. Avoid turning it
2724 into a tree here, thus handle tree sharing
2725 properly.
2726 ??? The SSA walk below still turns the SSA graph
2727 into a tree but until we find a testcase do not
2728 introduce additional tree sharing here. */
2729 bool existed_p;
2730 tree &cee = cache.get_or_insert (e, &existed_p);
2731 if (existed_p)
2732 ee = cee;
2733 else
2735 cee = e;
2736 ee = expand_simple_operations (e, stop, cache);
2737 if (ee != e)
2738 *cache.get (e) = ee;
2740 if (e == ee)
2741 continue;
2743 if (!ret)
2744 ret = copy_node (expr);
2746 TREE_OPERAND (ret, i) = ee;
2749 if (!ret)
2750 return expr;
2752 fold_defer_overflow_warnings ();
2753 ret = fold (ret);
2754 fold_undefer_and_ignore_overflow_warnings ();
2755 return ret;
2758 /* Stop if it's not ssa name or the one we don't want to expand. */
2759 if (TREE_CODE (expr) != SSA_NAME || expr == stop)
2760 return expr;
2762 stmt = SSA_NAME_DEF_STMT (expr);
2763 if (gimple_code (stmt) == GIMPLE_PHI)
2765 basic_block src, dest;
2767 if (gimple_phi_num_args (stmt) != 1)
2768 return expr;
2769 e = PHI_ARG_DEF (stmt, 0);
2771 /* Avoid propagating through loop exit phi nodes, which
2772 could break loop-closed SSA form restrictions. */
2773 dest = gimple_bb (stmt);
2774 src = single_pred (dest);
2775 if (TREE_CODE (e) == SSA_NAME
2776 && src->loop_father != dest->loop_father)
2777 return expr;
2779 return expand_simple_operations (e, stop, cache);
2781 if (gimple_code (stmt) != GIMPLE_ASSIGN)
2782 return expr;
2784 /* Avoid expanding to expressions that contain SSA names that need
2785 to take part in abnormal coalescing. */
2786 ssa_op_iter iter;
2787 FOR_EACH_SSA_TREE_OPERAND (e, stmt, iter, SSA_OP_USE)
2788 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e))
2789 return expr;
2791 e = gimple_assign_rhs1 (stmt);
2792 code = gimple_assign_rhs_code (stmt);
2793 if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
2795 if (is_gimple_min_invariant (e))
2796 return e;
2798 if (code == SSA_NAME)
2799 return expand_simple_operations (e, stop, cache);
2800 else if (code == ADDR_EXPR)
2802 poly_int64 offset;
2803 tree base = get_addr_base_and_unit_offset (TREE_OPERAND (e, 0),
2804 &offset);
2805 if (base
2806 && TREE_CODE (base) == MEM_REF)
2808 ee = expand_simple_operations (TREE_OPERAND (base, 0), stop,
2809 cache);
2810 return fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (expr), ee,
2811 wide_int_to_tree (sizetype,
2812 mem_ref_offset (base)
2813 + offset));
2817 return expr;
2820 switch (code)
2822 CASE_CONVERT:
2823 /* Casts are simple. */
2824 ee = expand_simple_operations (e, stop, cache);
2825 return fold_build1 (code, TREE_TYPE (expr), ee);
2827 case PLUS_EXPR:
2828 case MINUS_EXPR:
2829 case MULT_EXPR:
2830 if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (expr))
2831 && TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr)))
2832 return expr;
2833 /* Fallthru. */
2834 case POINTER_PLUS_EXPR:
2835 /* And increments and decrements by a constant are simple. */
2836 e1 = gimple_assign_rhs2 (stmt);
2837 if (!is_gimple_min_invariant (e1))
2838 return expr;
2840 ee = expand_simple_operations (e, stop, cache);
2841 return fold_build2 (code, TREE_TYPE (expr), ee, e1);
2843 default:
2844 return expr;
2848 tree
2849 expand_simple_operations (tree expr, tree stop)
2851 hash_map<tree, tree> cache;
2852 return expand_simple_operations (expr, stop, cache);
2855 /* Tries to simplify EXPR using the condition COND. Returns the simplified
2856 expression (or EXPR unchanged, if no simplification was possible). */
2858 static tree
2859 tree_simplify_using_condition_1 (tree cond, tree expr)
2861 bool changed;
2862 tree e, e0, e1, e2, notcond;
2863 enum tree_code code = TREE_CODE (expr);
2865 if (code == INTEGER_CST)
2866 return expr;
2868 if (code == TRUTH_OR_EXPR
2869 || code == TRUTH_AND_EXPR
2870 || code == COND_EXPR)
2872 changed = false;
2874 e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
2875 if (TREE_OPERAND (expr, 0) != e0)
2876 changed = true;
2878 e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
2879 if (TREE_OPERAND (expr, 1) != e1)
2880 changed = true;
2882 if (code == COND_EXPR)
2884 e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
2885 if (TREE_OPERAND (expr, 2) != e2)
2886 changed = true;
2888 else
2889 e2 = NULL_TREE;
2891 if (changed)
2893 if (code == COND_EXPR)
2894 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
2895 else
2896 expr = fold_build2 (code, boolean_type_node, e0, e1);
2899 return expr;
2902 /* In case COND is equality, we may be able to simplify EXPR by copy/constant
2903 propagation, and vice versa. Fold does not handle this, since it is
2904 considered too expensive. */
2905 if (TREE_CODE (cond) == EQ_EXPR)
2907 e0 = TREE_OPERAND (cond, 0);
2908 e1 = TREE_OPERAND (cond, 1);
2910 /* We know that e0 == e1. Check whether we cannot simplify expr
2911 using this fact. */
2912 e = simplify_replace_tree (expr, e0, e1);
2913 if (integer_zerop (e) || integer_nonzerop (e))
2914 return e;
2916 e = simplify_replace_tree (expr, e1, e0);
2917 if (integer_zerop (e) || integer_nonzerop (e))
2918 return e;
2920 if (TREE_CODE (expr) == EQ_EXPR)
2922 e0 = TREE_OPERAND (expr, 0);
2923 e1 = TREE_OPERAND (expr, 1);
2925 /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
2926 e = simplify_replace_tree (cond, e0, e1);
2927 if (integer_zerop (e))
2928 return e;
2929 e = simplify_replace_tree (cond, e1, e0);
2930 if (integer_zerop (e))
2931 return e;
2933 if (TREE_CODE (expr) == NE_EXPR)
2935 e0 = TREE_OPERAND (expr, 0);
2936 e1 = TREE_OPERAND (expr, 1);
2938 /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
2939 e = simplify_replace_tree (cond, e0, e1);
2940 if (integer_zerop (e))
2941 return boolean_true_node;
2942 e = simplify_replace_tree (cond, e1, e0);
2943 if (integer_zerop (e))
2944 return boolean_true_node;
2947 /* Check whether COND ==> EXPR. */
2948 notcond = invert_truthvalue (cond);
2949 e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, expr);
2950 if (e && integer_nonzerop (e))
2951 return e;
2953 /* Check whether COND ==> not EXPR. */
2954 e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, expr);
2955 if (e && integer_zerop (e))
2956 return e;
2958 return expr;
2961 /* Tries to simplify EXPR using the condition COND. Returns the simplified
2962 expression (or EXPR unchanged, if no simplification was possible).
2963 Wrapper around tree_simplify_using_condition_1 that ensures that chains
2964 of simple operations in definitions of ssa names in COND are expanded,
2965 so that things like casts or incrementing the value of the bound before
2966 the loop do not cause us to fail. */
2968 static tree
2969 tree_simplify_using_condition (tree cond, tree expr)
2971 cond = expand_simple_operations (cond);
2973 return tree_simplify_using_condition_1 (cond, expr);
2976 /* Tries to simplify EXPR using the conditions on entry to LOOP.
2977 Returns the simplified expression (or EXPR unchanged, if no
2978 simplification was possible). */
2980 tree
2981 simplify_using_initial_conditions (class loop *loop, tree expr)
2983 edge e;
2984 basic_block bb;
2985 gimple *stmt;
2986 tree cond, expanded, backup;
2987 int cnt = 0;
2989 if (TREE_CODE (expr) == INTEGER_CST)
2990 return expr;
2992 backup = expanded = expand_simple_operations (expr);
2994 /* Limit walking the dominators to avoid quadraticness in
2995 the number of BBs times the number of loops in degenerate
2996 cases. */
2997 for (bb = loop->header;
2998 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
2999 bb = get_immediate_dominator (CDI_DOMINATORS, bb))
3001 if (!single_pred_p (bb))
3002 continue;
3003 e = single_pred_edge (bb);
3005 if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
3006 continue;
3008 stmt = last_stmt (e->src);
3009 cond = fold_build2 (gimple_cond_code (stmt),
3010 boolean_type_node,
3011 gimple_cond_lhs (stmt),
3012 gimple_cond_rhs (stmt));
3013 if (e->flags & EDGE_FALSE_VALUE)
3014 cond = invert_truthvalue (cond);
3015 expanded = tree_simplify_using_condition (cond, expanded);
3016 /* Break if EXPR is simplified to const values. */
3017 if (expanded
3018 && (integer_zerop (expanded) || integer_nonzerop (expanded)))
3019 return expanded;
3021 ++cnt;
3024 /* Return the original expression if no simplification is done. */
3025 return operand_equal_p (backup, expanded, 0) ? expr : expanded;
3028 /* Tries to simplify EXPR using the evolutions of the loop invariants
3029 in the superloops of LOOP. Returns the simplified expression
3030 (or EXPR unchanged, if no simplification was possible). */
3032 static tree
3033 simplify_using_outer_evolutions (class loop *loop, tree expr)
3035 enum tree_code code = TREE_CODE (expr);
3036 bool changed;
3037 tree e, e0, e1, e2;
3039 if (is_gimple_min_invariant (expr))
3040 return expr;
3042 if (code == TRUTH_OR_EXPR
3043 || code == TRUTH_AND_EXPR
3044 || code == COND_EXPR)
3046 changed = false;
3048 e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
3049 if (TREE_OPERAND (expr, 0) != e0)
3050 changed = true;
3052 e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
3053 if (TREE_OPERAND (expr, 1) != e1)
3054 changed = true;
3056 if (code == COND_EXPR)
3058 e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
3059 if (TREE_OPERAND (expr, 2) != e2)
3060 changed = true;
3062 else
3063 e2 = NULL_TREE;
3065 if (changed)
3067 if (code == COND_EXPR)
3068 expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
3069 else
3070 expr = fold_build2 (code, boolean_type_node, e0, e1);
3073 return expr;
3076 e = instantiate_parameters (loop, expr);
3077 if (is_gimple_min_invariant (e))
3078 return e;
3080 return expr;
3083 /* Returns true if EXIT is the only possible exit from LOOP. */
3085 bool
3086 loop_only_exit_p (const class loop *loop, basic_block *body, const_edge exit)
3088 gimple_stmt_iterator bsi;
3089 unsigned i;
3091 if (exit != single_exit (loop))
3092 return false;
3094 for (i = 0; i < loop->num_nodes; i++)
3095 for (bsi = gsi_start_bb (body[i]); !gsi_end_p (bsi); gsi_next (&bsi))
3096 if (stmt_can_terminate_bb_p (gsi_stmt (bsi)))
3097 return false;
3099 return true;
3102 /* Stores description of number of iterations of LOOP derived from
3103 EXIT (an exit edge of the LOOP) in NITER. Returns true if some useful
3104 information could be derived (and fields of NITER have meaning described
3105 in comments at class tree_niter_desc declaration), false otherwise.
3106 When EVERY_ITERATION is true, only tests that are known to be executed
3107 every iteration are considered (i.e. only test that alone bounds the loop).
3108 If AT_STMT is not NULL, this function stores LOOP's condition statement in
3109 it when returning true. */
3111 bool
3112 number_of_iterations_exit_assumptions (class loop *loop, edge exit,
3113 class tree_niter_desc *niter,
3114 gcond **at_stmt, bool every_iteration,
3115 basic_block *body)
3117 gimple *last;
3118 gcond *stmt;
3119 tree type;
3120 tree op0, op1;
3121 enum tree_code code;
3122 affine_iv iv0, iv1;
3123 bool safe;
3125 /* The condition at a fake exit (if it exists) does not control its
3126 execution. */
3127 if (exit->flags & EDGE_FAKE)
3128 return false;
3130 /* Nothing to analyze if the loop is known to be infinite. */
3131 if (loop_constraint_set_p (loop, LOOP_C_INFINITE))
3132 return false;
3134 safe = dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src);
3136 if (every_iteration && !safe)
3137 return false;
3139 niter->assumptions = boolean_false_node;
3140 niter->control.base = NULL_TREE;
3141 niter->control.step = NULL_TREE;
3142 niter->control.no_overflow = false;
3143 last = last_stmt (exit->src);
3144 if (!last)
3145 return false;
3146 stmt = dyn_cast <gcond *> (last);
3147 if (!stmt)
3148 return false;
3150 if (at_stmt)
3151 *at_stmt = stmt;
3153 /* We want the condition for staying inside loop. */
3154 code = gimple_cond_code (stmt);
3155 if (exit->flags & EDGE_TRUE_VALUE)
3156 code = invert_tree_comparison (code, false);
3158 switch (code)
3160 case GT_EXPR:
3161 case GE_EXPR:
3162 case LT_EXPR:
3163 case LE_EXPR:
3164 case NE_EXPR:
3165 break;
3167 case EQ_EXPR:
3168 return number_of_iterations_cltz (loop, exit, code, niter);
3170 default:
3171 return false;
3174 op0 = gimple_cond_lhs (stmt);
3175 op1 = gimple_cond_rhs (stmt);
3176 type = TREE_TYPE (op0);
3178 if (TREE_CODE (type) != INTEGER_TYPE
3179 && !POINTER_TYPE_P (type))
3180 return false;
3182 tree iv0_niters = NULL_TREE;
3183 if (!simple_iv_with_niters (loop, loop_containing_stmt (stmt),
3184 op0, &iv0, safe ? &iv0_niters : NULL, false))
3185 return number_of_iterations_bitcount (loop, exit, code, niter);
3186 tree iv1_niters = NULL_TREE;
3187 if (!simple_iv_with_niters (loop, loop_containing_stmt (stmt),
3188 op1, &iv1, safe ? &iv1_niters : NULL, false))
3189 return false;
3190 /* Give up on complicated case. */
3191 if (iv0_niters && iv1_niters)
3192 return false;
3194 /* We don't want to see undefined signed overflow warnings while
3195 computing the number of iterations. */
3196 fold_defer_overflow_warnings ();
3198 iv0.base = expand_simple_operations (iv0.base);
3199 iv1.base = expand_simple_operations (iv1.base);
3200 bool body_from_caller = true;
3201 if (!body)
3203 body = get_loop_body (loop);
3204 body_from_caller = false;
3206 bool only_exit_p = loop_only_exit_p (loop, body, exit);
3207 if (!body_from_caller)
3208 free (body);
3209 if (!number_of_iterations_cond (loop, type, &iv0, code, &iv1, niter,
3210 only_exit_p, safe))
3212 fold_undefer_and_ignore_overflow_warnings ();
3213 return false;
3216 /* Incorporate additional assumption implied by control iv. */
3217 tree iv_niters = iv0_niters ? iv0_niters : iv1_niters;
3218 if (iv_niters)
3220 tree assumption = fold_build2 (LE_EXPR, boolean_type_node, niter->niter,
3221 fold_convert (TREE_TYPE (niter->niter),
3222 iv_niters));
3224 if (!integer_nonzerop (assumption))
3225 niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3226 niter->assumptions, assumption);
3228 /* Refine upper bound if possible. */
3229 if (TREE_CODE (iv_niters) == INTEGER_CST
3230 && niter->max > wi::to_widest (iv_niters))
3231 niter->max = wi::to_widest (iv_niters);
3234 /* There is no assumptions if the loop is known to be finite. */
3235 if (!integer_zerop (niter->assumptions)
3236 && loop_constraint_set_p (loop, LOOP_C_FINITE))
3237 niter->assumptions = boolean_true_node;
3239 if (optimize >= 3)
3241 niter->assumptions = simplify_using_outer_evolutions (loop,
3242 niter->assumptions);
3243 niter->may_be_zero = simplify_using_outer_evolutions (loop,
3244 niter->may_be_zero);
3245 niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
3248 niter->assumptions
3249 = simplify_using_initial_conditions (loop,
3250 niter->assumptions);
3251 niter->may_be_zero
3252 = simplify_using_initial_conditions (loop,
3253 niter->may_be_zero);
3255 fold_undefer_and_ignore_overflow_warnings ();
3257 /* If NITER has simplified into a constant, update MAX. */
3258 if (TREE_CODE (niter->niter) == INTEGER_CST)
3259 niter->max = wi::to_widest (niter->niter);
3261 return (!integer_zerop (niter->assumptions));
3264 /* Like number_of_iterations_exit_assumptions, but return TRUE only if
3265 the niter information holds unconditionally. */
3267 bool
3268 number_of_iterations_exit (class loop *loop, edge exit,
3269 class tree_niter_desc *niter,
3270 bool warn, bool every_iteration,
3271 basic_block *body)
3273 gcond *stmt;
3274 if (!number_of_iterations_exit_assumptions (loop, exit, niter,
3275 &stmt, every_iteration, body))
3276 return false;
3278 if (integer_nonzerop (niter->assumptions))
3279 return true;
3281 if (warn && dump_enabled_p ())
3282 dump_printf_loc (MSG_MISSED_OPTIMIZATION, stmt,
3283 "missed loop optimization: niters analysis ends up "
3284 "with assumptions.\n");
3286 return false;
3289 /* Try to determine the number of iterations of LOOP. If we succeed,
3290 expression giving number of iterations is returned and *EXIT is
3291 set to the edge from that the information is obtained. Otherwise
3292 chrec_dont_know is returned. */
3294 tree
3295 find_loop_niter (class loop *loop, edge *exit)
3297 unsigned i;
3298 auto_vec<edge> exits = get_loop_exit_edges (loop);
3299 edge ex;
3300 tree niter = NULL_TREE, aniter;
3301 class tree_niter_desc desc;
3303 *exit = NULL;
3304 FOR_EACH_VEC_ELT (exits, i, ex)
3306 if (!number_of_iterations_exit (loop, ex, &desc, false))
3307 continue;
3309 if (integer_nonzerop (desc.may_be_zero))
3311 /* We exit in the first iteration through this exit.
3312 We won't find anything better. */
3313 niter = build_int_cst (unsigned_type_node, 0);
3314 *exit = ex;
3315 break;
3318 if (!integer_zerop (desc.may_be_zero))
3319 continue;
3321 aniter = desc.niter;
3323 if (!niter)
3325 /* Nothing recorded yet. */
3326 niter = aniter;
3327 *exit = ex;
3328 continue;
3331 /* Prefer constants, the lower the better. */
3332 if (TREE_CODE (aniter) != INTEGER_CST)
3333 continue;
3335 if (TREE_CODE (niter) != INTEGER_CST)
3337 niter = aniter;
3338 *exit = ex;
3339 continue;
3342 if (tree_int_cst_lt (aniter, niter))
3344 niter = aniter;
3345 *exit = ex;
3346 continue;
3350 return niter ? niter : chrec_dont_know;
3353 /* Return true if loop is known to have bounded number of iterations. */
3355 bool
3356 finite_loop_p (class loop *loop)
3358 widest_int nit;
3359 int flags;
3361 flags = flags_from_decl_or_type (current_function_decl);
3362 if ((flags & (ECF_CONST|ECF_PURE)) && !(flags & ECF_LOOPING_CONST_OR_PURE))
3364 if (dump_file && (dump_flags & TDF_DETAILS))
3365 fprintf (dump_file, "Found loop %i to be finite: it is within pure or const function.\n",
3366 loop->num);
3367 return true;
3370 if (loop->any_upper_bound
3371 || max_loop_iterations (loop, &nit))
3373 if (dump_file && (dump_flags & TDF_DETAILS))
3374 fprintf (dump_file, "Found loop %i to be finite: upper bound found.\n",
3375 loop->num);
3376 return true;
3379 if (loop->finite_p)
3381 unsigned i;
3382 auto_vec<edge> exits = get_loop_exit_edges (loop);
3383 edge ex;
3385 /* If the loop has a normal exit, we can assume it will terminate. */
3386 FOR_EACH_VEC_ELT (exits, i, ex)
3387 if (!(ex->flags & (EDGE_EH | EDGE_ABNORMAL | EDGE_FAKE)))
3389 if (dump_file)
3390 fprintf (dump_file, "Assume loop %i to be finite: it has an exit "
3391 "and -ffinite-loops is on.\n", loop->num);
3392 return true;
3396 return false;
3401 Analysis of a number of iterations of a loop by a brute-force evaluation.
3405 /* Bound on the number of iterations we try to evaluate. */
3407 #define MAX_ITERATIONS_TO_TRACK \
3408 ((unsigned) param_max_iterations_to_track)
3410 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
3411 result by a chain of operations such that all but exactly one of their
3412 operands are constants. */
3414 static gphi *
3415 chain_of_csts_start (class loop *loop, tree x)
3417 gimple *stmt = SSA_NAME_DEF_STMT (x);
3418 tree use;
3419 basic_block bb = gimple_bb (stmt);
3420 enum tree_code code;
3422 if (!bb
3423 || !flow_bb_inside_loop_p (loop, bb))
3424 return NULL;
3426 if (gimple_code (stmt) == GIMPLE_PHI)
3428 if (bb == loop->header)
3429 return as_a <gphi *> (stmt);
3431 return NULL;
3434 if (gimple_code (stmt) != GIMPLE_ASSIGN
3435 || gimple_assign_rhs_class (stmt) == GIMPLE_TERNARY_RHS)
3436 return NULL;
3438 code = gimple_assign_rhs_code (stmt);
3439 if (gimple_references_memory_p (stmt)
3440 || TREE_CODE_CLASS (code) == tcc_reference
3441 || (code == ADDR_EXPR
3442 && !is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
3443 return NULL;
3445 use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
3446 if (use == NULL_TREE)
3447 return NULL;
3449 return chain_of_csts_start (loop, use);
3452 /* Determines whether the expression X is derived from a result of a phi node
3453 in header of LOOP such that
3455 * the derivation of X consists only from operations with constants
3456 * the initial value of the phi node is constant
3457 * the value of the phi node in the next iteration can be derived from the
3458 value in the current iteration by a chain of operations with constants,
3459 or is also a constant
3461 If such phi node exists, it is returned, otherwise NULL is returned. */
3463 static gphi *
3464 get_base_for (class loop *loop, tree x)
3466 gphi *phi;
3467 tree init, next;
3469 if (is_gimple_min_invariant (x))
3470 return NULL;
3472 phi = chain_of_csts_start (loop, x);
3473 if (!phi)
3474 return NULL;
3476 init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
3477 next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
3479 if (!is_gimple_min_invariant (init))
3480 return NULL;
3482 if (TREE_CODE (next) == SSA_NAME
3483 && chain_of_csts_start (loop, next) != phi)
3484 return NULL;
3486 return phi;
3489 /* Given an expression X, then
3491 * if X is NULL_TREE, we return the constant BASE.
3492 * if X is a constant, we return the constant X.
3493 * otherwise X is a SSA name, whose value in the considered loop is derived
3494 by a chain of operations with constant from a result of a phi node in
3495 the header of the loop. Then we return value of X when the value of the
3496 result of this phi node is given by the constant BASE. */
3498 static tree
3499 get_val_for (tree x, tree base)
3501 gimple *stmt;
3503 gcc_checking_assert (is_gimple_min_invariant (base));
3505 if (!x)
3506 return base;
3507 else if (is_gimple_min_invariant (x))
3508 return x;
3510 stmt = SSA_NAME_DEF_STMT (x);
3511 if (gimple_code (stmt) == GIMPLE_PHI)
3512 return base;
3514 gcc_checking_assert (is_gimple_assign (stmt));
3516 /* STMT must be either an assignment of a single SSA name or an
3517 expression involving an SSA name and a constant. Try to fold that
3518 expression using the value for the SSA name. */
3519 if (gimple_assign_ssa_name_copy_p (stmt))
3520 return get_val_for (gimple_assign_rhs1 (stmt), base);
3521 else if (gimple_assign_rhs_class (stmt) == GIMPLE_UNARY_RHS
3522 && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
3523 return fold_build1 (gimple_assign_rhs_code (stmt),
3524 TREE_TYPE (gimple_assign_lhs (stmt)),
3525 get_val_for (gimple_assign_rhs1 (stmt), base));
3526 else if (gimple_assign_rhs_class (stmt) == GIMPLE_BINARY_RHS)
3528 tree rhs1 = gimple_assign_rhs1 (stmt);
3529 tree rhs2 = gimple_assign_rhs2 (stmt);
3530 if (TREE_CODE (rhs1) == SSA_NAME)
3531 rhs1 = get_val_for (rhs1, base);
3532 else if (TREE_CODE (rhs2) == SSA_NAME)
3533 rhs2 = get_val_for (rhs2, base);
3534 else
3535 gcc_unreachable ();
3536 return fold_build2 (gimple_assign_rhs_code (stmt),
3537 TREE_TYPE (gimple_assign_lhs (stmt)), rhs1, rhs2);
3539 else
3540 gcc_unreachable ();
3544 /* Tries to count the number of iterations of LOOP till it exits by EXIT
3545 by brute force -- i.e. by determining the value of the operands of the
3546 condition at EXIT in first few iterations of the loop (assuming that
3547 these values are constant) and determining the first one in that the
3548 condition is not satisfied. Returns the constant giving the number
3549 of the iterations of LOOP if successful, chrec_dont_know otherwise. */
3551 tree
3552 loop_niter_by_eval (class loop *loop, edge exit)
3554 tree acnd;
3555 tree op[2], val[2], next[2], aval[2];
3556 gphi *phi;
3557 gimple *cond;
3558 unsigned i, j;
3559 enum tree_code cmp;
3561 cond = last_stmt (exit->src);
3562 if (!cond || gimple_code (cond) != GIMPLE_COND)
3563 return chrec_dont_know;
3565 cmp = gimple_cond_code (cond);
3566 if (exit->flags & EDGE_TRUE_VALUE)
3567 cmp = invert_tree_comparison (cmp, false);
3569 switch (cmp)
3571 case EQ_EXPR:
3572 case NE_EXPR:
3573 case GT_EXPR:
3574 case GE_EXPR:
3575 case LT_EXPR:
3576 case LE_EXPR:
3577 op[0] = gimple_cond_lhs (cond);
3578 op[1] = gimple_cond_rhs (cond);
3579 break;
3581 default:
3582 return chrec_dont_know;
3585 for (j = 0; j < 2; j++)
3587 if (is_gimple_min_invariant (op[j]))
3589 val[j] = op[j];
3590 next[j] = NULL_TREE;
3591 op[j] = NULL_TREE;
3593 else
3595 phi = get_base_for (loop, op[j]);
3596 if (!phi)
3597 return chrec_dont_know;
3598 val[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
3599 next[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
3603 /* Don't issue signed overflow warnings. */
3604 fold_defer_overflow_warnings ();
3606 for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
3608 for (j = 0; j < 2; j++)
3609 aval[j] = get_val_for (op[j], val[j]);
3611 acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
3612 if (acnd && integer_zerop (acnd))
3614 fold_undefer_and_ignore_overflow_warnings ();
3615 if (dump_file && (dump_flags & TDF_DETAILS))
3616 fprintf (dump_file,
3617 "Proved that loop %d iterates %d times using brute force.\n",
3618 loop->num, i);
3619 return build_int_cst (unsigned_type_node, i);
3622 for (j = 0; j < 2; j++)
3624 aval[j] = val[j];
3625 val[j] = get_val_for (next[j], val[j]);
3626 if (!is_gimple_min_invariant (val[j]))
3628 fold_undefer_and_ignore_overflow_warnings ();
3629 return chrec_dont_know;
3633 /* If the next iteration would use the same base values
3634 as the current one, there is no point looping further,
3635 all following iterations will be the same as this one. */
3636 if (val[0] == aval[0] && val[1] == aval[1])
3637 break;
3640 fold_undefer_and_ignore_overflow_warnings ();
3642 return chrec_dont_know;
3645 /* Finds the exit of the LOOP by that the loop exits after a constant
3646 number of iterations and stores the exit edge to *EXIT. The constant
3647 giving the number of iterations of LOOP is returned. The number of
3648 iterations is determined using loop_niter_by_eval (i.e. by brute force
3649 evaluation). If we are unable to find the exit for that loop_niter_by_eval
3650 determines the number of iterations, chrec_dont_know is returned. */
3652 tree
3653 find_loop_niter_by_eval (class loop *loop, edge *exit)
3655 unsigned i;
3656 auto_vec<edge> exits = get_loop_exit_edges (loop);
3657 edge ex;
3658 tree niter = NULL_TREE, aniter;
3660 *exit = NULL;
3662 /* Loops with multiple exits are expensive to handle and less important. */
3663 if (!flag_expensive_optimizations
3664 && exits.length () > 1)
3665 return chrec_dont_know;
3667 FOR_EACH_VEC_ELT (exits, i, ex)
3669 if (!just_once_each_iteration_p (loop, ex->src))
3670 continue;
3672 aniter = loop_niter_by_eval (loop, ex);
3673 if (chrec_contains_undetermined (aniter))
3674 continue;
3676 if (niter
3677 && !tree_int_cst_lt (aniter, niter))
3678 continue;
3680 niter = aniter;
3681 *exit = ex;
3684 return niter ? niter : chrec_dont_know;
3689 Analysis of upper bounds on number of iterations of a loop.
3693 static widest_int derive_constant_upper_bound_ops (tree, tree,
3694 enum tree_code, tree);
3696 /* Returns a constant upper bound on the value of the right-hand side of
3697 an assignment statement STMT. */
3699 static widest_int
3700 derive_constant_upper_bound_assign (gimple *stmt)
3702 enum tree_code code = gimple_assign_rhs_code (stmt);
3703 tree op0 = gimple_assign_rhs1 (stmt);
3704 tree op1 = gimple_assign_rhs2 (stmt);
3706 return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt)),
3707 op0, code, op1);
3710 /* Returns a constant upper bound on the value of expression VAL. VAL
3711 is considered to be unsigned. If its type is signed, its value must
3712 be nonnegative. */
3714 static widest_int
3715 derive_constant_upper_bound (tree val)
3717 enum tree_code code;
3718 tree op0, op1, op2;
3720 extract_ops_from_tree (val, &code, &op0, &op1, &op2);
3721 return derive_constant_upper_bound_ops (TREE_TYPE (val), op0, code, op1);
3724 /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
3725 whose type is TYPE. The expression is considered to be unsigned. If
3726 its type is signed, its value must be nonnegative. */
3728 static widest_int
3729 derive_constant_upper_bound_ops (tree type, tree op0,
3730 enum tree_code code, tree op1)
3732 tree subtype, maxt;
3733 widest_int bnd, max, cst;
3734 gimple *stmt;
3736 if (INTEGRAL_TYPE_P (type))
3737 maxt = TYPE_MAX_VALUE (type);
3738 else
3739 maxt = upper_bound_in_type (type, type);
3741 max = wi::to_widest (maxt);
3743 switch (code)
3745 case INTEGER_CST:
3746 return wi::to_widest (op0);
3748 CASE_CONVERT:
3749 subtype = TREE_TYPE (op0);
3750 if (!TYPE_UNSIGNED (subtype)
3751 /* If TYPE is also signed, the fact that VAL is nonnegative implies
3752 that OP0 is nonnegative. */
3753 && TYPE_UNSIGNED (type)
3754 && !tree_expr_nonnegative_p (op0))
3756 /* If we cannot prove that the casted expression is nonnegative,
3757 we cannot establish more useful upper bound than the precision
3758 of the type gives us. */
3759 return max;
3762 /* We now know that op0 is an nonnegative value. Try deriving an upper
3763 bound for it. */
3764 bnd = derive_constant_upper_bound (op0);
3766 /* If the bound does not fit in TYPE, max. value of TYPE could be
3767 attained. */
3768 if (wi::ltu_p (max, bnd))
3769 return max;
3771 return bnd;
3773 case PLUS_EXPR:
3774 case POINTER_PLUS_EXPR:
3775 case MINUS_EXPR:
3776 if (TREE_CODE (op1) != INTEGER_CST
3777 || !tree_expr_nonnegative_p (op0))
3778 return max;
3780 /* Canonicalize to OP0 - CST. Consider CST to be signed, in order to
3781 choose the most logical way how to treat this constant regardless
3782 of the signedness of the type. */
3783 cst = wi::sext (wi::to_widest (op1), TYPE_PRECISION (type));
3784 if (code != MINUS_EXPR)
3785 cst = -cst;
3787 bnd = derive_constant_upper_bound (op0);
3789 if (wi::neg_p (cst))
3791 cst = -cst;
3792 /* Avoid CST == 0x80000... */
3793 if (wi::neg_p (cst))
3794 return max;
3796 /* OP0 + CST. We need to check that
3797 BND <= MAX (type) - CST. */
3799 widest_int mmax = max - cst;
3800 if (wi::leu_p (bnd, mmax))
3801 return max;
3803 return bnd + cst;
3805 else
3807 /* OP0 - CST, where CST >= 0.
3809 If TYPE is signed, we have already verified that OP0 >= 0, and we
3810 know that the result is nonnegative. This implies that
3811 VAL <= BND - CST.
3813 If TYPE is unsigned, we must additionally know that OP0 >= CST,
3814 otherwise the operation underflows.
3817 /* This should only happen if the type is unsigned; however, for
3818 buggy programs that use overflowing signed arithmetics even with
3819 -fno-wrapv, this condition may also be true for signed values. */
3820 if (wi::ltu_p (bnd, cst))
3821 return max;
3823 if (TYPE_UNSIGNED (type))
3825 tree tem = fold_binary (GE_EXPR, boolean_type_node, op0,
3826 wide_int_to_tree (type, cst));
3827 if (!tem || integer_nonzerop (tem))
3828 return max;
3831 bnd -= cst;
3834 return bnd;
3836 case FLOOR_DIV_EXPR:
3837 case EXACT_DIV_EXPR:
3838 if (TREE_CODE (op1) != INTEGER_CST
3839 || tree_int_cst_sign_bit (op1))
3840 return max;
3842 bnd = derive_constant_upper_bound (op0);
3843 return wi::udiv_floor (bnd, wi::to_widest (op1));
3845 case BIT_AND_EXPR:
3846 if (TREE_CODE (op1) != INTEGER_CST
3847 || tree_int_cst_sign_bit (op1))
3848 return max;
3849 return wi::to_widest (op1);
3851 case SSA_NAME:
3852 stmt = SSA_NAME_DEF_STMT (op0);
3853 if (gimple_code (stmt) != GIMPLE_ASSIGN
3854 || gimple_assign_lhs (stmt) != op0)
3855 return max;
3856 return derive_constant_upper_bound_assign (stmt);
3858 default:
3859 return max;
3863 /* Emit a -Waggressive-loop-optimizations warning if needed. */
3865 static void
3866 do_warn_aggressive_loop_optimizations (class loop *loop,
3867 widest_int i_bound, gimple *stmt)
3869 /* Don't warn if the loop doesn't have known constant bound. */
3870 if (!loop->nb_iterations
3871 || TREE_CODE (loop->nb_iterations) != INTEGER_CST
3872 || !warn_aggressive_loop_optimizations
3873 /* To avoid warning multiple times for the same loop,
3874 only start warning when we preserve loops. */
3875 || (cfun->curr_properties & PROP_loops) == 0
3876 /* Only warn once per loop. */
3877 || loop->warned_aggressive_loop_optimizations
3878 /* Only warn if undefined behavior gives us lower estimate than the
3879 known constant bound. */
3880 || wi::cmpu (i_bound, wi::to_widest (loop->nb_iterations)) >= 0
3881 /* And undefined behavior happens unconditionally. */
3882 || !dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (stmt)))
3883 return;
3885 edge e = single_exit (loop);
3886 if (e == NULL)
3887 return;
3889 gimple *estmt = last_stmt (e->src);
3890 char buf[WIDE_INT_PRINT_BUFFER_SIZE];
3891 print_dec (i_bound, buf, TYPE_UNSIGNED (TREE_TYPE (loop->nb_iterations))
3892 ? UNSIGNED : SIGNED);
3893 auto_diagnostic_group d;
3894 if (warning_at (gimple_location (stmt), OPT_Waggressive_loop_optimizations,
3895 "iteration %s invokes undefined behavior", buf))
3896 inform (gimple_location (estmt), "within this loop");
3897 loop->warned_aggressive_loop_optimizations = true;
3900 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP. IS_EXIT
3901 is true if the loop is exited immediately after STMT, and this exit
3902 is taken at last when the STMT is executed BOUND + 1 times.
3903 REALISTIC is true if BOUND is expected to be close to the real number
3904 of iterations. UPPER is true if we are sure the loop iterates at most
3905 BOUND times. I_BOUND is a widest_int upper estimate on BOUND. */
3907 static void
3908 record_estimate (class loop *loop, tree bound, const widest_int &i_bound,
3909 gimple *at_stmt, bool is_exit, bool realistic, bool upper)
3911 widest_int delta;
3913 if (dump_file && (dump_flags & TDF_DETAILS))
3915 fprintf (dump_file, "Statement %s", is_exit ? "(exit)" : "");
3916 print_gimple_stmt (dump_file, at_stmt, 0, TDF_SLIM);
3917 fprintf (dump_file, " is %sexecuted at most ",
3918 upper ? "" : "probably ");
3919 print_generic_expr (dump_file, bound, TDF_SLIM);
3920 fprintf (dump_file, " (bounded by ");
3921 print_decu (i_bound, dump_file);
3922 fprintf (dump_file, ") + 1 times in loop %d.\n", loop->num);
3925 /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
3926 real number of iterations. */
3927 if (TREE_CODE (bound) != INTEGER_CST)
3928 realistic = false;
3929 else
3930 gcc_checking_assert (i_bound == wi::to_widest (bound));
3932 /* If we have a guaranteed upper bound, record it in the appropriate
3933 list, unless this is an !is_exit bound (i.e. undefined behavior in
3934 at_stmt) in a loop with known constant number of iterations. */
3935 if (upper
3936 && (is_exit
3937 || loop->nb_iterations == NULL_TREE
3938 || TREE_CODE (loop->nb_iterations) != INTEGER_CST))
3940 class nb_iter_bound *elt = ggc_alloc<nb_iter_bound> ();
3942 elt->bound = i_bound;
3943 elt->stmt = at_stmt;
3944 elt->is_exit = is_exit;
3945 elt->next = loop->bounds;
3946 loop->bounds = elt;
3949 /* If statement is executed on every path to the loop latch, we can directly
3950 infer the upper bound on the # of iterations of the loop. */
3951 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (at_stmt)))
3952 upper = false;
3954 /* Update the number of iteration estimates according to the bound.
3955 If at_stmt is an exit then the loop latch is executed at most BOUND times,
3956 otherwise it can be executed BOUND + 1 times. We will lower the estimate
3957 later if such statement must be executed on last iteration */
3958 if (is_exit)
3959 delta = 0;
3960 else
3961 delta = 1;
3962 widest_int new_i_bound = i_bound + delta;
3964 /* If an overflow occurred, ignore the result. */
3965 if (wi::ltu_p (new_i_bound, delta))
3966 return;
3968 if (upper && !is_exit)
3969 do_warn_aggressive_loop_optimizations (loop, new_i_bound, at_stmt);
3970 record_niter_bound (loop, new_i_bound, realistic, upper);
3973 /* Records the control iv analyzed in NITER for LOOP if the iv is valid
3974 and doesn't overflow. */
3976 static void
3977 record_control_iv (class loop *loop, class tree_niter_desc *niter)
3979 struct control_iv *iv;
3981 if (!niter->control.base || !niter->control.step)
3982 return;
3984 if (!integer_onep (niter->assumptions) || !niter->control.no_overflow)
3985 return;
3987 iv = ggc_alloc<control_iv> ();
3988 iv->base = niter->control.base;
3989 iv->step = niter->control.step;
3990 iv->next = loop->control_ivs;
3991 loop->control_ivs = iv;
3993 return;
3996 /* This function returns TRUE if below conditions are satisfied:
3997 1) VAR is SSA variable.
3998 2) VAR is an IV:{base, step} in its defining loop.
3999 3) IV doesn't overflow.
4000 4) Both base and step are integer constants.
4001 5) Base is the MIN/MAX value depends on IS_MIN.
4002 Store value of base to INIT correspondingly. */
4004 static bool
4005 get_cst_init_from_scev (tree var, wide_int *init, bool is_min)
4007 if (TREE_CODE (var) != SSA_NAME)
4008 return false;
4010 gimple *def_stmt = SSA_NAME_DEF_STMT (var);
4011 class loop *loop = loop_containing_stmt (def_stmt);
4013 if (loop == NULL)
4014 return false;
4016 affine_iv iv;
4017 if (!simple_iv (loop, loop, var, &iv, false))
4018 return false;
4020 if (!iv.no_overflow)
4021 return false;
4023 if (TREE_CODE (iv.base) != INTEGER_CST || TREE_CODE (iv.step) != INTEGER_CST)
4024 return false;
4026 if (is_min == tree_int_cst_sign_bit (iv.step))
4027 return false;
4029 *init = wi::to_wide (iv.base);
4030 return true;
4033 /* Record the estimate on number of iterations of LOOP based on the fact that
4034 the induction variable BASE + STEP * i evaluated in STMT does not wrap and
4035 its values belong to the range <LOW, HIGH>. REALISTIC is true if the
4036 estimated number of iterations is expected to be close to the real one.
4037 UPPER is true if we are sure the induction variable does not wrap. */
4039 static void
4040 record_nonwrapping_iv (class loop *loop, tree base, tree step, gimple *stmt,
4041 tree low, tree high, bool realistic, bool upper)
4043 tree niter_bound, extreme, delta;
4044 tree type = TREE_TYPE (base), unsigned_type;
4045 tree orig_base = base;
4047 if (TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
4048 return;
4050 if (dump_file && (dump_flags & TDF_DETAILS))
4052 fprintf (dump_file, "Induction variable (");
4053 print_generic_expr (dump_file, TREE_TYPE (base), TDF_SLIM);
4054 fprintf (dump_file, ") ");
4055 print_generic_expr (dump_file, base, TDF_SLIM);
4056 fprintf (dump_file, " + ");
4057 print_generic_expr (dump_file, step, TDF_SLIM);
4058 fprintf (dump_file, " * iteration does not wrap in statement ");
4059 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
4060 fprintf (dump_file, " in loop %d.\n", loop->num);
4063 unsigned_type = unsigned_type_for (type);
4064 base = fold_convert (unsigned_type, base);
4065 step = fold_convert (unsigned_type, step);
4067 if (tree_int_cst_sign_bit (step))
4069 wide_int max;
4070 Value_Range base_range (TREE_TYPE (orig_base));
4071 if (get_range_query (cfun)->range_of_expr (base_range, orig_base)
4072 && !base_range.undefined_p ())
4073 max = base_range.upper_bound ();
4074 extreme = fold_convert (unsigned_type, low);
4075 if (TREE_CODE (orig_base) == SSA_NAME
4076 && TREE_CODE (high) == INTEGER_CST
4077 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
4078 && (base_range.kind () == VR_RANGE
4079 || get_cst_init_from_scev (orig_base, &max, false))
4080 && wi::gts_p (wi::to_wide (high), max))
4081 base = wide_int_to_tree (unsigned_type, max);
4082 else if (TREE_CODE (base) != INTEGER_CST
4083 && dominated_by_p (CDI_DOMINATORS,
4084 loop->latch, gimple_bb (stmt)))
4085 base = fold_convert (unsigned_type, high);
4086 delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
4087 step = fold_build1 (NEGATE_EXPR, unsigned_type, step);
4089 else
4091 wide_int min;
4092 Value_Range base_range (TREE_TYPE (orig_base));
4093 if (get_range_query (cfun)->range_of_expr (base_range, orig_base)
4094 && !base_range.undefined_p ())
4095 min = base_range.lower_bound ();
4096 extreme = fold_convert (unsigned_type, high);
4097 if (TREE_CODE (orig_base) == SSA_NAME
4098 && TREE_CODE (low) == INTEGER_CST
4099 && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
4100 && (base_range.kind () == VR_RANGE
4101 || get_cst_init_from_scev (orig_base, &min, true))
4102 && wi::gts_p (min, wi::to_wide (low)))
4103 base = wide_int_to_tree (unsigned_type, min);
4104 else if (TREE_CODE (base) != INTEGER_CST
4105 && dominated_by_p (CDI_DOMINATORS,
4106 loop->latch, gimple_bb (stmt)))
4107 base = fold_convert (unsigned_type, low);
4108 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
4111 /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
4112 would get out of the range. */
4113 niter_bound = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step);
4114 widest_int max = derive_constant_upper_bound (niter_bound);
4115 record_estimate (loop, niter_bound, max, stmt, false, realistic, upper);
4118 /* Determine information about number of iterations a LOOP from the index
4119 IDX of a data reference accessed in STMT. RELIABLE is true if STMT is
4120 guaranteed to be executed in every iteration of LOOP. Callback for
4121 for_each_index. */
4123 struct ilb_data
4125 class loop *loop;
4126 gimple *stmt;
4129 static bool
4130 idx_infer_loop_bounds (tree base, tree *idx, void *dta)
4132 struct ilb_data *data = (struct ilb_data *) dta;
4133 tree ev, init, step;
4134 tree low, high, type, next;
4135 bool sign, upper = true, has_flexible_size = false;
4136 class loop *loop = data->loop;
4138 if (TREE_CODE (base) != ARRAY_REF)
4139 return true;
4141 /* For arrays that might have flexible sizes, it is not guaranteed that they
4142 do not really extend over their declared size. */
4143 if (array_ref_flexible_size_p (base))
4145 has_flexible_size = true;
4146 upper = false;
4149 class loop *dloop = loop_containing_stmt (data->stmt);
4150 if (!dloop)
4151 return true;
4153 ev = analyze_scalar_evolution (dloop, *idx);
4154 ev = instantiate_parameters (loop, ev);
4155 init = initial_condition (ev);
4156 step = evolution_part_in_loop_num (ev, loop->num);
4158 if (!init
4159 || !step
4160 || TREE_CODE (step) != INTEGER_CST
4161 || integer_zerop (step)
4162 || tree_contains_chrecs (init, NULL)
4163 || chrec_contains_symbols_defined_in_loop (init, loop->num))
4164 return true;
4166 low = array_ref_low_bound (base);
4167 high = array_ref_up_bound (base);
4169 /* The case of nonconstant bounds could be handled, but it would be
4170 complicated. */
4171 if (TREE_CODE (low) != INTEGER_CST
4172 || !high
4173 || TREE_CODE (high) != INTEGER_CST)
4174 return true;
4175 sign = tree_int_cst_sign_bit (step);
4176 type = TREE_TYPE (step);
4178 /* The array that might have flexible size most likely extends
4179 beyond its bounds. */
4180 if (has_flexible_size
4181 && operand_equal_p (low, high, 0))
4182 return true;
4184 /* In case the relevant bound of the array does not fit in type, or
4185 it does, but bound + step (in type) still belongs into the range of the
4186 array, the index may wrap and still stay within the range of the array
4187 (consider e.g. if the array is indexed by the full range of
4188 unsigned char).
4190 To make things simpler, we require both bounds to fit into type, although
4191 there are cases where this would not be strictly necessary. */
4192 if (!int_fits_type_p (high, type)
4193 || !int_fits_type_p (low, type))
4194 return true;
4195 low = fold_convert (type, low);
4196 high = fold_convert (type, high);
4198 if (sign)
4199 next = fold_binary (PLUS_EXPR, type, low, step);
4200 else
4201 next = fold_binary (PLUS_EXPR, type, high, step);
4203 if (tree_int_cst_compare (low, next) <= 0
4204 && tree_int_cst_compare (next, high) <= 0)
4205 return true;
4207 /* If access is not executed on every iteration, we must ensure that overlow
4208 may not make the access valid later. */
4209 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (data->stmt))
4210 && scev_probably_wraps_p (NULL_TREE,
4211 initial_condition_in_loop_num (ev, loop->num),
4212 step, data->stmt, loop, true))
4213 upper = false;
4215 record_nonwrapping_iv (loop, init, step, data->stmt, low, high, false, upper);
4216 return true;
4219 /* Determine information about number of iterations a LOOP from the bounds
4220 of arrays in the data reference REF accessed in STMT. RELIABLE is true if
4221 STMT is guaranteed to be executed in every iteration of LOOP.*/
4223 static void
4224 infer_loop_bounds_from_ref (class loop *loop, gimple *stmt, tree ref)
4226 struct ilb_data data;
4228 data.loop = loop;
4229 data.stmt = stmt;
4230 for_each_index (&ref, idx_infer_loop_bounds, &data);
4233 /* Determine information about number of iterations of a LOOP from the way
4234 arrays are used in STMT. RELIABLE is true if STMT is guaranteed to be
4235 executed in every iteration of LOOP. */
4237 static void
4238 infer_loop_bounds_from_array (class loop *loop, gimple *stmt)
4240 if (is_gimple_assign (stmt))
4242 tree op0 = gimple_assign_lhs (stmt);
4243 tree op1 = gimple_assign_rhs1 (stmt);
4245 /* For each memory access, analyze its access function
4246 and record a bound on the loop iteration domain. */
4247 if (REFERENCE_CLASS_P (op0))
4248 infer_loop_bounds_from_ref (loop, stmt, op0);
4250 if (REFERENCE_CLASS_P (op1))
4251 infer_loop_bounds_from_ref (loop, stmt, op1);
4253 else if (is_gimple_call (stmt))
4255 tree arg, lhs;
4256 unsigned i, n = gimple_call_num_args (stmt);
4258 lhs = gimple_call_lhs (stmt);
4259 if (lhs && REFERENCE_CLASS_P (lhs))
4260 infer_loop_bounds_from_ref (loop, stmt, lhs);
4262 for (i = 0; i < n; i++)
4264 arg = gimple_call_arg (stmt, i);
4265 if (REFERENCE_CLASS_P (arg))
4266 infer_loop_bounds_from_ref (loop, stmt, arg);
4271 /* Determine information about number of iterations of a LOOP from the fact
4272 that pointer arithmetics in STMT does not overflow. */
4274 static void
4275 infer_loop_bounds_from_pointer_arith (class loop *loop, gimple *stmt)
4277 tree def, base, step, scev, type, low, high;
4278 tree var, ptr;
4280 if (!is_gimple_assign (stmt)
4281 || gimple_assign_rhs_code (stmt) != POINTER_PLUS_EXPR)
4282 return;
4284 def = gimple_assign_lhs (stmt);
4285 if (TREE_CODE (def) != SSA_NAME)
4286 return;
4288 type = TREE_TYPE (def);
4289 if (!nowrap_type_p (type))
4290 return;
4292 ptr = gimple_assign_rhs1 (stmt);
4293 if (!expr_invariant_in_loop_p (loop, ptr))
4294 return;
4296 var = gimple_assign_rhs2 (stmt);
4297 if (TYPE_PRECISION (type) != TYPE_PRECISION (TREE_TYPE (var)))
4298 return;
4300 class loop *uloop = loop_containing_stmt (stmt);
4301 scev = instantiate_parameters (loop, analyze_scalar_evolution (uloop, def));
4302 if (chrec_contains_undetermined (scev))
4303 return;
4305 base = initial_condition_in_loop_num (scev, loop->num);
4306 step = evolution_part_in_loop_num (scev, loop->num);
4308 if (!base || !step
4309 || TREE_CODE (step) != INTEGER_CST
4310 || tree_contains_chrecs (base, NULL)
4311 || chrec_contains_symbols_defined_in_loop (base, loop->num))
4312 return;
4314 low = lower_bound_in_type (type, type);
4315 high = upper_bound_in_type (type, type);
4317 /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
4318 produce a NULL pointer. The contrary would mean NULL points to an object,
4319 while NULL is supposed to compare unequal with the address of all objects.
4320 Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
4321 NULL pointer since that would mean wrapping, which we assume here not to
4322 happen. So, we can exclude NULL from the valid range of pointer
4323 arithmetic. */
4324 if (flag_delete_null_pointer_checks && int_cst_value (low) == 0)
4325 low = build_int_cstu (TREE_TYPE (low), TYPE_ALIGN_UNIT (TREE_TYPE (type)));
4327 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
4330 /* Determine information about number of iterations of a LOOP from the fact
4331 that signed arithmetics in STMT does not overflow. */
4333 static void
4334 infer_loop_bounds_from_signedness (class loop *loop, gimple *stmt)
4336 tree def, base, step, scev, type, low, high;
4338 if (gimple_code (stmt) != GIMPLE_ASSIGN)
4339 return;
4341 def = gimple_assign_lhs (stmt);
4343 if (TREE_CODE (def) != SSA_NAME)
4344 return;
4346 type = TREE_TYPE (def);
4347 if (!INTEGRAL_TYPE_P (type)
4348 || !TYPE_OVERFLOW_UNDEFINED (type))
4349 return;
4351 scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
4352 if (chrec_contains_undetermined (scev))
4353 return;
4355 base = initial_condition_in_loop_num (scev, loop->num);
4356 step = evolution_part_in_loop_num (scev, loop->num);
4358 if (!base || !step
4359 || TREE_CODE (step) != INTEGER_CST
4360 || tree_contains_chrecs (base, NULL)
4361 || chrec_contains_symbols_defined_in_loop (base, loop->num))
4362 return;
4364 low = lower_bound_in_type (type, type);
4365 high = upper_bound_in_type (type, type);
4366 Value_Range r (TREE_TYPE (def));
4367 get_range_query (cfun)->range_of_expr (r, def);
4368 if (r.kind () == VR_RANGE)
4370 low = wide_int_to_tree (type, r.lower_bound ());
4371 high = wide_int_to_tree (type, r.upper_bound ());
4374 record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
4377 /* The following analyzers are extracting informations on the bounds
4378 of LOOP from the following undefined behaviors:
4380 - data references should not access elements over the statically
4381 allocated size,
4383 - signed variables should not overflow when flag_wrapv is not set.
4386 static void
4387 infer_loop_bounds_from_undefined (class loop *loop, basic_block *bbs)
4389 unsigned i;
4390 gimple_stmt_iterator bsi;
4391 basic_block bb;
4392 bool reliable;
4394 for (i = 0; i < loop->num_nodes; i++)
4396 bb = bbs[i];
4398 /* If BB is not executed in each iteration of the loop, we cannot
4399 use the operations in it to infer reliable upper bound on the
4400 # of iterations of the loop. However, we can use it as a guess.
4401 Reliable guesses come only from array bounds. */
4402 reliable = dominated_by_p (CDI_DOMINATORS, loop->latch, bb);
4404 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
4406 gimple *stmt = gsi_stmt (bsi);
4408 infer_loop_bounds_from_array (loop, stmt);
4410 if (reliable)
4412 infer_loop_bounds_from_signedness (loop, stmt);
4413 infer_loop_bounds_from_pointer_arith (loop, stmt);
4420 /* Compare wide ints, callback for qsort. */
4422 static int
4423 wide_int_cmp (const void *p1, const void *p2)
4425 const widest_int *d1 = (const widest_int *) p1;
4426 const widest_int *d2 = (const widest_int *) p2;
4427 return wi::cmpu (*d1, *d2);
4430 /* Return index of BOUND in BOUNDS array sorted in increasing order.
4431 Lookup by binary search. */
4433 static int
4434 bound_index (const vec<widest_int> &bounds, const widest_int &bound)
4436 unsigned int end = bounds.length ();
4437 unsigned int begin = 0;
4439 /* Find a matching index by means of a binary search. */
4440 while (begin != end)
4442 unsigned int middle = (begin + end) / 2;
4443 widest_int index = bounds[middle];
4445 if (index == bound)
4446 return middle;
4447 else if (wi::ltu_p (index, bound))
4448 begin = middle + 1;
4449 else
4450 end = middle;
4452 gcc_unreachable ();
4455 /* We recorded loop bounds only for statements dominating loop latch (and thus
4456 executed each loop iteration). If there are any bounds on statements not
4457 dominating the loop latch we can improve the estimate by walking the loop
4458 body and seeing if every path from loop header to loop latch contains
4459 some bounded statement. */
4461 static void
4462 discover_iteration_bound_by_body_walk (class loop *loop)
4464 class nb_iter_bound *elt;
4465 auto_vec<widest_int> bounds;
4466 vec<vec<basic_block> > queues = vNULL;
4467 vec<basic_block> queue = vNULL;
4468 ptrdiff_t queue_index;
4469 ptrdiff_t latch_index = 0;
4471 /* Discover what bounds may interest us. */
4472 for (elt = loop->bounds; elt; elt = elt->next)
4474 widest_int bound = elt->bound;
4476 /* Exit terminates loop at given iteration, while non-exits produce undefined
4477 effect on the next iteration. */
4478 if (!elt->is_exit)
4480 bound += 1;
4481 /* If an overflow occurred, ignore the result. */
4482 if (bound == 0)
4483 continue;
4486 if (!loop->any_upper_bound
4487 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
4488 bounds.safe_push (bound);
4491 /* Exit early if there is nothing to do. */
4492 if (!bounds.exists ())
4493 return;
4495 if (dump_file && (dump_flags & TDF_DETAILS))
4496 fprintf (dump_file, " Trying to walk loop body to reduce the bound.\n");
4498 /* Sort the bounds in decreasing order. */
4499 bounds.qsort (wide_int_cmp);
4501 /* For every basic block record the lowest bound that is guaranteed to
4502 terminate the loop. */
4504 hash_map<basic_block, ptrdiff_t> bb_bounds;
4505 for (elt = loop->bounds; elt; elt = elt->next)
4507 widest_int bound = elt->bound;
4508 if (!elt->is_exit)
4510 bound += 1;
4511 /* If an overflow occurred, ignore the result. */
4512 if (bound == 0)
4513 continue;
4516 if (!loop->any_upper_bound
4517 || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
4519 ptrdiff_t index = bound_index (bounds, bound);
4520 ptrdiff_t *entry = bb_bounds.get (gimple_bb (elt->stmt));
4521 if (!entry)
4522 bb_bounds.put (gimple_bb (elt->stmt), index);
4523 else if ((ptrdiff_t)*entry > index)
4524 *entry = index;
4528 hash_map<basic_block, ptrdiff_t> block_priority;
4530 /* Perform shortest path discovery loop->header ... loop->latch.
4532 The "distance" is given by the smallest loop bound of basic block
4533 present in the path and we look for path with largest smallest bound
4534 on it.
4536 To avoid the need for fibonacci heap on double ints we simply compress
4537 double ints into indexes to BOUNDS array and then represent the queue
4538 as arrays of queues for every index.
4539 Index of BOUNDS.length() means that the execution of given BB has
4540 no bounds determined.
4542 VISITED is a pointer map translating basic block into smallest index
4543 it was inserted into the priority queue with. */
4544 latch_index = -1;
4546 /* Start walk in loop header with index set to infinite bound. */
4547 queue_index = bounds.length ();
4548 queues.safe_grow_cleared (queue_index + 1, true);
4549 queue.safe_push (loop->header);
4550 queues[queue_index] = queue;
4551 block_priority.put (loop->header, queue_index);
4553 for (; queue_index >= 0; queue_index--)
4555 if (latch_index < queue_index)
4557 while (queues[queue_index].length ())
4559 basic_block bb;
4560 ptrdiff_t bound_index = queue_index;
4561 edge e;
4562 edge_iterator ei;
4564 queue = queues[queue_index];
4565 bb = queue.pop ();
4567 /* OK, we later inserted the BB with lower priority, skip it. */
4568 if (*block_priority.get (bb) > queue_index)
4569 continue;
4571 /* See if we can improve the bound. */
4572 ptrdiff_t *entry = bb_bounds.get (bb);
4573 if (entry && *entry < bound_index)
4574 bound_index = *entry;
4576 /* Insert succesors into the queue, watch for latch edge
4577 and record greatest index we saw. */
4578 FOR_EACH_EDGE (e, ei, bb->succs)
4580 bool insert = false;
4582 if (loop_exit_edge_p (loop, e))
4583 continue;
4585 if (e == loop_latch_edge (loop)
4586 && latch_index < bound_index)
4587 latch_index = bound_index;
4588 else if (!(entry = block_priority.get (e->dest)))
4590 insert = true;
4591 block_priority.put (e->dest, bound_index);
4593 else if (*entry < bound_index)
4595 insert = true;
4596 *entry = bound_index;
4599 if (insert)
4600 queues[bound_index].safe_push (e->dest);
4604 queues[queue_index].release ();
4607 gcc_assert (latch_index >= 0);
4608 if ((unsigned)latch_index < bounds.length ())
4610 if (dump_file && (dump_flags & TDF_DETAILS))
4612 fprintf (dump_file, "Found better loop bound ");
4613 print_decu (bounds[latch_index], dump_file);
4614 fprintf (dump_file, "\n");
4616 record_niter_bound (loop, bounds[latch_index], false, true);
4619 queues.release ();
4622 /* See if every path cross the loop goes through a statement that is known
4623 to not execute at the last iteration. In that case we can decrese iteration
4624 count by 1. */
4626 static void
4627 maybe_lower_iteration_bound (class loop *loop)
4629 hash_set<gimple *> *not_executed_last_iteration = NULL;
4630 class nb_iter_bound *elt;
4631 bool found_exit = false;
4632 auto_vec<basic_block> queue;
4633 bitmap visited;
4635 /* Collect all statements with interesting (i.e. lower than
4636 nb_iterations_upper_bound) bound on them.
4638 TODO: Due to the way record_estimate choose estimates to store, the bounds
4639 will be always nb_iterations_upper_bound-1. We can change this to record
4640 also statements not dominating the loop latch and update the walk bellow
4641 to the shortest path algorithm. */
4642 for (elt = loop->bounds; elt; elt = elt->next)
4644 if (!elt->is_exit
4645 && wi::ltu_p (elt->bound, loop->nb_iterations_upper_bound))
4647 if (!not_executed_last_iteration)
4648 not_executed_last_iteration = new hash_set<gimple *>;
4649 not_executed_last_iteration->add (elt->stmt);
4652 if (!not_executed_last_iteration)
4653 return;
4655 /* Start DFS walk in the loop header and see if we can reach the
4656 loop latch or any of the exits (including statements with side
4657 effects that may terminate the loop otherwise) without visiting
4658 any of the statements known to have undefined effect on the last
4659 iteration. */
4660 queue.safe_push (loop->header);
4661 visited = BITMAP_ALLOC (NULL);
4662 bitmap_set_bit (visited, loop->header->index);
4663 found_exit = false;
4667 basic_block bb = queue.pop ();
4668 gimple_stmt_iterator gsi;
4669 bool stmt_found = false;
4671 /* Loop for possible exits and statements bounding the execution. */
4672 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4674 gimple *stmt = gsi_stmt (gsi);
4675 if (not_executed_last_iteration->contains (stmt))
4677 stmt_found = true;
4678 break;
4680 if (gimple_has_side_effects (stmt))
4682 found_exit = true;
4683 break;
4686 if (found_exit)
4687 break;
4689 /* If no bounding statement is found, continue the walk. */
4690 if (!stmt_found)
4692 edge e;
4693 edge_iterator ei;
4695 FOR_EACH_EDGE (e, ei, bb->succs)
4697 if (loop_exit_edge_p (loop, e)
4698 || e == loop_latch_edge (loop))
4700 found_exit = true;
4701 break;
4703 if (bitmap_set_bit (visited, e->dest->index))
4704 queue.safe_push (e->dest);
4708 while (queue.length () && !found_exit);
4710 /* If every path through the loop reach bounding statement before exit,
4711 then we know the last iteration of the loop will have undefined effect
4712 and we can decrease number of iterations. */
4714 if (!found_exit)
4716 if (dump_file && (dump_flags & TDF_DETAILS))
4717 fprintf (dump_file, "Reducing loop iteration estimate by 1; "
4718 "undefined statement must be executed at the last iteration.\n");
4719 record_niter_bound (loop, loop->nb_iterations_upper_bound - 1,
4720 false, true);
4723 BITMAP_FREE (visited);
4724 delete not_executed_last_iteration;
4727 /* Get expected upper bound for number of loop iterations for
4728 BUILT_IN_EXPECT_WITH_PROBABILITY for a condition COND. */
4730 static tree
4731 get_upper_bound_based_on_builtin_expr_with_prob (gcond *cond)
4733 if (cond == NULL)
4734 return NULL_TREE;
4736 tree lhs = gimple_cond_lhs (cond);
4737 if (TREE_CODE (lhs) != SSA_NAME)
4738 return NULL_TREE;
4740 gimple *stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (cond));
4741 gcall *def = dyn_cast<gcall *> (stmt);
4742 if (def == NULL)
4743 return NULL_TREE;
4745 tree decl = gimple_call_fndecl (def);
4746 if (!decl
4747 || !fndecl_built_in_p (decl, BUILT_IN_EXPECT_WITH_PROBABILITY)
4748 || gimple_call_num_args (stmt) != 3)
4749 return NULL_TREE;
4751 tree c = gimple_call_arg (def, 1);
4752 tree condt = TREE_TYPE (lhs);
4753 tree res = fold_build2 (gimple_cond_code (cond),
4754 condt, c,
4755 gimple_cond_rhs (cond));
4756 if (TREE_CODE (res) != INTEGER_CST)
4757 return NULL_TREE;
4760 tree prob = gimple_call_arg (def, 2);
4761 tree t = TREE_TYPE (prob);
4762 tree one
4763 = build_real_from_int_cst (t,
4764 integer_one_node);
4765 if (integer_zerop (res))
4766 prob = fold_build2 (MINUS_EXPR, t, one, prob);
4767 tree r = fold_build2 (RDIV_EXPR, t, one, prob);
4768 if (TREE_CODE (r) != REAL_CST)
4769 return NULL_TREE;
4771 HOST_WIDE_INT probi
4772 = real_to_integer (TREE_REAL_CST_PTR (r));
4773 return build_int_cst (condt, probi);
4776 /* Records estimates on numbers of iterations of LOOP. If USE_UNDEFINED_P
4777 is true also use estimates derived from undefined behavior. */
4779 void
4780 estimate_numbers_of_iterations (class loop *loop)
4782 tree niter, type;
4783 unsigned i;
4784 class tree_niter_desc niter_desc;
4785 edge ex;
4786 widest_int bound;
4787 edge likely_exit;
4789 /* Give up if we already have tried to compute an estimation. */
4790 if (loop->estimate_state != EST_NOT_COMPUTED)
4791 return;
4793 if (dump_file && (dump_flags & TDF_DETAILS))
4794 fprintf (dump_file, "Estimating # of iterations of loop %d\n", loop->num);
4796 loop->estimate_state = EST_AVAILABLE;
4798 /* If we have a measured profile, use it to estimate the number of
4799 iterations. Normally this is recorded by branch_prob right after
4800 reading the profile. In case we however found a new loop, record the
4801 information here.
4803 Explicitly check for profile status so we do not report
4804 wrong prediction hitrates for guessed loop iterations heuristics.
4805 Do not recompute already recorded bounds - we ought to be better on
4806 updating iteration bounds than updating profile in general and thus
4807 recomputing iteration bounds later in the compilation process will just
4808 introduce random roundoff errors. */
4809 if (!loop->any_estimate
4810 && loop->header->count.reliable_p ())
4812 gcov_type nit = expected_loop_iterations_unbounded (loop);
4813 bound = gcov_type_to_wide_int (nit);
4814 record_niter_bound (loop, bound, true, false);
4817 /* Ensure that loop->nb_iterations is computed if possible. If it turns out
4818 to be constant, we avoid undefined behavior implied bounds and instead
4819 diagnose those loops with -Waggressive-loop-optimizations. */
4820 number_of_latch_executions (loop);
4822 basic_block *body = get_loop_body (loop);
4823 auto_vec<edge> exits = get_loop_exit_edges (loop, body);
4824 likely_exit = single_likely_exit (loop, exits);
4825 FOR_EACH_VEC_ELT (exits, i, ex)
4827 if (ex == likely_exit)
4829 gimple *stmt = last_stmt (ex->src);
4830 if (stmt != NULL)
4832 gcond *cond = dyn_cast<gcond *> (stmt);
4833 tree niter_bound
4834 = get_upper_bound_based_on_builtin_expr_with_prob (cond);
4835 if (niter_bound != NULL_TREE)
4837 widest_int max = derive_constant_upper_bound (niter_bound);
4838 record_estimate (loop, niter_bound, max, cond,
4839 true, true, false);
4844 if (!number_of_iterations_exit (loop, ex, &niter_desc,
4845 false, false, body))
4846 continue;
4848 niter = niter_desc.niter;
4849 type = TREE_TYPE (niter);
4850 if (TREE_CODE (niter_desc.may_be_zero) != INTEGER_CST)
4851 niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
4852 build_int_cst (type, 0),
4853 niter);
4854 record_estimate (loop, niter, niter_desc.max,
4855 last_stmt (ex->src),
4856 true, ex == likely_exit, true);
4857 record_control_iv (loop, &niter_desc);
4860 if (flag_aggressive_loop_optimizations)
4861 infer_loop_bounds_from_undefined (loop, body);
4862 free (body);
4864 discover_iteration_bound_by_body_walk (loop);
4866 maybe_lower_iteration_bound (loop);
4868 /* If we know the exact number of iterations of this loop, try to
4869 not break code with undefined behavior by not recording smaller
4870 maximum number of iterations. */
4871 if (loop->nb_iterations
4872 && TREE_CODE (loop->nb_iterations) == INTEGER_CST)
4874 loop->any_upper_bound = true;
4875 loop->nb_iterations_upper_bound = wi::to_widest (loop->nb_iterations);
4879 /* Sets NIT to the estimated number of executions of the latch of the
4880 LOOP. If CONSERVATIVE is true, we must be sure that NIT is at least as
4881 large as the number of iterations. If we have no reliable estimate,
4882 the function returns false, otherwise returns true. */
4884 bool
4885 estimated_loop_iterations (class loop *loop, widest_int *nit)
4887 /* When SCEV information is available, try to update loop iterations
4888 estimate. Otherwise just return whatever we recorded earlier. */
4889 if (scev_initialized_p ())
4890 estimate_numbers_of_iterations (loop);
4892 return (get_estimated_loop_iterations (loop, nit));
4895 /* Similar to estimated_loop_iterations, but returns the estimate only
4896 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
4897 on the number of iterations of LOOP could not be derived, returns -1. */
4899 HOST_WIDE_INT
4900 estimated_loop_iterations_int (class loop *loop)
4902 widest_int nit;
4903 HOST_WIDE_INT hwi_nit;
4905 if (!estimated_loop_iterations (loop, &nit))
4906 return -1;
4908 if (!wi::fits_shwi_p (nit))
4909 return -1;
4910 hwi_nit = nit.to_shwi ();
4912 return hwi_nit < 0 ? -1 : hwi_nit;
4916 /* Sets NIT to an upper bound for the maximum number of executions of the
4917 latch of the LOOP. If we have no reliable estimate, the function returns
4918 false, otherwise returns true. */
4920 bool
4921 max_loop_iterations (class loop *loop, widest_int *nit)
4923 /* When SCEV information is available, try to update loop iterations
4924 estimate. Otherwise just return whatever we recorded earlier. */
4925 if (scev_initialized_p ())
4926 estimate_numbers_of_iterations (loop);
4928 return get_max_loop_iterations (loop, nit);
4931 /* Similar to max_loop_iterations, but returns the estimate only
4932 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
4933 on the number of iterations of LOOP could not be derived, returns -1. */
4935 HOST_WIDE_INT
4936 max_loop_iterations_int (class loop *loop)
4938 widest_int nit;
4939 HOST_WIDE_INT hwi_nit;
4941 if (!max_loop_iterations (loop, &nit))
4942 return -1;
4944 if (!wi::fits_shwi_p (nit))
4945 return -1;
4946 hwi_nit = nit.to_shwi ();
4948 return hwi_nit < 0 ? -1 : hwi_nit;
4951 /* Sets NIT to an likely upper bound for the maximum number of executions of the
4952 latch of the LOOP. If we have no reliable estimate, the function returns
4953 false, otherwise returns true. */
4955 bool
4956 likely_max_loop_iterations (class loop *loop, widest_int *nit)
4958 /* When SCEV information is available, try to update loop iterations
4959 estimate. Otherwise just return whatever we recorded earlier. */
4960 if (scev_initialized_p ())
4961 estimate_numbers_of_iterations (loop);
4963 return get_likely_max_loop_iterations (loop, nit);
4966 /* Similar to max_loop_iterations, but returns the estimate only
4967 if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
4968 on the number of iterations of LOOP could not be derived, returns -1. */
4970 HOST_WIDE_INT
4971 likely_max_loop_iterations_int (class loop *loop)
4973 widest_int nit;
4974 HOST_WIDE_INT hwi_nit;
4976 if (!likely_max_loop_iterations (loop, &nit))
4977 return -1;
4979 if (!wi::fits_shwi_p (nit))
4980 return -1;
4981 hwi_nit = nit.to_shwi ();
4983 return hwi_nit < 0 ? -1 : hwi_nit;
4986 /* Returns an estimate for the number of executions of statements
4987 in the LOOP. For statements before the loop exit, this exceeds
4988 the number of execution of the latch by one. */
4990 HOST_WIDE_INT
4991 estimated_stmt_executions_int (class loop *loop)
4993 HOST_WIDE_INT nit = estimated_loop_iterations_int (loop);
4994 HOST_WIDE_INT snit;
4996 if (nit == -1)
4997 return -1;
4999 snit = (HOST_WIDE_INT) ((unsigned HOST_WIDE_INT) nit + 1);
5001 /* If the computation overflows, return -1. */
5002 return snit < 0 ? -1 : snit;
5005 /* Sets NIT to the maximum number of executions of the latch of the
5006 LOOP, plus one. If we have no reliable estimate, the function returns
5007 false, otherwise returns true. */
5009 bool
5010 max_stmt_executions (class loop *loop, widest_int *nit)
5012 widest_int nit_minus_one;
5014 if (!max_loop_iterations (loop, nit))
5015 return false;
5017 nit_minus_one = *nit;
5019 *nit += 1;
5021 return wi::gtu_p (*nit, nit_minus_one);
5024 /* Sets NIT to the estimated maximum number of executions of the latch of the
5025 LOOP, plus one. If we have no likely estimate, the function returns
5026 false, otherwise returns true. */
5028 bool
5029 likely_max_stmt_executions (class loop *loop, widest_int *nit)
5031 widest_int nit_minus_one;
5033 if (!likely_max_loop_iterations (loop, nit))
5034 return false;
5036 nit_minus_one = *nit;
5038 *nit += 1;
5040 return wi::gtu_p (*nit, nit_minus_one);
5043 /* Sets NIT to the estimated number of executions of the latch of the
5044 LOOP, plus one. If we have no reliable estimate, the function returns
5045 false, otherwise returns true. */
5047 bool
5048 estimated_stmt_executions (class loop *loop, widest_int *nit)
5050 widest_int nit_minus_one;
5052 if (!estimated_loop_iterations (loop, nit))
5053 return false;
5055 nit_minus_one = *nit;
5057 *nit += 1;
5059 return wi::gtu_p (*nit, nit_minus_one);
5062 /* Records estimates on numbers of iterations of loops. */
5064 void
5065 estimate_numbers_of_iterations (function *fn)
5067 /* We don't want to issue signed overflow warnings while getting
5068 loop iteration estimates. */
5069 fold_defer_overflow_warnings ();
5071 for (auto loop : loops_list (fn, 0))
5072 estimate_numbers_of_iterations (loop);
5074 fold_undefer_and_ignore_overflow_warnings ();
5077 /* Returns true if statement S1 dominates statement S2. */
5079 bool
5080 stmt_dominates_stmt_p (gimple *s1, gimple *s2)
5082 basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
5084 if (!bb1
5085 || s1 == s2)
5086 return true;
5088 if (bb1 == bb2)
5090 gimple_stmt_iterator bsi;
5092 if (gimple_code (s2) == GIMPLE_PHI)
5093 return false;
5095 if (gimple_code (s1) == GIMPLE_PHI)
5096 return true;
5098 for (bsi = gsi_start_bb (bb1); gsi_stmt (bsi) != s2; gsi_next (&bsi))
5099 if (gsi_stmt (bsi) == s1)
5100 return true;
5102 return false;
5105 return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
5108 /* Returns true when we can prove that the number of executions of
5109 STMT in the loop is at most NITER, according to the bound on
5110 the number of executions of the statement NITER_BOUND->stmt recorded in
5111 NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
5113 ??? This code can become quite a CPU hog - we can have many bounds,
5114 and large basic block forcing stmt_dominates_stmt_p to be queried
5115 many times on a large basic blocks, so the whole thing is O(n^2)
5116 for scev_probably_wraps_p invocation (that can be done n times).
5118 It would make more sense (and give better answers) to remember BB
5119 bounds computed by discover_iteration_bound_by_body_walk. */
5121 static bool
5122 n_of_executions_at_most (gimple *stmt,
5123 class nb_iter_bound *niter_bound,
5124 tree niter)
5126 widest_int bound = niter_bound->bound;
5127 tree nit_type = TREE_TYPE (niter), e;
5128 enum tree_code cmp;
5130 gcc_assert (TYPE_UNSIGNED (nit_type));
5132 /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
5133 the number of iterations is small. */
5134 if (!wi::fits_to_tree_p (bound, nit_type))
5135 return false;
5137 /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
5138 times. This means that:
5140 -- if NITER_BOUND->is_exit is true, then everything after
5141 it at most NITER_BOUND->bound times.
5143 -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
5144 is executed, then NITER_BOUND->stmt is executed as well in the same
5145 iteration then STMT is executed at most NITER_BOUND->bound + 1 times.
5147 If we can determine that NITER_BOUND->stmt is always executed
5148 after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
5149 We conclude that if both statements belong to the same
5150 basic block and STMT is before NITER_BOUND->stmt and there are no
5151 statements with side effects in between. */
5153 if (niter_bound->is_exit)
5155 if (stmt == niter_bound->stmt
5156 || !stmt_dominates_stmt_p (niter_bound->stmt, stmt))
5157 return false;
5158 cmp = GE_EXPR;
5160 else
5162 if (!stmt_dominates_stmt_p (niter_bound->stmt, stmt))
5164 gimple_stmt_iterator bsi;
5165 if (gimple_bb (stmt) != gimple_bb (niter_bound->stmt)
5166 || gimple_code (stmt) == GIMPLE_PHI
5167 || gimple_code (niter_bound->stmt) == GIMPLE_PHI)
5168 return false;
5170 /* By stmt_dominates_stmt_p we already know that STMT appears
5171 before NITER_BOUND->STMT. Still need to test that the loop
5172 cannot be terinated by a side effect in between. */
5173 for (bsi = gsi_for_stmt (stmt); gsi_stmt (bsi) != niter_bound->stmt;
5174 gsi_next (&bsi))
5175 if (gimple_has_side_effects (gsi_stmt (bsi)))
5176 return false;
5177 bound += 1;
5178 if (bound == 0
5179 || !wi::fits_to_tree_p (bound, nit_type))
5180 return false;
5182 cmp = GT_EXPR;
5185 e = fold_binary (cmp, boolean_type_node,
5186 niter, wide_int_to_tree (nit_type, bound));
5187 return e && integer_nonzerop (e);
5190 /* Returns true if the arithmetics in TYPE can be assumed not to wrap. */
5192 bool
5193 nowrap_type_p (tree type)
5195 if (ANY_INTEGRAL_TYPE_P (type)
5196 && TYPE_OVERFLOW_UNDEFINED (type))
5197 return true;
5199 if (POINTER_TYPE_P (type))
5200 return true;
5202 return false;
5205 /* Return true if we can prove LOOP is exited before evolution of induction
5206 variable {BASE, STEP} overflows with respect to its type bound. */
5208 static bool
5209 loop_exits_before_overflow (tree base, tree step,
5210 gimple *at_stmt, class loop *loop)
5212 widest_int niter;
5213 struct control_iv *civ;
5214 class nb_iter_bound *bound;
5215 tree e, delta, step_abs, unsigned_base;
5216 tree type = TREE_TYPE (step);
5217 tree unsigned_type, valid_niter;
5219 /* Don't issue signed overflow warnings. */
5220 fold_defer_overflow_warnings ();
5222 /* Compute the number of iterations before we reach the bound of the
5223 type, and verify that the loop is exited before this occurs. */
5224 unsigned_type = unsigned_type_for (type);
5225 unsigned_base = fold_convert (unsigned_type, base);
5227 if (tree_int_cst_sign_bit (step))
5229 tree extreme = fold_convert (unsigned_type,
5230 lower_bound_in_type (type, type));
5231 delta = fold_build2 (MINUS_EXPR, unsigned_type, unsigned_base, extreme);
5232 step_abs = fold_build1 (NEGATE_EXPR, unsigned_type,
5233 fold_convert (unsigned_type, step));
5235 else
5237 tree extreme = fold_convert (unsigned_type,
5238 upper_bound_in_type (type, type));
5239 delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, unsigned_base);
5240 step_abs = fold_convert (unsigned_type, step);
5243 valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
5245 estimate_numbers_of_iterations (loop);
5247 if (max_loop_iterations (loop, &niter)
5248 && wi::fits_to_tree_p (niter, TREE_TYPE (valid_niter))
5249 && (e = fold_binary (GT_EXPR, boolean_type_node, valid_niter,
5250 wide_int_to_tree (TREE_TYPE (valid_niter),
5251 niter))) != NULL
5252 && integer_nonzerop (e))
5254 fold_undefer_and_ignore_overflow_warnings ();
5255 return true;
5257 if (at_stmt)
5258 for (bound = loop->bounds; bound; bound = bound->next)
5260 if (n_of_executions_at_most (at_stmt, bound, valid_niter))
5262 fold_undefer_and_ignore_overflow_warnings ();
5263 return true;
5266 fold_undefer_and_ignore_overflow_warnings ();
5268 /* Try to prove loop is exited before {base, step} overflows with the
5269 help of analyzed loop control IV. This is done only for IVs with
5270 constant step because otherwise we don't have the information. */
5271 if (TREE_CODE (step) == INTEGER_CST)
5273 for (civ = loop->control_ivs; civ; civ = civ->next)
5275 enum tree_code code;
5276 tree civ_type = TREE_TYPE (civ->step);
5278 /* Have to consider type difference because operand_equal_p ignores
5279 that for constants. */
5280 if (TYPE_UNSIGNED (type) != TYPE_UNSIGNED (civ_type)
5281 || element_precision (type) != element_precision (civ_type))
5282 continue;
5284 /* Only consider control IV with same step. */
5285 if (!operand_equal_p (step, civ->step, 0))
5286 continue;
5288 /* Done proving if this is a no-overflow control IV. */
5289 if (operand_equal_p (base, civ->base, 0))
5290 return true;
5292 /* Control IV is recorded after expanding simple operations,
5293 Here we expand base and compare it too. */
5294 tree expanded_base = expand_simple_operations (base);
5295 if (operand_equal_p (expanded_base, civ->base, 0))
5296 return true;
5298 /* If this is a before stepping control IV, in other words, we have
5300 {civ_base, step} = {base + step, step}
5302 Because civ {base + step, step} doesn't overflow during loop
5303 iterations, {base, step} will not overflow if we can prove the
5304 operation "base + step" does not overflow. Specifically, we try
5305 to prove below conditions are satisfied:
5307 base <= UPPER_BOUND (type) - step ;;step > 0
5308 base >= LOWER_BOUND (type) - step ;;step < 0
5310 by proving the reverse conditions are false using loop's initial
5311 condition. */
5312 if (POINTER_TYPE_P (TREE_TYPE (base)))
5313 code = POINTER_PLUS_EXPR;
5314 else
5315 code = PLUS_EXPR;
5317 tree stepped = fold_build2 (code, TREE_TYPE (base), base, step);
5318 tree expanded_stepped = fold_build2 (code, TREE_TYPE (base),
5319 expanded_base, step);
5320 if (operand_equal_p (stepped, civ->base, 0)
5321 || operand_equal_p (expanded_stepped, civ->base, 0))
5323 tree extreme;
5325 if (tree_int_cst_sign_bit (step))
5327 code = LT_EXPR;
5328 extreme = lower_bound_in_type (type, type);
5330 else
5332 code = GT_EXPR;
5333 extreme = upper_bound_in_type (type, type);
5335 extreme = fold_build2 (MINUS_EXPR, type, extreme, step);
5336 e = fold_build2 (code, boolean_type_node, base, extreme);
5337 e = simplify_using_initial_conditions (loop, e);
5338 if (integer_zerop (e))
5339 return true;
5344 return false;
5347 /* VAR is scev variable whose evolution part is constant STEP, this function
5348 proves that VAR can't overflow by using value range info. If VAR's value
5349 range is [MIN, MAX], it can be proven by:
5350 MAX + step doesn't overflow ; if step > 0
5352 MIN + step doesn't underflow ; if step < 0.
5354 We can only do this if var is computed in every loop iteration, i.e, var's
5355 definition has to dominate loop latch. Consider below example:
5358 unsigned int i;
5360 <bb 3>:
5362 <bb 4>:
5363 # RANGE [0, 4294967294] NONZERO 65535
5364 # i_21 = PHI <0(3), i_18(9)>
5365 if (i_21 != 0)
5366 goto <bb 6>;
5367 else
5368 goto <bb 8>;
5370 <bb 6>:
5371 # RANGE [0, 65533] NONZERO 65535
5372 _6 = i_21 + 4294967295;
5373 # RANGE [0, 65533] NONZERO 65535
5374 _7 = (long unsigned int) _6;
5375 # RANGE [0, 524264] NONZERO 524280
5376 _8 = _7 * 8;
5377 # PT = nonlocal escaped
5378 _9 = a_14 + _8;
5379 *_9 = 0;
5381 <bb 8>:
5382 # RANGE [1, 65535] NONZERO 65535
5383 i_18 = i_21 + 1;
5384 if (i_18 >= 65535)
5385 goto <bb 10>;
5386 else
5387 goto <bb 9>;
5389 <bb 9>:
5390 goto <bb 4>;
5392 <bb 10>:
5393 return;
5396 VAR _6 doesn't overflow only with pre-condition (i_21 != 0), here we
5397 can't use _6 to prove no-overlfow for _7. In fact, var _7 takes value
5398 sequence (4294967295, 0, 1, ..., 65533) in loop life time, rather than
5399 (4294967295, 4294967296, ...). */
5401 static bool
5402 scev_var_range_cant_overflow (tree var, tree step, class loop *loop)
5404 tree type;
5405 wide_int minv, maxv, diff, step_wi;
5407 if (TREE_CODE (step) != INTEGER_CST || !INTEGRAL_TYPE_P (TREE_TYPE (var)))
5408 return false;
5410 /* Check if VAR evaluates in every loop iteration. It's not the case
5411 if VAR is default definition or does not dominate loop's latch. */
5412 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
5413 if (!def_bb || !dominated_by_p (CDI_DOMINATORS, loop->latch, def_bb))
5414 return false;
5416 Value_Range r (TREE_TYPE (var));
5417 get_range_query (cfun)->range_of_expr (r, var);
5418 if (r.kind () != VR_RANGE)
5419 return false;
5421 /* VAR is a scev whose evolution part is STEP and value range info
5422 is [MIN, MAX], we can prove its no-overflowness by conditions:
5424 type_MAX - MAX >= step ; if step > 0
5425 MIN - type_MIN >= |step| ; if step < 0.
5427 Or VAR must take value outside of value range, which is not true. */
5428 step_wi = wi::to_wide (step);
5429 type = TREE_TYPE (var);
5430 if (tree_int_cst_sign_bit (step))
5432 diff = r.lower_bound () - wi::to_wide (lower_bound_in_type (type, type));
5433 step_wi = - step_wi;
5435 else
5436 diff = wi::to_wide (upper_bound_in_type (type, type)) - r.upper_bound ();
5438 return (wi::geu_p (diff, step_wi));
5441 /* Return false only when the induction variable BASE + STEP * I is
5442 known to not overflow: i.e. when the number of iterations is small
5443 enough with respect to the step and initial condition in order to
5444 keep the evolution confined in TYPEs bounds. Return true when the
5445 iv is known to overflow or when the property is not computable.
5447 USE_OVERFLOW_SEMANTICS is true if this function should assume that
5448 the rules for overflow of the given language apply (e.g., that signed
5449 arithmetics in C does not overflow).
5451 If VAR is a ssa variable, this function also returns false if VAR can
5452 be proven not overflow with value range info. */
5454 bool
5455 scev_probably_wraps_p (tree var, tree base, tree step,
5456 gimple *at_stmt, class loop *loop,
5457 bool use_overflow_semantics)
5459 /* FIXME: We really need something like
5460 http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
5462 We used to test for the following situation that frequently appears
5463 during address arithmetics:
5465 D.1621_13 = (long unsigned intD.4) D.1620_12;
5466 D.1622_14 = D.1621_13 * 8;
5467 D.1623_15 = (doubleD.29 *) D.1622_14;
5469 And derived that the sequence corresponding to D_14
5470 can be proved to not wrap because it is used for computing a
5471 memory access; however, this is not really the case -- for example,
5472 if D_12 = (unsigned char) [254,+,1], then D_14 has values
5473 2032, 2040, 0, 8, ..., but the code is still legal. */
5475 if (chrec_contains_undetermined (base)
5476 || chrec_contains_undetermined (step))
5477 return true;
5479 if (integer_zerop (step))
5480 return false;
5482 /* If we can use the fact that signed and pointer arithmetics does not
5483 wrap, we are done. */
5484 if (use_overflow_semantics && nowrap_type_p (TREE_TYPE (base)))
5485 return false;
5487 /* To be able to use estimates on number of iterations of the loop,
5488 we must have an upper bound on the absolute value of the step. */
5489 if (TREE_CODE (step) != INTEGER_CST)
5490 return true;
5492 /* Check if var can be proven not overflow with value range info. */
5493 if (var && TREE_CODE (var) == SSA_NAME
5494 && scev_var_range_cant_overflow (var, step, loop))
5495 return false;
5497 if (loop_exits_before_overflow (base, step, at_stmt, loop))
5498 return false;
5500 /* At this point we still don't have a proof that the iv does not
5501 overflow: give up. */
5502 return true;
5505 /* Frees the information on upper bounds on numbers of iterations of LOOP. */
5507 void
5508 free_numbers_of_iterations_estimates (class loop *loop)
5510 struct control_iv *civ;
5511 class nb_iter_bound *bound;
5513 loop->nb_iterations = NULL;
5514 loop->estimate_state = EST_NOT_COMPUTED;
5515 for (bound = loop->bounds; bound;)
5517 class nb_iter_bound *next = bound->next;
5518 ggc_free (bound);
5519 bound = next;
5521 loop->bounds = NULL;
5523 for (civ = loop->control_ivs; civ;)
5525 struct control_iv *next = civ->next;
5526 ggc_free (civ);
5527 civ = next;
5529 loop->control_ivs = NULL;
5532 /* Frees the information on upper bounds on numbers of iterations of loops. */
5534 void
5535 free_numbers_of_iterations_estimates (function *fn)
5537 for (auto loop : loops_list (fn, 0))
5538 free_numbers_of_iterations_estimates (loop);
5541 /* Substitute value VAL for ssa name NAME inside expressions held
5542 at LOOP. */
5544 void
5545 substitute_in_loop_info (class loop *loop, tree name, tree val)
5547 loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);