Line data Source code
1 : /* Functions to determine/estimate number of iterations of a loop.
2 : Copyright (C) 2004-2026 Free Software Foundation, Inc.
3 :
4 : This file is part of GCC.
5 :
6 : GCC is free software; you can redistribute it and/or modify it
7 : under the terms of the GNU General Public License as published by the
8 : Free Software Foundation; either version 3, or (at your option) any
9 : later version.
10 :
11 : GCC is distributed in the hope that it will be useful, but WITHOUT
12 : ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 : FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 : for more details.
15 :
16 : You should have received a copy of the GNU General Public License
17 : along with GCC; see the file COPYING3. If not see
18 : <http://www.gnu.org/licenses/>. */
19 :
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 "gimple-iterator.h"
36 : #include "tree-cfg.h"
37 : #include "tree-ssa-loop-ivopts.h"
38 : #include "tree-ssa-loop-niter.h"
39 : #include "tree-ssa-loop.h"
40 : #include "cfgloop.h"
41 : #include "tree-chrec.h"
42 : #include "tree-scalar-evolution.h"
43 : #include "tree-data-ref.h"
44 : #include "tree-dfa.h"
45 : #include "internal-fn.h"
46 : #include "gimple-range.h"
47 : #include "sreal.h"
48 :
49 :
50 : /*
51 :
52 : Analysis of number of iterations of an affine exit test.
53 :
54 : */
55 :
56 : /* Bounds on some value, BELOW <= X <= UP. */
57 :
58 : struct bounds
59 : {
60 : mpz_t below, up;
61 : };
62 :
63 : /* Splits expression EXPR to a variable part VAR and constant OFFSET. */
64 :
65 : static void
66 59830540 : split_to_var_and_offset (tree expr, tree *var, mpz_t offset)
67 : {
68 59830540 : tree type = TREE_TYPE (expr);
69 59830540 : tree op0, op1;
70 59830540 : bool negate = false;
71 :
72 59830540 : *var = expr;
73 59830540 : mpz_set_ui (offset, 0);
74 :
75 59830540 : switch (TREE_CODE (expr))
76 : {
77 8046 : case MINUS_EXPR:
78 8046 : negate = true;
79 : /* Fallthru. */
80 :
81 6075637 : case PLUS_EXPR:
82 6075637 : case POINTER_PLUS_EXPR:
83 6075637 : op0 = TREE_OPERAND (expr, 0);
84 6075637 : op1 = TREE_OPERAND (expr, 1);
85 :
86 6075637 : if (TREE_CODE (op1) != INTEGER_CST)
87 : break;
88 :
89 6063971 : *var = op0;
90 : /* Always sign extend the offset. */
91 6063971 : wi::to_mpz (wi::to_wide (op1), offset, SIGNED);
92 6063971 : if (negate)
93 34 : mpz_neg (offset, offset);
94 : break;
95 :
96 26469198 : case INTEGER_CST:
97 26469198 : *var = build_int_cst_type (type, 0);
98 26469198 : wi::to_mpz (wi::to_wide (expr), offset, TYPE_SIGN (type));
99 26469198 : break;
100 :
101 : default:
102 : break;
103 : }
104 59830540 : }
105 :
106 : /* From condition C0 CMP C1 derives information regarding the value range
107 : of VAR, which is of TYPE. Results are stored in to BELOW and UP. */
108 :
109 : static void
110 21637664 : refine_value_range_using_guard (tree type, tree var,
111 : tree c0, enum tree_code cmp, tree c1,
112 : mpz_t below, mpz_t up)
113 : {
114 21637664 : tree varc0, varc1, ctype;
115 21637664 : mpz_t offc0, offc1;
116 21637664 : mpz_t mint, maxt, minc1, maxc1;
117 21637664 : bool no_wrap = nowrap_type_p (type);
118 21637664 : bool c0_ok, c1_ok;
119 21637664 : signop sgn = TYPE_SIGN (type);
120 :
121 21637664 : switch (cmp)
122 : {
123 10212301 : case LT_EXPR:
124 10212301 : case LE_EXPR:
125 10212301 : case GT_EXPR:
126 10212301 : case GE_EXPR:
127 10212301 : STRIP_SIGN_NOPS (c0);
128 10212301 : STRIP_SIGN_NOPS (c1);
129 10212301 : ctype = TREE_TYPE (c0);
130 10212301 : if (!useless_type_conversion_p (ctype, type))
131 18575642 : return;
132 :
133 : break;
134 :
135 : case EQ_EXPR:
136 : /* We could derive quite precise information from EQ_EXPR, however,
137 : such a guard is unlikely to appear, so we do not bother with
138 : handling it. */
139 : return;
140 :
141 5269647 : case NE_EXPR:
142 : /* NE_EXPR comparisons do not contain much of useful information,
143 : except for cases of comparing with bounds. */
144 5269647 : if (TREE_CODE (c1) != INTEGER_CST
145 4946490 : || !INTEGRAL_TYPE_P (type))
146 : return;
147 :
148 : /* Ensure that the condition speaks about an expression in the same
149 : type as X and Y. */
150 4946490 : ctype = TREE_TYPE (c0);
151 4946490 : if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
152 : return;
153 2973117 : c0 = fold_convert (type, c0);
154 2973117 : c1 = fold_convert (type, c1);
155 :
156 2973117 : if (operand_equal_p (var, c0, 0))
157 : {
158 : /* Case of comparing VAR with its below/up bounds. */
159 316103 : auto_mpz valc1;
160 316103 : wi::to_mpz (wi::to_wide (c1), valc1, TYPE_SIGN (type));
161 316103 : if (mpz_cmp (valc1, below) == 0)
162 97708 : cmp = GT_EXPR;
163 316103 : if (mpz_cmp (valc1, up) == 0)
164 49193 : cmp = LT_EXPR;
165 316103 : }
166 : else
167 : {
168 : /* Case of comparing with the bounds of the type. */
169 2657014 : wide_int min = wi::min_value (type);
170 2657014 : wide_int max = wi::max_value (type);
171 :
172 2657014 : if (wi::to_wide (c1) == min)
173 754777 : cmp = GT_EXPR;
174 2657014 : if (wi::to_wide (c1) == max)
175 32326 : cmp = LT_EXPR;
176 2657014 : }
177 :
178 : /* Quick return if no useful information. */
179 2973117 : if (cmp == NE_EXPR)
180 : return;
181 :
182 : break;
183 :
184 : default:
185 : return;
186 : }
187 :
188 9353890 : mpz_init (offc0);
189 9353890 : mpz_init (offc1);
190 9353890 : split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
191 9353890 : split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
192 :
193 : /* We are only interested in comparisons of expressions based on VAR. */
194 9353890 : if (operand_equal_p (var, varc1, 0))
195 : {
196 878192 : std::swap (varc0, varc1);
197 878192 : mpz_swap (offc0, offc1);
198 878192 : cmp = swap_tree_comparison (cmp);
199 : }
200 8475698 : else if (!operand_equal_p (var, varc0, 0))
201 : {
202 6291868 : mpz_clear (offc0);
203 6291868 : mpz_clear (offc1);
204 6291868 : return;
205 : }
206 :
207 3062022 : mpz_init (mint);
208 3062022 : mpz_init (maxt);
209 3062022 : get_type_static_bounds (type, mint, maxt);
210 3062022 : mpz_init (minc1);
211 3062022 : mpz_init (maxc1);
212 6124044 : int_range_max r (TREE_TYPE (varc1));
213 : /* Setup range information for varc1. */
214 3062022 : if (integer_zerop (varc1))
215 : {
216 1504353 : wi::to_mpz (0, minc1, TYPE_SIGN (type));
217 1504353 : wi::to_mpz (0, maxc1, TYPE_SIGN (type));
218 : }
219 1557669 : else if (TREE_CODE (varc1) == SSA_NAME
220 1460593 : && INTEGRAL_TYPE_P (type)
221 2921186 : && get_range_query (cfun)->range_of_expr (r, varc1)
222 1460593 : && !r.undefined_p ()
223 3015546 : && !r.varying_p ())
224 : {
225 1521514 : gcc_assert (wi::le_p (r.lower_bound (), r.upper_bound (), sgn));
226 760757 : wi::to_mpz (r.lower_bound (), minc1, sgn);
227 760757 : wi::to_mpz (r.upper_bound (), maxc1, sgn);
228 : }
229 : else
230 : {
231 796912 : mpz_set (minc1, mint);
232 796912 : mpz_set (maxc1, maxt);
233 : }
234 :
235 : /* Compute valid range information for varc1 + offc1. Note nothing
236 : useful can be derived if it overflows or underflows. Overflow or
237 : underflow could happen when:
238 :
239 : offc1 > 0 && varc1 + offc1 > MAX_VAL (type)
240 : offc1 < 0 && varc1 + offc1 < MIN_VAL (type). */
241 3062022 : mpz_add (minc1, minc1, offc1);
242 3062022 : mpz_add (maxc1, maxc1, offc1);
243 6124044 : c1_ok = (no_wrap
244 868665 : || mpz_sgn (offc1) == 0
245 134440 : || (mpz_sgn (offc1) < 0 && mpz_cmp (minc1, mint) >= 0)
246 3195113 : || (mpz_sgn (offc1) > 0 && mpz_cmp (maxc1, maxt) <= 0));
247 30359 : if (!c1_ok)
248 30359 : goto end;
249 :
250 3031663 : if (mpz_cmp (minc1, mint) < 0)
251 29559 : mpz_set (minc1, mint);
252 3031663 : if (mpz_cmp (maxc1, maxt) > 0)
253 17583 : mpz_set (maxc1, maxt);
254 :
255 3031663 : if (cmp == LT_EXPR)
256 : {
257 430006 : cmp = LE_EXPR;
258 430006 : mpz_sub_ui (maxc1, maxc1, 1);
259 : }
260 3031663 : if (cmp == GT_EXPR)
261 : {
262 1570891 : cmp = GE_EXPR;
263 1570891 : mpz_add_ui (minc1, minc1, 1);
264 : }
265 :
266 : /* Compute range information for varc0. If there is no overflow,
267 : the condition implied that
268 :
269 : (varc0) cmp (varc1 + offc1 - offc0)
270 :
271 : We can possibly improve the upper bound of varc0 if cmp is LE_EXPR,
272 : or the below bound if cmp is GE_EXPR.
273 :
274 : To prove there is no overflow/underflow, we need to check below
275 : four cases:
276 : 1) cmp == LE_EXPR && offc0 > 0
277 :
278 : (varc0 + offc0) doesn't overflow
279 : && (varc1 + offc1 - offc0) doesn't underflow
280 :
281 : 2) cmp == LE_EXPR && offc0 < 0
282 :
283 : (varc0 + offc0) doesn't underflow
284 : && (varc1 + offc1 - offc0) doesn't overfloe
285 :
286 : In this case, (varc0 + offc0) will never underflow if we can
287 : prove (varc1 + offc1 - offc0) doesn't overflow.
288 :
289 : 3) cmp == GE_EXPR && offc0 < 0
290 :
291 : (varc0 + offc0) doesn't underflow
292 : && (varc1 + offc1 - offc0) doesn't overflow
293 :
294 : 4) cmp == GE_EXPR && offc0 > 0
295 :
296 : (varc0 + offc0) doesn't overflow
297 : && (varc1 + offc1 - offc0) doesn't underflow
298 :
299 : In this case, (varc0 + offc0) will never overflow if we can
300 : prove (varc1 + offc1 - offc0) doesn't underflow.
301 :
302 : Note we only handle case 2 and 4 in below code. */
303 :
304 3031663 : mpz_sub (minc1, minc1, offc0);
305 3031663 : mpz_sub (maxc1, maxc1, offc0);
306 6063326 : c0_ok = (no_wrap
307 838306 : || mpz_sgn (offc0) == 0
308 52299 : || (cmp == LE_EXPR
309 34373 : && mpz_sgn (offc0) < 0 && mpz_cmp (maxc1, maxt) <= 0)
310 3081138 : || (cmp == GE_EXPR
311 17926 : && mpz_sgn (offc0) > 0 && mpz_cmp (minc1, mint) >= 0));
312 47079 : if (!c0_ok)
313 47079 : goto end;
314 :
315 2984584 : if (cmp == LE_EXPR)
316 : {
317 1127282 : if (mpz_cmp (up, maxc1) > 0)
318 352118 : mpz_set (up, maxc1);
319 : }
320 : else
321 : {
322 1857302 : if (mpz_cmp (below, minc1) < 0)
323 1126961 : mpz_set (below, minc1);
324 : }
325 :
326 730341 : end:
327 3062022 : mpz_clear (mint);
328 3062022 : mpz_clear (maxt);
329 3062022 : mpz_clear (minc1);
330 3062022 : mpz_clear (maxc1);
331 3062022 : mpz_clear (offc0);
332 3062022 : mpz_clear (offc1);
333 : }
334 :
335 : /* Stores estimates of the minimum and maximum values of the expression
336 : VAR + OFF in TYPE to MIN and MAX. The estimates are valid on entry
337 : to LOOP, i.e. on the loop preheader edge. */
338 :
339 : static void
340 26169114 : determine_value_range (class loop *loop, tree type, tree var, mpz_t off,
341 : mpz_t min, mpz_t max)
342 : {
343 26169114 : int cnt = 0;
344 26169114 : mpz_t minm, maxm;
345 26169114 : basic_block bb;
346 26169114 : wide_int minv, maxv;
347 26169114 : enum value_range_kind rtype = VR_VARYING;
348 :
349 : /* If the expression is a constant, we know its value exactly. */
350 26169114 : if (integer_zerop (var))
351 : {
352 18427919 : mpz_set (min, off);
353 18427919 : mpz_set (max, off);
354 18427919 : return;
355 : }
356 :
357 7741195 : get_type_static_bounds (type, min, max);
358 :
359 : /* See if we have some range info from VRP. */
360 7741195 : if (INTEGRAL_TYPE_P (type))
361 : {
362 6255208 : edge e = loop_preheader_edge (loop);
363 6255208 : signop sgn = TYPE_SIGN (type);
364 6255208 : gphi_iterator gsi;
365 :
366 : /* Either for VAR itself... */
367 6255208 : int_range_max var_range (TREE_TYPE (var));
368 12510416 : get_range_query (cfun)->range_on_edge (var_range, e, var);
369 6255208 : if (var_range.varying_p () || var_range.undefined_p ())
370 : rtype = VR_VARYING;
371 : else
372 : rtype = VR_RANGE;
373 6255208 : if (!var_range.undefined_p ())
374 : {
375 6238644 : minv = var_range.lower_bound ();
376 6238712 : maxv = var_range.upper_bound ();
377 : }
378 :
379 : /* Or for PHI results in loop->header where VAR is used as
380 : PHI argument from the loop preheader edge. */
381 6255208 : int_range_max phi_range (TREE_TYPE (var));
382 23180557 : for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
383 : {
384 16925366 : gphi *phi = gsi.phi ();
385 16925366 : if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var
386 2739738 : && get_range_query (cfun)->range_on_edge (phi_range,
387 : e, gimple_phi_result (phi))
388 1369869 : && !phi_range.varying_p ()
389 17698320 : && !phi_range.undefined_p ())
390 : {
391 772950 : if (rtype != VR_RANGE)
392 : {
393 258644 : rtype = VR_RANGE;
394 258644 : minv = phi_range.lower_bound ();
395 258659 : maxv = phi_range.upper_bound ();
396 : }
397 : else
398 : {
399 514308 : minv = wi::max (minv, phi_range.lower_bound (), sgn);
400 514308 : maxv = wi::min (maxv, phi_range.upper_bound (), sgn);
401 : /* If the PHI result range are inconsistent with
402 : the VAR range, give up on looking at the PHI
403 : results. This can happen if VR_UNDEFINED is
404 : involved. */
405 514306 : if (wi::gt_p (minv, maxv, sgn))
406 : {
407 17 : int_range_max vr (TREE_TYPE (var));
408 34 : get_range_query (cfun)->range_on_edge (vr, e, var);
409 17 : if (vr.varying_p () || vr.undefined_p ())
410 : rtype = VR_VARYING;
411 : else
412 : rtype = VR_RANGE;
413 17 : if (!vr.undefined_p ())
414 : {
415 17 : minv = vr.lower_bound ();
416 17 : maxv = vr.upper_bound ();
417 : }
418 17 : break;
419 17 : }
420 : }
421 : }
422 : }
423 6255208 : mpz_init (minm);
424 6255208 : mpz_init (maxm);
425 6255208 : if (rtype != VR_RANGE)
426 : {
427 3071544 : mpz_set (minm, min);
428 3071544 : mpz_set (maxm, max);
429 : }
430 : else
431 : {
432 3183664 : gcc_assert (wi::le_p (minv, maxv, sgn));
433 3183664 : wi::to_mpz (minv, minm, sgn);
434 3183664 : wi::to_mpz (maxv, maxm, sgn);
435 : }
436 : /* Now walk the dominators of the loop header and use the entry
437 : guards to refine the estimates. */
438 6255208 : for (bb = loop->header;
439 62830912 : bb != ENTRY_BLOCK_PTR_FOR_FN (cfun)
440 62830912 : && cnt < param_max_niter_dominators_walk;
441 56575704 : bb = get_immediate_dominator (CDI_DOMINATORS, bb))
442 : {
443 56575704 : edge e;
444 56575704 : tree c0, c1;
445 56575704 : enum tree_code cmp;
446 :
447 56575704 : if (!single_pred_p (bb))
448 28201310 : continue;
449 28374394 : e = single_pred_edge (bb);
450 :
451 28374394 : if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
452 6736730 : continue;
453 :
454 43275328 : gcond *cond = as_a <gcond *> (*gsi_last_bb (e->src));
455 21637664 : c0 = gimple_cond_lhs (cond);
456 21637664 : cmp = gimple_cond_code (cond);
457 21637664 : c1 = gimple_cond_rhs (cond);
458 :
459 21637664 : if (e->flags & EDGE_FALSE_VALUE)
460 11655840 : cmp = invert_tree_comparison (cmp, false);
461 :
462 21637664 : refine_value_range_using_guard (type, var, c0, cmp, c1, minm, maxm);
463 21637664 : ++cnt;
464 : }
465 :
466 6255208 : mpz_add (minm, minm, off);
467 6255208 : mpz_add (maxm, maxm, off);
468 : /* If the computation may not wrap or off is zero, then this
469 : is always fine. If off is negative and minv + off isn't
470 : smaller than type's minimum, or off is positive and
471 : maxv + off isn't bigger than type's maximum, use the more
472 : precise range too. */
473 6255208 : if (nowrap_type_p (type)
474 2449534 : || mpz_sgn (off) == 0
475 624726 : || (mpz_sgn (off) < 0 && mpz_cmp (minm, min) >= 0)
476 6799630 : || (mpz_sgn (off) > 0 && mpz_cmp (maxm, max) <= 0))
477 : {
478 6034569 : mpz_set (min, minm);
479 6034569 : mpz_set (max, maxm);
480 6034569 : mpz_clear (minm);
481 6034569 : mpz_clear (maxm);
482 6034569 : return;
483 : }
484 220639 : mpz_clear (minm);
485 220639 : mpz_clear (maxm);
486 6255208 : }
487 :
488 : /* If the computation may wrap, we know nothing about the value, except for
489 : the range of the type. */
490 1706626 : if (!nowrap_type_p (type))
491 : return;
492 :
493 : /* Since the addition of OFF does not wrap, if OFF is positive, then we may
494 : add it to MIN, otherwise to MAX. */
495 1485875 : if (mpz_sgn (off) < 0)
496 22415 : mpz_add (max, max, off);
497 : else
498 1463460 : mpz_add (min, min, off);
499 26169182 : }
500 :
501 : /* Stores the bounds on the difference of the values of the expressions
502 : (var + X) and (var + Y), computed in TYPE, to BNDS. */
503 :
504 : static void
505 174390 : bound_difference_of_offsetted_base (tree type, mpz_t x, mpz_t y,
506 : bounds *bnds)
507 : {
508 174390 : int rel = mpz_cmp (x, y);
509 174390 : bool may_wrap = !nowrap_type_p (type);
510 :
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). */
524 :
525 174390 : if (rel == 0)
526 : {
527 640 : mpz_set_ui (bnds->below, 0);
528 640 : mpz_set_ui (bnds->up, 0);
529 640 : return;
530 : }
531 :
532 173750 : auto_mpz m;
533 173750 : wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), m, UNSIGNED);
534 173750 : mpz_add_ui (m, m, 1);
535 173750 : mpz_sub (bnds->up, x, y);
536 173750 : mpz_set (bnds->below, bnds->up);
537 :
538 173750 : if (may_wrap)
539 : {
540 148742 : if (rel > 0)
541 147291 : mpz_sub (bnds->below, bnds->below, m);
542 : else
543 1451 : mpz_add (bnds->up, bnds->up, m);
544 : }
545 173750 : }
546 :
547 : /* From condition C0 CMP C1 derives information regarding the
548 : difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
549 : and stores it to BNDS. */
550 :
551 : static void
552 20351652 : refine_bounds_using_guard (tree type, tree varx, mpz_t offx,
553 : tree vary, mpz_t offy,
554 : tree c0, enum tree_code cmp, tree c1,
555 : bounds *bnds)
556 : {
557 20351652 : tree varc0, varc1, ctype;
558 20351652 : mpz_t offc0, offc1, loffx, loffy, bnd;
559 20351652 : bool lbound = false;
560 20351652 : bool no_wrap = nowrap_type_p (type);
561 20351652 : bool x_ok, y_ok;
562 :
563 20351652 : switch (cmp)
564 : {
565 8715417 : case LT_EXPR:
566 8715417 : case LE_EXPR:
567 8715417 : case GT_EXPR:
568 8715417 : case GE_EXPR:
569 8715417 : STRIP_SIGN_NOPS (c0);
570 8715417 : STRIP_SIGN_NOPS (c1);
571 8715417 : ctype = TREE_TYPE (c0);
572 8715417 : if (!useless_type_conversion_p (ctype, type))
573 13049219 : return;
574 :
575 : break;
576 :
577 : case EQ_EXPR:
578 : /* We could derive quite precise information from EQ_EXPR, however, such
579 : a guard is unlikely to appear, so we do not bother with handling
580 : it. */
581 : return;
582 :
583 5569324 : case NE_EXPR:
584 : /* NE_EXPR comparisons do not contain much of useful information, except for
585 : special case of comparing with the bounds of the type. */
586 5569324 : if (TREE_CODE (c1) != INTEGER_CST
587 4840082 : || !INTEGRAL_TYPE_P (type))
588 : return;
589 :
590 : /* Ensure that the condition speaks about an expression in the same type
591 : as X and Y. */
592 4279678 : ctype = TREE_TYPE (c0);
593 4279678 : if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
594 : return;
595 2438101 : c0 = fold_convert (type, c0);
596 2438101 : c1 = fold_convert (type, c1);
597 :
598 2438101 : if (TYPE_MIN_VALUE (type)
599 2438101 : && operand_equal_p (c1, TYPE_MIN_VALUE (type), 0))
600 : {
601 : cmp = GT_EXPR;
602 : break;
603 : }
604 1738266 : if (TYPE_MAX_VALUE (type)
605 1738266 : && operand_equal_p (c1, TYPE_MAX_VALUE (type), 0))
606 : {
607 : cmp = LT_EXPR;
608 : break;
609 : }
610 :
611 : return;
612 : default:
613 : return;
614 : }
615 :
616 7302433 : mpz_init (offc0);
617 7302433 : mpz_init (offc1);
618 7302433 : split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
619 7302433 : split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
620 :
621 : /* We are only interested in comparisons of expressions based on VARX and
622 : VARY. TODO -- we might also be able to derive some bounds from
623 : expressions containing just one of the variables. */
624 :
625 7302433 : if (operand_equal_p (varx, varc1, 0))
626 : {
627 972597 : std::swap (varc0, varc1);
628 972597 : mpz_swap (offc0, offc1);
629 972597 : cmp = swap_tree_comparison (cmp);
630 : }
631 :
632 7302433 : if (!operand_equal_p (varx, varc0, 0)
633 7302433 : || !operand_equal_p (vary, varc1, 0))
634 5412068 : goto end;
635 :
636 1890365 : mpz_init_set (loffx, offx);
637 1890365 : mpz_init_set (loffy, offy);
638 :
639 1890365 : if (cmp == GT_EXPR || cmp == GE_EXPR)
640 : {
641 1801468 : std::swap (varx, vary);
642 1801468 : mpz_swap (offc0, offc1);
643 1801468 : mpz_swap (loffx, loffy);
644 1801468 : cmp = swap_tree_comparison (cmp);
645 1801468 : lbound = true;
646 : }
647 :
648 : /* If there is no overflow, the condition implies that
649 :
650 : (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
651 :
652 : The overflows and underflows may complicate things a bit; each
653 : overflow decreases the appropriate offset by M, and underflow
654 : increases it by M. The above inequality would not necessarily be
655 : true if
656 :
657 : -- VARX + OFFX underflows and VARX + OFFC0 does not, or
658 : VARX + OFFC0 overflows, but VARX + OFFX does not.
659 : This may only happen if OFFX < OFFC0.
660 : -- VARY + OFFY overflows and VARY + OFFC1 does not, or
661 : VARY + OFFC1 underflows and VARY + OFFY does not.
662 : This may only happen if OFFY > OFFC1. */
663 :
664 1890365 : if (no_wrap)
665 : {
666 : x_ok = true;
667 : y_ok = true;
668 : }
669 : else
670 : {
671 629888 : x_ok = (integer_zerop (varx)
672 629888 : || mpz_cmp (loffx, offc0) >= 0);
673 629888 : y_ok = (integer_zerop (vary)
674 629888 : || mpz_cmp (loffy, offc1) <= 0);
675 : }
676 :
677 627171 : if (x_ok && y_ok)
678 : {
679 1883682 : mpz_init (bnd);
680 1883682 : mpz_sub (bnd, loffx, loffy);
681 1883682 : mpz_add (bnd, bnd, offc1);
682 1883682 : mpz_sub (bnd, bnd, offc0);
683 :
684 1883682 : if (cmp == LT_EXPR)
685 1532149 : mpz_sub_ui (bnd, bnd, 1);
686 :
687 1883682 : if (lbound)
688 : {
689 1796059 : mpz_neg (bnd, bnd);
690 1796059 : if (mpz_cmp (bnds->below, bnd) < 0)
691 474865 : mpz_set (bnds->below, bnd);
692 : }
693 : else
694 : {
695 87623 : if (mpz_cmp (bnd, bnds->up) < 0)
696 4162 : mpz_set (bnds->up, bnd);
697 : }
698 1883682 : mpz_clear (bnd);
699 : }
700 :
701 1890365 : mpz_clear (loffx);
702 1890365 : mpz_clear (loffy);
703 7302433 : end:
704 7302433 : mpz_clear (offc0);
705 7302433 : mpz_clear (offc1);
706 : }
707 :
708 : /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
709 : The subtraction is considered to be performed in arbitrary precision,
710 : without overflows.
711 :
712 : We do not attempt to be too clever regarding the value ranges of X and
713 : Y; most of the time, they are just integers or ssa names offsetted by
714 : integer. However, we try to use the information contained in the
715 : comparisons before the loop (usually created by loop header copying). */
716 :
717 : static void
718 13258947 : bound_difference (class loop *loop, tree x, tree y, bounds *bnds)
719 : {
720 13258947 : tree type = TREE_TYPE (x);
721 13258947 : tree varx, vary;
722 13258947 : mpz_t offx, offy;
723 13258947 : int cnt = 0;
724 13258947 : edge e;
725 13258947 : basic_block bb;
726 13258947 : tree c0, c1;
727 13258947 : enum tree_code cmp;
728 :
729 : /* Get rid of unnecessary casts, but preserve the value of
730 : the expressions. */
731 13258947 : STRIP_SIGN_NOPS (x);
732 13258947 : STRIP_SIGN_NOPS (y);
733 :
734 13258947 : mpz_init (bnds->below);
735 13258947 : mpz_init (bnds->up);
736 13258947 : mpz_init (offx);
737 13258947 : mpz_init (offy);
738 13258947 : split_to_var_and_offset (x, &varx, offx);
739 13258947 : split_to_var_and_offset (y, &vary, offy);
740 :
741 13258947 : if (!integer_zerop (varx)
742 13258947 : && operand_equal_p (varx, vary, 0))
743 : {
744 : /* Special case VARX == VARY -- we just need to compare the
745 : offsets. The matters are a bit more complicated in the
746 : case addition of offsets may wrap. */
747 174390 : bound_difference_of_offsetted_base (type, offx, offy, bnds);
748 : }
749 : else
750 : {
751 : /* Otherwise, use the value ranges to determine the initial
752 : estimates on below and up. */
753 13084557 : auto_mpz minx, maxx, miny, maxy;
754 13084557 : determine_value_range (loop, type, varx, offx, minx, maxx);
755 13084557 : determine_value_range (loop, type, vary, offy, miny, maxy);
756 :
757 13084557 : mpz_sub (bnds->below, minx, maxy);
758 13084557 : mpz_sub (bnds->up, maxx, miny);
759 13084557 : }
760 :
761 : /* If both X and Y are constants, we cannot get any more precise. */
762 13258947 : if (integer_zerop (varx) && integer_zerop (vary))
763 7282340 : goto end;
764 :
765 : /* Now walk the dominators of the loop header and use the entry
766 : guards to refine the estimates. */
767 5976607 : for (bb = loop->header;
768 58864671 : bb != ENTRY_BLOCK_PTR_FOR_FN (cfun)
769 58864671 : && cnt < param_max_niter_dominators_walk;
770 52888064 : bb = get_immediate_dominator (CDI_DOMINATORS, bb))
771 : {
772 52888064 : if (!single_pred_p (bb))
773 25414745 : continue;
774 27473319 : e = single_pred_edge (bb);
775 :
776 27473319 : if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
777 7121667 : continue;
778 :
779 40703304 : gcond *cond = as_a <gcond *> (*gsi_last_bb (e->src));
780 20351652 : c0 = gimple_cond_lhs (cond);
781 20351652 : cmp = gimple_cond_code (cond);
782 20351652 : c1 = gimple_cond_rhs (cond);
783 :
784 20351652 : if (e->flags & EDGE_FALSE_VALUE)
785 11296963 : cmp = invert_tree_comparison (cmp, false);
786 :
787 20351652 : refine_bounds_using_guard (type, varx, offx, vary, offy,
788 : c0, cmp, c1, bnds);
789 20351652 : ++cnt;
790 : }
791 :
792 5976607 : end:
793 13258947 : mpz_clear (offx);
794 13258947 : mpz_clear (offy);
795 13258947 : }
796 :
797 : /* Update the bounds in BNDS that restrict the value of X to the bounds
798 : that restrict the value of X + DELTA. X can be obtained as a
799 : difference of two values in TYPE. */
800 :
801 : static void
802 2164247 : bounds_add (bounds *bnds, const widest_int &delta, tree type)
803 : {
804 2164247 : mpz_t mdelta, max;
805 :
806 2164247 : mpz_init (mdelta);
807 2164247 : wi::to_mpz (delta, mdelta, SIGNED);
808 :
809 2164247 : mpz_init (max);
810 2164247 : wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
811 :
812 2164247 : mpz_add (bnds->up, bnds->up, mdelta);
813 2164247 : mpz_add (bnds->below, bnds->below, mdelta);
814 :
815 2164247 : if (mpz_cmp (bnds->up, max) > 0)
816 122513 : mpz_set (bnds->up, max);
817 :
818 2164247 : mpz_neg (max, max);
819 2164247 : if (mpz_cmp (bnds->below, max) < 0)
820 9501 : mpz_set (bnds->below, max);
821 :
822 2164247 : mpz_clear (mdelta);
823 2164247 : mpz_clear (max);
824 2164247 : }
825 :
826 : /* Update the bounds in BNDS that restrict the value of X to the bounds
827 : that restrict the value of -X. */
828 :
829 : static void
830 2604254 : bounds_negate (bounds *bnds)
831 : {
832 2604254 : mpz_t tmp;
833 :
834 2604254 : mpz_init_set (tmp, bnds->up);
835 2604254 : mpz_neg (bnds->up, bnds->below);
836 2604254 : mpz_neg (bnds->below, tmp);
837 2604254 : mpz_clear (tmp);
838 2604254 : }
839 :
840 : /* Returns inverse of X modulo 2^s, where MASK = 2^s-1. */
841 :
842 : static tree
843 176181 : inverse (tree x, tree mask)
844 : {
845 176181 : tree type = TREE_TYPE (x);
846 176181 : tree rslt;
847 176181 : unsigned ctr = tree_floor_log2 (mask);
848 :
849 176181 : if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
850 : {
851 176163 : unsigned HOST_WIDE_INT ix;
852 176163 : unsigned HOST_WIDE_INT imask;
853 176163 : unsigned HOST_WIDE_INT irslt = 1;
854 :
855 176163 : gcc_assert (cst_and_fits_in_hwi (x));
856 176163 : gcc_assert (cst_and_fits_in_hwi (mask));
857 :
858 176163 : ix = int_cst_value (x);
859 176163 : imask = int_cst_value (mask);
860 :
861 10001415 : for (; ctr; ctr--)
862 : {
863 9649089 : irslt *= ix;
864 9649089 : ix *= ix;
865 : }
866 176163 : irslt &= imask;
867 :
868 176163 : rslt = build_int_cst_type (type, irslt);
869 : }
870 : else
871 : {
872 18 : rslt = build_int_cst (type, 1);
873 2180 : for (; ctr; ctr--)
874 : {
875 2162 : rslt = int_const_binop (MULT_EXPR, rslt, x);
876 2162 : x = int_const_binop (MULT_EXPR, x, x);
877 : }
878 18 : rslt = int_const_binop (BIT_AND_EXPR, rslt, mask);
879 : }
880 :
881 176181 : return rslt;
882 : }
883 :
884 : /* Derives the upper bound BND on the number of executions of loop with exit
885 : condition S * i <> C. If NO_OVERFLOW is true, then the control variable of
886 : the loop does not overflow. EXIT_MUST_BE_TAKEN is true if we are guaranteed
887 : that the loop ends through this exit, i.e., the induction variable ever
888 : reaches the value of C.
889 :
890 : The value C is equal to final - base, where final and base are the final and
891 : initial value of the actual induction variable in the analysed loop. BNDS
892 : bounds the value of this difference when computed in signed type with
893 : unbounded range, while the computation of C is performed in an unsigned
894 : type with the range matching the range of the type of the induction variable.
895 : In particular, BNDS.up contains an upper bound on C in the following cases:
896 : -- if the iv must reach its final value without overflow, i.e., if
897 : NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
898 : -- if final >= base, which we know to hold when BNDS.below >= 0. */
899 :
900 : static void
901 7676153 : number_of_iterations_ne_max (mpz_t bnd, bool no_overflow, tree c, tree s,
902 : bounds *bnds, bool exit_must_be_taken)
903 : {
904 7676153 : widest_int max;
905 7676153 : mpz_t d;
906 7676153 : tree type = TREE_TYPE (c);
907 15352306 : bool bnds_u_valid = ((no_overflow && exit_must_be_taken)
908 7676153 : || mpz_sgn (bnds->below) >= 0);
909 :
910 7676153 : if (integer_onep (s)
911 880786 : || (TREE_CODE (c) == INTEGER_CST
912 346574 : && TREE_CODE (s) == INTEGER_CST
913 1228073 : && wi::mod_trunc (wi::to_wide (c), wi::to_wide (s),
914 8369301 : TYPE_SIGN (type)) == 0)
915 8211078 : || (TYPE_OVERFLOW_UNDEFINED (type)
916 0 : && multiple_of_p (type, c, s)))
917 : {
918 : /* If C is an exact multiple of S, then its value will be reached before
919 : the induction variable overflows (unless the loop is exited in some
920 : other way before). Note that the actual induction variable in the
921 : loop (which ranges from base to final instead of from 0 to C) may
922 : overflow, in which case BNDS.up will not be giving a correct upper
923 : bound on C; thus, BNDS_U_VALID had to be computed in advance. */
924 : no_overflow = true;
925 : exit_must_be_taken = true;
926 : }
927 :
928 : /* If the induction variable can overflow, or if we do not know that the
929 : exit is taken before it would, the number of iterations is at most the
930 : period of the control variable. In the latter case the final value need
931 : not be reached by walking there from the initial value; the number of
932 : iterations is computed modulo the period of the control variable (or the
933 : loop is infinite, but in that case the whole # of iterations analysis
934 : will fail). */
935 534925 : if (!no_overflow || !exit_must_be_taken)
936 : {
937 629460 : max = wi::mask <widest_int> (TYPE_PRECISION (type)
938 629460 : - wi::ctz (wi::to_wide (s)), false);
939 314730 : wi::to_mpz (max, bnd, UNSIGNED);
940 314730 : return;
941 : }
942 :
943 : /* Now we know that the induction variable does not overflow, so the loop
944 : iterates at most (range of type / S) times. */
945 7361423 : wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), bnd, UNSIGNED);
946 :
947 : /* If the induction variable is guaranteed to reach the value of C before
948 : overflow, ... */
949 7361423 : if (exit_must_be_taken)
950 : {
951 : /* ... then we can strengthen this to C / S, and possibly we can use
952 : the upper bound on C given by BNDS. */
953 7361423 : if (TREE_CODE (c) == INTEGER_CST)
954 6445925 : wi::to_mpz (wi::to_wide (c), bnd, UNSIGNED);
955 915498 : else if (bnds_u_valid)
956 763625 : mpz_set (bnd, bnds->up);
957 : }
958 :
959 7361423 : mpz_init (d);
960 7361423 : wi::to_mpz (wi::to_wide (s), d, UNSIGNED);
961 7361423 : mpz_fdiv_q (bnd, bnd, d);
962 7361423 : mpz_clear (d);
963 7676153 : }
964 :
965 : /* Determines number of iterations of loop whose ending condition
966 : is IV <> FINAL. TYPE is the type of the iv. The number of
967 : iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
968 : we know that the exit must be taken eventually, i.e., that the IV
969 : ever reaches the value FINAL (we derived this earlier, and possibly set
970 : NITER->assumptions to make sure this is the case). BNDS contains the
971 : bounds on the difference FINAL - IV->base. */
972 :
973 : static bool
974 7676153 : number_of_iterations_ne (class loop *loop, tree type, affine_iv *iv,
975 : tree final, class tree_niter_desc *niter,
976 : bool exit_must_be_taken, bounds *bnds)
977 : {
978 7676153 : tree niter_type = unsigned_type_for (type);
979 7676153 : tree s, c, d, bits, assumption, tmp, bound;
980 :
981 7676153 : niter->control = *iv;
982 7676153 : niter->bound = final;
983 7676153 : niter->cmp = NE_EXPR;
984 :
985 : /* Rearrange the terms so that we get inequality S * i <> C, with S
986 : positive. Also cast everything to the unsigned type. If IV does
987 : not overflow, BNDS bounds the value of C. Also, this is the
988 : case if the computation |FINAL - IV->base| does not overflow, i.e.,
989 : if BNDS->below in the result is nonnegative. */
990 7676153 : if (tree_int_cst_sign_bit (iv->step))
991 : {
992 2604254 : s = fold_build1 (NEGATE_EXPR, niter_type,
993 : fold_convert (niter_type, iv->step));
994 2604254 : c = fold_build2 (MINUS_EXPR, niter_type,
995 : fold_convert (niter_type, iv->base),
996 : fold_convert (niter_type, final));
997 2604254 : bounds_negate (bnds);
998 : }
999 : else
1000 : {
1001 5071899 : s = fold_convert (niter_type, iv->step);
1002 5071899 : c = fold_build2 (MINUS_EXPR, niter_type,
1003 : fold_convert (niter_type, final),
1004 : fold_convert (niter_type, iv->base));
1005 : }
1006 :
1007 7676153 : auto_mpz max;
1008 7676153 : number_of_iterations_ne_max (max, iv->no_overflow, c, s, bnds,
1009 : exit_must_be_taken);
1010 15352306 : niter->max = widest_int::from (wi::from_mpz (niter_type, max, false),
1011 15352306 : TYPE_SIGN (niter_type));
1012 :
1013 : /* Compute no-overflow information for the control iv. This can be
1014 : proven when below two conditions are satisfied:
1015 :
1016 : 1) IV evaluates toward FINAL at beginning, i.e:
1017 : base <= FINAL ; step > 0
1018 : base >= FINAL ; step < 0
1019 :
1020 : 2) |FINAL - base| is an exact multiple of step.
1021 :
1022 : Unfortunately, it's hard to prove above conditions after pass loop-ch
1023 : because loop with exit condition (IV != FINAL) usually will be guarded
1024 : by initial-condition (IV.base - IV.step != FINAL). In this case, we
1025 : can alternatively try to prove below conditions:
1026 :
1027 : 1') IV evaluates toward FINAL at beginning, i.e:
1028 : new_base = base - step < FINAL ; step > 0
1029 : && base - step doesn't underflow
1030 : new_base = base - step > FINAL ; step < 0
1031 : && base - step doesn't overflow
1032 :
1033 : Please refer to PR34114 as an example of loop-ch's impact.
1034 :
1035 : Note, for NE_EXPR, base equals to FINAL is a special case, in
1036 : which the loop exits immediately, and the iv does not overflow.
1037 :
1038 : Also note, we prove condition 2) by checking base and final separately
1039 : along with condition 1) or 1'). Since we ensure the difference
1040 : computation of c does not wrap with cond below and the adjusted s
1041 : will fit a signed type as well as an unsigned we can safely do
1042 : this using the type of the IV if it is not pointer typed. */
1043 7676153 : tree mtype = type;
1044 7676153 : if (POINTER_TYPE_P (type))
1045 612180 : mtype = niter_type;
1046 7676153 : if (!niter->control.no_overflow
1047 7676153 : && (integer_onep (s)
1048 213842 : || (multiple_of_p (mtype, fold_convert (mtype, iv->base),
1049 213842 : fold_convert (mtype, s), false)
1050 34689 : && multiple_of_p (mtype, fold_convert (mtype, final),
1051 34689 : fold_convert (mtype, s), false))))
1052 : {
1053 2459438 : tree t, cond, relaxed_cond = boolean_false_node;
1054 :
1055 2459438 : if (tree_int_cst_sign_bit (iv->step))
1056 : {
1057 2353209 : cond = fold_build2 (GE_EXPR, boolean_type_node, iv->base, final);
1058 2353209 : if (INTEGRAL_NB_TYPE_P (type))
1059 : {
1060 : /* Only when base - step doesn't overflow. */
1061 2353209 : t = TYPE_MAX_VALUE (type);
1062 2353209 : t = fold_build2 (PLUS_EXPR, type, t, iv->step);
1063 2353209 : t = fold_build2 (GE_EXPR, boolean_type_node, t, iv->base);
1064 2353209 : if (integer_nonzerop (t))
1065 : {
1066 2189841 : t = fold_build2 (MINUS_EXPR, type, iv->base, iv->step);
1067 2189841 : relaxed_cond = fold_build2 (GT_EXPR, boolean_type_node, t,
1068 : final);
1069 : }
1070 : }
1071 : }
1072 : else
1073 : {
1074 106229 : cond = fold_build2 (LE_EXPR, boolean_type_node, iv->base, final);
1075 106229 : if (INTEGRAL_NB_TYPE_P (type))
1076 : {
1077 : /* Only when base - step doesn't underflow. */
1078 106229 : t = TYPE_MIN_VALUE (type);
1079 106229 : t = fold_build2 (PLUS_EXPR, type, t, iv->step);
1080 106229 : t = fold_build2 (LE_EXPR, boolean_type_node, t, iv->base);
1081 106229 : if (integer_nonzerop (t))
1082 : {
1083 66119 : t = fold_build2 (MINUS_EXPR, type, iv->base, iv->step);
1084 66119 : relaxed_cond = fold_build2 (LT_EXPR, boolean_type_node, t,
1085 : final);
1086 : }
1087 : }
1088 : }
1089 :
1090 2459438 : t = simplify_using_initial_conditions (loop, cond);
1091 2459438 : if (!t || !integer_onep (t))
1092 65631 : t = simplify_using_initial_conditions (loop, relaxed_cond);
1093 :
1094 2459438 : if (t && integer_onep (t))
1095 : {
1096 2394317 : niter->control.no_overflow = true;
1097 2394317 : niter->niter = fold_build2 (EXACT_DIV_EXPR, niter_type, c, s);
1098 2394317 : return true;
1099 : }
1100 : }
1101 :
1102 : /* Let nsd (step, size of mode) = d. If d does not divide c, the loop
1103 : is infinite. Otherwise, the number of iterations is
1104 : (inverse(s/d) * (c/d)) mod (size of mode/d). */
1105 5281836 : bits = num_ending_zeros (s);
1106 15845508 : bound = build_low_bits_mask (niter_type,
1107 5281836 : (TYPE_PRECISION (niter_type)
1108 5281836 : - tree_to_uhwi (bits)));
1109 :
1110 5281836 : d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
1111 : build_int_cst (niter_type, 1), bits);
1112 5281836 : s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
1113 :
1114 5281836 : if (!exit_must_be_taken)
1115 : {
1116 : /* If we cannot assume that the exit is taken eventually, record the
1117 : assumptions for divisibility of c. */
1118 1916481 : assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
1119 1916481 : assumption = fold_build2 (EQ_EXPR, boolean_type_node,
1120 : assumption, build_int_cst (niter_type, 0));
1121 1916481 : if (!integer_nonzerop (assumption))
1122 298038 : niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1123 : niter->assumptions, assumption);
1124 : }
1125 :
1126 5281836 : c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
1127 5281836 : if (integer_onep (s))
1128 : {
1129 5105655 : niter->niter = c;
1130 : }
1131 : else
1132 : {
1133 176181 : tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
1134 176181 : niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
1135 : }
1136 : return true;
1137 7676153 : }
1138 :
1139 : /* Checks whether we can determine the final value of the control variable
1140 : of the loop with ending condition IV0 < IV1 (computed in TYPE).
1141 : DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
1142 : of the step. The assumptions necessary to ensure that the computation
1143 : of the final value does not overflow are recorded in NITER. If we
1144 : find the final value, we adjust DELTA and return TRUE. Otherwise
1145 : we return false. BNDS bounds the value of IV1->base - IV0->base,
1146 : and will be updated by the same amount as DELTA. EXIT_MUST_BE_TAKEN is
1147 : true if we know that the exit must be taken eventually. */
1148 :
1149 : static bool
1150 388535 : number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
1151 : class tree_niter_desc *niter,
1152 : tree *delta, tree step,
1153 : bool exit_must_be_taken, bounds *bnds)
1154 : {
1155 388535 : tree niter_type = TREE_TYPE (step);
1156 388535 : tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
1157 388535 : tree tmod;
1158 388535 : tree assumption = boolean_true_node, bound, noloop;
1159 388535 : bool fv_comp_no_overflow;
1160 388535 : tree type1 = type;
1161 388535 : if (POINTER_TYPE_P (type))
1162 127217 : type1 = sizetype;
1163 :
1164 388535 : if (TREE_CODE (mod) != INTEGER_CST)
1165 : return false;
1166 36875 : if (integer_nonzerop (mod))
1167 16967 : mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
1168 36875 : tmod = fold_convert (type1, mod);
1169 :
1170 36875 : auto_mpz mmod;
1171 36875 : wi::to_mpz (wi::to_wide (mod), mmod, UNSIGNED);
1172 36875 : mpz_neg (mmod, mmod);
1173 :
1174 : /* If the induction variable does not overflow and the exit is taken,
1175 : then the computation of the final value does not overflow. This is
1176 : also obviously the case if the new final value is equal to the
1177 : current one. Finally, we postulate this for pointer type variables,
1178 : as the code cannot rely on the object to that the pointer points being
1179 : placed at the end of the address space (and more pragmatically,
1180 : TYPE_{MIN,MAX}_VALUE is not defined for pointers). */
1181 36875 : if (integer_zerop (mod) || POINTER_TYPE_P (type))
1182 : fv_comp_no_overflow = true;
1183 16253 : else if (!exit_must_be_taken)
1184 : fv_comp_no_overflow = false;
1185 : else
1186 8051 : fv_comp_no_overflow =
1187 8051 : (iv0->no_overflow && integer_nonzerop (iv0->step))
1188 8985 : || (iv1->no_overflow && integer_nonzerop (iv1->step));
1189 :
1190 36875 : if (integer_nonzerop (iv0->step))
1191 : {
1192 : /* The final value of the iv is iv1->base + MOD, assuming that this
1193 : computation does not overflow, and that
1194 : iv0->base <= iv1->base + MOD. */
1195 32071 : if (!fv_comp_no_overflow)
1196 : {
1197 6181 : bound = fold_build2 (MINUS_EXPR, type1,
1198 : TYPE_MAX_VALUE (type1), tmod);
1199 6181 : assumption = fold_build2 (LE_EXPR, boolean_type_node,
1200 : iv1->base, bound);
1201 6181 : if (integer_zerop (assumption))
1202 : return false;
1203 : }
1204 : }
1205 : else
1206 : {
1207 : /* The final value of the iv is iv0->base - MOD, assuming that this
1208 : computation does not overflow, and that
1209 : iv0->base - MOD <= iv1->base. */
1210 4804 : if (!fv_comp_no_overflow)
1211 : {
1212 2021 : bound = fold_build2 (PLUS_EXPR, type1,
1213 : TYPE_MIN_VALUE (type1), tmod);
1214 2021 : assumption = fold_build2 (GE_EXPR, boolean_type_node,
1215 : iv0->base, bound);
1216 2021 : if (integer_zerop (assumption))
1217 : return false;
1218 : }
1219 : }
1220 :
1221 : /* IV0 < IV1 does not loop if IV0->base >= IV1->base. */
1222 36819 : if (fv_comp_no_overflow && mpz_cmp (mmod, bnds->below) < 0)
1223 17547 : noloop = boolean_false_node;
1224 : else
1225 19272 : noloop = fold_build2 (GE_EXPR, boolean_type_node,
1226 : iv0->base, iv1->base);
1227 :
1228 36819 : if (!integer_nonzerop (assumption))
1229 434 : niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1230 : niter->assumptions,
1231 : assumption);
1232 36819 : if (!integer_zerop (noloop))
1233 3711 : niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1234 : niter->may_be_zero,
1235 : noloop);
1236 36819 : bounds_add (bnds, wi::to_widest (mod), type);
1237 36819 : *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
1238 :
1239 36819 : return true;
1240 36875 : }
1241 :
1242 : /* Add assertions to NITER that ensure that the control variable of the loop
1243 : with ending condition IV0 < IV1 does not overflow. Types of IV0 and IV1
1244 : are TYPE. Returns false if we can prove that there is an overflow, true
1245 : otherwise. STEP is the absolute value of the step. */
1246 :
1247 : static bool
1248 351716 : assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1249 : class tree_niter_desc *niter, tree step)
1250 : {
1251 351716 : tree bound, d, assumption, diff;
1252 351716 : tree niter_type = TREE_TYPE (step);
1253 :
1254 351716 : if (integer_nonzerop (iv0->step))
1255 : {
1256 : /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
1257 288433 : if (iv0->no_overflow)
1258 : return true;
1259 :
1260 : /* If iv0->base is a constant, we can determine the last value before
1261 : overflow precisely; otherwise we conservatively assume
1262 : MAX - STEP + 1. */
1263 :
1264 46636 : if (TREE_CODE (iv0->base) == INTEGER_CST)
1265 : {
1266 15802 : d = fold_build2 (MINUS_EXPR, niter_type,
1267 : fold_convert (niter_type, TYPE_MAX_VALUE (type)),
1268 : fold_convert (niter_type, iv0->base));
1269 15802 : diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
1270 : }
1271 : else
1272 30834 : diff = fold_build2 (MINUS_EXPR, niter_type, step,
1273 : build_int_cst (niter_type, 1));
1274 46636 : bound = fold_build2 (MINUS_EXPR, type,
1275 : TYPE_MAX_VALUE (type), fold_convert (type, diff));
1276 46636 : assumption = fold_build2 (LE_EXPR, boolean_type_node,
1277 : iv1->base, bound);
1278 : }
1279 : else
1280 : {
1281 : /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
1282 63283 : if (iv1->no_overflow)
1283 : return true;
1284 :
1285 31843 : if (TREE_CODE (iv1->base) == INTEGER_CST)
1286 : {
1287 63 : d = fold_build2 (MINUS_EXPR, niter_type,
1288 : fold_convert (niter_type, iv1->base),
1289 : fold_convert (niter_type, TYPE_MIN_VALUE (type)));
1290 63 : diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
1291 : }
1292 : else
1293 31780 : diff = fold_build2 (MINUS_EXPR, niter_type, step,
1294 : build_int_cst (niter_type, 1));
1295 31843 : bound = fold_build2 (PLUS_EXPR, type,
1296 : TYPE_MIN_VALUE (type), fold_convert (type, diff));
1297 31843 : assumption = fold_build2 (GE_EXPR, boolean_type_node,
1298 : iv0->base, bound);
1299 : }
1300 :
1301 78479 : if (integer_zerop (assumption))
1302 : return false;
1303 78413 : if (!integer_nonzerop (assumption))
1304 55842 : niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1305 : niter->assumptions, assumption);
1306 :
1307 78413 : iv0->no_overflow = true;
1308 78413 : iv1->no_overflow = true;
1309 78413 : return true;
1310 : }
1311 :
1312 : /* Add an assumption to NITER that a loop whose ending condition
1313 : is IV0 < IV1 rolls. TYPE is the type of the control iv. BNDS
1314 : bounds the value of IV1->base - IV0->base. */
1315 :
1316 : static void
1317 351650 : assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1318 : class tree_niter_desc *niter, bounds *bnds)
1319 : {
1320 351650 : tree assumption = boolean_true_node, bound, diff;
1321 351650 : tree mbz, mbzl, mbzr, type1;
1322 351650 : bool rolls_p, no_overflow_p;
1323 351650 : widest_int dstep;
1324 351650 : mpz_t mstep, max;
1325 :
1326 : /* We are going to compute the number of iterations as
1327 : (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1328 : variant of TYPE. This formula only works if
1329 :
1330 : -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1331 :
1332 : (where MAX is the maximum value of the unsigned variant of TYPE, and
1333 : the computations in this formula are performed in full precision,
1334 : i.e., without overflows).
1335 :
1336 : Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1337 : we have a condition of the form iv0->base - step < iv1->base before the loop,
1338 : and for loops iv0->base < iv1->base - step * i the condition
1339 : iv0->base < iv1->base + step, due to loop header copying, which enable us
1340 : to prove the lower bound.
1341 :
1342 : The upper bound is more complicated. Unless the expressions for initial
1343 : and final value themselves contain enough information, we usually cannot
1344 : derive it from the context. */
1345 :
1346 : /* First check whether the answer does not follow from the bounds we gathered
1347 : before. */
1348 351650 : if (integer_nonzerop (iv0->step))
1349 288431 : dstep = wi::to_widest (iv0->step);
1350 : else
1351 : {
1352 63219 : dstep = wi::sext (wi::to_widest (iv1->step), TYPE_PRECISION (type));
1353 63219 : dstep = -dstep;
1354 : }
1355 :
1356 351650 : mpz_init (mstep);
1357 351650 : wi::to_mpz (dstep, mstep, UNSIGNED);
1358 351650 : mpz_neg (mstep, mstep);
1359 351650 : mpz_add_ui (mstep, mstep, 1);
1360 :
1361 351650 : rolls_p = mpz_cmp (mstep, bnds->below) <= 0;
1362 :
1363 351650 : mpz_init (max);
1364 351650 : wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
1365 351650 : mpz_add (max, max, mstep);
1366 703300 : no_overflow_p = (mpz_cmp (bnds->up, max) <= 0
1367 : /* For pointers, only values lying inside a single object
1368 : can be compared or manipulated by pointer arithmetics.
1369 : Gcc in general does not allow or handle objects larger
1370 : than half of the address space, hence the upper bound
1371 : is satisfied for pointers. */
1372 351650 : || POINTER_TYPE_P (type));
1373 351650 : mpz_clear (mstep);
1374 351650 : mpz_clear (max);
1375 :
1376 351650 : if (rolls_p && no_overflow_p)
1377 128977 : return;
1378 :
1379 222673 : type1 = type;
1380 222673 : if (POINTER_TYPE_P (type))
1381 68016 : type1 = sizetype;
1382 :
1383 : /* Now the hard part; we must formulate the assumption(s) as expressions, and
1384 : we must be careful not to introduce overflow. */
1385 :
1386 222673 : if (integer_nonzerop (iv0->step))
1387 : {
1388 180830 : diff = fold_build2 (MINUS_EXPR, type1,
1389 : iv0->step, build_int_cst (type1, 1));
1390 :
1391 : /* We need to know that iv0->base >= MIN + iv0->step - 1. Since
1392 : 0 address never belongs to any object, we can assume this for
1393 : pointers. */
1394 180830 : if (!POINTER_TYPE_P (type))
1395 : {
1396 116817 : bound = fold_build2 (PLUS_EXPR, type1,
1397 : TYPE_MIN_VALUE (type), diff);
1398 116817 : assumption = fold_build2 (GE_EXPR, boolean_type_node,
1399 : iv0->base, bound);
1400 : }
1401 :
1402 : /* And then we can compute iv0->base - diff, and compare it with
1403 : iv1->base. */
1404 180830 : mbzl = fold_build2 (MINUS_EXPR, type1,
1405 : fold_convert (type1, iv0->base), diff);
1406 180830 : mbzr = fold_convert (type1, iv1->base);
1407 : }
1408 : else
1409 : {
1410 41843 : diff = fold_build2 (PLUS_EXPR, type1,
1411 : iv1->step, build_int_cst (type1, 1));
1412 :
1413 41843 : if (!POINTER_TYPE_P (type))
1414 : {
1415 37840 : bound = fold_build2 (PLUS_EXPR, type1,
1416 : TYPE_MAX_VALUE (type), diff);
1417 37840 : assumption = fold_build2 (LE_EXPR, boolean_type_node,
1418 : iv1->base, bound);
1419 : }
1420 :
1421 41843 : mbzl = fold_convert (type1, iv0->base);
1422 41843 : mbzr = fold_build2 (MINUS_EXPR, type1,
1423 : fold_convert (type1, iv1->base), diff);
1424 : }
1425 :
1426 222673 : if (!integer_nonzerop (assumption))
1427 94341 : niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1428 : niter->assumptions, assumption);
1429 222673 : if (!rolls_p)
1430 : {
1431 205626 : mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
1432 205626 : niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1433 : niter->may_be_zero, mbz);
1434 : }
1435 351650 : }
1436 :
1437 : /* Determines number of iterations of loop whose ending condition
1438 : is IV0 < IV1 which likes: {base, -C} < n, or n < {base, C}.
1439 : The number of iterations is stored to NITER. */
1440 :
1441 : static bool
1442 66741 : number_of_iterations_until_wrap (class loop *loop, tree type, affine_iv *iv0,
1443 : affine_iv *iv1, class tree_niter_desc *niter)
1444 : {
1445 66741 : tree niter_type = unsigned_type_for (type);
1446 66741 : tree step, num, assumptions, may_be_zero, span;
1447 66741 : wide_int high, low, max, min;
1448 :
1449 66741 : may_be_zero = fold_build2 (LE_EXPR, boolean_type_node, iv1->base, iv0->base);
1450 66741 : if (integer_onep (may_be_zero))
1451 : return false;
1452 :
1453 66527 : int prec = TYPE_PRECISION (type);
1454 66527 : signop sgn = TYPE_SIGN (type);
1455 66527 : min = wi::min_value (prec, sgn);
1456 66527 : max = wi::max_value (prec, sgn);
1457 :
1458 : /* n < {base, C}. */
1459 66527 : if (integer_zerop (iv0->step) && !tree_int_cst_sign_bit (iv1->step))
1460 : {
1461 : /* MIN + C - 1 <= n. */
1462 41637 : tree last = wide_int_to_tree (type, min + wi::to_wide (iv1->step) - 1);
1463 41637 : assumptions = fold_build2 (LE_EXPR, boolean_type_node, last, iv0->base);
1464 41637 : if (integer_zerop (assumptions))
1465 : return false;
1466 :
1467 41635 : step = fold_convert (niter_type, iv1->step);
1468 41635 : num = fold_build2 (MINUS_EXPR, niter_type,
1469 : wide_int_to_tree (niter_type, max),
1470 : fold_convert (niter_type, iv1->base));
1471 :
1472 : /* When base has the form iv + 1, if we know iv >= n, then iv + 1 < n
1473 : only when iv + 1 overflows, i.e. when iv == TYPE_VALUE_MAX. */
1474 41635 : if (sgn == UNSIGNED
1475 6253 : && integer_onep (step)
1476 1081 : && TREE_CODE (iv1->base) == PLUS_EXPR
1477 42312 : && integer_onep (TREE_OPERAND (iv1->base, 1)))
1478 : {
1479 471 : tree cond = fold_build2 (GE_EXPR, boolean_type_node,
1480 : TREE_OPERAND (iv1->base, 0), iv0->base);
1481 471 : cond = simplify_using_initial_conditions (loop, cond);
1482 471 : if (integer_onep (cond))
1483 31 : may_be_zero = fold_build2 (EQ_EXPR, boolean_type_node,
1484 : TREE_OPERAND (iv1->base, 0),
1485 : TYPE_MAX_VALUE (type));
1486 : }
1487 :
1488 41635 : high = max;
1489 41635 : if (TREE_CODE (iv1->base) == INTEGER_CST)
1490 28847 : low = wi::to_wide (iv1->base) - 1;
1491 12788 : else if (TREE_CODE (iv0->base) == INTEGER_CST)
1492 6261 : low = wi::to_wide (iv0->base);
1493 : else
1494 6527 : low = min;
1495 : }
1496 : /* {base, -C} < n. */
1497 24890 : else if (tree_int_cst_sign_bit (iv0->step) && integer_zerop (iv1->step))
1498 : {
1499 : /* MAX + (-C) + 1 >= n. */
1500 24890 : tree last = wide_int_to_tree (type, max + wi::to_wide (iv0->step) + 1);
1501 24890 : assumptions = fold_build2 (GE_EXPR, boolean_type_node, last, iv1->base);
1502 24890 : if (integer_zerop (assumptions))
1503 : return false;
1504 :
1505 24890 : step = fold_build1 (NEGATE_EXPR, niter_type,
1506 : fold_convert (niter_type, iv0->step));
1507 24890 : num = fold_build2 (MINUS_EXPR, niter_type,
1508 : fold_convert (niter_type, iv0->base),
1509 : wide_int_to_tree (niter_type, min));
1510 24890 : low = min;
1511 24890 : if (TREE_CODE (iv0->base) == INTEGER_CST)
1512 1320 : high = wi::to_wide (iv0->base) + 1;
1513 23570 : else if (TREE_CODE (iv1->base) == INTEGER_CST)
1514 2318 : high = wi::to_wide (iv1->base);
1515 : else
1516 21252 : high = max;
1517 : }
1518 : else
1519 : return false;
1520 :
1521 : /* (delta + step - 1) / step */
1522 66525 : num = fold_build2 (PLUS_EXPR, niter_type, num, step);
1523 66525 : niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, num, step);
1524 :
1525 66525 : widest_int delta, s;
1526 66525 : delta = widest_int::from (high, sgn) - widest_int::from (low, sgn);
1527 66525 : s = wi::to_widest (step);
1528 66525 : delta = delta + s - 1;
1529 66525 : niter->max = wi::udiv_floor (delta, s);
1530 :
1531 66525 : niter->may_be_zero = may_be_zero;
1532 :
1533 66525 : if (!integer_nonzerop (assumptions))
1534 8783 : niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1535 : niter->assumptions, assumptions);
1536 :
1537 66525 : niter->control.no_overflow = false;
1538 :
1539 : /* Update bound and exit condition as:
1540 : bound = niter * STEP + (IVbase - STEP).
1541 : { IVbase - STEP, +, STEP } != bound
1542 : Here, biasing IVbase by 1 step makes 'bound' be the value before wrap.
1543 : */
1544 66525 : tree base_type = TREE_TYPE (niter->control.base);
1545 66525 : if (POINTER_TYPE_P (base_type))
1546 : {
1547 6107 : tree utype = unsigned_type_for (base_type);
1548 6107 : niter->control.base
1549 6107 : = fold_build2 (MINUS_EXPR, utype,
1550 : fold_convert (utype, niter->control.base),
1551 : fold_convert (utype, niter->control.step));
1552 6107 : niter->control.base = fold_convert (base_type, niter->control.base);
1553 : }
1554 : else
1555 60418 : niter->control.base
1556 60418 : = fold_build2 (MINUS_EXPR, base_type, niter->control.base,
1557 : niter->control.step);
1558 :
1559 66525 : span = fold_build2 (MULT_EXPR, niter_type, niter->niter,
1560 : fold_convert (niter_type, niter->control.step));
1561 66525 : niter->bound = fold_build2 (PLUS_EXPR, niter_type, span,
1562 : fold_convert (niter_type, niter->control.base));
1563 66525 : niter->bound = fold_convert (type, niter->bound);
1564 66525 : niter->cmp = NE_EXPR;
1565 :
1566 66525 : return true;
1567 66741 : }
1568 :
1569 : /* Determines number of iterations of loop whose ending condition
1570 : is IV0 < IV1. TYPE is the type of the iv. The number of
1571 : iterations is stored to NITER. BNDS bounds the difference
1572 : IV1->base - IV0->base. EXIT_MUST_BE_TAKEN is true if we know
1573 : that the exit must be taken eventually. */
1574 :
1575 : static bool
1576 5619549 : number_of_iterations_lt (class loop *loop, tree type, affine_iv *iv0,
1577 : affine_iv *iv1, class tree_niter_desc *niter,
1578 : bool exit_must_be_taken, bounds *bnds)
1579 : {
1580 5619549 : tree niter_type = unsigned_type_for (type);
1581 5619549 : tree delta, step, s;
1582 5619549 : mpz_t mstep, tmp;
1583 :
1584 5619549 : if (integer_nonzerop (iv0->step))
1585 : {
1586 5281907 : niter->control = *iv0;
1587 5281907 : niter->cmp = LT_EXPR;
1588 5281907 : niter->bound = iv1->base;
1589 : }
1590 : else
1591 : {
1592 337642 : niter->control = *iv1;
1593 337642 : niter->cmp = GT_EXPR;
1594 337642 : niter->bound = iv0->base;
1595 : }
1596 :
1597 : /* {base, -C} < n, or n < {base, C} */
1598 5619549 : if (tree_int_cst_sign_bit (iv0->step)
1599 5619549 : || (!integer_zerop (iv1->step) && !tree_int_cst_sign_bit (iv1->step)))
1600 66741 : return number_of_iterations_until_wrap (loop, type, iv0, iv1, niter);
1601 :
1602 5552808 : delta = fold_build2 (MINUS_EXPR, niter_type,
1603 : fold_convert (niter_type, iv1->base),
1604 : fold_convert (niter_type, iv0->base));
1605 :
1606 : /* First handle the special case that the step is +-1. */
1607 10489321 : if ((integer_onep (iv0->step) && integer_zerop (iv1->step))
1608 5552808 : || (integer_all_onesp (iv1->step) && integer_zerop (iv0->step)))
1609 : {
1610 : /* for (i = iv0->base; i < iv1->base; i++)
1611 :
1612 : or
1613 :
1614 : for (i = iv1->base; i > iv0->base; i--).
1615 :
1616 : In both cases # of iterations is iv1->base - iv0->base, assuming that
1617 : iv1->base >= iv0->base.
1618 :
1619 : First try to derive a lower bound on the value of
1620 : iv1->base - iv0->base, computed in full precision. If the difference
1621 : is nonnegative, we are done, otherwise we must record the
1622 : condition. */
1623 :
1624 5164273 : if (mpz_sgn (bnds->below) < 0)
1625 1940583 : niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
1626 : iv1->base, iv0->base);
1627 5164273 : niter->niter = delta;
1628 10328546 : niter->max = widest_int::from (wi::from_mpz (niter_type, bnds->up, false),
1629 10328546 : TYPE_SIGN (niter_type));
1630 5164273 : niter->control.no_overflow = true;
1631 5164273 : return true;
1632 : }
1633 :
1634 388535 : if (integer_nonzerop (iv0->step))
1635 320504 : step = fold_convert (niter_type, iv0->step);
1636 : else
1637 68031 : step = fold_build1 (NEGATE_EXPR, niter_type,
1638 : fold_convert (niter_type, iv1->step));
1639 :
1640 : /* If we can determine the final value of the control iv exactly, we can
1641 : transform the condition to != comparison. In particular, this will be
1642 : the case if DELTA is constant. */
1643 388535 : if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step,
1644 : exit_must_be_taken, bnds))
1645 : {
1646 36819 : affine_iv zps;
1647 :
1648 36819 : zps.base = build_int_cst (niter_type, 0);
1649 36819 : zps.step = step;
1650 : /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1651 : zps does not overflow. */
1652 36819 : zps.no_overflow = true;
1653 :
1654 36819 : return number_of_iterations_ne (loop, type, &zps,
1655 : delta, niter, true, bnds);
1656 : }
1657 :
1658 : /* Make sure that the control iv does not overflow. */
1659 351716 : if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
1660 : return false;
1661 :
1662 : /* We determine the number of iterations as (delta + step - 1) / step. For
1663 : this to work, we must know that iv1->base >= iv0->base - step + 1,
1664 : otherwise the loop does not roll. */
1665 351650 : assert_loop_rolls_lt (type, iv0, iv1, niter, bnds);
1666 :
1667 351650 : s = fold_build2 (MINUS_EXPR, niter_type,
1668 : step, build_int_cst (niter_type, 1));
1669 351650 : delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
1670 351650 : niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
1671 :
1672 351650 : mpz_init (mstep);
1673 351650 : mpz_init (tmp);
1674 351650 : wi::to_mpz (wi::to_wide (step), mstep, UNSIGNED);
1675 351650 : mpz_add (tmp, bnds->up, mstep);
1676 351650 : mpz_sub_ui (tmp, tmp, 1);
1677 351650 : mpz_fdiv_q (tmp, tmp, mstep);
1678 703300 : niter->max = widest_int::from (wi::from_mpz (niter_type, tmp, false),
1679 703300 : TYPE_SIGN (niter_type));
1680 351650 : mpz_clear (mstep);
1681 351650 : mpz_clear (tmp);
1682 :
1683 351650 : return true;
1684 : }
1685 :
1686 : /* Determines number of iterations of loop whose ending condition
1687 : is IV0 <= IV1. TYPE is the type of the iv. The number of
1688 : iterations is stored to NITER. EXIT_MUST_BE_TAKEN is true if
1689 : we know that this condition must eventually become false (we derived this
1690 : earlier, and possibly set NITER->assumptions to make sure this
1691 : is the case). BNDS bounds the difference IV1->base - IV0->base. */
1692 :
1693 : static bool
1694 2127492 : number_of_iterations_le (class loop *loop, tree type, affine_iv *iv0,
1695 : affine_iv *iv1, class tree_niter_desc *niter,
1696 : bool exit_must_be_taken, bounds *bnds)
1697 : {
1698 2127492 : tree assumption;
1699 2127492 : tree type1 = type;
1700 2127492 : if (POINTER_TYPE_P (type))
1701 6160 : type1 = sizetype;
1702 :
1703 : /* Say that IV0 is the control variable. Then IV0 <= IV1 iff
1704 : IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1705 : value of the type. This we must know anyway, since if it is
1706 : equal to this value, the loop rolls forever. We do not check
1707 : this condition for pointer type ivs, as the code cannot rely on
1708 : the object to that the pointer points being placed at the end of
1709 : the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1710 : not defined for pointers). */
1711 :
1712 2127492 : if (!exit_must_be_taken && !POINTER_TYPE_P (type))
1713 : {
1714 659281 : if (integer_nonzerop (iv0->step))
1715 594891 : assumption = fold_build2 (NE_EXPR, boolean_type_node,
1716 : iv1->base, TYPE_MAX_VALUE (type));
1717 : else
1718 64390 : assumption = fold_build2 (NE_EXPR, boolean_type_node,
1719 : iv0->base, TYPE_MIN_VALUE (type));
1720 :
1721 659281 : if (integer_zerop (assumption))
1722 : return false;
1723 659217 : if (!integer_nonzerop (assumption))
1724 257398 : niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1725 : niter->assumptions, assumption);
1726 : }
1727 :
1728 2127428 : if (integer_nonzerop (iv0->step))
1729 : {
1730 2028457 : if (POINTER_TYPE_P (type))
1731 1238 : iv1->base = fold_build_pointer_plus_hwi (iv1->base, 1);
1732 : else
1733 2027219 : iv1->base = fold_build2 (PLUS_EXPR, type1, iv1->base,
1734 : build_int_cst (type1, 1));
1735 : }
1736 98971 : else if (POINTER_TYPE_P (type))
1737 4922 : iv0->base = fold_build_pointer_plus_hwi (iv0->base, -1);
1738 : else
1739 94049 : iv0->base = fold_build2 (MINUS_EXPR, type1,
1740 : iv0->base, build_int_cst (type1, 1));
1741 :
1742 2127428 : bounds_add (bnds, 1, type1);
1743 :
1744 2127428 : return number_of_iterations_lt (loop, type, iv0, iv1, niter, exit_must_be_taken,
1745 2127428 : bnds);
1746 : }
1747 :
1748 : /* Dumps description of affine induction variable IV to FILE. */
1749 :
1750 : static void
1751 95236 : dump_affine_iv (FILE *file, affine_iv *iv)
1752 : {
1753 95236 : if (!integer_zerop (iv->step))
1754 47618 : fprintf (file, "[");
1755 :
1756 95236 : print_generic_expr (file, iv->base, TDF_SLIM);
1757 :
1758 95236 : if (!integer_zerop (iv->step))
1759 : {
1760 47618 : fprintf (file, ", + , ");
1761 47618 : print_generic_expr (file, iv->step, TDF_SLIM);
1762 84709 : fprintf (file, "]%s", iv->no_overflow ? "(no_overflow)" : "");
1763 : }
1764 95236 : }
1765 :
1766 : DEBUG_FUNCTION void
1767 0 : debug (affine_iv *iv)
1768 : {
1769 0 : dump_affine_iv (stderr, iv);
1770 0 : fputc ('\n', stderr);
1771 0 : }
1772 :
1773 : /* Determine the number of iterations according to condition (for staying
1774 : inside loop) which compares two induction variables using comparison
1775 : operator CODE. The induction variable on left side of the comparison
1776 : is IV0, the right-hand side is IV1. Both induction variables must have
1777 : type TYPE, which must be an integer or pointer type. The steps of the
1778 : ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1779 :
1780 : LOOP is the loop whose number of iterations we are determining.
1781 :
1782 : ONLY_EXIT is true if we are sure this is the only way the loop could be
1783 : exited (including possibly non-returning function calls, exceptions, etc.)
1784 : -- in this case we can use the information whether the control induction
1785 : variables can overflow or not in a more efficient way.
1786 :
1787 : if EVERY_ITERATION is true, we know the test is executed on every iteration.
1788 :
1789 : The results (number of iterations and assumptions as described in
1790 : comments at class tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1791 : Returns false if it fails to determine number of iterations, true if it
1792 : was determined (possibly with some assumptions). */
1793 :
1794 : static bool
1795 13498090 : number_of_iterations_cond (class loop *loop,
1796 : tree type, affine_iv *iv0, enum tree_code code,
1797 : affine_iv *iv1, class tree_niter_desc *niter,
1798 : bool only_exit, bool every_iteration)
1799 : {
1800 13498090 : bool exit_must_be_taken = false, ret;
1801 13498090 : bounds bnds;
1802 :
1803 : /* If the test is not executed every iteration, wrapping may make the test
1804 : to pass again.
1805 : TODO: the overflow case can be still used as unreliable estimate of upper
1806 : bound. But we have no API to pass it down to number of iterations code
1807 : and, at present, it will not use it anyway. */
1808 13498090 : if (!every_iteration
1809 67744 : && (!iv0->no_overflow || !iv1->no_overflow
1810 44547 : || code == NE_EXPR || code == EQ_EXPR))
1811 : return false;
1812 :
1813 : /* The meaning of these assumptions is this:
1814 : if !assumptions
1815 : then the rest of information does not have to be valid
1816 : if may_be_zero then the loop does not roll, even if
1817 : niter != 0. */
1818 13451206 : niter->assumptions = boolean_true_node;
1819 13451206 : niter->may_be_zero = boolean_false_node;
1820 13451206 : niter->niter = NULL_TREE;
1821 13451206 : niter->max = 0;
1822 13451206 : niter->bound = NULL_TREE;
1823 13451206 : niter->cmp = ERROR_MARK;
1824 :
1825 : /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1826 : the control variable is on lhs. */
1827 13451206 : if (code == GE_EXPR || code == GT_EXPR
1828 13451206 : || (code == NE_EXPR && integer_zerop (iv0->step)))
1829 : {
1830 3155117 : std::swap (iv0, iv1);
1831 3155117 : code = swap_tree_comparison (code);
1832 : }
1833 :
1834 13451206 : if (POINTER_TYPE_P (type))
1835 : {
1836 : /* Comparison of pointers is undefined unless both iv0 and iv1 point
1837 : to the same object. If they do, the control variable cannot wrap
1838 : (as wrap around the bounds of memory will never return a pointer
1839 : that would be guaranteed to point to the same object, even if we
1840 : avoid undefined behavior by casting to size_t and back). */
1841 794508 : iv0->no_overflow = true;
1842 794508 : iv1->no_overflow = true;
1843 : }
1844 :
1845 : /* If the control induction variable does not overflow and the only exit
1846 : from the loop is the one that we analyze, we know it must be taken
1847 : eventually. */
1848 13451206 : if (only_exit)
1849 : {
1850 8813700 : if (!integer_zerop (iv0->step) && iv0->no_overflow)
1851 : exit_must_be_taken = true;
1852 2223757 : else if (!integer_zerop (iv1->step) && iv1->no_overflow)
1853 6752525 : exit_must_be_taken = true;
1854 : }
1855 :
1856 : /* We can handle cases which neither of the sides of the comparison is
1857 : invariant:
1858 :
1859 : {iv0.base, iv0.step} cmp_code {iv1.base, iv1.step}
1860 : as if:
1861 : {iv0.base, iv0.step - iv1.step} cmp_code {iv1.base, 0}
1862 :
1863 : provided that either below condition is satisfied:
1864 :
1865 : a) the test is NE_EXPR;
1866 : b) iv0 and iv1 do not overflow and iv0.step - iv1.step is of
1867 : the same sign and of less or equal magnitude than iv0.step
1868 :
1869 : This rarely occurs in practice, but it is simple enough to manage. */
1870 13451206 : if (!integer_zerop (iv0->step) && !integer_zerop (iv1->step))
1871 : {
1872 5533 : tree step_type = POINTER_TYPE_P (type) ? sizetype : type;
1873 5533 : tree step = fold_binary_to_constant (MINUS_EXPR, step_type,
1874 : iv0->step, iv1->step);
1875 :
1876 : /* For code other than NE_EXPR we have to ensure moving the evolution
1877 : of IV1 to that of IV0 does not introduce overflow. */
1878 5533 : if (TREE_CODE (step) != INTEGER_CST
1879 5533 : || !iv0->no_overflow || !iv1->no_overflow)
1880 : {
1881 1279 : if (code != NE_EXPR)
1882 : return false;
1883 0 : iv0->no_overflow = false;
1884 : }
1885 : /* If the new step of IV0 has changed sign or is of greater
1886 : magnitude then we do not know whether IV0 does overflow
1887 : and thus the transform is not valid for code other than NE_EXPR. */
1888 4254 : else if (tree_int_cst_sign_bit (step) != tree_int_cst_sign_bit (iv0->step)
1889 7912 : || wi::gtu_p (wi::abs (wi::to_widest (step)),
1890 11570 : wi::abs (wi::to_widest (iv0->step))))
1891 : {
1892 2988 : if (POINTER_TYPE_P (type) && code != NE_EXPR)
1893 : /* For relational pointer compares we have further guarantees
1894 : that the pointers always point to the same object (or one
1895 : after it) and that objects do not cross the zero page. So
1896 : not only is the transform always valid for relational
1897 : pointer compares, we also know the resulting IV does not
1898 : overflow. */
1899 : ;
1900 813 : else if (code != NE_EXPR)
1901 : return false;
1902 : else
1903 450 : iv0->no_overflow = false;
1904 : }
1905 :
1906 3441 : iv0->step = step;
1907 3441 : iv1->step = build_int_cst (step_type, 0);
1908 3441 : iv1->no_overflow = true;
1909 : }
1910 :
1911 : /* If the result of the comparison is a constant, the loop is weird. More
1912 : precise handling would be possible, but the situation is not common enough
1913 : to waste time on it. */
1914 13449114 : if (integer_zerop (iv0->step) && integer_zerop (iv1->step))
1915 : return false;
1916 :
1917 : /* If the loop exits immediately, there is nothing to do. */
1918 13350324 : tree tem = fold_binary (code, boolean_type_node, iv0->base, iv1->base);
1919 13350324 : if (tem && integer_zerop (tem))
1920 : {
1921 91377 : if (!every_iteration)
1922 : return false;
1923 91314 : niter->niter = build_int_cst (unsigned_type_for (type), 0);
1924 91314 : niter->max = 0;
1925 91314 : return true;
1926 : }
1927 :
1928 : /* OK, now we know we have a senseful loop. Handle several cases, depending
1929 : on what comparison operator is used. */
1930 13258947 : bound_difference (loop, iv1->base, iv0->base, &bnds);
1931 :
1932 13258947 : if (dump_file && (dump_flags & TDF_DETAILS))
1933 : {
1934 47618 : fprintf (dump_file,
1935 : "Analyzing # of iterations of loop %d\n", loop->num);
1936 :
1937 47618 : fprintf (dump_file, " exit condition ");
1938 47618 : dump_affine_iv (dump_file, iv0);
1939 57391 : fprintf (dump_file, " %s ",
1940 : code == NE_EXPR ? "!="
1941 9773 : : code == LT_EXPR ? "<"
1942 : : "<=");
1943 47618 : dump_affine_iv (dump_file, iv1);
1944 47618 : fprintf (dump_file, "\n");
1945 :
1946 47618 : fprintf (dump_file, " bounds on difference of bases: ");
1947 47618 : mpz_out_str (dump_file, 10, bnds.below);
1948 47618 : fprintf (dump_file, " ... ");
1949 47618 : mpz_out_str (dump_file, 10, bnds.up);
1950 47618 : fprintf (dump_file, "\n");
1951 : }
1952 :
1953 13258947 : switch (code)
1954 : {
1955 7639334 : case NE_EXPR:
1956 7639334 : gcc_assert (integer_zerop (iv1->step));
1957 7639334 : ret = number_of_iterations_ne (loop, type, iv0, iv1->base, niter,
1958 : exit_must_be_taken, &bnds);
1959 7639334 : break;
1960 :
1961 3492121 : case LT_EXPR:
1962 3492121 : ret = number_of_iterations_lt (loop, type, iv0, iv1, niter,
1963 : exit_must_be_taken, &bnds);
1964 3492121 : break;
1965 :
1966 2127492 : case LE_EXPR:
1967 2127492 : ret = number_of_iterations_le (loop, type, iv0, iv1, niter,
1968 : exit_must_be_taken, &bnds);
1969 2127492 : break;
1970 :
1971 0 : default:
1972 0 : gcc_unreachable ();
1973 : }
1974 :
1975 13258947 : mpz_clear (bnds.up);
1976 13258947 : mpz_clear (bnds.below);
1977 :
1978 13258947 : if (dump_file && (dump_flags & TDF_DETAILS))
1979 : {
1980 47618 : if (ret)
1981 : {
1982 47618 : fprintf (dump_file, " result:\n");
1983 47618 : if (!integer_nonzerop (niter->assumptions))
1984 : {
1985 303 : fprintf (dump_file, " under assumptions ");
1986 303 : print_generic_expr (dump_file, niter->assumptions, TDF_SLIM);
1987 303 : fprintf (dump_file, "\n");
1988 : }
1989 :
1990 47618 : if (!integer_zerop (niter->may_be_zero))
1991 : {
1992 717 : fprintf (dump_file, " zero if ");
1993 717 : print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
1994 717 : fprintf (dump_file, "\n");
1995 : }
1996 :
1997 47618 : fprintf (dump_file, " # of iterations ");
1998 47618 : print_generic_expr (dump_file, niter->niter, TDF_SLIM);
1999 47618 : fprintf (dump_file, ", bounded by ");
2000 47618 : print_decu (niter->max, dump_file);
2001 47618 : fprintf (dump_file, "\n");
2002 : }
2003 : else
2004 0 : fprintf (dump_file, " failed\n\n");
2005 : }
2006 : return ret;
2007 : }
2008 :
2009 : /* Return an expression that computes the popcount of src. */
2010 :
2011 : static tree
2012 3587 : build_popcount_expr (tree src)
2013 : {
2014 3587 : tree fn;
2015 3587 : bool use_ifn = false;
2016 3587 : int prec = TYPE_PRECISION (TREE_TYPE (src));
2017 3587 : int i_prec = TYPE_PRECISION (integer_type_node);
2018 3587 : int li_prec = TYPE_PRECISION (long_integer_type_node);
2019 3587 : int lli_prec = TYPE_PRECISION (long_long_integer_type_node);
2020 :
2021 3587 : tree utype = unsigned_type_for (TREE_TYPE (src));
2022 3587 : src = fold_convert (utype, src);
2023 :
2024 3587 : if (direct_internal_fn_supported_p (IFN_POPCOUNT, utype, OPTIMIZE_FOR_BOTH))
2025 : use_ifn = true;
2026 3536 : else if (prec <= i_prec)
2027 3460 : fn = builtin_decl_implicit (BUILT_IN_POPCOUNT);
2028 76 : else if (prec == li_prec)
2029 59 : fn = builtin_decl_implicit (BUILT_IN_POPCOUNTL);
2030 17 : else if (prec == lli_prec || prec == 2 * lli_prec)
2031 17 : fn = builtin_decl_implicit (BUILT_IN_POPCOUNTLL);
2032 : else
2033 : return NULL_TREE;
2034 :
2035 3587 : tree call;
2036 3536 : if (use_ifn)
2037 51 : call = build_call_expr_internal_loc (UNKNOWN_LOCATION, IFN_POPCOUNT,
2038 : integer_type_node, 1, src);
2039 3536 : else if (prec == 2 * lli_prec)
2040 : {
2041 17 : tree src1 = fold_convert (long_long_unsigned_type_node,
2042 : fold_build2 (RSHIFT_EXPR, TREE_TYPE (src),
2043 : unshare_expr (src),
2044 : build_int_cst (integer_type_node,
2045 : lli_prec)));
2046 17 : tree src2 = fold_convert (long_long_unsigned_type_node, src);
2047 17 : tree call1 = build_call_expr (fn, 1, src1);
2048 17 : tree call2 = build_call_expr (fn, 1, src2);
2049 17 : call = fold_build2 (PLUS_EXPR, integer_type_node, call1, call2);
2050 : }
2051 : else
2052 : {
2053 3519 : if (prec < i_prec)
2054 293 : src = fold_convert (unsigned_type_node, src);
2055 :
2056 3519 : call = build_call_expr (fn, 1, src);
2057 : }
2058 :
2059 : return call;
2060 : }
2061 :
2062 : /* Utility function to check if OP is defined by a stmt
2063 : that is a val - 1. */
2064 :
2065 : static bool
2066 138280 : ssa_defined_by_minus_one_stmt_p (tree op, tree val)
2067 : {
2068 138280 : gassign *stmt;
2069 138280 : return (TREE_CODE (op) == SSA_NAME
2070 165889 : && (stmt = safe_dyn_cast<gassign *> (SSA_NAME_DEF_STMT (op)))
2071 76439 : && (gimple_assign_rhs_code (stmt) == PLUS_EXPR)
2072 10474 : && val == gimple_assign_rhs1 (stmt)
2073 142322 : && integer_minus_onep (gimple_assign_rhs2 (stmt)));
2074 : }
2075 :
2076 : /* See comment below for number_of_iterations_bitcount.
2077 : For popcount, we have:
2078 :
2079 : modify:
2080 : _1 = iv_1 + -1
2081 : iv_2 = iv_1 & _1
2082 :
2083 : test:
2084 : if (iv != 0)
2085 :
2086 : modification count:
2087 : popcount (src)
2088 :
2089 : */
2090 :
2091 : static bool
2092 3907382 : number_of_iterations_popcount (loop_p loop, const_edge exit,
2093 : enum tree_code code,
2094 : class tree_niter_desc *niter)
2095 : {
2096 3907382 : bool modify_before_test = true;
2097 3907382 : HOST_WIDE_INT max;
2098 :
2099 : /* Check that condition for staying inside the loop is like
2100 : if (iv != 0). */
2101 7814764 : gcond *cond_stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
2102 3907382 : if (!cond_stmt
2103 3907382 : || code != NE_EXPR
2104 1943205 : || !integer_zerop (gimple_cond_rhs (cond_stmt))
2105 5288761 : || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2106 : return false;
2107 :
2108 1381379 : tree iv_2 = gimple_cond_lhs (cond_stmt);
2109 1381379 : gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2110 1381379 : gimple *test_phi = NULL;
2111 :
2112 : /* If the test comes before the iv modification, then these will actually be
2113 : iv_1 and a phi node. */
2114 1381379 : if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2115 393046 : && gimple_bb (iv_2_stmt) == loop->header
2116 298396 : && gimple_phi_num_args (iv_2_stmt) == 2
2117 1679775 : && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2118 : loop_latch_edge (loop)->dest_idx))
2119 : == SSA_NAME))
2120 : {
2121 : /* iv_2 is actually one of the inputs to the phi. */
2122 275332 : test_phi = iv_2_stmt;
2123 275332 : iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2124 275332 : iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2125 275332 : modify_before_test = false;
2126 : }
2127 :
2128 : /* Make sure iv_2_stmt is an and stmt (iv_2 = _1 & iv_1). */
2129 1381379 : if (!is_gimple_assign (iv_2_stmt)
2130 1381379 : || gimple_assign_rhs_code (iv_2_stmt) != BIT_AND_EXPR)
2131 : return false;
2132 :
2133 70191 : tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2134 70191 : tree _1 = gimple_assign_rhs2 (iv_2_stmt);
2135 :
2136 : /* Check that _1 is defined by (_1 = iv_1 + -1).
2137 : Also make sure that _1 is the same in and_stmt and _1 defining stmt.
2138 : Also canonicalize if _1 and _b11 are reversed. */
2139 70191 : if (ssa_defined_by_minus_one_stmt_p (iv_1, _1))
2140 : std::swap (iv_1, _1);
2141 68089 : else if (ssa_defined_by_minus_one_stmt_p (_1, iv_1))
2142 : ;
2143 : else
2144 : return false;
2145 :
2146 : /* Check the recurrence. A test before the modification must test the
2147 : PHI of the recurrence. */
2148 3811 : gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2149 3811 : if (gimple_code (phi) != GIMPLE_PHI
2150 3811 : || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2151 3792 : || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx))
2152 7603 : || (test_phi && phi != test_phi))
2153 : return false;
2154 :
2155 : /* We found a match. */
2156 3587 : tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2157 3587 : int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2158 :
2159 : /* Get the corresponding popcount builtin. */
2160 3587 : tree expr = build_popcount_expr (src);
2161 :
2162 3587 : if (!expr)
2163 : return false;
2164 :
2165 3587 : max = src_precision;
2166 :
2167 3587 : tree may_be_zero = boolean_false_node;
2168 :
2169 3587 : if (modify_before_test)
2170 : {
2171 1735 : expr = fold_build2 (MINUS_EXPR, integer_type_node, expr,
2172 : integer_one_node);
2173 1735 : max = max - 1;
2174 1735 : may_be_zero = fold_build2 (EQ_EXPR, boolean_type_node, src,
2175 : build_zero_cst (TREE_TYPE (src)));
2176 : }
2177 :
2178 3587 : expr = fold_convert (unsigned_type_node, expr);
2179 :
2180 3587 : niter->assumptions = boolean_true_node;
2181 3587 : niter->may_be_zero = simplify_using_initial_conditions (loop, may_be_zero);
2182 3587 : niter->niter = simplify_using_initial_conditions(loop, expr);
2183 :
2184 3587 : if (TREE_CODE (niter->niter) == INTEGER_CST)
2185 411 : niter->max = tree_to_uhwi (niter->niter);
2186 : else
2187 3176 : niter->max = max;
2188 :
2189 3587 : niter->bound = NULL_TREE;
2190 3587 : niter->cmp = ERROR_MARK;
2191 3587 : return true;
2192 : }
2193 :
2194 : /* Return an expression that counts the leading/trailing zeroes of src.
2195 :
2196 : If define_at_zero is true, then the built expression will be defined to
2197 : return the precision of src when src == 0 (using the second argument of
2198 : the internal function or a conditional expression).
2199 : Otherwise, the result for src == 0 is undefined. */
2200 :
2201 : static tree
2202 9962 : build_cltz_expr (tree src, bool leading, bool define_at_zero)
2203 : {
2204 9962 : tree fn;
2205 9962 : internal_fn ifn = leading ? IFN_CLZ : IFN_CTZ;
2206 9962 : bool use_ifn = false;
2207 9962 : int prec = TYPE_PRECISION (TREE_TYPE (src));
2208 9962 : int i_prec = TYPE_PRECISION (integer_type_node);
2209 9962 : int li_prec = TYPE_PRECISION (long_integer_type_node);
2210 9962 : int lli_prec = TYPE_PRECISION (long_long_integer_type_node);
2211 :
2212 9962 : tree utype = unsigned_type_for (TREE_TYPE (src));
2213 9962 : src = fold_convert (utype, src);
2214 :
2215 9962 : if (direct_internal_fn_supported_p (ifn, utype, OPTIMIZE_FOR_BOTH))
2216 : use_ifn = true;
2217 3483 : else if (prec <= i_prec)
2218 1728 : fn = leading ? builtin_decl_implicit (BUILT_IN_CLZ)
2219 13445 : : builtin_decl_implicit (BUILT_IN_CTZ);
2220 1755 : else if (prec == li_prec)
2221 0 : fn = leading ? builtin_decl_implicit (BUILT_IN_CLZL)
2222 13445 : : builtin_decl_implicit (BUILT_IN_CTZL);
2223 1755 : else if (prec == lli_prec || prec == 2 * lli_prec)
2224 1755 : fn = leading ? builtin_decl_implicit (BUILT_IN_CLZLL)
2225 13445 : : builtin_decl_implicit (BUILT_IN_CTZLL);
2226 : else
2227 : return NULL_TREE;
2228 :
2229 9962 : tree call;
2230 3483 : if (use_ifn)
2231 : {
2232 6479 : tree arg2 = (define_at_zero
2233 6479 : ? build_int_cst (integer_type_node, prec) : NULL_TREE);
2234 10095 : call = build_call_expr_internal_loc (UNKNOWN_LOCATION, ifn,
2235 : integer_type_node, arg2 ? 2 : 1,
2236 : src, arg2);
2237 : }
2238 3483 : else if (fn == NULL_TREE)
2239 : return NULL_TREE;
2240 3483 : else if (prec == 2 * lli_prec)
2241 : {
2242 844 : tree src1 = fold_convert (long_long_unsigned_type_node,
2243 : fold_build2 (RSHIFT_EXPR, TREE_TYPE (src),
2244 : unshare_expr (src),
2245 : build_int_cst (integer_type_node,
2246 : lli_prec)));
2247 844 : tree src2 = fold_convert (long_long_unsigned_type_node, src);
2248 : /* We count the zeroes in src1, and add the number in src2 when src1
2249 : is 0. */
2250 844 : if (!leading)
2251 0 : std::swap (src1, src2);
2252 844 : tree call1 = build_call_expr (fn, 1, src1);
2253 844 : tree call2 = build_call_expr (fn, 1, src2);
2254 844 : if (define_at_zero)
2255 : {
2256 250 : tree is_zero2 = fold_build2 (NE_EXPR, boolean_type_node, src2,
2257 : build_zero_cst (TREE_TYPE (src2)));
2258 250 : call2 = fold_build3 (COND_EXPR, integer_type_node, is_zero2, call2,
2259 : build_int_cst (integer_type_node, lli_prec));
2260 : }
2261 844 : tree is_zero1 = fold_build2 (NE_EXPR, boolean_type_node, src1,
2262 : build_zero_cst (TREE_TYPE (src1)));
2263 844 : call = fold_build3 (COND_EXPR, integer_type_node, is_zero1, call1,
2264 : fold_build2 (PLUS_EXPR, integer_type_node, call2,
2265 : build_int_cst (integer_type_node,
2266 : lli_prec)));
2267 : }
2268 : else
2269 : {
2270 2639 : if (prec < i_prec)
2271 1728 : src = fold_convert (unsigned_type_node, src);
2272 :
2273 2639 : call = build_call_expr (fn, 1, src);
2274 2639 : if (leading && prec < i_prec)
2275 1547 : call = fold_build2 (MINUS_EXPR, integer_type_node, call,
2276 : build_int_cst (integer_type_node, i_prec - prec));
2277 2639 : if (define_at_zero)
2278 : {
2279 : /* SRC can be a shift, so do not share it with the call. */
2280 938 : tree is_zero = fold_build2 (NE_EXPR, boolean_type_node,
2281 : unshare_expr (src),
2282 : build_zero_cst (TREE_TYPE (src)));
2283 938 : call = fold_build3 (COND_EXPR, integer_type_node, is_zero, call,
2284 : build_int_cst (integer_type_node, prec));
2285 : }
2286 : }
2287 :
2288 : return call;
2289 : }
2290 :
2291 : /* Returns true if STMT is equivalent to x << 1. */
2292 :
2293 : static bool
2294 1171090 : is_lshift_by_1 (gassign *stmt)
2295 : {
2296 1171090 : if (gimple_assign_rhs_code (stmt) == LSHIFT_EXPR
2297 1172545 : && integer_onep (gimple_assign_rhs2 (stmt)))
2298 : return true;
2299 1170203 : if (gimple_assign_rhs_code (stmt) == MULT_EXPR
2300 1338 : && tree_fits_shwi_p (gimple_assign_rhs2 (stmt))
2301 1171223 : && tree_to_shwi (gimple_assign_rhs2 (stmt)) == 2)
2302 227 : return true;
2303 : return false;
2304 : }
2305 :
2306 : /* Returns true if STMT is equivalent to x >> 1. */
2307 :
2308 : static bool
2309 1169976 : is_rshift_by_1 (gassign *stmt)
2310 : {
2311 1169976 : if (gimple_assign_rhs_code (stmt) == RSHIFT_EXPR
2312 1194075 : && integer_onep (gimple_assign_rhs2 (stmt)))
2313 : return true;
2314 2099531 : if (trunc_or_exact_div_p (gimple_assign_rhs_code (stmt))
2315 1261 : && tree_fits_shwi_p (gimple_assign_rhs2 (stmt))
2316 1158449 : && tree_to_shwi (gimple_assign_rhs2 (stmt)) == 2)
2317 97 : return true;
2318 : return false;
2319 : }
2320 :
2321 : /* Helper for number_of_iterations_cltz that uses ranger to determine
2322 : if SRC's range, shifted left (when LEFT_SHIFT is true) or right
2323 : by NUM_IGNORED_BITS, is guaranteed to be != 0 on LOOP's preheader
2324 : edge.
2325 : Return true if so or false otherwise. */
2326 :
2327 : static bool
2328 1261 : shifted_range_nonzero_p (loop_p loop, tree src,
2329 : bool left_shift, int num_ignored_bits)
2330 : {
2331 1261 : int_range_max r (TREE_TYPE (src));
2332 1261 : gcc_assert (num_ignored_bits >= 0);
2333 :
2334 1261 : if (get_range_query (cfun)->range_on_edge
2335 1261 : (r, loop_preheader_edge (loop), src)
2336 1261 : && !r.varying_p ()
2337 1950 : && !r.undefined_p ())
2338 : {
2339 685 : if (num_ignored_bits)
2340 : {
2341 581 : range_op_handler op (left_shift ? LSHIFT_EXPR : RSHIFT_EXPR);
2342 389 : int_range_max shifted_range (TREE_TYPE (src));
2343 389 : wide_int shift_count = wi::shwi (num_ignored_bits,
2344 389 : TYPE_PRECISION (TREE_TYPE
2345 389 : (src)));
2346 389 : int_range_max shift_amount
2347 389 : (TREE_TYPE (src), shift_count, shift_count);
2348 :
2349 389 : if (op.fold_range (shifted_range, TREE_TYPE (src), r,
2350 : shift_amount))
2351 389 : r = shifted_range;
2352 389 : }
2353 :
2354 : /* If the range does not contain zero we are good. */
2355 685 : if (!range_includes_zero_p (r))
2356 498 : return true;
2357 : }
2358 :
2359 : return false;
2360 1261 : }
2361 :
2362 :
2363 : /* See comment below for number_of_iterations_bitcount.
2364 : For c[lt]z, we have:
2365 :
2366 : modify:
2367 : iv_2 = iv_1 << 1 OR iv_1 >> 1
2368 :
2369 : test:
2370 : if (iv & 1 << (prec-1)) OR (iv & 1)
2371 :
2372 : modification count:
2373 : src precision - c[lt]z (src)
2374 :
2375 : */
2376 :
2377 : static bool
2378 7224199 : number_of_iterations_cltz (loop_p loop, const_edge exit,
2379 : enum tree_code code,
2380 : class tree_niter_desc *niter)
2381 : {
2382 7224199 : bool modify_before_test = true;
2383 7224199 : HOST_WIDE_INT max;
2384 7224199 : int checked_bit;
2385 7224199 : tree iv_2;
2386 :
2387 : /* Check that condition for staying inside the loop is like
2388 : if (iv == 0). */
2389 14448398 : gcond *cond_stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
2390 7224199 : if (!cond_stmt
2391 7224199 : || (code != EQ_EXPR && code != GE_EXPR)
2392 3637113 : || !integer_zerop (gimple_cond_rhs (cond_stmt))
2393 1378104 : || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2394 : return false;
2395 :
2396 1378061 : if (code == EQ_EXPR)
2397 : {
2398 : /* Make sure we check a bitwise and with a suitable constant */
2399 1239702 : auto *and_stmt
2400 1239702 : = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (gimple_cond_lhs (cond_stmt)));
2401 764182 : if (!and_stmt
2402 764182 : || gimple_assign_rhs_code (and_stmt) != BIT_AND_EXPR
2403 140969 : || !integer_pow2p (gimple_assign_rhs2 (and_stmt))
2404 19741 : || TREE_CODE (gimple_assign_rhs1 (and_stmt)) != SSA_NAME)
2405 : return false;
2406 :
2407 39482 : checked_bit = tree_log2 (gimple_assign_rhs2 (and_stmt));
2408 :
2409 19741 : iv_2 = gimple_assign_rhs1 (and_stmt);
2410 : }
2411 : else
2412 : {
2413 : /* We have a GE_EXPR - a signed comparison with zero is equivalent to
2414 : testing the leading bit, so check for this pattern too. */
2415 :
2416 138359 : iv_2 = gimple_cond_lhs (cond_stmt);
2417 138359 : tree test_value_type = TREE_TYPE (iv_2);
2418 :
2419 138359 : if (TYPE_UNSIGNED (test_value_type))
2420 : return false;
2421 :
2422 138359 : gimple *test_value_stmt = SSA_NAME_DEF_STMT (iv_2);
2423 :
2424 138359 : if (is_gimple_assign (test_value_stmt)
2425 138359 : && gimple_assign_rhs_code (test_value_stmt) == NOP_EXPR)
2426 : {
2427 : /* If the test value comes from a NOP_EXPR, then we need to unwrap
2428 : this. We conservatively require that both types have the same
2429 : precision. */
2430 5412 : iv_2 = gimple_assign_rhs1 (test_value_stmt);
2431 5412 : tree rhs_type = TREE_TYPE (iv_2);
2432 5412 : if (TREE_CODE (iv_2) != SSA_NAME
2433 5412 : || !INTEGRAL_NB_TYPE_P (rhs_type)
2434 10813 : || (TYPE_PRECISION (rhs_type)
2435 5401 : != TYPE_PRECISION (test_value_type)))
2436 : return false;
2437 : }
2438 :
2439 137946 : checked_bit = TYPE_PRECISION (test_value_type) - 1;
2440 : }
2441 :
2442 157687 : gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2443 157687 : gimple *test_phi = NULL;
2444 :
2445 : /* If the test comes before the iv modification, then these will actually be
2446 : iv_1 and a phi node. */
2447 157687 : if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2448 25993 : && gimple_bb (iv_2_stmt) == loop->header
2449 14941 : && gimple_phi_num_args (iv_2_stmt) == 2
2450 172628 : && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2451 : loop_latch_edge (loop)->dest_idx))
2452 : == SSA_NAME))
2453 : {
2454 : /* iv_2 is actually one of the inputs to the phi. */
2455 14842 : test_phi = iv_2_stmt;
2456 14842 : iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2457 14842 : iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2458 14842 : modify_before_test = false;
2459 : }
2460 :
2461 : /* Make sure iv_2_stmt is a logical shift by one stmt:
2462 : iv_2 = iv_1 {<<|>>} 1 */
2463 157687 : if (!is_gimple_assign (iv_2_stmt))
2464 : return false;
2465 127866 : bool left_shift = false;
2466 255223 : if (!((left_shift = is_lshift_by_1 (as_a <gassign *> (iv_2_stmt)))
2467 127357 : || is_rshift_by_1 (as_a <gassign *> (iv_2_stmt))))
2468 : return false;
2469 :
2470 2183 : tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2471 :
2472 : /* Check the recurrence. A test before the modification must test the
2473 : PHI of the recurrence. */
2474 2183 : gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2475 2183 : if (gimple_code (phi) != GIMPLE_PHI
2476 2120 : || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2477 2114 : || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx))
2478 4297 : || (test_phi && phi != test_phi))
2479 : return false;
2480 :
2481 : /* We found a match. */
2482 1909 : tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2483 :
2484 : /* If the type is signed, verify via Ranger on the preheader edge
2485 : that the initial value entering the loop is non-negative. */
2486 1909 : if (!TYPE_UNSIGNED (TREE_TYPE (src)))
2487 : {
2488 1037 : int_range_max r (TREE_TYPE (src));
2489 1037 : edge e = loop_preheader_edge (loop);
2490 2074 : if (!get_range_query (cfun)->range_on_edge (r, e, src)
2491 1037 : || r.undefined_p ()
2492 2074 : || !r.nonnegative_p ())
2493 648 : return false;
2494 1037 : }
2495 :
2496 1261 : int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2497 :
2498 : /* Save the original SSA name before preprocessing for ranger queries. */
2499 1261 : tree unshifted_src = src;
2500 :
2501 : /* Apply any needed preprocessing to src. */
2502 1261 : int num_ignored_bits;
2503 1261 : if (left_shift)
2504 382 : num_ignored_bits = src_precision - checked_bit - 1;
2505 : else
2506 : num_ignored_bits = checked_bit;
2507 :
2508 1261 : if (modify_before_test)
2509 521 : num_ignored_bits++;
2510 :
2511 1261 : if (num_ignored_bits != 0)
2512 1137 : src = fold_build2 (left_shift ? LSHIFT_EXPR : RSHIFT_EXPR,
2513 : TREE_TYPE (src), src,
2514 : build_int_cst (integer_type_node, num_ignored_bits));
2515 :
2516 : /* Get the corresponding c[lt]z builtin. */
2517 1261 : tree expr = build_cltz_expr (src, left_shift, false);
2518 :
2519 1261 : if (!expr)
2520 : return false;
2521 :
2522 1261 : max = src_precision - num_ignored_bits - 1;
2523 :
2524 1261 : expr = fold_convert (unsigned_type_node, expr);
2525 :
2526 : /* If the copy-header (ch) pass peeled one iteration we're shifting
2527 : SRC by preprocessing it above.
2528 :
2529 : A loop like
2530 : if (bits)
2531 : {
2532 : while (!(bits & 1))
2533 : {
2534 : bits >>= 1;
2535 : cnt += 1;
2536 : }
2537 : return cnt;
2538 : }
2539 : ch (roughly) transforms into:
2540 : if (bits)
2541 : {
2542 : if (!(bits & 1)
2543 : {
2544 : do
2545 : {
2546 : bits >>= 1;
2547 : cnt += 1;
2548 : } while (!(bits & 1));
2549 : }
2550 : else
2551 : cnt = 1;
2552 : return cnt;
2553 : }
2554 :
2555 : Then, our preprocessed SRC (that is used for c[tl]z computation)
2556 : will be bits >> 1, and the assumption is bits >> 1 != 0. */
2557 :
2558 1261 : tree assumptions;
2559 1261 : if (shifted_range_nonzero_p (loop, unshifted_src,
2560 : left_shift, num_ignored_bits))
2561 498 : assumptions = boolean_true_node;
2562 : else
2563 : {
2564 : /* If ranger couldn't prove the assumption, try
2565 : simplify_using_initial_conditions. */
2566 763 : assumptions = fold_build2 (NE_EXPR, boolean_type_node, src,
2567 : build_zero_cst (TREE_TYPE (src)));
2568 763 : assumptions = simplify_using_initial_conditions (loop, assumptions);
2569 : }
2570 :
2571 1261 : niter->assumptions = assumptions;
2572 1261 : niter->may_be_zero = boolean_false_node;
2573 1261 : niter->niter = simplify_using_initial_conditions (loop, expr);
2574 :
2575 1261 : if (TREE_CODE (niter->niter) == INTEGER_CST)
2576 100 : niter->max = tree_to_uhwi (niter->niter);
2577 : else
2578 1161 : niter->max = max;
2579 :
2580 1261 : niter->bound = NULL_TREE;
2581 1261 : niter->cmp = ERROR_MARK;
2582 :
2583 1261 : return true;
2584 : }
2585 :
2586 : /* See comment below for number_of_iterations_bitcount.
2587 : For c[lt]z complement, we have:
2588 :
2589 : modify:
2590 : iv_2 = iv_1 >> 1 OR iv_1 << 1
2591 :
2592 : test:
2593 : if (iv != 0)
2594 :
2595 : modification count:
2596 : src precision - c[lt]z (src)
2597 :
2598 : */
2599 :
2600 : static bool
2601 3903716 : number_of_iterations_cltz_complement (loop_p loop, const_edge exit,
2602 : enum tree_code code,
2603 : class tree_niter_desc *niter)
2604 : {
2605 3903716 : bool modify_before_test = true;
2606 3903716 : HOST_WIDE_INT max;
2607 :
2608 : /* Check that condition for staying inside the loop is like
2609 : if (iv != 0). */
2610 7807432 : gcond *cond_stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
2611 3903716 : if (!cond_stmt
2612 3903716 : || code != NE_EXPR
2613 1939618 : || !integer_zerop (gimple_cond_rhs (cond_stmt))
2614 5281508 : || TREE_CODE (gimple_cond_lhs (cond_stmt)) != SSA_NAME)
2615 : return false;
2616 :
2617 1377792 : tree iv_2 = gimple_cond_lhs (cond_stmt);
2618 1377792 : gimple *iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2619 1377792 : gimple *test_phi = NULL;
2620 :
2621 : /* If the test comes before the iv modification, then these will actually be
2622 : iv_1 and a phi node. */
2623 1377792 : if (gimple_code (iv_2_stmt) == GIMPLE_PHI
2624 391194 : && gimple_bb (iv_2_stmt) == loop->header
2625 296544 : && gimple_phi_num_args (iv_2_stmt) == 2
2626 1674336 : && (TREE_CODE (gimple_phi_arg_def (iv_2_stmt,
2627 : loop_latch_edge (loop)->dest_idx))
2628 : == SSA_NAME))
2629 : {
2630 : /* iv_2 is actually one of the inputs to the phi. */
2631 273480 : test_phi = iv_2_stmt;
2632 273480 : iv_2 = gimple_phi_arg_def (iv_2_stmt, loop_latch_edge (loop)->dest_idx);
2633 273480 : iv_2_stmt = SSA_NAME_DEF_STMT (iv_2);
2634 273480 : modify_before_test = false;
2635 : }
2636 :
2637 : /* Make sure iv_2_stmt is a logical shift by one stmt:
2638 : iv_2 = iv_1 {>>|<<} 1 */
2639 1377792 : if (!is_gimple_assign (iv_2_stmt))
2640 : return false;
2641 1043224 : bool left_shift = false;
2642 2085843 : if (!((left_shift = is_lshift_by_1 (as_a <gassign *> (iv_2_stmt)))
2643 1042619 : || is_rshift_by_1 (as_a <gassign *> (iv_2_stmt))))
2644 : return false;
2645 :
2646 11518 : tree iv_1 = gimple_assign_rhs1 (iv_2_stmt);
2647 :
2648 : /* Check the recurrence. A test before the modification must test the
2649 : PHI of the recurrence. */
2650 11518 : gimple *phi = SSA_NAME_DEF_STMT (iv_1);
2651 11518 : if (gimple_code (phi) != GIMPLE_PHI
2652 10778 : || (gimple_bb (phi) != loop_latch_edge (loop)->dest)
2653 9605 : || (iv_2 != gimple_phi_arg_def (phi, loop_latch_edge (loop)->dest_idx))
2654 20870 : || (test_phi && phi != test_phi))
2655 : return false;
2656 :
2657 : /* We found a match. */
2658 9147 : tree src = gimple_phi_arg_def (phi, loop_preheader_edge (loop)->dest_idx);
2659 :
2660 : /* If the type is signed, verify via Ranger on the preheader edge
2661 : that the initial value entering the loop is non-negative. */
2662 9147 : if (!TYPE_UNSIGNED (TREE_TYPE (src)))
2663 : {
2664 920 : int_range_max r (TREE_TYPE (src));
2665 920 : edge e = loop_preheader_edge (loop);
2666 1840 : if (!get_range_query (cfun)->range_on_edge (r, e, src)
2667 920 : || r.undefined_p ()
2668 1840 : || !r.nonnegative_p ())
2669 446 : return false;
2670 920 : }
2671 :
2672 8701 : int src_precision = TYPE_PRECISION (TREE_TYPE (src));
2673 :
2674 8701 : tree src_zero = fold_build2 (EQ_EXPR, boolean_type_node, src,
2675 : build_zero_cst (TREE_TYPE (src)));
2676 8701 : bool src_nonzero
2677 8701 : = integer_zerop (simplify_using_initial_conditions (loop, src_zero));
2678 :
2679 : /* If the IV is modified before the test, the first value tested is SRC
2680 : shifted by one. If SRC can be zero, count the zeros of that value
2681 : instead of subtracting one from the count of SRC. Then the result is
2682 : also right for a zero SRC. */
2683 8701 : tree count_src = src;
2684 8701 : if (modify_before_test && !src_nonzero)
2685 : {
2686 3252 : tree utype = unsigned_type_for (TREE_TYPE (src));
2687 6487 : count_src = fold_build2 (left_shift ? LSHIFT_EXPR : RSHIFT_EXPR, utype,
2688 : fold_convert (utype, src), integer_one_node);
2689 : }
2690 :
2691 : /* Get the corresponding c[lt]z builtin. It needs a value at zero only
2692 : if its argument can be zero. */
2693 8701 : tree expr = build_cltz_expr (count_src, !left_shift, !src_nonzero);
2694 :
2695 8701 : if (!expr)
2696 : return false;
2697 :
2698 8701 : expr = fold_build2 (MINUS_EXPR, integer_type_node,
2699 : build_int_cst (integer_type_node, src_precision),
2700 : expr);
2701 :
2702 8701 : max = src_precision;
2703 :
2704 8701 : if (modify_before_test)
2705 : {
2706 7008 : if (src_nonzero)
2707 3756 : expr = fold_build2 (MINUS_EXPR, integer_type_node, expr,
2708 : integer_one_node);
2709 7008 : max = max - 1;
2710 : }
2711 :
2712 8701 : expr = fold_convert (unsigned_type_node, expr);
2713 :
2714 8701 : niter->assumptions = boolean_true_node;
2715 8701 : niter->may_be_zero = boolean_false_node;
2716 8701 : niter->niter = simplify_using_initial_conditions (loop, expr);
2717 :
2718 8701 : if (TREE_CODE (niter->niter) == INTEGER_CST)
2719 69 : niter->max = tree_to_uhwi (niter->niter);
2720 : else
2721 8632 : niter->max = max;
2722 :
2723 8701 : niter->bound = NULL_TREE;
2724 8701 : niter->cmp = ERROR_MARK;
2725 8701 : return true;
2726 : }
2727 :
2728 : /* See if LOOP contains a bit counting idiom. The idiom consists of two parts:
2729 : 1. A modification to the induction variabler;.
2730 : 2. A test to determine whether or not to exit the loop.
2731 :
2732 : These can come in either order - i.e.:
2733 :
2734 : <bb 3>
2735 : iv_1 = PHI <src(2), iv_2(4)>
2736 : if (test (iv_1))
2737 : goto <bb 4>
2738 : else
2739 : goto <bb 5>
2740 :
2741 : <bb 4>
2742 : iv_2 = modify (iv_1)
2743 : goto <bb 3>
2744 :
2745 : OR
2746 :
2747 : <bb 3>
2748 : iv_1 = PHI <src(2), iv_2(4)>
2749 : iv_2 = modify (iv_1)
2750 :
2751 : <bb 4>
2752 : if (test (iv_2))
2753 : goto <bb 3>
2754 : else
2755 : goto <bb 5>
2756 :
2757 : The second form can be generated by copying the loop header out of the loop.
2758 :
2759 : In the first case, the number of latch executions will be equal to the
2760 : number of induction variable modifications required before the test fails.
2761 :
2762 : In the second case (modify_before_test), if we assume that the number of
2763 : modifications required before the test fails is nonzero, then the number of
2764 : latch executions will be one less than this number.
2765 :
2766 : If we recognise the pattern, then we update niter accordingly, and return
2767 : true. */
2768 :
2769 : static bool
2770 3907382 : number_of_iterations_bitcount (loop_p loop, const_edge exit,
2771 : enum tree_code code,
2772 : class tree_niter_desc *niter)
2773 : {
2774 3907382 : return (number_of_iterations_popcount (loop, exit, code, niter)
2775 3903795 : || number_of_iterations_cltz (loop, exit, code, niter)
2776 7811098 : || number_of_iterations_cltz_complement (loop, exit, code, niter));
2777 : }
2778 :
2779 : /* Substitute NEW_TREE for OLD in EXPR and fold the result.
2780 : If VALUEIZE is non-NULL then OLD and NEW_TREE are ignored and instead
2781 : all SSA names are replaced with the result of calling the VALUEIZE
2782 : function with the SSA name as argument. */
2783 :
2784 : tree
2785 160172810 : simplify_replace_tree (tree expr, tree old, tree new_tree,
2786 : tree (*valueize) (tree, void*), void *context,
2787 : bool do_fold)
2788 : {
2789 160172810 : unsigned i, n;
2790 160172810 : tree ret = NULL_TREE, e, se;
2791 :
2792 160172810 : if (!expr)
2793 : return NULL_TREE;
2794 :
2795 : /* Do not bother to replace constants. */
2796 32285615 : if (CONSTANT_CLASS_P (expr))
2797 : return expr;
2798 :
2799 24397901 : if (valueize)
2800 : {
2801 278796 : if (TREE_CODE (expr) == SSA_NAME)
2802 : {
2803 86650 : new_tree = valueize (expr, context);
2804 86650 : if (new_tree != expr)
2805 : return new_tree;
2806 : }
2807 : }
2808 24119105 : else if (expr == old
2809 24119105 : || operand_equal_p (expr, old, 0))
2810 214271 : return unshare_expr (new_tree);
2811 :
2812 24183008 : if (!EXPR_P (expr))
2813 : return expr;
2814 :
2815 12951844 : n = TREE_OPERAND_LENGTH (expr);
2816 36313368 : for (i = 0; i < n; i++)
2817 : {
2818 23361524 : e = TREE_OPERAND (expr, i);
2819 23361524 : se = simplify_replace_tree (e, old, new_tree, valueize, context, do_fold);
2820 23361524 : if (e == se)
2821 23086376 : continue;
2822 :
2823 275148 : if (!ret)
2824 274666 : ret = copy_node (expr);
2825 :
2826 275148 : TREE_OPERAND (ret, i) = se;
2827 : }
2828 :
2829 12951844 : return (ret ? (do_fold ? fold (ret) : ret) : expr);
2830 : }
2831 :
2832 : /* Expand definitions of ssa names in EXPR as long as they are simple
2833 : enough, and return the new expression. If STOP is specified, stop
2834 : expanding if EXPR equals to it. */
2835 :
2836 : static tree
2837 127415573 : expand_simple_operations (tree expr, tree stop, hash_map<tree, tree> &cache)
2838 : {
2839 127730923 : unsigned i, n;
2840 127730923 : tree ret = NULL_TREE, e, ee, e1;
2841 127730923 : enum tree_code code;
2842 127730923 : gimple *stmt;
2843 :
2844 127730923 : if (expr == NULL_TREE)
2845 : return expr;
2846 :
2847 127730923 : if (is_gimple_min_invariant (expr))
2848 : return expr;
2849 :
2850 87433018 : code = TREE_CODE (expr);
2851 87433018 : if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
2852 : {
2853 20993955 : n = TREE_OPERAND_LENGTH (expr);
2854 58049456 : for (i = 0; i < n; i++)
2855 : {
2856 37055501 : e = TREE_OPERAND (expr, i);
2857 37055501 : if (!e)
2858 33580224 : continue;
2859 : /* SCEV analysis feeds us with a proper expression
2860 : graph matching the SSA graph. Avoid turning it
2861 : into a tree here, thus handle tree sharing
2862 : properly.
2863 : ??? The SSA walk below still turns the SSA graph
2864 : into a tree but until we find a testcase do not
2865 : introduce additional tree sharing here. */
2866 37035141 : bool existed_p;
2867 37035141 : tree &cee = cache.get_or_insert (e, &existed_p);
2868 37035141 : if (existed_p)
2869 147284 : ee = cee;
2870 : else
2871 : {
2872 36887857 : cee = e;
2873 36887857 : ee = expand_simple_operations (e, stop, cache);
2874 36887857 : if (ee != e)
2875 3473709 : *cache.get (e) = ee;
2876 : }
2877 37035141 : if (e == ee)
2878 33559864 : continue;
2879 :
2880 3475277 : if (!ret)
2881 3300443 : ret = copy_node (expr);
2882 :
2883 3475277 : TREE_OPERAND (ret, i) = ee;
2884 : }
2885 :
2886 20993955 : if (!ret)
2887 : return expr;
2888 :
2889 3300443 : ret = fold (ret);
2890 3300443 : return ret;
2891 : }
2892 :
2893 : /* Stop if it's not ssa name or the one we don't want to expand. */
2894 66439063 : if (TREE_CODE (expr) != SSA_NAME || expr == stop)
2895 : return expr;
2896 :
2897 66239591 : stmt = SSA_NAME_DEF_STMT (expr);
2898 66239591 : if (gimple_code (stmt) == GIMPLE_PHI)
2899 : {
2900 17552389 : basic_block src, dest;
2901 :
2902 17552389 : if (gimple_phi_num_args (stmt) != 1)
2903 : return expr;
2904 442361 : e = PHI_ARG_DEF (stmt, 0);
2905 :
2906 : /* Avoid propagating through loop exit phi nodes, which
2907 : could break loop-closed SSA form restrictions. */
2908 442361 : dest = gimple_bb (stmt);
2909 442361 : src = single_pred (dest);
2910 442361 : if (TREE_CODE (e) == SSA_NAME
2911 438787 : && src->loop_father != dest->loop_father)
2912 : return expr;
2913 :
2914 : return expand_simple_operations (e, stop, cache);
2915 : }
2916 48687202 : auto assign = dyn_cast<gassign *> (stmt);
2917 43000448 : if (!assign)
2918 : return expr;
2919 :
2920 : /* Avoid expanding to expressions that contain SSA names that need
2921 : to take part in abnormal coalescing. */
2922 43000448 : ssa_op_iter iter;
2923 89913933 : FOR_EACH_SSA_TREE_OPERAND (e, assign, iter, SSA_OP_USE)
2924 46914079 : if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e))
2925 : return expr;
2926 :
2927 42999854 : e = gimple_assign_rhs1 (assign);
2928 42999854 : code = gimple_assign_rhs_code (assign);
2929 42999854 : if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
2930 : {
2931 16709533 : if (is_gimple_min_invariant (e))
2932 : return e;
2933 :
2934 16704804 : if (code == SSA_NAME)
2935 : return expand_simple_operations (e, stop, cache);
2936 16480243 : else if (code == ADDR_EXPR)
2937 : {
2938 17643 : poly_int64 offset;
2939 17643 : tree base = get_addr_base_and_unit_offset (TREE_OPERAND (e, 0),
2940 : &offset);
2941 17643 : if (base
2942 17183 : && TREE_CODE (base) == MEM_REF)
2943 : {
2944 17183 : ee = expand_simple_operations (TREE_OPERAND (base, 0), stop,
2945 : cache);
2946 17183 : return fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (expr), ee,
2947 : wide_int_to_tree (sizetype,
2948 : mem_ref_offset (base)
2949 : + offset));
2950 : }
2951 : }
2952 :
2953 : return expr;
2954 : }
2955 :
2956 26290321 : switch (code)
2957 : {
2958 6570754 : CASE_CONVERT:
2959 : /* Casts are simple. */
2960 6570754 : ee = expand_simple_operations (e, stop, cache);
2961 6570754 : return fold_build1 (code, TREE_TYPE (expr), ee);
2962 :
2963 14444713 : case PLUS_EXPR:
2964 14444713 : case MINUS_EXPR:
2965 14444713 : case MULT_EXPR:
2966 28889426 : if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (expr))
2967 28886881 : && TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr)))
2968 : return expr;
2969 : /* Fallthru. */
2970 15152243 : case POINTER_PLUS_EXPR:
2971 : /* And increments and decrements by a constant are simple. */
2972 15152243 : e1 = gimple_assign_rhs2 (stmt);
2973 15152243 : if (!is_gimple_min_invariant (e1))
2974 : return expr;
2975 :
2976 7590563 : ee = expand_simple_operations (e, stop, cache);
2977 7590563 : return fold_build2 (code, TREE_TYPE (expr), ee, e1);
2978 :
2979 : default:
2980 : return expr;
2981 : }
2982 : }
2983 :
2984 : tree
2985 76349216 : expand_simple_operations (tree expr, tree stop)
2986 : {
2987 76349216 : hash_map<tree, tree> cache;
2988 76349216 : return expand_simple_operations (expr, stop, cache);
2989 76349216 : }
2990 :
2991 : /* Tries to simplify EXPR using the condition COND. Returns the simplified
2992 : expression (or EXPR unchanged, if no simplification was possible). */
2993 :
2994 : static tree
2995 9219572 : tree_simplify_using_condition_1 (tree cond, tree expr)
2996 : {
2997 9219572 : bool changed;
2998 9219572 : tree e, e0, e1, e2, notcond;
2999 9219572 : enum tree_code code = TREE_CODE (expr);
3000 :
3001 9219572 : if (code == INTEGER_CST)
3002 : return expr;
3003 :
3004 9217407 : if (code == TRUTH_OR_EXPR
3005 9217407 : || code == TRUTH_AND_EXPR
3006 9217407 : || code == COND_EXPR)
3007 : {
3008 105996 : changed = false;
3009 :
3010 105996 : e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
3011 105996 : if (TREE_OPERAND (expr, 0) != e0)
3012 137 : changed = true;
3013 :
3014 105996 : e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
3015 105996 : if (TREE_OPERAND (expr, 1) != e1)
3016 4 : changed = true;
3017 :
3018 105996 : if (code == COND_EXPR)
3019 : {
3020 4152 : e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
3021 4152 : if (TREE_OPERAND (expr, 2) != e2)
3022 : changed = true;
3023 : }
3024 : else
3025 : e2 = NULL_TREE;
3026 :
3027 105996 : if (changed)
3028 : {
3029 141 : if (code == COND_EXPR)
3030 0 : expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
3031 : else
3032 141 : expr = fold_build2 (code, boolean_type_node, e0, e1);
3033 : }
3034 :
3035 : return expr;
3036 : }
3037 :
3038 : /* In case COND is equality, we may be able to simplify EXPR by copy/constant
3039 : propagation, and vice versa. Fold does not handle this, since it is
3040 : considered too expensive. */
3041 9111411 : if (TREE_CODE (cond) == EQ_EXPR)
3042 : {
3043 2165069 : e0 = TREE_OPERAND (cond, 0);
3044 2165069 : e1 = TREE_OPERAND (cond, 1);
3045 :
3046 : /* We know that e0 == e1. Check whether we cannot simplify expr
3047 : using this fact. */
3048 2165069 : e = simplify_replace_tree (expr, e0, e1);
3049 2165069 : if (integer_zerop (e) || integer_nonzerop (e))
3050 : return e;
3051 :
3052 2163405 : e = simplify_replace_tree (expr, e1, e0);
3053 2163405 : if (integer_zerop (e) || integer_nonzerop (e))
3054 : return e;
3055 : }
3056 9109503 : if (TREE_CODE (expr) == EQ_EXPR)
3057 : {
3058 1092885 : e0 = TREE_OPERAND (expr, 0);
3059 1092885 : e1 = TREE_OPERAND (expr, 1);
3060 :
3061 : /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true. */
3062 1092885 : e = simplify_replace_tree (cond, e0, e1);
3063 1092885 : if (integer_zerop (e))
3064 : return e;
3065 1080278 : e = simplify_replace_tree (cond, e1, e0);
3066 1080278 : if (integer_zerop (e))
3067 : return e;
3068 : }
3069 9096896 : if (TREE_CODE (expr) == NE_EXPR)
3070 : {
3071 1083737 : e0 = TREE_OPERAND (expr, 0);
3072 1083737 : e1 = TREE_OPERAND (expr, 1);
3073 :
3074 : /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true. */
3075 1083737 : e = simplify_replace_tree (cond, e0, e1);
3076 1083737 : if (integer_zerop (e))
3077 11314 : return boolean_true_node;
3078 1072423 : e = simplify_replace_tree (cond, e1, e0);
3079 1072423 : if (integer_zerop (e))
3080 0 : return boolean_true_node;
3081 : }
3082 :
3083 : /* Check whether COND ==> EXPR. */
3084 9085582 : notcond = invert_truthvalue (cond);
3085 9085582 : e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, expr);
3086 9085582 : if (e && integer_nonzerop (e))
3087 : return e;
3088 :
3089 : /* Check whether COND ==> not EXPR. */
3090 9083214 : e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, expr);
3091 9083214 : if (e && integer_zerop (e))
3092 40348 : return e;
3093 :
3094 : return expr;
3095 : }
3096 :
3097 : /* Tries to simplify EXPR using the condition COND. Returns the simplified
3098 : expression (or EXPR unchanged, if no simplification was possible).
3099 : Wrapper around tree_simplify_using_condition_1 that ensures that chains
3100 : of simple operations in definitions of ssa names in COND are expanded,
3101 : so that things like casts or incrementing the value of the bound before
3102 : the loop do not cause us to fail. */
3103 :
3104 : static tree
3105 9003428 : tree_simplify_using_condition (tree cond, tree expr)
3106 : {
3107 9003428 : cond = expand_simple_operations (cond);
3108 :
3109 9003428 : return tree_simplify_using_condition_1 (cond, expr);
3110 : }
3111 :
3112 : /* Tries to simplify EXPR using the conditions on entry to LOOP.
3113 : Returns the simplified expression (or EXPR unchanged, if no
3114 : simplification was possible). */
3115 :
3116 : tree
3117 29345614 : simplify_using_initial_conditions (class loop *loop, tree expr)
3118 : {
3119 29345614 : edge e;
3120 29345614 : basic_block bb;
3121 29345614 : tree cond, expanded, backup;
3122 29345614 : int cnt = 0;
3123 :
3124 29345614 : if (TREE_CODE (expr) == INTEGER_CST)
3125 : return expr;
3126 :
3127 3041812 : value_range expr_range (TREE_TYPE (expr));
3128 3041812 : tree val;
3129 3041812 : if (TREE_TYPE (expr) == boolean_type_node
3130 6057686 : && get_range_query (cfun)->range_on_edge (expr_range,
3131 : loop_preheader_edge (loop),
3132 : expr)
3133 6070655 : && expr_range.singleton_p (&val))
3134 95179 : return val;
3135 :
3136 2946633 : backup = expanded = expand_simple_operations (expr);
3137 :
3138 : /* Limit walking the dominators to avoid quadraticness in
3139 : the number of BBs times the number of loops in degenerate
3140 : cases. */
3141 2946633 : for (bb = loop->header;
3142 28347249 : bb != ENTRY_BLOCK_PTR_FOR_FN (cfun)
3143 28347249 : && cnt < param_max_niter_dominators_walk;
3144 25400616 : bb = get_immediate_dominator (CDI_DOMINATORS, bb))
3145 : {
3146 25469049 : if (!single_pred_p (bb))
3147 12829999 : continue;
3148 12639050 : e = single_pred_edge (bb);
3149 :
3150 12639050 : if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
3151 3635622 : continue;
3152 :
3153 18006856 : gcond *stmt = as_a <gcond *> (*gsi_last_bb (e->src));
3154 9003428 : cond = fold_build2 (gimple_cond_code (stmt),
3155 : boolean_type_node,
3156 : gimple_cond_lhs (stmt),
3157 : gimple_cond_rhs (stmt));
3158 9003428 : if (e->flags & EDGE_FALSE_VALUE)
3159 5072145 : cond = invert_truthvalue (cond);
3160 9003428 : expanded = tree_simplify_using_condition (cond, expanded);
3161 : /* Break if EXPR is simplified to const values. */
3162 9003428 : if (expanded
3163 9003428 : && (integer_zerop (expanded) || integer_nonzerop (expanded)))
3164 : return expanded;
3165 :
3166 8934995 : ++cnt;
3167 : }
3168 :
3169 : /* Return the original expression if no simplification is done. */
3170 2878200 : return operand_equal_p (backup, expanded, 0) ? expr : expanded;
3171 3041812 : }
3172 :
3173 : /* Tries to simplify EXPR using the evolutions of the loop invariants
3174 : in the superloops of LOOP. Returns the simplified expression
3175 : (or EXPR unchanged, if no simplification was possible). */
3176 :
3177 : static tree
3178 6907675 : simplify_using_outer_evolutions (class loop *loop, tree expr)
3179 : {
3180 6907675 : enum tree_code code = TREE_CODE (expr);
3181 6907675 : bool changed;
3182 6907675 : tree e, e0, e1, e2;
3183 :
3184 6907675 : if (is_gimple_min_invariant (expr))
3185 : return expr;
3186 :
3187 1586675 : if (code == TRUTH_OR_EXPR
3188 1586675 : || code == TRUTH_AND_EXPR
3189 1586675 : || code == COND_EXPR)
3190 : {
3191 9146 : changed = false;
3192 :
3193 9146 : e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
3194 9146 : if (TREE_OPERAND (expr, 0) != e0)
3195 0 : changed = true;
3196 :
3197 9146 : e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
3198 9146 : if (TREE_OPERAND (expr, 1) != e1)
3199 0 : changed = true;
3200 :
3201 9146 : if (code == COND_EXPR)
3202 : {
3203 0 : e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
3204 0 : if (TREE_OPERAND (expr, 2) != e2)
3205 : changed = true;
3206 : }
3207 : else
3208 : e2 = NULL_TREE;
3209 :
3210 9146 : if (changed)
3211 : {
3212 0 : if (code == COND_EXPR)
3213 0 : expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
3214 : else
3215 0 : expr = fold_build2 (code, boolean_type_node, e0, e1);
3216 : }
3217 :
3218 : return expr;
3219 : }
3220 :
3221 1577529 : e = instantiate_parameters (loop, expr);
3222 1577529 : if (is_gimple_min_invariant (e))
3223 0 : return e;
3224 :
3225 : return expr;
3226 : }
3227 :
3228 : /* Returns true if EXIT is the only possible exit from LOOP. */
3229 :
3230 : bool
3231 13920834 : loop_only_exit_p (const class loop *loop, basic_block *body, const_edge exit)
3232 : {
3233 13920834 : gimple_stmt_iterator bsi;
3234 13920834 : unsigned i;
3235 :
3236 13920834 : if (exit != single_exit (loop))
3237 : return false;
3238 :
3239 46402625 : for (i = 0; i < loop->num_nodes; i++)
3240 310255667 : for (bsi = gsi_start_bb (body[i]); !gsi_end_p (bsi); gsi_next (&bsi))
3241 237260181 : if (stmt_can_terminate_bb_p (gsi_stmt (bsi)))
3242 : return false;
3243 :
3244 : return true;
3245 : }
3246 :
3247 : /* Stores description of number of iterations of LOOP derived from
3248 : EXIT (an exit edge of the LOOP) in NITER. Returns true if some useful
3249 : information could be derived (and fields of NITER have meaning described
3250 : in comments at class tree_niter_desc declaration), false otherwise.
3251 : When EVERY_ITERATION is true, only tests that are known to be executed
3252 : every iteration are considered (i.e. only test that alone bounds the loop).
3253 : If AT_STMT is not NULL, this function stores LOOP's condition statement in
3254 : it when returning true. */
3255 :
3256 : bool
3257 25354134 : number_of_iterations_exit_assumptions (class loop *loop, const_edge exit,
3258 : class tree_niter_desc *niter,
3259 : gcond **at_stmt, bool every_iteration,
3260 : basic_block *body)
3261 : {
3262 25354134 : tree type;
3263 25354134 : tree op0, op1;
3264 25354134 : enum tree_code code;
3265 25354134 : affine_iv iv0, iv1;
3266 25354134 : bool safe;
3267 :
3268 : /* The condition at a fake exit (if it exists) does not control its
3269 : execution. */
3270 25354134 : if (exit->flags & EDGE_FAKE)
3271 : return false;
3272 :
3273 : /* Nothing to analyze if the loop is known to be infinite. */
3274 25353688 : if (loop_constraint_set_p (loop, LOOP_C_INFINITE))
3275 : return false;
3276 :
3277 25353688 : safe = dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src);
3278 :
3279 25353688 : if (every_iteration && !safe)
3280 : return false;
3281 :
3282 24221482 : niter->assumptions = boolean_false_node;
3283 24221482 : niter->control.base = NULL_TREE;
3284 24221482 : niter->control.step = NULL_TREE;
3285 24221482 : niter->control.no_overflow = false;
3286 48442964 : gcond *stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
3287 22209208 : if (!stmt)
3288 : return false;
3289 :
3290 22209208 : if (at_stmt)
3291 21542128 : *at_stmt = stmt;
3292 :
3293 : /* We want the condition for staying inside loop. */
3294 22209208 : code = gimple_cond_code (stmt);
3295 22209208 : if (exit->flags & EDGE_TRUE_VALUE)
3296 8312919 : code = invert_tree_comparison (code, false);
3297 :
3298 22209208 : switch (code)
3299 : {
3300 18888439 : case GT_EXPR:
3301 18888439 : case GE_EXPR:
3302 18888439 : case LT_EXPR:
3303 18888439 : case LE_EXPR:
3304 18888439 : case NE_EXPR:
3305 18888439 : break;
3306 :
3307 3320404 : case EQ_EXPR:
3308 3320404 : return number_of_iterations_cltz (loop, exit, code, niter);
3309 :
3310 : default:
3311 : return false;
3312 : }
3313 :
3314 18888439 : op0 = gimple_cond_lhs (stmt);
3315 18888439 : op1 = gimple_cond_rhs (stmt);
3316 18888439 : type = TREE_TYPE (op0);
3317 :
3318 18888439 : if (!INTEGRAL_NB_TYPE_P (type)
3319 : && !POINTER_TYPE_P (type))
3320 : return false;
3321 :
3322 18105485 : tree iv0_niters = NULL_TREE;
3323 36210970 : if (!simple_iv_with_niters (loop, loop_containing_stmt (stmt),
3324 : op0, &iv0, safe ? &iv0_niters : NULL, false))
3325 3907382 : return number_of_iterations_bitcount (loop, exit, code, niter);
3326 14198103 : tree iv1_niters = NULL_TREE;
3327 28396206 : if (!simple_iv_with_niters (loop, loop_containing_stmt (stmt),
3328 : op1, &iv1, safe ? &iv1_niters : NULL, false))
3329 : return false;
3330 : /* Give up on complicated case. */
3331 13498090 : if (iv0_niters && iv1_niters)
3332 : return false;
3333 :
3334 13498090 : iv0.base = expand_simple_operations (iv0.base);
3335 13498090 : iv1.base = expand_simple_operations (iv1.base);
3336 13498090 : bool body_from_caller = true;
3337 13498090 : if (!body)
3338 : {
3339 8122645 : body = get_loop_body (loop);
3340 8122645 : body_from_caller = false;
3341 : }
3342 13498090 : bool only_exit_p = loop_only_exit_p (loop, body, exit);
3343 13498090 : if (!body_from_caller)
3344 8122645 : free (body);
3345 13498090 : if (!number_of_iterations_cond (loop, type, &iv0, code, &iv1, niter,
3346 : only_exit_p, safe))
3347 : {
3348 : return false;
3349 : }
3350 :
3351 : /* Incorporate additional assumption implied by control iv. */
3352 13349915 : tree iv_niters = iv0_niters ? iv0_niters : iv1_niters;
3353 13349915 : if (iv_niters)
3354 : {
3355 25861 : tree assumption = fold_build2 (LE_EXPR, boolean_type_node, niter->niter,
3356 : fold_convert (TREE_TYPE (niter->niter),
3357 : iv_niters));
3358 :
3359 25861 : if (!integer_nonzerop (assumption))
3360 25640 : niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3361 : niter->assumptions, assumption);
3362 :
3363 : /* Refine upper bound if possible. */
3364 25861 : if (TREE_CODE (iv_niters) == INTEGER_CST
3365 51722 : && niter->max > wi::to_widest (iv_niters))
3366 22597 : niter->max = wi::to_widest (iv_niters);
3367 : }
3368 :
3369 : /* There is no assumptions if the loop is known to be finite. */
3370 13349915 : if (!integer_zerop (niter->assumptions)
3371 13349915 : && loop_constraint_set_p (loop, LOOP_C_FINITE))
3372 13246 : niter->assumptions = boolean_true_node;
3373 :
3374 13349915 : if (optimize >= 3)
3375 : {
3376 2296461 : niter->assumptions = simplify_using_outer_evolutions (loop,
3377 : niter->assumptions);
3378 2296461 : niter->may_be_zero = simplify_using_outer_evolutions (loop,
3379 : niter->may_be_zero);
3380 2296461 : niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
3381 : }
3382 :
3383 13349915 : niter->assumptions
3384 13349915 : = simplify_using_initial_conditions (loop,
3385 : niter->assumptions);
3386 13349915 : niter->may_be_zero
3387 13349915 : = simplify_using_initial_conditions (loop,
3388 : niter->may_be_zero);
3389 :
3390 : /* If NITER has simplified into a constant, update MAX. */
3391 13349915 : if (TREE_CODE (niter->niter) == INTEGER_CST)
3392 7603144 : niter->max = wi::to_widest (niter->niter);
3393 :
3394 13349915 : return (!integer_zerop (niter->assumptions));
3395 : }
3396 :
3397 : /* Like number_of_iterations_exit_assumptions, but return TRUE only if
3398 : the niter information holds unconditionally. */
3399 :
3400 : bool
3401 24590326 : number_of_iterations_exit (class loop *loop, const_edge exit,
3402 : class tree_niter_desc *niter,
3403 : bool warn, bool every_iteration,
3404 : basic_block *body)
3405 : {
3406 24590326 : gcond *stmt;
3407 24590326 : if (!number_of_iterations_exit_assumptions (loop, exit, niter,
3408 : &stmt, every_iteration, body))
3409 : return false;
3410 :
3411 12983057 : if (integer_nonzerop (niter->assumptions))
3412 : return true;
3413 :
3414 591232 : if (warn && dump_enabled_p ())
3415 4 : dump_printf_loc (MSG_MISSED_OPTIMIZATION, stmt,
3416 : "missed loop optimization: niters analysis ends up "
3417 : "with assumptions.\n");
3418 :
3419 : return false;
3420 : }
3421 :
3422 : /* Try to determine the number of iterations of LOOP. If we succeed,
3423 : expression giving number of iterations is returned and *EXIT is
3424 : set to the edge from that the information is obtained. Otherwise
3425 : chrec_dont_know is returned. */
3426 :
3427 : tree
3428 793242 : find_loop_niter (class loop *loop, edge *exit)
3429 : {
3430 793242 : unsigned i;
3431 793242 : auto_vec<edge> exits = get_loop_exit_edges (loop);
3432 793242 : edge ex;
3433 793242 : tree niter = NULL_TREE, aniter;
3434 793242 : class tree_niter_desc desc;
3435 :
3436 793242 : *exit = NULL;
3437 3445066 : FOR_EACH_VEC_ELT (exits, i, ex)
3438 : {
3439 2651824 : if (!number_of_iterations_exit (loop, ex, &desc, false))
3440 2116865 : continue;
3441 :
3442 534959 : if (integer_nonzerop (desc.may_be_zero))
3443 : {
3444 : /* We exit in the first iteration through this exit.
3445 : We won't find anything better. */
3446 0 : niter = build_int_cst (unsigned_type_node, 0);
3447 0 : *exit = ex;
3448 0 : break;
3449 : }
3450 :
3451 534959 : if (!integer_zerop (desc.may_be_zero))
3452 57415 : continue;
3453 :
3454 477544 : aniter = desc.niter;
3455 :
3456 477544 : if (!niter)
3457 : {
3458 : /* Nothing recorded yet. */
3459 467898 : niter = aniter;
3460 467898 : *exit = ex;
3461 467898 : continue;
3462 : }
3463 :
3464 : /* Prefer constants, the lower the better. */
3465 9646 : if (TREE_CODE (aniter) != INTEGER_CST)
3466 5427 : continue;
3467 :
3468 4219 : if (TREE_CODE (niter) != INTEGER_CST)
3469 : {
3470 1030 : niter = aniter;
3471 1030 : *exit = ex;
3472 1030 : continue;
3473 : }
3474 :
3475 3189 : if (tree_int_cst_lt (aniter, niter))
3476 : {
3477 258 : niter = aniter;
3478 258 : *exit = ex;
3479 258 : continue;
3480 : }
3481 : }
3482 :
3483 793242 : return niter ? niter : chrec_dont_know;
3484 793242 : }
3485 :
3486 : /* Return true if loop is known to have bounded number of iterations. */
3487 :
3488 : bool
3489 3086983 : finite_loop_p (class loop *loop)
3490 : {
3491 3086983 : widest_int nit;
3492 3086983 : int flags;
3493 :
3494 3086983 : if (loop->finite_p)
3495 : {
3496 2288712 : unsigned i;
3497 2288712 : auto_vec<edge> exits = get_loop_exit_edges (loop);
3498 2288712 : edge ex;
3499 :
3500 : /* If the loop has a normal exit, we can assume it will terminate. */
3501 4590413 : FOR_EACH_VEC_ELT (exits, i, ex)
3502 2296890 : if (!(ex->flags & (EDGE_EH | EDGE_ABNORMAL | EDGE_FAKE)))
3503 : {
3504 2284238 : if (dump_file)
3505 181 : fprintf (dump_file, "Assume loop %i to be finite: it has an exit "
3506 : "and -ffinite-loops is on or loop was "
3507 : "previously finite.\n",
3508 : loop->num);
3509 2284238 : return true;
3510 : }
3511 2288712 : }
3512 :
3513 802745 : flags = flags_from_decl_or_type (current_function_decl);
3514 802745 : if ((flags & (ECF_CONST|ECF_PURE)) && !(flags & ECF_LOOPING_CONST_OR_PURE))
3515 : {
3516 2747 : if (dump_file && (dump_flags & TDF_DETAILS))
3517 0 : fprintf (dump_file,
3518 : "Found loop %i to be finite: it is within "
3519 : "pure or const function.\n",
3520 : loop->num);
3521 2747 : loop->finite_p = true;
3522 2747 : return true;
3523 : }
3524 :
3525 799998 : if (loop->any_upper_bound
3526 : /* Loop with no normal exit will not pass max_loop_iterations. */
3527 799998 : || (!loop->finite_p && max_loop_iterations (loop, &nit)))
3528 : {
3529 425338 : if (dump_file && (dump_flags & TDF_DETAILS))
3530 31 : fprintf (dump_file, "Found loop %i to be finite: upper bound found.\n",
3531 : loop->num);
3532 425338 : loop->finite_p = true;
3533 425338 : return true;
3534 : }
3535 :
3536 : return false;
3537 3086983 : }
3538 :
3539 : /*
3540 :
3541 : Analysis of a number of iterations of a loop by a brute-force evaluation.
3542 :
3543 : */
3544 :
3545 : /* Bound on the number of iterations we try to evaluate. */
3546 :
3547 : #define MAX_ITERATIONS_TO_TRACK \
3548 : ((unsigned) param_max_iterations_to_track)
3549 :
3550 : /* Returns the loop phi node of LOOP such that ssa name X is derived from its
3551 : result by a chain of operations such that all but exactly one of their
3552 : operands are constants. */
3553 :
3554 : static gphi *
3555 2008184 : chain_of_csts_start (class loop *loop, tree x)
3556 : {
3557 2397540 : gimple *stmt = SSA_NAME_DEF_STMT (x);
3558 2397540 : tree use;
3559 2397540 : basic_block bb = gimple_bb (stmt);
3560 2397540 : enum tree_code code;
3561 :
3562 2397540 : if (!bb
3563 2397540 : || !flow_bb_inside_loop_p (loop, bb))
3564 : return NULL;
3565 :
3566 1839877 : if (gimple_code (stmt) == GIMPLE_PHI)
3567 : {
3568 737721 : if (bb == loop->header)
3569 676828 : return as_a <gphi *> (stmt);
3570 :
3571 : return NULL;
3572 : }
3573 :
3574 1102156 : auto assign = dyn_cast<gassign *> (stmt);
3575 979376 : if (!assign || gimple_assign_rhs_class (assign) == GIMPLE_TERNARY_RHS)
3576 : return NULL;
3577 :
3578 979353 : code = gimple_assign_rhs_code (assign);
3579 979353 : if (gimple_references_memory_p (assign)
3580 524198 : || TREE_CODE_CLASS (code) == tcc_reference
3581 498513 : || (code == ADDR_EXPR
3582 547 : && !is_gimple_min_invariant (gimple_assign_rhs1 (assign))))
3583 : return NULL;
3584 :
3585 497966 : use = SINGLE_SSA_TREE_OPERAND (assign, SSA_OP_USE);
3586 497966 : if (use == NULL_TREE)
3587 : return NULL;
3588 :
3589 : return chain_of_csts_start (loop, use);
3590 : }
3591 :
3592 : /* Determines whether the expression X is derived from a result of a phi node
3593 : in header of LOOP such that
3594 :
3595 : * the derivation of X consists only from operations with constants
3596 : * the initial value of the phi node is constant
3597 : * the value of the phi node in the next iteration can be derived from the
3598 : value in the current iteration by a chain of operations with constants,
3599 : or is also a constant
3600 :
3601 : If such phi node exists, it is returned, otherwise NULL is returned. */
3602 :
3603 : static gphi *
3604 1814083 : get_base_for (class loop *loop, tree x)
3605 : {
3606 1814083 : gphi *phi;
3607 1814083 : tree init, next;
3608 :
3609 1814083 : if (is_gimple_min_invariant (x))
3610 : return NULL;
3611 :
3612 1814083 : phi = chain_of_csts_start (loop, x);
3613 1814083 : if (!phi)
3614 : return NULL;
3615 :
3616 499446 : init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
3617 499446 : next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
3618 :
3619 499446 : if (!is_gimple_min_invariant (init))
3620 : return NULL;
3621 :
3622 219995 : if (TREE_CODE (next) == SSA_NAME
3623 219995 : && chain_of_csts_start (loop, next) != phi)
3624 16755 : return NULL;
3625 :
3626 : return phi;
3627 : }
3628 :
3629 : /* Given an expression X, then
3630 :
3631 : * if X is NULL_TREE, we return the constant BASE.
3632 : * if X is a constant, we return the constant X.
3633 : * otherwise X is a SSA name, whose value in the considered loop is derived
3634 : by a chain of operations with constant from a result of a phi node in
3635 : the header of the loop. Then we return value of X when the value of the
3636 : result of this phi node is given by the constant BASE. */
3637 :
3638 : static tree
3639 7602972 : get_val_for (tree x, tree base)
3640 : {
3641 7610369 : gimple *stmt;
3642 :
3643 7610369 : gcc_checking_assert (is_gimple_min_invariant (base));
3644 :
3645 7610369 : if (!x)
3646 : return base;
3647 5320803 : else if (is_gimple_min_invariant (x))
3648 : return x;
3649 :
3650 5295171 : stmt = SSA_NAME_DEF_STMT (x);
3651 5295171 : if (gimple_code (stmt) == GIMPLE_PHI)
3652 : return base;
3653 :
3654 2811352 : gcc_checking_assert (is_gimple_assign (stmt));
3655 :
3656 : /* STMT must be either an assignment of a single SSA name or an
3657 : expression involving an SSA name and a constant. Try to fold that
3658 : expression using the value for the SSA name. */
3659 2811352 : if (gimple_assign_ssa_name_copy_p (stmt))
3660 7397 : return get_val_for (gimple_assign_rhs1 (stmt), base);
3661 2803955 : else if (gimple_assign_rhs_class (stmt) == GIMPLE_UNARY_RHS
3662 2803955 : && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
3663 286956 : return fold_build1 (gimple_assign_rhs_code (stmt),
3664 : TREE_TYPE (gimple_assign_lhs (stmt)),
3665 : get_val_for (gimple_assign_rhs1 (stmt), base));
3666 2516999 : else if (gimple_assign_rhs_class (stmt) == GIMPLE_BINARY_RHS)
3667 : {
3668 2516999 : tree rhs1 = gimple_assign_rhs1 (stmt);
3669 2516999 : tree rhs2 = gimple_assign_rhs2 (stmt);
3670 2516999 : if (TREE_CODE (rhs1) == SSA_NAME)
3671 2454389 : rhs1 = get_val_for (rhs1, base);
3672 62610 : else if (TREE_CODE (rhs2) == SSA_NAME)
3673 62610 : rhs2 = get_val_for (rhs2, base);
3674 : else
3675 0 : gcc_unreachable ();
3676 2516999 : return fold_build2 (gimple_assign_rhs_code (stmt),
3677 : TREE_TYPE (gimple_assign_lhs (stmt)), rhs1, rhs2);
3678 : }
3679 : else
3680 0 : gcc_unreachable ();
3681 : }
3682 :
3683 :
3684 : /* Tries to count the number of iterations of LOOP till it exits by EXIT
3685 : by brute force -- i.e. by determining the value of the operands of the
3686 : condition at EXIT in first few iterations of the loop (assuming that
3687 : these values are constant) and determining the first one in that the
3688 : condition is not satisfied. Returns the constant giving the number
3689 : of the iterations of LOOP if successful, chrec_dont_know otherwise. */
3690 :
3691 : tree
3692 1778173 : loop_niter_by_eval (class loop *loop, edge exit)
3693 : {
3694 1778173 : tree acnd;
3695 1778173 : tree op[2], val[2], next[2], aval[2];
3696 1778173 : gphi *phi;
3697 1778173 : unsigned i, j;
3698 1778173 : enum tree_code cmp;
3699 :
3700 3556346 : gcond *cond = safe_dyn_cast <gcond *> (*gsi_last_bb (exit->src));
3701 1778173 : if (!cond)
3702 127902 : return chrec_dont_know;
3703 :
3704 1650271 : cmp = gimple_cond_code (cond);
3705 1650271 : op[0] = gimple_cond_lhs (cond);
3706 1650271 : op[1] = gimple_cond_rhs (cond);
3707 1650271 : if (exit->flags & EDGE_TRUE_VALUE)
3708 595590 : cmp = invert_tree_comparison (cmp, HONOR_NANS (op[0]));
3709 :
3710 1650271 : switch (cmp)
3711 : {
3712 : case EQ_EXPR:
3713 : case NE_EXPR:
3714 : case GT_EXPR:
3715 : case GE_EXPR:
3716 : case LT_EXPR:
3717 : case LE_EXPR:
3718 : break;
3719 :
3720 9748 : default:
3721 9748 : return chrec_dont_know;
3722 : }
3723 :
3724 1873228 : for (j = 0; j < 2; j++)
3725 : {
3726 1843548 : if (is_gimple_min_invariant (op[j]))
3727 : {
3728 29465 : val[j] = op[j];
3729 29465 : next[j] = NULL_TREE;
3730 29465 : op[j] = NULL_TREE;
3731 : }
3732 : else
3733 : {
3734 1814083 : phi = get_base_for (loop, op[j]);
3735 1814083 : if (!phi)
3736 : {
3737 1610843 : gassign *def;
3738 1610843 : if (j == 0
3739 1437498 : && (cmp == NE_EXPR || cmp == EQ_EXPR)
3740 834944 : && TREE_CODE (op[0]) == SSA_NAME
3741 834944 : && TREE_CODE (op[1]) == INTEGER_CST
3742 530368 : && (def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (op[0])))
3743 1901760 : && gimple_assign_rhs_code (def) == MEM_REF)
3744 : {
3745 61060 : tree mem = gimple_assign_rhs1 (def);
3746 61060 : affine_iv iv;
3747 61060 : if (TYPE_MODE (TREE_TYPE (mem)) == TYPE_MODE (char_type_node)
3748 : && CHAR_TYPE_SIZE == 8
3749 23748 : && simple_iv (loop, loop,
3750 23748 : TREE_OPERAND (mem, 0), &iv, false)
3751 17346 : && tree_fits_uhwi_p (TREE_OPERAND (mem, 1))
3752 78406 : && tree_fits_uhwi_p (iv.step))
3753 : {
3754 17346 : tree str, off;
3755 : /* iv.base can be &"Foo" but also (char *)&"Foo" + 1. */
3756 17346 : split_constant_offset (iv.base, &str, &off);
3757 17346 : STRIP_NOPS (str);
3758 17346 : if (TREE_CODE (str) == ADDR_EXPR
3759 3326 : && TREE_CODE (TREE_OPERAND (str, 0)) == STRING_CST
3760 19182 : && tree_fits_uhwi_p (off))
3761 : {
3762 1836 : str = TREE_OPERAND (str, 0);
3763 1836 : unsigned i = 0;
3764 1836 : uint8_t op1 = TREE_INT_CST_LOW (op[1]);
3765 1836 : for (unsigned HOST_WIDE_INT idx
3766 1836 : = (tree_to_uhwi (TREE_OPERAND (mem, 1))
3767 1836 : + tree_to_uhwi (off));
3768 31396 : idx < (unsigned)TREE_STRING_LENGTH (str)
3769 15698 : && i < MAX_ITERATIONS_TO_TRACK;
3770 13862 : idx += tree_to_uhwi (iv.step), ++i)
3771 : {
3772 14806 : uint8_t c = TREE_STRING_POINTER (str)[idx];
3773 14806 : if ((cmp == NE_EXPR && op1 == c)
3774 13896 : || (cmp == EQ_EXPR && op1 != c))
3775 944 : return build_int_cst (unsigned_type_node, i);
3776 : }
3777 : }
3778 : }
3779 : }
3780 1609899 : return chrec_dont_know;
3781 : }
3782 203240 : val[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
3783 203240 : next[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
3784 : }
3785 : }
3786 :
3787 1214872 : for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
3788 : {
3789 3641820 : for (j = 0; j < 2; j++)
3790 2427880 : aval[j] = get_val_for (op[j], val[j]);
3791 :
3792 1213940 : acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
3793 1213940 : if (acnd && integer_zerop (acnd))
3794 : {
3795 28020 : if (dump_file && (dump_flags & TDF_DETAILS))
3796 3 : fprintf (dump_file,
3797 : "Proved that loop %d iterates %d times using brute force.\n",
3798 : loop->num, i);
3799 28020 : return build_int_cst (unsigned_type_node, i);
3800 : }
3801 :
3802 3556354 : for (j = 0; j < 2; j++)
3803 : {
3804 2371137 : aval[j] = val[j];
3805 2371137 : val[j] = get_val_for (next[j], val[j]);
3806 2371137 : if (!is_gimple_min_invariant (val[j]))
3807 703 : return chrec_dont_know;
3808 : }
3809 :
3810 : /* If the next iteration would use the same base values
3811 : as the current one, there is no point looping further,
3812 : all following iterations will be the same as this one. */
3813 1185217 : if (val[0] == aval[0] && val[1] == aval[1])
3814 : break;
3815 : }
3816 :
3817 957 : return chrec_dont_know;
3818 : }
3819 :
3820 : /* Finds the exit of the LOOP by that the loop exits after a constant
3821 : number of iterations and stores the exit edge to *EXIT. The constant
3822 : giving the number of iterations of LOOP is returned. The number of
3823 : iterations is determined using loop_niter_by_eval (i.e. by brute force
3824 : evaluation). If we are unable to find the exit for that loop_niter_by_eval
3825 : determines the number of iterations, chrec_dont_know is returned. */
3826 :
3827 : tree
3828 819649 : find_loop_niter_by_eval (class loop *loop, edge *exit)
3829 : {
3830 819649 : unsigned i;
3831 819649 : auto_vec<edge> exits = get_loop_exit_edges (loop);
3832 819649 : edge ex;
3833 819649 : tree niter = NULL_TREE, aniter;
3834 :
3835 819649 : *exit = NULL;
3836 :
3837 : /* Loops with multiple exits are expensive to handle and less important. */
3838 819649 : if (!flag_expensive_optimizations
3839 840950 : && exits.length () > 1)
3840 4350 : return chrec_dont_know;
3841 :
3842 2451892 : FOR_EACH_VEC_ELT (exits, i, ex)
3843 : {
3844 1636593 : if (!just_once_each_iteration_p (loop, ex->src))
3845 442342 : continue;
3846 :
3847 1194251 : aniter = loop_niter_by_eval (loop, ex);
3848 1194251 : if (chrec_contains_undetermined (aniter))
3849 1178486 : continue;
3850 :
3851 15814 : if (niter
3852 15765 : && !tree_int_cst_lt (aniter, niter))
3853 49 : continue;
3854 :
3855 15716 : niter = aniter;
3856 15716 : *exit = ex;
3857 : }
3858 :
3859 815299 : return niter ? niter : chrec_dont_know;
3860 819649 : }
3861 :
3862 : /*
3863 :
3864 : Analysis of upper bounds on number of iterations of a loop.
3865 :
3866 : */
3867 :
3868 : static widest_int derive_constant_upper_bound_ops (tree, tree,
3869 : enum tree_code, tree);
3870 :
3871 : /* Returns a constant upper bound on the value of the right-hand side of
3872 : an assignment statement STMT. */
3873 :
3874 : static widest_int
3875 332 : derive_constant_upper_bound_assign (gimple *stmt)
3876 : {
3877 332 : enum tree_code code = gimple_assign_rhs_code (stmt);
3878 332 : tree op0 = gimple_assign_rhs1 (stmt);
3879 332 : tree op1 = gimple_assign_rhs2 (stmt);
3880 :
3881 332 : return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt)),
3882 332 : op0, code, op1);
3883 : }
3884 :
3885 : /* Returns a constant upper bound on the value of expression VAL. VAL
3886 : is considered to be unsigned. If its type is signed, its value must
3887 : be nonnegative. */
3888 :
3889 : static widest_int
3890 11678304 : derive_constant_upper_bound (tree val)
3891 : {
3892 11678304 : enum tree_code code;
3893 11678304 : tree op0, op1, op2;
3894 :
3895 11678304 : extract_ops_from_tree (val, &code, &op0, &op1, &op2);
3896 11678304 : return derive_constant_upper_bound_ops (TREE_TYPE (val), op0, code, op1);
3897 : }
3898 :
3899 : /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
3900 : whose type is TYPE. The expression is considered to be unsigned. If
3901 : its type is signed, its value must be nonnegative. */
3902 :
3903 : static widest_int
3904 11678636 : derive_constant_upper_bound_ops (tree type, tree op0,
3905 : enum tree_code code, tree op1)
3906 : {
3907 11678636 : tree subtype, maxt;
3908 11678636 : widest_int bnd, max, cst;
3909 11678636 : gimple *stmt;
3910 :
3911 11678636 : if (INTEGRAL_TYPE_P (type))
3912 11678636 : maxt = TYPE_MAX_VALUE (type);
3913 : else
3914 0 : maxt = upper_bound_in_type (type, type);
3915 :
3916 11678636 : max = wi::to_widest (maxt);
3917 :
3918 11678636 : switch (code)
3919 : {
3920 11613438 : case INTEGER_CST:
3921 11613438 : return wi::to_widest (op0);
3922 :
3923 1017 : CASE_CONVERT:
3924 1017 : subtype = TREE_TYPE (op0);
3925 1017 : if (!TYPE_UNSIGNED (subtype)
3926 : /* If TYPE is also signed, the fact that VAL is nonnegative implies
3927 : that OP0 is nonnegative. */
3928 738 : && TYPE_UNSIGNED (type)
3929 1755 : && !tree_expr_nonnegative_p (op0))
3930 : {
3931 : /* If we cannot prove that the casted expression is nonnegative,
3932 : we cannot establish more useful upper bound than the precision
3933 : of the type gives us. */
3934 650 : return max;
3935 : }
3936 :
3937 : /* We now know that op0 is an nonnegative value. Try deriving an upper
3938 : bound for it. */
3939 367 : bnd = derive_constant_upper_bound (op0);
3940 :
3941 : /* If the bound does not fit in TYPE, max. value of TYPE could be
3942 : attained. */
3943 367 : if (wi::ltu_p (max, bnd))
3944 0 : return max;
3945 :
3946 367 : return bnd;
3947 :
3948 35247 : case PLUS_EXPR:
3949 35247 : case POINTER_PLUS_EXPR:
3950 35247 : case MINUS_EXPR:
3951 35247 : if (TREE_CODE (op1) != INTEGER_CST
3952 35247 : || !tree_expr_nonnegative_p (op0))
3953 34812 : return max;
3954 :
3955 : /* Canonicalize to OP0 - CST. Consider CST to be signed, in order to
3956 : choose the most logical way how to treat this constant regardless
3957 : of the signedness of the type. */
3958 435 : cst = wi::sext (wi::to_widest (op1), TYPE_PRECISION (type));
3959 435 : if (code != MINUS_EXPR)
3960 435 : cst = -cst;
3961 :
3962 435 : bnd = derive_constant_upper_bound (op0);
3963 :
3964 435 : if (wi::neg_p (cst))
3965 : {
3966 28 : cst = -cst;
3967 : /* Avoid CST == 0x80000... */
3968 28 : if (wi::neg_p (cst))
3969 0 : return max;
3970 :
3971 : /* OP0 + CST. We need to check that
3972 : BND <= MAX (type) - CST. */
3973 :
3974 28 : widest_int mmax = max - cst;
3975 28 : if (wi::leu_p (bnd, mmax))
3976 0 : return max;
3977 :
3978 28 : return bnd + cst;
3979 28 : }
3980 : else
3981 : {
3982 : /* OP0 - CST, where CST >= 0.
3983 :
3984 : If TYPE is signed, we have already verified that OP0 >= 0, and we
3985 : know that the result is nonnegative. This implies that
3986 : VAL <= BND - CST.
3987 :
3988 : If TYPE is unsigned, we must additionally know that OP0 >= CST,
3989 : otherwise the operation underflows.
3990 : */
3991 :
3992 : /* This should only happen if the type is unsigned; however, for
3993 : buggy programs that use overflowing signed arithmetics even with
3994 : -fno-wrapv, this condition may also be true for signed values. */
3995 407 : if (wi::ltu_p (bnd, cst))
3996 0 : return max;
3997 :
3998 407 : if (TYPE_UNSIGNED (type))
3999 : {
4000 402 : tree tem = fold_binary (GE_EXPR, boolean_type_node, op0,
4001 : wide_int_to_tree (type, cst));
4002 402 : if (!tem || integer_nonzerop (tem))
4003 50 : return max;
4004 : }
4005 :
4006 357 : bnd -= cst;
4007 : }
4008 :
4009 357 : return bnd;
4010 :
4011 0 : case FLOOR_DIV_EXPR:
4012 0 : case EXACT_DIV_EXPR:
4013 0 : if (TREE_CODE (op1) != INTEGER_CST
4014 0 : || tree_int_cst_sign_bit (op1))
4015 0 : return max;
4016 :
4017 0 : bnd = derive_constant_upper_bound (op0);
4018 0 : return wi::udiv_floor (bnd, wi::to_widest (op1));
4019 :
4020 7 : case BIT_AND_EXPR:
4021 7 : if (TREE_CODE (op1) != INTEGER_CST
4022 7 : || tree_int_cst_sign_bit (op1))
4023 0 : return max;
4024 7 : return wi::to_widest (op1);
4025 :
4026 543 : case SSA_NAME:
4027 543 : stmt = SSA_NAME_DEF_STMT (op0);
4028 543 : if (gimple_code (stmt) != GIMPLE_ASSIGN
4029 543 : || gimple_assign_lhs (stmt) != op0)
4030 211 : return max;
4031 332 : return derive_constant_upper_bound_assign (stmt);
4032 :
4033 28384 : default:
4034 28384 : return max;
4035 : }
4036 11678649 : }
4037 :
4038 : /* Emit a -Waggressive-loop-optimizations warning if needed. */
4039 :
4040 : static void
4041 10715139 : do_warn_aggressive_loop_optimizations (class loop *loop,
4042 : widest_int i_bound, gimple *stmt)
4043 : {
4044 : /* Don't warn if the loop doesn't have known constant bound. */
4045 10715139 : if (!loop->nb_iterations
4046 10715139 : || TREE_CODE (loop->nb_iterations) != INTEGER_CST
4047 4980358 : || !warn_aggressive_loop_optimizations
4048 : /* To avoid warning multiple times for the same loop,
4049 : only start warning when we preserve loops. */
4050 4980190 : || (cfun->curr_properties & PROP_loops) == 0
4051 : /* Only warn once per loop. */
4052 4980190 : || loop->warned_aggressive_loop_optimizations
4053 : /* Only warn if undefined behavior gives us lower estimate than the
4054 : known constant bound. */
4055 10715139 : || wi::cmpu (i_bound, wi::to_widest (loop->nb_iterations)) >= 0
4056 : /* And undefined behavior happens unconditionally. */
4057 10715194 : || !dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (stmt)))
4058 10715084 : return;
4059 :
4060 55 : edge e = single_exit (loop);
4061 55 : if (e == NULL)
4062 : return;
4063 :
4064 55 : gimple *estmt = last_nondebug_stmt (e->src);
4065 55 : char buf[WIDE_INT_PRINT_BUFFER_SIZE], *p;
4066 55 : unsigned len;
4067 55 : if (print_dec_buf_size (i_bound, TYPE_SIGN (TREE_TYPE (loop->nb_iterations)),
4068 : &len))
4069 0 : p = XALLOCAVEC (char, len);
4070 : else
4071 : p = buf;
4072 55 : print_dec (i_bound, p, TYPE_SIGN (TREE_TYPE (loop->nb_iterations)));
4073 55 : auto_diagnostic_group d;
4074 55 : if (warning_at (gimple_location (stmt), OPT_Waggressive_loop_optimizations,
4075 : "iteration %s invokes undefined behavior", p))
4076 9 : inform (gimple_location (estmt), "within this loop");
4077 55 : loop->warned_aggressive_loop_optimizations = true;
4078 55 : }
4079 :
4080 : /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP. IS_EXIT
4081 : is true if the loop is exited immediately after STMT, and this exit
4082 : is taken at last when the STMT is executed BOUND + 1 times.
4083 : REALISTIC is true if BOUND is expected to be close to the real number
4084 : of iterations. UPPER is true if we are sure the loop iterates at most
4085 : BOUND times. I_BOUND is a widest_int upper estimate on BOUND. */
4086 :
4087 : static void
4088 16648250 : record_estimate (class loop *loop, tree bound, const widest_int &i_bound,
4089 : gimple *at_stmt, bool is_exit, bool realistic, bool upper)
4090 : {
4091 16648250 : widest_int delta;
4092 :
4093 16648250 : if (dump_file && (dump_flags & TDF_DETAILS))
4094 : {
4095 139176 : fprintf (dump_file, "Statement %s", is_exit ? "(exit)" : "");
4096 77519 : print_gimple_stmt (dump_file, at_stmt, 0, TDF_SLIM);
4097 78290 : fprintf (dump_file, " is %sexecuted at most ",
4098 : upper ? "" : "probably ");
4099 77519 : print_generic_expr (dump_file, bound, TDF_SLIM);
4100 77519 : fprintf (dump_file, " (bounded by ");
4101 77519 : print_decu (i_bound, dump_file);
4102 77519 : fprintf (dump_file, ") + 1 times in loop %d.\n", loop->num);
4103 : }
4104 :
4105 : /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
4106 : real number of iterations. */
4107 16648250 : if (TREE_CODE (bound) != INTEGER_CST)
4108 : realistic = false;
4109 : else
4110 14684774 : gcc_checking_assert (i_bound == wi::to_widest (bound));
4111 :
4112 16648250 : if (wi::min_precision (i_bound, SIGNED) > bound_wide_int ().get_precision ())
4113 : return;
4114 :
4115 : /* If we have a guaranteed upper bound, record it in the appropriate
4116 : list, unless this is an !is_exit bound (i.e. undefined behavior in
4117 : at_stmt) in a loop with known constant number of iterations. */
4118 16648223 : if (upper
4119 16088245 : && (is_exit
4120 11117511 : || loop->nb_iterations == NULL_TREE
4121 11117511 : || TREE_CODE (loop->nb_iterations) != INTEGER_CST))
4122 : {
4123 10909457 : class nb_iter_bound *elt = ggc_alloc<nb_iter_bound> ();
4124 :
4125 10909457 : elt->bound = bound_wide_int::from (i_bound, SIGNED);
4126 10909457 : elt->stmt = at_stmt;
4127 10909457 : elt->is_exit = is_exit;
4128 10909457 : elt->next = loop->bounds;
4129 10909457 : loop->bounds = elt;
4130 : }
4131 :
4132 : /* If statement is executed on every path to the loop latch, we can directly
4133 : infer the upper bound on the # of iterations of the loop. */
4134 16648223 : if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (at_stmt)))
4135 477556 : upper = false;
4136 :
4137 : /* Update the number of iteration estimates according to the bound.
4138 : If at_stmt is an exit then the loop latch is executed at most BOUND times,
4139 : otherwise it can be executed BOUND + 1 times. We will lower the estimate
4140 : later if such statement must be executed on last iteration */
4141 16648223 : if (is_exit)
4142 4970740 : delta = 0;
4143 : else
4144 11677483 : delta = 1;
4145 16648223 : widest_int new_i_bound = i_bound + delta;
4146 :
4147 : /* If an overflow occurred, ignore the result. */
4148 16648223 : if (wi::ltu_p (new_i_bound, delta))
4149 0 : return;
4150 :
4151 16648223 : if (upper && !is_exit)
4152 10715139 : do_warn_aggressive_loop_optimizations (loop, new_i_bound, at_stmt);
4153 16648223 : record_niter_bound (loop, new_i_bound, realistic, upper);
4154 16648250 : }
4155 :
4156 : /* Records the control iv analyzed in NITER for LOOP if the iv is valid
4157 : and doesn't overflow. */
4158 :
4159 : static void
4160 4970748 : record_control_iv (class loop *loop, class tree_niter_desc *niter)
4161 : {
4162 4970748 : struct control_iv *iv;
4163 :
4164 4970748 : if (!niter->control.base || !niter->control.step)
4165 : return;
4166 :
4167 4928910 : if (!integer_onep (niter->assumptions) || !niter->control.no_overflow)
4168 : return;
4169 :
4170 4775160 : iv = ggc_alloc<control_iv> ();
4171 4775160 : iv->base = niter->control.base;
4172 4775160 : iv->step = niter->control.step;
4173 4775160 : iv->next = loop->control_ivs;
4174 4775160 : loop->control_ivs = iv;
4175 :
4176 4775160 : return;
4177 : }
4178 :
4179 : /* This function returns TRUE if below conditions are satisfied:
4180 : 1) VAR is SSA variable.
4181 : 2) VAR is an IV:{base, step} in its defining loop.
4182 : 3) IV doesn't overflow.
4183 : 4) Both base and step are integer constants.
4184 : 5) Base is the MIN/MAX value depends on IS_MIN.
4185 : Store value of base to INIT correspondingly. */
4186 :
4187 : static bool
4188 125118 : get_cst_init_from_scev (tree var, wide_int *init, bool is_min)
4189 : {
4190 125118 : if (TREE_CODE (var) != SSA_NAME)
4191 : return false;
4192 :
4193 125118 : gimple *def_stmt = SSA_NAME_DEF_STMT (var);
4194 125118 : class loop *loop = loop_containing_stmt (def_stmt);
4195 :
4196 112579 : if (loop == NULL)
4197 : return false;
4198 :
4199 112579 : affine_iv iv;
4200 112579 : if (!simple_iv (loop, loop, var, &iv, false))
4201 : return false;
4202 :
4203 6428 : if (!iv.no_overflow)
4204 : return false;
4205 :
4206 6373 : if (TREE_CODE (iv.base) != INTEGER_CST || TREE_CODE (iv.step) != INTEGER_CST)
4207 : return false;
4208 :
4209 4980 : if (is_min == tree_int_cst_sign_bit (iv.step))
4210 : return false;
4211 :
4212 4747 : *init = wi::to_wide (iv.base);
4213 4747 : return true;
4214 : }
4215 :
4216 : /* Record the estimate on number of iterations of LOOP based on the fact that
4217 : the induction variable BASE + STEP * i evaluated in STMT does not wrap and
4218 : its values belong to the range <LOW, HIGH>. REALISTIC is true if the
4219 : estimated number of iterations is expected to be close to the real one.
4220 : UPPER is true if we are sure the induction variable does not wrap. */
4221 :
4222 : static void
4223 11677496 : record_nonwrapping_iv (class loop *loop, tree base, tree step, gimple *stmt,
4224 : tree low, tree high, bool realistic, bool upper)
4225 : {
4226 11677496 : tree niter_bound, extreme, delta;
4227 11677496 : tree type = TREE_TYPE (base), unsigned_type;
4228 11677496 : tree orig_base = base;
4229 :
4230 11677496 : if (TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
4231 0 : return;
4232 :
4233 11677496 : if (dump_file && (dump_flags & TDF_DETAILS))
4234 : {
4235 61657 : fprintf (dump_file, "Induction variable (");
4236 61657 : print_generic_expr (dump_file, TREE_TYPE (base), TDF_SLIM);
4237 61657 : fprintf (dump_file, ") ");
4238 61657 : print_generic_expr (dump_file, base, TDF_SLIM);
4239 61657 : fprintf (dump_file, " + ");
4240 61657 : print_generic_expr (dump_file, step, TDF_SLIM);
4241 61657 : fprintf (dump_file, " * iteration does not wrap in statement ");
4242 61657 : print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
4243 61657 : fprintf (dump_file, " in loop %d.\n", loop->num);
4244 : }
4245 :
4246 11677496 : unsigned_type = unsigned_type_for (type);
4247 11677496 : base = fold_convert (unsigned_type, base);
4248 11677496 : step = fold_convert (unsigned_type, step);
4249 :
4250 11677496 : if (tree_int_cst_sign_bit (step))
4251 : {
4252 360172 : wide_int max;
4253 360172 : value_range base_range (TREE_TYPE (orig_base));
4254 720344 : if (get_range_query (cfun)->range_of_expr (base_range, orig_base)
4255 360172 : && !base_range.undefined_p ())
4256 360093 : max = wi::to_wide (base_range.ubound ());
4257 360172 : extreme = fold_convert (unsigned_type, low);
4258 360172 : if (TREE_CODE (orig_base) == SSA_NAME
4259 20191 : && TREE_CODE (high) == INTEGER_CST
4260 20191 : && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
4261 20117 : && ((!base_range.varying_p ()
4262 6985 : && !base_range.undefined_p ())
4263 13211 : || get_cst_init_from_scev (orig_base, &max, false))
4264 367078 : && wi::gts_p (wi::to_wide (high), max))
4265 2225 : base = wide_int_to_tree (unsigned_type, max);
4266 357947 : else if (TREE_CODE (base) != INTEGER_CST
4267 573796 : && dominated_by_p (CDI_DOMINATORS,
4268 215849 : loop->latch, gimple_bb (stmt)))
4269 213944 : base = fold_convert (unsigned_type, high);
4270 360172 : delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
4271 360172 : step = fold_build1 (NEGATE_EXPR, unsigned_type, step);
4272 360173 : }
4273 : else
4274 : {
4275 11317324 : wide_int min;
4276 11317324 : value_range base_range (TREE_TYPE (orig_base));
4277 22634648 : if (get_range_query (cfun)->range_of_expr (base_range, orig_base)
4278 11317324 : && !base_range.undefined_p ())
4279 11315068 : min = wi::to_wide (base_range.lbound ());
4280 11317324 : extreme = fold_convert (unsigned_type, high);
4281 11317324 : if (TREE_CODE (orig_base) == SSA_NAME
4282 886990 : && TREE_CODE (low) == INTEGER_CST
4283 886990 : && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
4284 266295 : && ((!base_range.varying_p ()
4285 156384 : && !base_range.undefined_p ())
4286 111907 : || get_cst_init_from_scev (orig_base, &min, true))
4287 11476459 : && wi::gts_p (min, wi::to_wide (low)))
4288 13006 : base = wide_int_to_tree (unsigned_type, min);
4289 11304318 : else if (TREE_CODE (base) != INTEGER_CST
4290 14815984 : && dominated_by_p (CDI_DOMINATORS,
4291 3511666 : loop->latch, gimple_bb (stmt)))
4292 3449507 : base = fold_convert (unsigned_type, low);
4293 11317324 : delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
4294 11317336 : }
4295 :
4296 : /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
4297 : would get out of the range. */
4298 11677496 : niter_bound = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step);
4299 11677496 : widest_int max = derive_constant_upper_bound (niter_bound);
4300 11677496 : record_estimate (loop, niter_bound, max, stmt, false, realistic, upper);
4301 11677496 : }
4302 :
4303 : /* Determine information about number of iterations a LOOP from the index
4304 : IDX of a data reference accessed in STMT. RELIABLE is true if STMT is
4305 : guaranteed to be executed in every iteration of LOOP. Callback for
4306 : for_each_index. */
4307 :
4308 : struct ilb_data
4309 : {
4310 : class loop *loop;
4311 : gimple *stmt;
4312 : };
4313 :
4314 : static bool
4315 37407388 : idx_infer_loop_bounds (tree base, tree *idx, void *dta)
4316 : {
4317 37407388 : struct ilb_data *data = (struct ilb_data *) dta;
4318 37407388 : tree ev, init, step;
4319 37407388 : tree low, high, type, next;
4320 37407388 : bool sign, upper = true, has_flexible_size = false;
4321 37407388 : class loop *loop = data->loop;
4322 :
4323 37407388 : if (TREE_CODE (base) != ARRAY_REF)
4324 : return true;
4325 :
4326 : /* For arrays that might have flexible sizes, it is not guaranteed that they
4327 : do not really extend over their declared size. */
4328 10391388 : if (array_ref_flexible_size_p (base))
4329 : {
4330 2468784 : has_flexible_size = true;
4331 2468784 : upper = false;
4332 : }
4333 :
4334 10391388 : class loop *dloop = loop_containing_stmt (data->stmt);
4335 10391388 : if (!dloop)
4336 : return true;
4337 :
4338 10391388 : ev = analyze_scalar_evolution (dloop, *idx);
4339 10391388 : ev = instantiate_parameters (loop, ev);
4340 10391388 : init = initial_condition (ev);
4341 10391388 : step = evolution_part_in_loop_num (ev, loop->num);
4342 :
4343 10391388 : if (!init
4344 10391388 : || !step
4345 5896332 : || TREE_CODE (step) != INTEGER_CST
4346 4492327 : || integer_zerop (step)
4347 4492327 : || tree_contains_chrecs (init, NULL)
4348 14883715 : || chrec_contains_symbols_defined_in_loop (init, loop->num))
4349 : return true;
4350 :
4351 4492327 : low = array_ref_low_bound (base);
4352 4492327 : high = array_ref_up_bound (base);
4353 :
4354 : /* The case of nonconstant bounds could be handled, but it would be
4355 : complicated. */
4356 4492327 : if (TREE_CODE (low) != INTEGER_CST
4357 4492327 : || !high
4358 3768841 : || TREE_CODE (high) != INTEGER_CST)
4359 : return true;
4360 3536560 : sign = tree_int_cst_sign_bit (step);
4361 3536560 : type = TREE_TYPE (step);
4362 :
4363 : /* The array that might have flexible size most likely extends
4364 : beyond its bounds. */
4365 3536560 : if (has_flexible_size
4366 3536560 : && operand_equal_p (low, high, 0))
4367 : return true;
4368 :
4369 : /* In case the relevant bound of the array does not fit in type, or
4370 : it does, but bound + step (in type) still belongs into the range of the
4371 : array, the index may wrap and still stay within the range of the array
4372 : (consider e.g. if the array is indexed by the full range of
4373 : unsigned char).
4374 :
4375 : To make things simpler, we require both bounds to fit into type, although
4376 : there are cases where this would not be strictly necessary. */
4377 3518165 : if (!int_fits_type_p (high, type)
4378 3518133 : || !int_fits_type_p (low, type))
4379 : return true;
4380 3518133 : low = fold_convert (type, low);
4381 3518133 : high = fold_convert (type, high);
4382 :
4383 3518133 : if (sign)
4384 65849 : next = fold_binary (PLUS_EXPR, type, low, step);
4385 : else
4386 3452284 : next = fold_binary (PLUS_EXPR, type, high, step);
4387 :
4388 3518133 : if (tree_int_cst_compare (low, next) <= 0
4389 3518133 : && tree_int_cst_compare (next, high) <= 0)
4390 : return true;
4391 :
4392 : /* If access is not executed on every iteration, we must ensure that overflow
4393 : may not make the access valid later. */
4394 3518133 : if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (data->stmt)))
4395 : {
4396 469986 : if (scev_probably_wraps_p (NULL_TREE,
4397 469986 : initial_condition_in_loop_num (ev, loop->num),
4398 : step, data->stmt, loop, true))
4399 3518133 : upper = false;
4400 : }
4401 : else
4402 3048147 : record_nonwrapping_chrec (ev);
4403 :
4404 3518133 : record_nonwrapping_iv (loop, init, step, data->stmt, low, high, false, upper);
4405 3518133 : return true;
4406 : }
4407 :
4408 : /* Determine information about number of iterations a LOOP from the bounds
4409 : of arrays in the data reference REF accessed in STMT. RELIABLE is true if
4410 : STMT is guaranteed to be executed in every iteration of LOOP.*/
4411 :
4412 : static void
4413 38223728 : infer_loop_bounds_from_ref (class loop *loop, gimple *stmt, tree ref)
4414 : {
4415 38223728 : struct ilb_data data;
4416 :
4417 38223728 : data.loop = loop;
4418 38223728 : data.stmt = stmt;
4419 0 : for_each_index (&ref, idx_infer_loop_bounds, &data);
4420 0 : }
4421 :
4422 : /* Determine information about number of iterations of a LOOP from the way
4423 : arrays are used in STMT. RELIABLE is true if STMT is guaranteed to be
4424 : executed in every iteration of LOOP. */
4425 :
4426 : static void
4427 277759805 : infer_loop_bounds_from_array (class loop *loop, gimple *stmt)
4428 : {
4429 277759805 : if (auto assign = dyn_cast<gassign *> (stmt))
4430 : {
4431 108369224 : tree op0 = gimple_assign_lhs (assign);
4432 108369224 : tree op1 = gimple_assign_rhs1 (assign);
4433 :
4434 : /* For each memory access, analyze its access function
4435 : and record a bound on the loop iteration domain. */
4436 108369224 : if (REFERENCE_CLASS_P (op0))
4437 15273175 : infer_loop_bounds_from_ref (loop, assign, op0);
4438 :
4439 108369224 : if (REFERENCE_CLASS_P (op1))
4440 22775674 : infer_loop_bounds_from_ref (loop, assign, op1);
4441 : }
4442 169390581 : else if (is_gimple_call (stmt))
4443 : {
4444 7598186 : tree arg, lhs;
4445 7598186 : unsigned i, n = gimple_call_num_args (stmt);
4446 :
4447 7598186 : lhs = gimple_call_lhs (stmt);
4448 7598186 : if (lhs && REFERENCE_CLASS_P (lhs))
4449 4982 : infer_loop_bounds_from_ref (loop, stmt, lhs);
4450 :
4451 24683776 : for (i = 0; i < n; i++)
4452 : {
4453 17085590 : arg = gimple_call_arg (stmt, i);
4454 17085590 : if (REFERENCE_CLASS_P (arg))
4455 169897 : infer_loop_bounds_from_ref (loop, stmt, arg);
4456 : }
4457 : }
4458 277759805 : }
4459 :
4460 : /* Determine information about number of iterations of a LOOP from the fact
4461 : that pointer arithmetics in STMT does not overflow. */
4462 :
4463 : static void
4464 137200768 : infer_loop_bounds_from_pointer_arith (class loop *loop, gimple *stmt)
4465 : {
4466 137200768 : tree def, base, step, scev, type, low, high;
4467 137200768 : tree var, ptr;
4468 :
4469 137200768 : auto assign = dyn_cast<gassign *> (stmt);
4470 75848761 : if (!assign || gimple_assign_rhs_code (assign) != POINTER_PLUS_EXPR)
4471 : return;
4472 :
4473 4763136 : def = gimple_assign_lhs (assign);
4474 4763136 : if (TREE_CODE (def) != SSA_NAME)
4475 : return;
4476 :
4477 4763136 : type = TREE_TYPE (def);
4478 4763136 : if (!nowrap_type_p (type))
4479 : return;
4480 :
4481 4762799 : ptr = gimple_assign_rhs1 (assign);
4482 4762799 : if (!expr_invariant_in_loop_p (loop, ptr))
4483 : return;
4484 :
4485 2617492 : var = gimple_assign_rhs2 (stmt);
4486 2617492 : if (TYPE_PRECISION (type) != TYPE_PRECISION (TREE_TYPE (var)))
4487 : return;
4488 :
4489 2617492 : class loop *uloop = loop_containing_stmt (stmt);
4490 2617492 : scev = instantiate_parameters (loop, analyze_scalar_evolution (uloop, def));
4491 2617492 : if (chrec_contains_undetermined (scev))
4492 : return;
4493 :
4494 2159335 : base = initial_condition_in_loop_num (scev, loop->num);
4495 2159335 : step = evolution_part_in_loop_num (scev, loop->num);
4496 :
4497 2159335 : if (!base || !step
4498 2110302 : || TREE_CODE (step) != INTEGER_CST
4499 1920241 : || tree_contains_chrecs (base, NULL)
4500 4079576 : || chrec_contains_symbols_defined_in_loop (base, loop->num))
4501 : return;
4502 :
4503 1920241 : low = lower_bound_in_type (type, type);
4504 1920241 : high = upper_bound_in_type (type, type);
4505 :
4506 : /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
4507 : produce a NULL pointer. The contrary would mean NULL points to an object,
4508 : while NULL is supposed to compare unequal with the address of all objects.
4509 : Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
4510 : NULL pointer since that would mean wrapping, which we assume here not to
4511 : happen. So, we can exclude NULL from the valid range of pointer
4512 : arithmetic. */
4513 1920241 : if (flag_delete_null_pointer_checks && int_cst_value (low) == 0)
4514 1920229 : low = build_int_cstu (TREE_TYPE (low), TYPE_ALIGN_UNIT (TREE_TYPE (type)));
4515 :
4516 1920241 : record_nonwrapping_chrec (scev);
4517 1920241 : record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
4518 : }
4519 :
4520 : /* Determine information about number of iterations of a LOOP from the fact
4521 : that signed arithmetics in STMT does not overflow. */
4522 :
4523 : static void
4524 137200768 : infer_loop_bounds_from_signedness (class loop *loop, gimple *stmt)
4525 : {
4526 137200768 : tree def, base, step, scev, type, low, high;
4527 :
4528 137200768 : auto assign = dyn_cast<gassign *> (stmt);
4529 54900409 : if (!assign)
4530 130961646 : return;
4531 :
4532 54900409 : def = gimple_assign_lhs (assign);
4533 :
4534 54900409 : if (TREE_CODE (def) != SSA_NAME)
4535 : return;
4536 :
4537 46778510 : type = TREE_TYPE (def);
4538 46778510 : if (!INTEGRAL_TYPE_P (type)
4539 46778510 : || !TYPE_OVERFLOW_UNDEFINED (type))
4540 : return;
4541 :
4542 15904394 : scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
4543 15904394 : if (chrec_contains_undetermined (scev))
4544 : return;
4545 :
4546 7768412 : base = initial_condition_in_loop_num (scev, loop->num);
4547 7768412 : step = evolution_part_in_loop_num (scev, loop->num);
4548 :
4549 7768412 : if (!base || !step
4550 6906601 : || TREE_CODE (step) != INTEGER_CST
4551 6239122 : || tree_contains_chrecs (base, NULL)
4552 14007534 : || chrec_contains_symbols_defined_in_loop (base, loop->num))
4553 : return;
4554 :
4555 6239122 : low = lower_bound_in_type (type, type);
4556 6239122 : high = upper_bound_in_type (type, type);
4557 6239122 : int_range_max r (TREE_TYPE (def));
4558 12478244 : get_range_query (cfun)->range_of_expr (r, def);
4559 6239122 : if (!r.varying_p () && !r.undefined_p ())
4560 : {
4561 5726000 : low = wide_int_to_tree (type, r.lower_bound ());
4562 5726012 : high = wide_int_to_tree (type, r.upper_bound ());
4563 : }
4564 :
4565 6239122 : record_nonwrapping_chrec (scev);
4566 6239122 : record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
4567 6239122 : }
4568 :
4569 : /* The following analyzers are extracting information on the bounds
4570 : of LOOP from the following undefined behaviors:
4571 :
4572 : - data references should not access elements over the statically
4573 : allocated size,
4574 :
4575 : - signed variables should not overflow when flag_wrapv is not set.
4576 : */
4577 :
4578 : static void
4579 6784738 : infer_loop_bounds_from_undefined (class loop *loop, basic_block *bbs)
4580 : {
4581 6784738 : unsigned i;
4582 6784738 : gimple_stmt_iterator bsi;
4583 6784738 : basic_block bb;
4584 6784738 : bool reliable;
4585 :
4586 46555792 : for (i = 0; i < loop->num_nodes; i++)
4587 : {
4588 39771054 : bb = bbs[i];
4589 :
4590 : /* If BB is not executed in each iteration of the loop, we cannot
4591 : use the operations in it to infer reliable upper bound on the
4592 : # of iterations of the loop. However, we can use it as a guess.
4593 : Reliable guesses come only from array bounds. */
4594 39771054 : reliable = dominated_by_p (CDI_DOMINATORS, loop->latch, bb);
4595 :
4596 357301913 : for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
4597 : {
4598 277759805 : gimple *stmt = gsi_stmt (bsi);
4599 :
4600 277759805 : infer_loop_bounds_from_array (loop, stmt);
4601 :
4602 277759805 : if (reliable)
4603 : {
4604 137200768 : infer_loop_bounds_from_signedness (loop, stmt);
4605 137200768 : infer_loop_bounds_from_pointer_arith (loop, stmt);
4606 : }
4607 : }
4608 :
4609 : }
4610 6784738 : }
4611 :
4612 : /* Compare wide ints, callback for qsort. */
4613 :
4614 : static int
4615 28824 : wide_int_cmp (const void *p1, const void *p2)
4616 : {
4617 28824 : const bound_wide_int *d1 = (const bound_wide_int *) p1;
4618 28824 : const bound_wide_int *d2 = (const bound_wide_int *) p2;
4619 28824 : return wi::cmpu (*d1, *d2);
4620 : }
4621 :
4622 : /* Return index of BOUND in BOUNDS array sorted in increasing order.
4623 : Lookup by binary search. */
4624 :
4625 : static int
4626 7106 : bound_index (const vec<bound_wide_int> &bounds, const bound_wide_int &bound)
4627 : {
4628 7106 : unsigned int end = bounds.length ();
4629 7106 : unsigned int begin = 0;
4630 :
4631 : /* Find a matching index by means of a binary search. */
4632 8050 : while (begin != end)
4633 : {
4634 8050 : unsigned int middle = (begin + end) / 2;
4635 8050 : bound_wide_int index = bounds[middle];
4636 :
4637 8050 : if (index == bound)
4638 7106 : return middle;
4639 944 : else if (wi::ltu_p (index, bound))
4640 236 : begin = middle + 1;
4641 : else
4642 : end = middle;
4643 : }
4644 0 : gcc_unreachable ();
4645 : }
4646 :
4647 : /* We recorded loop bounds only for statements dominating loop latch (and thus
4648 : executed each loop iteration). If there are any bounds on statements not
4649 : dominating the loop latch we can improve the estimate by walking the loop
4650 : body and seeing if every path from loop header to loop latch contains
4651 : some bounded statement. */
4652 :
4653 : static void
4654 6827701 : discover_iteration_bound_by_body_walk (class loop *loop)
4655 : {
4656 6827701 : class nb_iter_bound *elt;
4657 6827701 : auto_vec<bound_wide_int> bounds;
4658 6827701 : vec<vec<basic_block> > queues = vNULL;
4659 6827701 : vec<basic_block> queue = vNULL;
4660 6827701 : ptrdiff_t queue_index;
4661 6827701 : ptrdiff_t latch_index = 0;
4662 :
4663 : /* Discover what bounds may interest us. */
4664 17737158 : for (elt = loop->bounds; elt; elt = elt->next)
4665 : {
4666 10909457 : bound_wide_int bound = elt->bound;
4667 :
4668 : /* Exit terminates loop at given iteration, while non-exits produce undefined
4669 : effect on the next iteration. */
4670 10909457 : if (!elt->is_exit)
4671 : {
4672 5938723 : bound += 1;
4673 : /* If an overflow occurred, ignore the result. */
4674 5938723 : if (bound == 0)
4675 0 : continue;
4676 : }
4677 :
4678 10909457 : if (!loop->any_upper_bound
4679 10909457 : || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
4680 7106 : bounds.safe_push (bound);
4681 : }
4682 :
4683 : /* Exit early if there is nothing to do. */
4684 6827701 : if (!bounds.exists ())
4685 6823729 : return;
4686 :
4687 3972 : if (dump_file && (dump_flags & TDF_DETAILS))
4688 16 : fprintf (dump_file, " Trying to walk loop body to reduce the bound.\n");
4689 :
4690 : /* Sort the bounds in decreasing order. */
4691 3972 : bounds.qsort (wide_int_cmp);
4692 :
4693 : /* For every basic block record the lowest bound that is guaranteed to
4694 : terminate the loop. */
4695 :
4696 3972 : hash_map<basic_block, ptrdiff_t> bb_bounds;
4697 19933 : for (elt = loop->bounds; elt; elt = elt->next)
4698 : {
4699 15961 : bound_wide_int bound = elt->bound;
4700 15961 : if (!elt->is_exit)
4701 : {
4702 11464 : bound += 1;
4703 : /* If an overflow occurred, ignore the result. */
4704 11464 : if (bound == 0)
4705 0 : continue;
4706 : }
4707 :
4708 15961 : if (!loop->any_upper_bound
4709 15961 : || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
4710 : {
4711 7106 : ptrdiff_t index = bound_index (bounds, bound);
4712 7106 : ptrdiff_t *entry = bb_bounds.get (gimple_bb (elt->stmt));
4713 7106 : if (!entry)
4714 5014 : bb_bounds.put (gimple_bb (elt->stmt), index);
4715 2092 : else if ((ptrdiff_t)*entry > index)
4716 126 : *entry = index;
4717 : }
4718 : }
4719 :
4720 3972 : hash_map<basic_block, ptrdiff_t> block_priority;
4721 :
4722 : /* Perform shortest path discovery loop->header ... loop->latch.
4723 :
4724 : The "distance" is given by the smallest loop bound of basic block
4725 : present in the path and we look for path with largest smallest bound
4726 : on it.
4727 :
4728 : To avoid the need for fibonacci heap on double ints we simply compress
4729 : double ints into indexes to BOUNDS array and then represent the queue
4730 : as arrays of queues for every index.
4731 : Index of BOUNDS.length() means that the execution of given BB has
4732 : no bounds determined.
4733 :
4734 : VISITED is a pointer map translating basic block into smallest index
4735 : it was inserted into the priority queue with. */
4736 3972 : latch_index = -1;
4737 :
4738 : /* Start walk in loop header with index set to infinite bound. */
4739 3972 : queue_index = bounds.length ();
4740 3972 : queues.safe_grow_cleared (queue_index + 1, true);
4741 3972 : queue.safe_push (loop->header);
4742 3972 : queues[queue_index] = queue;
4743 3972 : block_priority.put (loop->header, queue_index);
4744 :
4745 19022 : for (; queue_index >= 0; queue_index--)
4746 : {
4747 11078 : if (latch_index < queue_index)
4748 : {
4749 43609 : while (queues[queue_index].length ())
4750 : {
4751 39419 : basic_block bb;
4752 39419 : ptrdiff_t bound_index = queue_index;
4753 39419 : edge e;
4754 39419 : edge_iterator ei;
4755 :
4756 39419 : queue = queues[queue_index];
4757 39419 : bb = queue.pop ();
4758 :
4759 : /* OK, we later inserted the BB with lower priority, skip it. */
4760 39419 : if (*block_priority.get (bb) > queue_index)
4761 0 : continue;
4762 :
4763 : /* See if we can improve the bound. */
4764 39419 : ptrdiff_t *entry = bb_bounds.get (bb);
4765 39419 : if (entry && *entry < bound_index)
4766 4431 : bound_index = *entry;
4767 :
4768 : /* Insert successors into the queue, watch for latch edge
4769 : and record greatest index we saw. */
4770 100586 : FOR_EACH_EDGE (e, ei, bb->succs)
4771 : {
4772 61167 : bool insert = false;
4773 :
4774 61167 : if (loop_exit_edge_p (loop, e))
4775 10870 : continue;
4776 :
4777 50297 : if (e == loop_latch_edge (loop)
4778 50297 : && latch_index < bound_index)
4779 : latch_index = bound_index;
4780 46325 : else if (!(entry = block_priority.get (e->dest)))
4781 : {
4782 37002 : insert = true;
4783 37002 : block_priority.put (e->dest, bound_index);
4784 : }
4785 9323 : else if (*entry < bound_index)
4786 : {
4787 147 : insert = true;
4788 147 : *entry = bound_index;
4789 : }
4790 :
4791 37149 : if (insert)
4792 37149 : queues[bound_index].safe_push (e->dest);
4793 : }
4794 : }
4795 : }
4796 11078 : queues[queue_index].release ();
4797 : }
4798 :
4799 3972 : gcc_assert (latch_index >= 0);
4800 3972 : if ((unsigned)latch_index < bounds.length ())
4801 : {
4802 121 : if (dump_file && (dump_flags & TDF_DETAILS))
4803 : {
4804 0 : fprintf (dump_file, "Found better loop bound ");
4805 0 : print_decu (bounds[latch_index], dump_file);
4806 0 : fprintf (dump_file, "\n");
4807 : }
4808 121 : record_niter_bound (loop, widest_int::from (bounds[latch_index],
4809 : SIGNED), false, true);
4810 : }
4811 :
4812 3972 : queues.release ();
4813 6827701 : }
4814 :
4815 : /* See if every path cross the loop goes through a statement that is known
4816 : to not execute at the last iteration. In that case we can decrease iteration
4817 : count by 1. */
4818 :
4819 : static void
4820 6827701 : maybe_lower_iteration_bound (class loop *loop)
4821 : {
4822 6827701 : hash_set<gimple *> *not_executed_last_iteration = NULL;
4823 6827701 : class nb_iter_bound *elt;
4824 6827701 : bool found_exit = false;
4825 6827701 : auto_vec<basic_block> queue;
4826 6827701 : bitmap visited;
4827 :
4828 : /* Collect all statements with interesting (i.e. lower than
4829 : nb_iterations_upper_bound) bound on them.
4830 :
4831 : TODO: Due to the way record_estimate choose estimates to store, the bounds
4832 : will be always nb_iterations_upper_bound-1. We can change this to record
4833 : also statements not dominating the loop latch and update the walk below
4834 : to the shortest path algorithm. */
4835 17737158 : for (elt = loop->bounds; elt; elt = elt->next)
4836 : {
4837 10909457 : if (!elt->is_exit
4838 10909457 : && wi::ltu_p (elt->bound, loop->nb_iterations_upper_bound))
4839 : {
4840 2261986 : if (!not_executed_last_iteration)
4841 1247482 : not_executed_last_iteration = new hash_set<gimple *>;
4842 2261986 : not_executed_last_iteration->add (elt->stmt);
4843 : }
4844 : }
4845 6827701 : if (!not_executed_last_iteration)
4846 5580219 : return;
4847 :
4848 : /* Start DFS walk in the loop header and see if we can reach the
4849 : loop latch or any of the exits (including statements with side
4850 : effects that may terminate the loop otherwise) without visiting
4851 : any of the statements known to have undefined effect on the last
4852 : iteration. */
4853 1247482 : queue.safe_push (loop->header);
4854 1247482 : visited = BITMAP_ALLOC (NULL);
4855 1247482 : bitmap_set_bit (visited, loop->header->index);
4856 1247482 : found_exit = false;
4857 :
4858 1343327 : do
4859 : {
4860 1343327 : basic_block bb = queue.pop ();
4861 1343327 : gimple_stmt_iterator gsi;
4862 1343327 : bool stmt_found = false;
4863 :
4864 : /* Loop for possible exits and statements bounding the execution. */
4865 7101662 : for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4866 : {
4867 4483310 : gimple *stmt = gsi_stmt (gsi);
4868 4483310 : if (not_executed_last_iteration->contains (stmt))
4869 : {
4870 : stmt_found = true;
4871 68302 : break;
4872 : }
4873 4440320 : if (gimple_has_side_effects (stmt))
4874 : {
4875 : found_exit = true;
4876 : break;
4877 : }
4878 : }
4879 1343327 : if (found_exit)
4880 : break;
4881 :
4882 : /* If no bounding statement is found, continue the walk. */
4883 1318015 : if (!stmt_found)
4884 : {
4885 1275025 : edge e;
4886 1275025 : edge_iterator ei;
4887 :
4888 2145470 : FOR_EACH_EDGE (e, ei, bb->succs)
4889 : {
4890 2055286 : if (loop_exit_edge_p (loop, e)
4891 871125 : || e == loop_latch_edge (loop)
4892 : /* When exiting an inner loop, verify it is finite. */
4893 871090 : || (!flow_bb_inside_loop_p (bb->loop_father, e->dest)
4894 10005 : && !finite_loop_p (bb->loop_father))
4895 : /* When we enter an irreducible region and the entry
4896 : does not contain a bounding stmt assume it might be
4897 : infinite. */
4898 2925731 : || (bb->flags & BB_IRREDUCIBLE_LOOP))
4899 : {
4900 : found_exit = true;
4901 : break;
4902 : }
4903 870445 : if (bitmap_set_bit (visited, e->dest->index))
4904 845243 : queue.safe_push (e->dest);
4905 : }
4906 : }
4907 : }
4908 1318015 : while (queue.length () && !found_exit);
4909 :
4910 : /* If every path through the loop reach bounding statement before exit,
4911 : then we know the last iteration of the loop will have undefined effect
4912 : and we can decrease number of iterations. */
4913 :
4914 1247482 : if (!found_exit)
4915 : {
4916 37329 : if (dump_file && (dump_flags & TDF_DETAILS))
4917 68 : fprintf (dump_file, "Reducing loop iteration estimate by 1; "
4918 : "undefined statement must be executed at the last iteration.\n");
4919 74658 : record_niter_bound (loop, widest_int::from (loop->nb_iterations_upper_bound,
4920 111987 : SIGNED) - 1,
4921 : false, true);
4922 : }
4923 :
4924 1247482 : BITMAP_FREE (visited);
4925 1247482 : delete not_executed_last_iteration;
4926 6827701 : }
4927 :
4928 : /* Get expected upper bound for number of loop iterations for
4929 : BUILT_IN_EXPECT_WITH_PROBABILITY for a condition COND. */
4930 :
4931 : static tree
4932 5309099 : get_upper_bound_based_on_builtin_expr_with_prob (gcond *cond)
4933 : {
4934 5309099 : if (cond == NULL)
4935 : return NULL_TREE;
4936 :
4937 5151321 : tree lhs = gimple_cond_lhs (cond);
4938 5151321 : if (TREE_CODE (lhs) != SSA_NAME)
4939 : return NULL_TREE;
4940 :
4941 5150981 : gimple *stmt = SSA_NAME_DEF_STMT (gimple_cond_lhs (cond));
4942 5150981 : gcall *def = dyn_cast<gcall *> (stmt);
4943 195899 : if (def == NULL)
4944 : return NULL_TREE;
4945 :
4946 195899 : tree decl = gimple_call_fndecl (def);
4947 195899 : if (!decl
4948 166412 : || !fndecl_built_in_p (decl, BUILT_IN_EXPECT_WITH_PROBABILITY)
4949 195907 : || gimple_call_num_args (stmt) != 3)
4950 : return NULL_TREE;
4951 :
4952 8 : tree c = gimple_call_arg (def, 1);
4953 8 : tree condt = TREE_TYPE (lhs);
4954 8 : tree res = fold_build2 (gimple_cond_code (cond),
4955 : condt, c,
4956 : gimple_cond_rhs (cond));
4957 8 : if (TREE_CODE (res) != INTEGER_CST)
4958 : return NULL_TREE;
4959 :
4960 :
4961 8 : tree prob = gimple_call_arg (def, 2);
4962 8 : tree t = TREE_TYPE (prob);
4963 8 : tree one
4964 16 : = build_real_from_int_cst (t,
4965 8 : integer_one_node);
4966 8 : if (integer_zerop (res))
4967 4 : prob = fold_build2 (MINUS_EXPR, t, one, prob);
4968 8 : tree r = fold_build2 (RDIV_EXPR, t, one, prob);
4969 8 : if (TREE_CODE (r) != REAL_CST)
4970 : return NULL_TREE;
4971 :
4972 6 : HOST_WIDE_INT probi
4973 6 : = real_to_integer (TREE_REAL_CST_PTR (r));
4974 6 : return build_int_cst (condt, probi);
4975 : }
4976 :
4977 : /* Records estimates on numbers of iterations of LOOP. If USE_UNDEFINED_P
4978 : is true also use estimates derived from undefined behavior. */
4979 :
4980 : void
4981 27072905 : estimate_numbers_of_iterations (class loop *loop)
4982 : {
4983 27072905 : tree niter, type;
4984 27072905 : unsigned i;
4985 27072905 : class tree_niter_desc niter_desc;
4986 27072905 : edge ex;
4987 27072905 : widest_int bound;
4988 27072905 : edge likely_exit;
4989 :
4990 : /* Give up if we already have tried to compute an estimation. */
4991 27072905 : if (loop->estimate_state != EST_NOT_COMPUTED)
4992 20245204 : return;
4993 :
4994 6827701 : if (dump_file && (dump_flags & TDF_DETAILS))
4995 15997 : fprintf (dump_file, "Estimating # of iterations of loop %d\n", loop->num);
4996 :
4997 6827701 : loop->estimate_state = EST_AVAILABLE;
4998 :
4999 6827701 : sreal nit;
5000 6827701 : bool reliable;
5001 :
5002 : /* If we have a measured profile, use it to estimate the number of
5003 : iterations. Normally this is recorded by branch_prob right after
5004 : reading the profile. In case we however found a new loop, record the
5005 : information here.
5006 :
5007 : Explicitly check for profile status so we do not report
5008 : wrong prediction hitrates for guessed loop iterations heuristics.
5009 : Do not recompute already recorded bounds - we ought to be better on
5010 : updating iteration bounds than updating profile in general and thus
5011 : recomputing iteration bounds later in the compilation process will just
5012 : introduce random roundoff errors. */
5013 6827701 : if (!loop->any_estimate
5014 4672583 : && expected_loop_iterations_by_profile (loop, &nit, &reliable)
5015 10579625 : && reliable)
5016 : {
5017 19 : bound = nit.to_nearest_int ();
5018 19 : record_niter_bound (loop, bound, true, false);
5019 : }
5020 :
5021 : /* Ensure that loop->nb_iterations is computed if possible. If it turns out
5022 : to be constant, we avoid undefined behavior implied bounds and instead
5023 : diagnose those loops with -Waggressive-loop-optimizations. */
5024 6827701 : number_of_latch_executions (loop);
5025 :
5026 6827701 : basic_block *body = get_loop_body (loop);
5027 6827701 : auto_vec<edge> exits = get_loop_exit_edges (loop, body);
5028 6827701 : likely_exit = single_likely_exit (loop, exits);
5029 25890699 : FOR_EACH_VEC_ELT (exits, i, ex)
5030 : {
5031 12235297 : if (ex == likely_exit)
5032 : {
5033 5309099 : gimple *stmt = *gsi_last_bb (ex->src);
5034 5309099 : if (stmt != NULL)
5035 : {
5036 5309099 : gcond *cond = dyn_cast<gcond *> (stmt);
5037 5309099 : tree niter_bound
5038 5309099 : = get_upper_bound_based_on_builtin_expr_with_prob (cond);
5039 5309099 : if (niter_bound != NULL_TREE)
5040 : {
5041 6 : widest_int max = derive_constant_upper_bound (niter_bound);
5042 6 : record_estimate (loop, niter_bound, max, cond,
5043 : true, true, false);
5044 6 : }
5045 : }
5046 : }
5047 :
5048 12235297 : if (!number_of_iterations_exit (loop, ex, &niter_desc,
5049 : false, false, body))
5050 7264549 : continue;
5051 :
5052 4970748 : niter = niter_desc.niter;
5053 4970748 : type = TREE_TYPE (niter);
5054 4970748 : if (TREE_CODE (niter_desc.may_be_zero) != INTEGER_CST)
5055 779308 : niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
5056 : build_int_cst (type, 0),
5057 : niter);
5058 4970748 : record_estimate (loop, niter, niter_desc.max,
5059 : last_nondebug_stmt (ex->src),
5060 : true, ex == likely_exit, true);
5061 4970748 : record_control_iv (loop, &niter_desc);
5062 : }
5063 :
5064 6827701 : if (flag_aggressive_loop_optimizations)
5065 6784738 : infer_loop_bounds_from_undefined (loop, body);
5066 6827701 : free (body);
5067 :
5068 6827701 : discover_iteration_bound_by_body_walk (loop);
5069 :
5070 6827701 : maybe_lower_iteration_bound (loop);
5071 :
5072 : /* If we know the exact number of iterations of this loop, try to
5073 : not break code with undefined behavior by not recording smaller
5074 : maximum number of iterations. */
5075 6827701 : if (loop->nb_iterations
5076 6827701 : && TREE_CODE (loop->nb_iterations) == INTEGER_CST
5077 13655402 : && (wi::min_precision (wi::to_widest (loop->nb_iterations), SIGNED)
5078 2074188 : <= bound_wide_int ().get_precision ()))
5079 : {
5080 2074188 : loop->any_upper_bound = true;
5081 2074188 : loop->nb_iterations_upper_bound
5082 2074188 : = bound_wide_int::from (wi::to_widest (loop->nb_iterations), SIGNED);
5083 : }
5084 27072919 : }
5085 :
5086 : /* Sets NIT to the estimated number of executions of the latch of the
5087 : LOOP. If CONSERVATIVE is true, we must be sure that NIT is at least as
5088 : large as the number of iterations. If we have no reliable estimate,
5089 : the function returns false, otherwise returns true. */
5090 :
5091 : bool
5092 9521686 : estimated_loop_iterations (class loop *loop, widest_int *nit)
5093 : {
5094 : /* When SCEV information is available, try to update loop iterations
5095 : estimate. Otherwise just return whatever we recorded earlier. */
5096 9521686 : if (scev_initialized_p ())
5097 9521686 : estimate_numbers_of_iterations (loop);
5098 :
5099 9521686 : return (get_estimated_loop_iterations (loop, nit));
5100 : }
5101 :
5102 : /* Similar to estimated_loop_iterations, but returns the estimate only
5103 : if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
5104 : on the number of iterations of LOOP could not be derived, returns -1. */
5105 :
5106 : HOST_WIDE_INT
5107 9247824 : estimated_loop_iterations_int (class loop *loop)
5108 : {
5109 9247824 : widest_int nit;
5110 9247824 : HOST_WIDE_INT hwi_nit;
5111 :
5112 9247824 : if (!estimated_loop_iterations (loop, &nit))
5113 : return -1;
5114 :
5115 4060819 : if (!wi::fits_shwi_p (nit))
5116 : return -1;
5117 4060798 : hwi_nit = nit.to_shwi ();
5118 :
5119 4060798 : return hwi_nit < 0 ? -1 : hwi_nit;
5120 9247824 : }
5121 :
5122 :
5123 : /* Sets NIT to an upper bound for the maximum number of executions of the
5124 : latch of the LOOP. If we have no reliable estimate, the function returns
5125 : false, otherwise returns true. */
5126 :
5127 : bool
5128 9004621 : max_loop_iterations (class loop *loop, widest_int *nit)
5129 : {
5130 : /* When SCEV information is available, try to update loop iterations
5131 : estimate. Otherwise just return whatever we recorded earlier. */
5132 9004621 : if (scev_initialized_p ())
5133 8996528 : estimate_numbers_of_iterations (loop);
5134 :
5135 9004621 : return get_max_loop_iterations (loop, nit);
5136 : }
5137 :
5138 : /* Similar to max_loop_iterations, but returns the estimate only
5139 : if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
5140 : on the number of iterations of LOOP could not be derived, returns -1. */
5141 :
5142 : HOST_WIDE_INT
5143 2357348 : max_loop_iterations_int (class loop *loop)
5144 : {
5145 2357348 : widest_int nit;
5146 2357348 : HOST_WIDE_INT hwi_nit;
5147 :
5148 2357348 : if (!max_loop_iterations (loop, &nit))
5149 : return -1;
5150 :
5151 1787594 : if (!wi::fits_shwi_p (nit))
5152 : return -1;
5153 1712972 : hwi_nit = nit.to_shwi ();
5154 :
5155 1712972 : return hwi_nit < 0 ? -1 : hwi_nit;
5156 2357348 : }
5157 :
5158 : /* Sets NIT to an likely upper bound for the maximum number of executions of the
5159 : latch of the LOOP. If we have no reliable estimate, the function returns
5160 : false, otherwise returns true. */
5161 :
5162 : bool
5163 379709 : likely_max_loop_iterations (class loop *loop, widest_int *nit)
5164 : {
5165 : /* When SCEV information is available, try to update loop iterations
5166 : estimate. Otherwise just return whatever we recorded earlier. */
5167 379709 : if (scev_initialized_p ())
5168 379709 : estimate_numbers_of_iterations (loop);
5169 :
5170 379709 : return get_likely_max_loop_iterations (loop, nit);
5171 : }
5172 :
5173 : /* Similar to max_loop_iterations, but returns the estimate only
5174 : if it fits to HOST_WIDE_INT. If this is not the case, or the estimate
5175 : on the number of iterations of LOOP could not be derived, returns -1. */
5176 :
5177 : HOST_WIDE_INT
5178 113184 : likely_max_loop_iterations_int (class loop *loop)
5179 : {
5180 113184 : widest_int nit;
5181 113184 : HOST_WIDE_INT hwi_nit;
5182 :
5183 113184 : if (!likely_max_loop_iterations (loop, &nit))
5184 : return -1;
5185 :
5186 92481 : if (!wi::fits_shwi_p (nit))
5187 : return -1;
5188 84634 : hwi_nit = nit.to_shwi ();
5189 :
5190 84634 : return hwi_nit < 0 ? -1 : hwi_nit;
5191 113184 : }
5192 :
5193 : /* Returns an estimate for the number of executions of statements
5194 : in the LOOP. For statements before the loop exit, this exceeds
5195 : the number of execution of the latch by one. */
5196 :
5197 : HOST_WIDE_INT
5198 9067270 : estimated_stmt_executions_int (class loop *loop)
5199 : {
5200 9067270 : HOST_WIDE_INT nit = estimated_loop_iterations_int (loop);
5201 9067270 : HOST_WIDE_INT snit;
5202 :
5203 9067270 : if (nit == -1)
5204 : return -1;
5205 :
5206 3993590 : snit = (HOST_WIDE_INT) ((unsigned HOST_WIDE_INT) nit + 1);
5207 :
5208 : /* If the computation overflows, return -1. */
5209 3993590 : return snit < 0 ? -1 : snit;
5210 : }
5211 :
5212 : /* Sets NIT to the maximum number of executions of the latch of the
5213 : LOOP, plus one. If we have no reliable estimate, the function returns
5214 : false, otherwise returns true. */
5215 :
5216 : bool
5217 154 : max_stmt_executions (class loop *loop, widest_int *nit)
5218 : {
5219 154 : widest_int nit_minus_one;
5220 :
5221 154 : if (!max_loop_iterations (loop, nit))
5222 : return false;
5223 :
5224 154 : nit_minus_one = *nit;
5225 :
5226 154 : *nit += 1;
5227 :
5228 154 : return wi::gtu_p (*nit, nit_minus_one);
5229 154 : }
5230 :
5231 : /* Sets NIT to the estimated maximum number of executions of the latch of the
5232 : LOOP, plus one. If we have no likely estimate, the function returns
5233 : false, otherwise returns true. */
5234 :
5235 : bool
5236 266525 : likely_max_stmt_executions (class loop *loop, widest_int *nit)
5237 : {
5238 266525 : widest_int nit_minus_one;
5239 :
5240 266525 : if (!likely_max_loop_iterations (loop, nit))
5241 : return false;
5242 :
5243 152604 : nit_minus_one = *nit;
5244 :
5245 152604 : *nit += 1;
5246 :
5247 152604 : return wi::gtu_p (*nit, nit_minus_one);
5248 266525 : }
5249 :
5250 : /* Sets NIT to the estimated number of executions of the latch of the
5251 : LOOP, plus one. If we have no reliable estimate, the function returns
5252 : false, otherwise returns true. */
5253 :
5254 : bool
5255 273862 : estimated_stmt_executions (class loop *loop, widest_int *nit)
5256 : {
5257 273862 : widest_int nit_minus_one;
5258 :
5259 273862 : if (!estimated_loop_iterations (loop, nit))
5260 : return false;
5261 :
5262 6046 : nit_minus_one = *nit;
5263 :
5264 6046 : *nit += 1;
5265 :
5266 6046 : return wi::gtu_p (*nit, nit_minus_one);
5267 273862 : }
5268 :
5269 : /* Records estimates on numbers of iterations of loops. */
5270 :
5271 : void
5272 1277172 : estimate_numbers_of_iterations (function *fn)
5273 : {
5274 7699087 : for (auto loop : loops_list (fn, 0))
5275 3867571 : estimate_numbers_of_iterations (loop);
5276 1277172 : }
5277 :
5278 : /* Returns true if statement S1 dominates statement S2. */
5279 :
5280 : bool
5281 2333759 : stmt_dominates_stmt_p (gimple *s1, gimple *s2)
5282 : {
5283 2333759 : basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
5284 :
5285 2333759 : if (!bb1
5286 2333759 : || s1 == s2)
5287 : return true;
5288 :
5289 2324149 : if (bb1 == bb2)
5290 : {
5291 969935 : gimple_stmt_iterator bsi;
5292 :
5293 969935 : if (gimple_code (s2) == GIMPLE_PHI)
5294 : return false;
5295 :
5296 569707 : if (gimple_code (s1) == GIMPLE_PHI)
5297 : return true;
5298 :
5299 20518013 : for (bsi = gsi_start_bb (bb1); gsi_stmt (bsi) != s2; gsi_next (&bsi))
5300 19646306 : if (gsi_stmt (bsi) == s1)
5301 : return true;
5302 :
5303 : return false;
5304 : }
5305 :
5306 1354214 : return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
5307 : }
5308 :
5309 : /* Returns true when we can prove that the number of executions of
5310 : STMT in the loop is at most NITER, according to the bound on
5311 : the number of executions of the statement NITER_BOUND->stmt recorded in
5312 : NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
5313 :
5314 : ??? This code can become quite a CPU hog - we can have many bounds,
5315 : and large basic block forcing stmt_dominates_stmt_p to be queried
5316 : many times on a large basic blocks, so the whole thing is O(n^2)
5317 : for scev_probably_wraps_p invocation (that can be done n times).
5318 :
5319 : It would make more sense (and give better answers) to remember BB
5320 : bounds computed by discover_iteration_bound_by_body_walk. */
5321 :
5322 : static bool
5323 2520746 : n_of_executions_at_most (gimple *stmt,
5324 : class nb_iter_bound *niter_bound,
5325 : tree niter)
5326 : {
5327 2520746 : widest_int bound = widest_int::from (niter_bound->bound, SIGNED);
5328 2520746 : tree nit_type = TREE_TYPE (niter), e;
5329 2520746 : enum tree_code cmp;
5330 :
5331 2520746 : gcc_assert (TYPE_UNSIGNED (nit_type));
5332 :
5333 : /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
5334 : the number of iterations is small. */
5335 2520746 : if (!wi::fits_to_tree_p (bound, nit_type))
5336 : return false;
5337 :
5338 : /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
5339 : times. This means that:
5340 :
5341 : -- if NITER_BOUND->is_exit is true, then everything after
5342 : it at most NITER_BOUND->bound times.
5343 :
5344 : -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
5345 : is executed, then NITER_BOUND->stmt is executed as well in the same
5346 : iteration then STMT is executed at most NITER_BOUND->bound + 1 times.
5347 :
5348 : If we can determine that NITER_BOUND->stmt is always executed
5349 : after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
5350 : We conclude that if both statements belong to the same
5351 : basic block and STMT is before NITER_BOUND->stmt and there are no
5352 : statements with side effects in between. */
5353 :
5354 2333759 : if (niter_bound->is_exit)
5355 : {
5356 821157 : if (stmt == niter_bound->stmt
5357 821157 : || !stmt_dominates_stmt_p (niter_bound->stmt, stmt))
5358 : return false;
5359 : cmp = GE_EXPR;
5360 : }
5361 : else
5362 : {
5363 1512602 : if (!stmt_dominates_stmt_p (niter_bound->stmt, stmt))
5364 : {
5365 658651 : gimple_stmt_iterator bsi;
5366 658651 : if (gimple_bb (stmt) != gimple_bb (niter_bound->stmt)
5367 335947 : || gimple_code (stmt) == GIMPLE_PHI
5368 850800 : || gimple_code (niter_bound->stmt) == GIMPLE_PHI)
5369 472529 : return false;
5370 :
5371 : /* By stmt_dominates_stmt_p we already know that STMT appears
5372 : before NITER_BOUND->STMT. Still need to test that the loop
5373 : cannot be terinated by a side effect in between. */
5374 8420947 : for (bsi = gsi_for_stmt (stmt); gsi_stmt (bsi) != niter_bound->stmt;
5375 8228798 : gsi_next (&bsi))
5376 8229667 : if (gimple_has_side_effects (gsi_stmt (bsi)))
5377 : return false;
5378 191280 : bound += 1;
5379 382560 : if (bound == 0
5380 191280 : || !wi::fits_to_tree_p (bound, nit_type))
5381 : return false;
5382 : }
5383 : cmp = GT_EXPR;
5384 : }
5385 :
5386 1170291 : e = fold_binary (cmp, boolean_type_node,
5387 : niter, wide_int_to_tree (nit_type, bound));
5388 1170291 : return e && integer_nonzerop (e);
5389 2520746 : }
5390 :
5391 : /* Returns true if the arithmetics in TYPE can be assumed not to wrap. */
5392 :
5393 : bool
5394 90572400 : nowrap_type_p (tree type)
5395 : {
5396 12206067 : if ((ANY_INTEGRAL_TYPE_P (type) || POINTER_TYPE_P (type))
5397 102778463 : && TYPE_OVERFLOW_UNDEFINED (type))
5398 57687498 : return true;
5399 :
5400 : return false;
5401 : }
5402 :
5403 : /* Return an upper bound on the number of times the affine IV {BASE, +, STEP}
5404 : of type TYPE can step while staying within TYPE's range. */
5405 :
5406 : tree
5407 3587304 : get_niter_type_bound (tree type, tree base, tree step)
5408 : {
5409 3587304 : tree unsigned_type = unsigned_type_for (type);
5410 3587304 : tree unsigned_base = fold_convert (unsigned_type, base);
5411 3587304 : tree delta, step_abs;
5412 :
5413 3587304 : if (tree_int_cst_sign_bit (step))
5414 : {
5415 513433 : tree extreme = fold_convert (unsigned_type,
5416 : lower_bound_in_type (type, type));
5417 513433 : delta = fold_build2 (MINUS_EXPR, unsigned_type, unsigned_base, extreme);
5418 513433 : step_abs = fold_build1 (NEGATE_EXPR, unsigned_type,
5419 : fold_convert (unsigned_type, step));
5420 : }
5421 : else
5422 : {
5423 3073871 : tree extreme = fold_convert (unsigned_type,
5424 : upper_bound_in_type (type, type));
5425 3073871 : delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, unsigned_base);
5426 3073871 : step_abs = fold_convert (unsigned_type, step);
5427 : }
5428 :
5429 3587304 : return fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
5430 : }
5431 :
5432 : /* Return true if we can prove LOOP is exited before evolution of induction
5433 : variable {BASE, STEP} overflows with respect to its type bound. */
5434 :
5435 : static bool
5436 3555612 : loop_exits_before_overflow (tree base, tree step,
5437 : gimple *at_stmt, class loop *loop)
5438 : {
5439 3555612 : widest_int niter;
5440 3555612 : struct control_iv *civ;
5441 3555612 : class nb_iter_bound *bound;
5442 3555612 : tree e;
5443 3555612 : tree type = TREE_TYPE (step);
5444 3555612 : tree valid_niter;
5445 :
5446 : /* Compute the number of iterations before we reach the bound of the
5447 : type, and verify that the loop is exited before this occurs. */
5448 3555612 : valid_niter = get_niter_type_bound (type, base, step);
5449 :
5450 3555612 : estimate_numbers_of_iterations (loop);
5451 :
5452 3555612 : if (max_loop_iterations (loop, &niter)
5453 3044343 : && wi::fits_to_tree_p (niter, TREE_TYPE (valid_niter))
5454 2819922 : && (e = fold_binary (GT_EXPR, boolean_type_node, valid_niter,
5455 : wide_int_to_tree (TREE_TYPE (valid_niter),
5456 : niter))) != NULL
5457 6284451 : && integer_nonzerop (e))
5458 1213194 : return true;
5459 2342418 : if (at_stmt)
5460 3787889 : for (bound = loop->bounds; bound; bound = bound->next)
5461 : {
5462 2520746 : if (n_of_executions_at_most (at_stmt, bound, valid_niter))
5463 : return true;
5464 : }
5465 :
5466 : /* Try to prove loop is exited before {base, step} overflows with the
5467 : help of analyzed loop control IV. This is done only for IVs with
5468 : constant step because otherwise we don't have the information. */
5469 2330561 : if (TREE_CODE (step) == INTEGER_CST)
5470 : {
5471 3563689 : for (civ = loop->control_ivs; civ; civ = civ->next)
5472 : {
5473 1403159 : enum tree_code code;
5474 1403159 : tree civ_type = TREE_TYPE (civ->step);
5475 :
5476 : /* Have to consider type difference because operand_equal_p ignores
5477 : that for constants. */
5478 1403159 : if (TYPE_UNSIGNED (type) != TYPE_UNSIGNED (civ_type)
5479 1403159 : || element_precision (type) != element_precision (civ_type))
5480 839112 : continue;
5481 :
5482 : /* Only consider control IV with same step. */
5483 564047 : if (!operand_equal_p (step, civ->step, 0))
5484 219289 : continue;
5485 :
5486 : /* Done proving if this is a no-overflow control IV. */
5487 344758 : if (operand_equal_p (base, civ->base, 0))
5488 : return true;
5489 :
5490 : /* Control IV is recorded after expanding simple operations,
5491 : Here we expand base and compare it too. */
5492 249895 : tree expanded_base = expand_simple_operations (base);
5493 249895 : if (operand_equal_p (expanded_base, civ->base, 0))
5494 : return true;
5495 :
5496 : /* If this is a before stepping control IV, in other words, we have
5497 :
5498 : {civ_base, step} = {base + step, step}
5499 :
5500 : Because civ {base + step, step} doesn't overflow during loop
5501 : iterations, {base, step} will not overflow if we can prove the
5502 : operation "base + step" does not overflow. Specifically, we try
5503 : to prove below conditions are satisfied:
5504 :
5505 : base <= UPPER_BOUND (type) - step ;;step > 0
5506 : base >= LOWER_BOUND (type) - step ;;step < 0
5507 :
5508 : by proving the reverse conditions are false using loop's initial
5509 : condition. */
5510 220321 : if (POINTER_TYPE_P (TREE_TYPE (base)))
5511 : code = POINTER_PLUS_EXPR;
5512 : else
5513 : code = PLUS_EXPR;
5514 :
5515 220321 : tree stepped = fold_build2 (code, TREE_TYPE (base), base, step);
5516 220321 : tree expanded_stepped = fold_build2 (code, TREE_TYPE (base),
5517 : expanded_base, step);
5518 220321 : if (operand_equal_p (stepped, civ->base, 0)
5519 220321 : || operand_equal_p (expanded_stepped, civ->base, 0))
5520 : {
5521 66364 : tree extreme;
5522 :
5523 66364 : if (tree_int_cst_sign_bit (step))
5524 : {
5525 23060 : code = LT_EXPR;
5526 23060 : extreme = lower_bound_in_type (type, type);
5527 : }
5528 : else
5529 : {
5530 43304 : code = GT_EXPR;
5531 43304 : extreme = upper_bound_in_type (type, type);
5532 : }
5533 66364 : extreme = fold_build2 (MINUS_EXPR, type, extreme, step);
5534 66364 : e = fold_build2 (code, boolean_type_node, base, extreme);
5535 66364 : e = simplify_using_initial_conditions (loop, e);
5536 66364 : if (integer_zerop (e))
5537 : return true;
5538 : }
5539 : }
5540 : }
5541 :
5542 : return false;
5543 3555612 : }
5544 :
5545 : /* VAR is scev variable whose evolution part is constant STEP, this function
5546 : proves that VAR can't overflow by using value range info. If VAR's value
5547 : range is [MIN, MAX], it can be proven by:
5548 : MAX + step doesn't overflow ; if step > 0
5549 : or
5550 : MIN + step doesn't underflow ; if step < 0.
5551 :
5552 : We can only do this if var is computed in every loop iteration, i.e, var's
5553 : definition has to dominate loop latch. Consider below example:
5554 :
5555 : {
5556 : unsigned int i;
5557 :
5558 : <bb 3>:
5559 :
5560 : <bb 4>:
5561 : # RANGE [0, 4294967294] NONZERO 65535
5562 : # i_21 = PHI <0(3), i_18(9)>
5563 : if (i_21 != 0)
5564 : goto <bb 6>;
5565 : else
5566 : goto <bb 8>;
5567 :
5568 : <bb 6>:
5569 : # RANGE [0, 65533] NONZERO 65535
5570 : _6 = i_21 + 4294967295;
5571 : # RANGE [0, 65533] NONZERO 65535
5572 : _7 = (long unsigned int) _6;
5573 : # RANGE [0, 524264] NONZERO 524280
5574 : _8 = _7 * 8;
5575 : # PT = nonlocal escaped
5576 : _9 = a_14 + _8;
5577 : *_9 = 0;
5578 :
5579 : <bb 8>:
5580 : # RANGE [1, 65535] NONZERO 65535
5581 : i_18 = i_21 + 1;
5582 : if (i_18 >= 65535)
5583 : goto <bb 10>;
5584 : else
5585 : goto <bb 9>;
5586 :
5587 : <bb 9>:
5588 : goto <bb 4>;
5589 :
5590 : <bb 10>:
5591 : return;
5592 : }
5593 :
5594 : VAR _6 doesn't overflow only with pre-condition (i_21 != 0), here we
5595 : can't use _6 to prove no-overflow for _7. In fact, var _7 takes value
5596 : sequence (4294967295, 0, 1, ..., 65533) in loop life time, rather than
5597 : (4294967295, 4294967296, ...). */
5598 :
5599 : static bool
5600 350151 : scev_var_range_cant_overflow (tree var, tree step, class loop *loop)
5601 : {
5602 350151 : tree type;
5603 350151 : wide_int minv, maxv, diff, step_wi;
5604 :
5605 350151 : if (TREE_CODE (step) != INTEGER_CST || !INTEGRAL_TYPE_P (TREE_TYPE (var)))
5606 : return false;
5607 :
5608 : /* Check if VAR evaluates in every loop iteration. It's not the case
5609 : if VAR is default definition or does not dominate loop's latch. */
5610 350151 : basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
5611 350151 : if (!def_bb || !dominated_by_p (CDI_DOMINATORS, loop->latch, def_bb))
5612 : return false;
5613 :
5614 347564 : int_range_max r (TREE_TYPE (var));
5615 695128 : get_range_query (cfun)->range_of_expr (r, var);
5616 347564 : if (r.varying_p () || r.undefined_p ())
5617 : return false;
5618 :
5619 : /* VAR is a scev whose evolution part is STEP and value range info
5620 : is [MIN, MAX], we can prove its no-overflowness by conditions:
5621 :
5622 : type_MAX - MAX >= step ; if step > 0
5623 : MIN - type_MIN >= |step| ; if step < 0.
5624 :
5625 : Or VAR must take value outside of value range, which is not true. */
5626 142412 : step_wi = wi::to_wide (step);
5627 142412 : type = TREE_TYPE (var);
5628 142412 : if (tree_int_cst_sign_bit (step))
5629 : {
5630 8884 : diff = r.lower_bound () - wi::to_wide (lower_bound_in_type (type, type));
5631 8884 : step_wi = - step_wi;
5632 : }
5633 : else
5634 133528 : diff = wi::to_wide (upper_bound_in_type (type, type)) - r.upper_bound ();
5635 :
5636 142412 : return (wi::geu_p (diff, step_wi));
5637 697715 : }
5638 :
5639 : /* Return false only when the induction variable BASE + STEP * I is
5640 : known to not overflow: i.e. when the number of iterations is small
5641 : enough with respect to the step and initial condition in order to
5642 : keep the evolution confined in TYPEs bounds. Return true when the
5643 : iv is known to overflow or when the property is not computable.
5644 :
5645 : USE_OVERFLOW_SEMANTICS is true if this function should assume that
5646 : the rules for overflow of the given language apply (e.g., that signed
5647 : arithmetics in C does not overflow).
5648 :
5649 : If VAR is a ssa variable, this function also returns false if VAR can
5650 : be proven not overflow with value range info.
5651 :
5652 : If NOWRAP_BOUND is nonzero and we can't prove it differently, get
5653 : STEP's type bound, build a bound MIN (NOWRAP_BOUND, STEP_TYPE_BOUND)
5654 : and store it in NOWRAP_BOUND. */
5655 :
5656 : bool
5657 8286598 : scev_probably_wraps_p (tree var, tree base, tree step,
5658 : gimple *at_stmt, class loop *loop,
5659 : bool use_overflow_semantics, tree *nowrap_bound)
5660 : {
5661 : /* FIXME: We really need something like
5662 : http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
5663 :
5664 : We used to test for the following situation that frequently appears
5665 : during address arithmetics:
5666 :
5667 : D.1621_13 = (long unsigned intD.4) D.1620_12;
5668 : D.1622_14 = D.1621_13 * 8;
5669 : D.1623_15 = (doubleD.29 *) D.1622_14;
5670 :
5671 : And derived that the sequence corresponding to D_14
5672 : can be proved to not wrap because it is used for computing a
5673 : memory access; however, this is not really the case -- for example,
5674 : if D_12 = (unsigned char) [254,+,1], then D_14 has values
5675 : 2032, 2040, 0, 8, ..., but the code is still legal. */
5676 :
5677 8286598 : if (chrec_contains_undetermined (base)
5678 8286598 : || chrec_contains_undetermined (step))
5679 : return true;
5680 :
5681 8286598 : if (integer_zerop (step))
5682 : return false;
5683 :
5684 : /* If we can use the fact that signed and pointer arithmetics does not
5685 : wrap, we are done. */
5686 8286598 : if (use_overflow_semantics && nowrap_type_p (TREE_TYPE (base)))
5687 : return false;
5688 :
5689 : /* To be able to use estimates on number of iterations of the loop,
5690 : we must have an upper bound on the absolute value of the step. */
5691 4354279 : if (TREE_CODE (step) != INTEGER_CST)
5692 : return true;
5693 :
5694 : /* Check if var can be proven not overflow with value range info. */
5695 364511 : if (var && TREE_CODE (var) == SSA_NAME
5696 4032004 : && scev_var_range_cant_overflow (var, step, loop))
5697 : return false;
5698 :
5699 3555612 : if (loop_exits_before_overflow (base, step, at_stmt, loop))
5700 : return false;
5701 :
5702 : /* Check the nonwrapping flag, which may be set by niter analysis (e.g., the
5703 : above loop exits before overflow). */
5704 2160530 : if (var && nonwrapping_chrec_p (analyze_scalar_evolution (loop, var)))
5705 : return false;
5706 :
5707 : /* If we can use a bound to guarantee no wrapping, save it. */
5708 2156817 : if (nowrap_bound)
5709 : {
5710 1202 : tree b = get_niter_type_bound (TREE_TYPE (step), base, step);
5711 1202 : scev_combine_nowrap_bounds (nowrap_bound, b);
5712 1202 : return false;
5713 : }
5714 :
5715 : /* At this point we still don't have a proof that the iv does not
5716 : overflow: give up. */
5717 : return true;
5718 : }
5719 :
5720 : /* Frees the information on upper bounds on numbers of iterations of LOOP. */
5721 :
5722 : void
5723 63699652 : free_numbers_of_iterations_estimates (class loop *loop)
5724 : {
5725 63699652 : struct control_iv *civ;
5726 63699652 : class nb_iter_bound *bound;
5727 :
5728 63699652 : loop->nb_iterations = NULL;
5729 63699652 : loop->estimate_state = EST_NOT_COMPUTED;
5730 74291815 : for (bound = loop->bounds; bound;)
5731 : {
5732 10592163 : class nb_iter_bound *next = bound->next;
5733 10592163 : ggc_free (bound);
5734 10592163 : bound = next;
5735 : }
5736 63699652 : loop->bounds = NULL;
5737 :
5738 68350143 : for (civ = loop->control_ivs; civ;)
5739 : {
5740 4650491 : struct control_iv *next = civ->next;
5741 4650491 : ggc_free (civ);
5742 4650491 : civ = next;
5743 : }
5744 63699652 : loop->control_ivs = NULL;
5745 63699652 : }
5746 :
5747 : /* Frees the information on upper bounds on numbers of iterations of loops. */
5748 :
5749 : void
5750 80933366 : free_numbers_of_iterations_estimates (function *fn)
5751 : {
5752 305865672 : for (auto loop : loops_list (fn, 0))
5753 63065574 : free_numbers_of_iterations_estimates (loop);
5754 80933366 : }
5755 :
5756 : /* Substitute value VAL for ssa name NAME inside expressions held
5757 : at LOOP. */
5758 :
5759 : void
5760 127988854 : substitute_in_loop_info (class loop *loop, tree name, tree val)
5761 : {
5762 127988854 : loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);
5763 127988854 : }
|