a6779585b790a84f261d268f64dae79e3851d56d
[dragonfly.git] / contrib / gcc-5.0 / gcc / tree-ssa-loop-niter.c
1 /* Functions to determine/estimate number of iterations of a loop.
2    Copyright (C) 2004-2015 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 "tm.h"
24 #include "hash-set.h"
25 #include "machmode.h"
26 #include "vec.h"
27 #include "double-int.h"
28 #include "input.h"
29 #include "alias.h"
30 #include "symtab.h"
31 #include "wide-int.h"
32 #include "inchash.h"
33 #include "tree.h"
34 #include "fold-const.h"
35 #include "calls.h"
36 #include "hashtab.h"
37 #include "hard-reg-set.h"
38 #include "function.h"
39 #include "rtl.h"
40 #include "flags.h"
41 #include "statistics.h"
42 #include "real.h"
43 #include "fixed-value.h"
44 #include "insn-config.h"
45 #include "expmed.h"
46 #include "dojump.h"
47 #include "explow.h"
48 #include "emit-rtl.h"
49 #include "varasm.h"
50 #include "stmt.h"
51 #include "expr.h"
52 #include "tm_p.h"
53 #include "predict.h"
54 #include "dominance.h"
55 #include "cfg.h"
56 #include "basic-block.h"
57 #include "gimple-pretty-print.h"
58 #include "intl.h"
59 #include "tree-ssa-alias.h"
60 #include "internal-fn.h"
61 #include "gimple-expr.h"
62 #include "is-a.h"
63 #include "gimple.h"
64 #include "gimplify.h"
65 #include "gimple-iterator.h"
66 #include "gimple-ssa.h"
67 #include "tree-cfg.h"
68 #include "tree-phinodes.h"
69 #include "ssa-iterators.h"
70 #include "tree-ssa-loop-ivopts.h"
71 #include "tree-ssa-loop-niter.h"
72 #include "tree-ssa-loop.h"
73 #include "dumpfile.h"
74 #include "cfgloop.h"
75 #include "tree-chrec.h"
76 #include "tree-scalar-evolution.h"
77 #include "tree-data-ref.h"
78 #include "params.h"
79 #include "diagnostic-core.h"
80 #include "tree-inline.h"
81 #include "tree-pass.h"
82 #include "stringpool.h"
83 #include "tree-ssanames.h"
84 #include "wide-int-print.h"
85
86
87 #define SWAP(X, Y) do { affine_iv *tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
88
89 /* The maximum number of dominator BBs we search for conditions
90    of loop header copies we use for simplifying a conditional
91    expression.  */
92 #define MAX_DOMINATORS_TO_WALK 8
93
94 /*
95
96    Analysis of number of iterations of an affine exit test.
97
98 */
99
100 /* Bounds on some value, BELOW <= X <= UP.  */
101
102 typedef struct
103 {
104   mpz_t below, up;
105 } bounds;
106
107
108 /* Splits expression EXPR to a variable part VAR and constant OFFSET.  */
109
110 static void
111 split_to_var_and_offset (tree expr, tree *var, mpz_t offset)
112 {
113   tree type = TREE_TYPE (expr);
114   tree op0, op1;
115   bool negate = false;
116
117   *var = expr;
118   mpz_set_ui (offset, 0);
119
120   switch (TREE_CODE (expr))
121     {
122     case MINUS_EXPR:
123       negate = true;
124       /* Fallthru.  */
125
126     case PLUS_EXPR:
127     case POINTER_PLUS_EXPR:
128       op0 = TREE_OPERAND (expr, 0);
129       op1 = TREE_OPERAND (expr, 1);
130
131       if (TREE_CODE (op1) != INTEGER_CST)
132         break;
133
134       *var = op0;
135       /* Always sign extend the offset.  */
136       wi::to_mpz (op1, offset, SIGNED);
137       if (negate)
138         mpz_neg (offset, offset);
139       break;
140
141     case INTEGER_CST:
142       *var = build_int_cst_type (type, 0);
143       wi::to_mpz (expr, offset, TYPE_SIGN (type));
144       break;
145
146     default:
147       break;
148     }
149 }
150
151 /* Stores estimate on the minimum/maximum value of the expression VAR + OFF
152    in TYPE to MIN and MAX.  */
153
154 static void
155 determine_value_range (struct loop *loop, tree type, tree var, mpz_t off,
156                        mpz_t min, mpz_t max)
157 {
158   wide_int minv, maxv;
159   enum value_range_type rtype = VR_VARYING;
160
161   /* If the expression is a constant, we know its value exactly.  */
162   if (integer_zerop (var))
163     {
164       mpz_set (min, off);
165       mpz_set (max, off);
166       return;
167     }
168
169   get_type_static_bounds (type, min, max);
170
171   /* See if we have some range info from VRP.  */
172   if (TREE_CODE (var) == SSA_NAME && INTEGRAL_TYPE_P (type))
173     {
174       edge e = loop_preheader_edge (loop);
175       signop sgn = TYPE_SIGN (type);
176       gphi_iterator gsi;
177
178       /* Either for VAR itself...  */
179       rtype = get_range_info (var, &minv, &maxv);
180       /* Or for PHI results in loop->header where VAR is used as
181          PHI argument from the loop preheader edge.  */
182       for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
183         {
184           gphi *phi = gsi.phi ();
185           wide_int minc, maxc;
186           if (PHI_ARG_DEF_FROM_EDGE (phi, e) == var
187               && (get_range_info (gimple_phi_result (phi), &minc, &maxc)
188                   == VR_RANGE))
189             {
190               if (rtype != VR_RANGE)
191                 {
192                   rtype = VR_RANGE;
193                   minv = minc;
194                   maxv = maxc;
195                 }
196               else
197                 {
198                   minv = wi::max (minv, minc, sgn);
199                   maxv = wi::min (maxv, maxc, sgn);
200                   /* If the PHI result range are inconsistent with
201                      the VAR range, give up on looking at the PHI
202                      results.  This can happen if VR_UNDEFINED is
203                      involved.  */
204                   if (wi::gt_p (minv, maxv, sgn))
205                     {
206                       rtype = get_range_info (var, &minv, &maxv);
207                       break;
208                     }
209                 }
210             }
211         }
212       if (rtype == VR_RANGE)
213         {
214           mpz_t minm, maxm;
215           gcc_assert (wi::le_p (minv, maxv, sgn));
216           mpz_init (minm);
217           mpz_init (maxm);
218           wi::to_mpz (minv, minm, sgn);
219           wi::to_mpz (maxv, maxm, sgn);
220           mpz_add (minm, minm, off);
221           mpz_add (maxm, maxm, off);
222           /* If the computation may not wrap or off is zero, then this
223              is always fine.  If off is negative and minv + off isn't
224              smaller than type's minimum, or off is positive and
225              maxv + off isn't bigger than type's maximum, use the more
226              precise range too.  */
227           if (nowrap_type_p (type)
228               || mpz_sgn (off) == 0
229               || (mpz_sgn (off) < 0 && mpz_cmp (minm, min) >= 0)
230               || (mpz_sgn (off) > 0 && mpz_cmp (maxm, max) <= 0))
231             {
232               mpz_set (min, minm);
233               mpz_set (max, maxm);
234               mpz_clear (minm);
235               mpz_clear (maxm);
236               return;
237             }
238           mpz_clear (minm);
239           mpz_clear (maxm);
240         }
241     }
242
243   /* If the computation may wrap, we know nothing about the value, except for
244      the range of the type.  */
245   if (!nowrap_type_p (type))
246     return;
247
248   /* Since the addition of OFF does not wrap, if OFF is positive, then we may
249      add it to MIN, otherwise to MAX.  */
250   if (mpz_sgn (off) < 0)
251     mpz_add (max, max, off);
252   else
253     mpz_add (min, min, off);
254 }
255
256 /* Stores the bounds on the difference of the values of the expressions
257    (var + X) and (var + Y), computed in TYPE, to BNDS.  */
258
259 static void
260 bound_difference_of_offsetted_base (tree type, mpz_t x, mpz_t y,
261                                     bounds *bnds)
262 {
263   int rel = mpz_cmp (x, y);
264   bool may_wrap = !nowrap_type_p (type);
265   mpz_t m;
266
267   /* If X == Y, then the expressions are always equal.
268      If X > Y, there are the following possibilities:
269        a) neither of var + X and var + Y overflow or underflow, or both of
270           them do.  Then their difference is X - Y.
271        b) var + X overflows, and var + Y does not.  Then the values of the
272           expressions are var + X - M and var + Y, where M is the range of
273           the type, and their difference is X - Y - M.
274        c) var + Y underflows and var + X does not.  Their difference again
275           is M - X + Y.
276        Therefore, if the arithmetics in type does not overflow, then the
277        bounds are (X - Y, X - Y), otherwise they are (X - Y - M, X - Y)
278      Similarly, if X < Y, the bounds are either (X - Y, X - Y) or
279      (X - Y, X - Y + M).  */
280
281   if (rel == 0)
282     {
283       mpz_set_ui (bnds->below, 0);
284       mpz_set_ui (bnds->up, 0);
285       return;
286     }
287
288   mpz_init (m);
289   wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), m, UNSIGNED);
290   mpz_add_ui (m, m, 1);
291   mpz_sub (bnds->up, x, y);
292   mpz_set (bnds->below, bnds->up);
293
294   if (may_wrap)
295     {
296       if (rel > 0)
297         mpz_sub (bnds->below, bnds->below, m);
298       else
299         mpz_add (bnds->up, bnds->up, m);
300     }
301
302   mpz_clear (m);
303 }
304
305 /* From condition C0 CMP C1 derives information regarding the
306    difference of values of VARX + OFFX and VARY + OFFY, computed in TYPE,
307    and stores it to BNDS.  */
308
309 static void
310 refine_bounds_using_guard (tree type, tree varx, mpz_t offx,
311                            tree vary, mpz_t offy,
312                            tree c0, enum tree_code cmp, tree c1,
313                            bounds *bnds)
314 {
315   tree varc0, varc1, tmp, ctype;
316   mpz_t offc0, offc1, loffx, loffy, bnd;
317   bool lbound = false;
318   bool no_wrap = nowrap_type_p (type);
319   bool x_ok, y_ok;
320
321   switch (cmp)
322     {
323     case LT_EXPR:
324     case LE_EXPR:
325     case GT_EXPR:
326     case GE_EXPR:
327       STRIP_SIGN_NOPS (c0);
328       STRIP_SIGN_NOPS (c1);
329       ctype = TREE_TYPE (c0);
330       if (!useless_type_conversion_p (ctype, type))
331         return;
332
333       break;
334
335     case EQ_EXPR:
336       /* We could derive quite precise information from EQ_EXPR, however, such
337          a guard is unlikely to appear, so we do not bother with handling
338          it.  */
339       return;
340
341     case NE_EXPR:
342       /* NE_EXPR comparisons do not contain much of useful information, except for
343          special case of comparing with the bounds of the type.  */
344       if (TREE_CODE (c1) != INTEGER_CST
345           || !INTEGRAL_TYPE_P (type))
346         return;
347
348       /* Ensure that the condition speaks about an expression in the same type
349          as X and Y.  */
350       ctype = TREE_TYPE (c0);
351       if (TYPE_PRECISION (ctype) != TYPE_PRECISION (type))
352         return;
353       c0 = fold_convert (type, c0);
354       c1 = fold_convert (type, c1);
355
356       if (TYPE_MIN_VALUE (type)
357           && operand_equal_p (c1, TYPE_MIN_VALUE (type), 0))
358         {
359           cmp = GT_EXPR;
360           break;
361         }
362       if (TYPE_MAX_VALUE (type)
363           && operand_equal_p (c1, TYPE_MAX_VALUE (type), 0))
364         {
365           cmp = LT_EXPR;
366           break;
367         }
368
369       return;
370     default:
371       return;
372     }
373
374   mpz_init (offc0);
375   mpz_init (offc1);
376   split_to_var_and_offset (expand_simple_operations (c0), &varc0, offc0);
377   split_to_var_and_offset (expand_simple_operations (c1), &varc1, offc1);
378
379   /* We are only interested in comparisons of expressions based on VARX and
380      VARY.  TODO -- we might also be able to derive some bounds from
381      expressions containing just one of the variables.  */
382
383   if (operand_equal_p (varx, varc1, 0))
384     {
385       tmp = varc0; varc0 = varc1; varc1 = tmp;
386       mpz_swap (offc0, offc1);
387       cmp = swap_tree_comparison (cmp);
388     }
389
390   if (!operand_equal_p (varx, varc0, 0)
391       || !operand_equal_p (vary, varc1, 0))
392     goto end;
393
394   mpz_init_set (loffx, offx);
395   mpz_init_set (loffy, offy);
396
397   if (cmp == GT_EXPR || cmp == GE_EXPR)
398     {
399       tmp = varx; varx = vary; vary = tmp;
400       mpz_swap (offc0, offc1);
401       mpz_swap (loffx, loffy);
402       cmp = swap_tree_comparison (cmp);
403       lbound = true;
404     }
405
406   /* If there is no overflow, the condition implies that
407
408      (VARX + OFFX) cmp (VARY + OFFY) + (OFFX - OFFY + OFFC1 - OFFC0).
409
410      The overflows and underflows may complicate things a bit; each
411      overflow decreases the appropriate offset by M, and underflow
412      increases it by M.  The above inequality would not necessarily be
413      true if
414
415      -- VARX + OFFX underflows and VARX + OFFC0 does not, or
416         VARX + OFFC0 overflows, but VARX + OFFX does not.
417         This may only happen if OFFX < OFFC0.
418      -- VARY + OFFY overflows and VARY + OFFC1 does not, or
419         VARY + OFFC1 underflows and VARY + OFFY does not.
420         This may only happen if OFFY > OFFC1.  */
421
422   if (no_wrap)
423     {
424       x_ok = true;
425       y_ok = true;
426     }
427   else
428     {
429       x_ok = (integer_zerop (varx)
430               || mpz_cmp (loffx, offc0) >= 0);
431       y_ok = (integer_zerop (vary)
432               || mpz_cmp (loffy, offc1) <= 0);
433     }
434
435   if (x_ok && y_ok)
436     {
437       mpz_init (bnd);
438       mpz_sub (bnd, loffx, loffy);
439       mpz_add (bnd, bnd, offc1);
440       mpz_sub (bnd, bnd, offc0);
441
442       if (cmp == LT_EXPR)
443         mpz_sub_ui (bnd, bnd, 1);
444
445       if (lbound)
446         {
447           mpz_neg (bnd, bnd);
448           if (mpz_cmp (bnds->below, bnd) < 0)
449             mpz_set (bnds->below, bnd);
450         }
451       else
452         {
453           if (mpz_cmp (bnd, bnds->up) < 0)
454             mpz_set (bnds->up, bnd);
455         }
456       mpz_clear (bnd);
457     }
458
459   mpz_clear (loffx);
460   mpz_clear (loffy);
461 end:
462   mpz_clear (offc0);
463   mpz_clear (offc1);
464 }
465
466 /* Stores the bounds on the value of the expression X - Y in LOOP to BNDS.
467    The subtraction is considered to be performed in arbitrary precision,
468    without overflows.
469
470    We do not attempt to be too clever regarding the value ranges of X and
471    Y; most of the time, they are just integers or ssa names offsetted by
472    integer.  However, we try to use the information contained in the
473    comparisons before the loop (usually created by loop header copying).  */
474
475 static void
476 bound_difference (struct loop *loop, tree x, tree y, bounds *bnds)
477 {
478   tree type = TREE_TYPE (x);
479   tree varx, vary;
480   mpz_t offx, offy;
481   mpz_t minx, maxx, miny, maxy;
482   int cnt = 0;
483   edge e;
484   basic_block bb;
485   tree c0, c1;
486   gimple cond;
487   enum tree_code cmp;
488
489   /* Get rid of unnecessary casts, but preserve the value of
490      the expressions.  */
491   STRIP_SIGN_NOPS (x);
492   STRIP_SIGN_NOPS (y);
493
494   mpz_init (bnds->below);
495   mpz_init (bnds->up);
496   mpz_init (offx);
497   mpz_init (offy);
498   split_to_var_and_offset (x, &varx, offx);
499   split_to_var_and_offset (y, &vary, offy);
500
501   if (!integer_zerop (varx)
502       && operand_equal_p (varx, vary, 0))
503     {
504       /* Special case VARX == VARY -- we just need to compare the
505          offsets.  The matters are a bit more complicated in the
506          case addition of offsets may wrap.  */
507       bound_difference_of_offsetted_base (type, offx, offy, bnds);
508     }
509   else
510     {
511       /* Otherwise, use the value ranges to determine the initial
512          estimates on below and up.  */
513       mpz_init (minx);
514       mpz_init (maxx);
515       mpz_init (miny);
516       mpz_init (maxy);
517       determine_value_range (loop, type, varx, offx, minx, maxx);
518       determine_value_range (loop, type, vary, offy, miny, maxy);
519
520       mpz_sub (bnds->below, minx, maxy);
521       mpz_sub (bnds->up, maxx, miny);
522       mpz_clear (minx);
523       mpz_clear (maxx);
524       mpz_clear (miny);
525       mpz_clear (maxy);
526     }
527
528   /* If both X and Y are constants, we cannot get any more precise.  */
529   if (integer_zerop (varx) && integer_zerop (vary))
530     goto end;
531
532   /* Now walk the dominators of the loop header and use the entry
533      guards to refine the estimates.  */
534   for (bb = loop->header;
535        bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
536        bb = get_immediate_dominator (CDI_DOMINATORS, bb))
537     {
538       if (!single_pred_p (bb))
539         continue;
540       e = single_pred_edge (bb);
541
542       if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
543         continue;
544
545       cond = last_stmt (e->src);
546       c0 = gimple_cond_lhs (cond);
547       cmp = gimple_cond_code (cond);
548       c1 = gimple_cond_rhs (cond);
549
550       if (e->flags & EDGE_FALSE_VALUE)
551         cmp = invert_tree_comparison (cmp, false);
552
553       refine_bounds_using_guard (type, varx, offx, vary, offy,
554                                  c0, cmp, c1, bnds);
555       ++cnt;
556     }
557
558 end:
559   mpz_clear (offx);
560   mpz_clear (offy);
561 }
562
563 /* Update the bounds in BNDS that restrict the value of X to the bounds
564    that restrict the value of X + DELTA.  X can be obtained as a
565    difference of two values in TYPE.  */
566
567 static void
568 bounds_add (bounds *bnds, const widest_int &delta, tree type)
569 {
570   mpz_t mdelta, max;
571
572   mpz_init (mdelta);
573   wi::to_mpz (delta, mdelta, SIGNED);
574
575   mpz_init (max);
576   wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
577
578   mpz_add (bnds->up, bnds->up, mdelta);
579   mpz_add (bnds->below, bnds->below, mdelta);
580
581   if (mpz_cmp (bnds->up, max) > 0)
582     mpz_set (bnds->up, max);
583
584   mpz_neg (max, max);
585   if (mpz_cmp (bnds->below, max) < 0)
586     mpz_set (bnds->below, max);
587
588   mpz_clear (mdelta);
589   mpz_clear (max);
590 }
591
592 /* Update the bounds in BNDS that restrict the value of X to the bounds
593    that restrict the value of -X.  */
594
595 static void
596 bounds_negate (bounds *bnds)
597 {
598   mpz_t tmp;
599
600   mpz_init_set (tmp, bnds->up);
601   mpz_neg (bnds->up, bnds->below);
602   mpz_neg (bnds->below, tmp);
603   mpz_clear (tmp);
604 }
605
606 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1.  */
607
608 static tree
609 inverse (tree x, tree mask)
610 {
611   tree type = TREE_TYPE (x);
612   tree rslt;
613   unsigned ctr = tree_floor_log2 (mask);
614
615   if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
616     {
617       unsigned HOST_WIDE_INT ix;
618       unsigned HOST_WIDE_INT imask;
619       unsigned HOST_WIDE_INT irslt = 1;
620
621       gcc_assert (cst_and_fits_in_hwi (x));
622       gcc_assert (cst_and_fits_in_hwi (mask));
623
624       ix = int_cst_value (x);
625       imask = int_cst_value (mask);
626
627       for (; ctr; ctr--)
628         {
629           irslt *= ix;
630           ix *= ix;
631         }
632       irslt &= imask;
633
634       rslt = build_int_cst_type (type, irslt);
635     }
636   else
637     {
638       rslt = build_int_cst (type, 1);
639       for (; ctr; ctr--)
640         {
641           rslt = int_const_binop (MULT_EXPR, rslt, x);
642           x = int_const_binop (MULT_EXPR, x, x);
643         }
644       rslt = int_const_binop (BIT_AND_EXPR, rslt, mask);
645     }
646
647   return rslt;
648 }
649
650 /* Derives the upper bound BND on the number of executions of loop with exit
651    condition S * i <> C.  If NO_OVERFLOW is true, then the control variable of
652    the loop does not overflow.  EXIT_MUST_BE_TAKEN is true if we are guaranteed
653    that the loop ends through this exit, i.e., the induction variable ever
654    reaches the value of C.  
655    
656    The value C is equal to final - base, where final and base are the final and
657    initial value of the actual induction variable in the analysed loop.  BNDS
658    bounds the value of this difference when computed in signed type with
659    unbounded range, while the computation of C is performed in an unsigned
660    type with the range matching the range of the type of the induction variable.
661    In particular, BNDS.up contains an upper bound on C in the following cases:
662    -- if the iv must reach its final value without overflow, i.e., if
663       NO_OVERFLOW && EXIT_MUST_BE_TAKEN is true, or
664    -- if final >= base, which we know to hold when BNDS.below >= 0.  */
665
666 static void
667 number_of_iterations_ne_max (mpz_t bnd, bool no_overflow, tree c, tree s,
668                              bounds *bnds, bool exit_must_be_taken)
669 {
670   widest_int max;
671   mpz_t d;
672   tree type = TREE_TYPE (c);
673   bool bnds_u_valid = ((no_overflow && exit_must_be_taken)
674                        || mpz_sgn (bnds->below) >= 0);
675
676   if (integer_onep (s)
677       || (TREE_CODE (c) == INTEGER_CST
678           && TREE_CODE (s) == INTEGER_CST
679           && wi::mod_trunc (c, s, TYPE_SIGN (type)) == 0)
680       || (TYPE_OVERFLOW_UNDEFINED (type)
681           && multiple_of_p (type, c, s)))
682     {
683       /* If C is an exact multiple of S, then its value will be reached before
684          the induction variable overflows (unless the loop is exited in some
685          other way before).  Note that the actual induction variable in the
686          loop (which ranges from base to final instead of from 0 to C) may
687          overflow, in which case BNDS.up will not be giving a correct upper
688          bound on C; thus, BNDS_U_VALID had to be computed in advance.  */
689       no_overflow = true;
690       exit_must_be_taken = true;
691     }
692
693   /* If the induction variable can overflow, the number of iterations is at
694      most the period of the control variable (or infinite, but in that case
695      the whole # of iterations analysis will fail).  */
696   if (!no_overflow)
697     {
698       max = wi::mask <widest_int> (TYPE_PRECISION (type) - wi::ctz (s), false);
699       wi::to_mpz (max, bnd, UNSIGNED);
700       return;
701     }
702
703   /* Now we know that the induction variable does not overflow, so the loop
704      iterates at most (range of type / S) times.  */
705   wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), bnd, UNSIGNED);
706
707   /* If the induction variable is guaranteed to reach the value of C before
708      overflow, ... */
709   if (exit_must_be_taken)
710     {
711       /* ... then we can strengthen this to C / S, and possibly we can use
712          the upper bound on C given by BNDS.  */
713       if (TREE_CODE (c) == INTEGER_CST)
714         wi::to_mpz (c, bnd, UNSIGNED);
715       else if (bnds_u_valid)
716         mpz_set (bnd, bnds->up);
717     }
718
719   mpz_init (d);
720   wi::to_mpz (s, d, UNSIGNED);
721   mpz_fdiv_q (bnd, bnd, d);
722   mpz_clear (d);
723 }
724
725 /* Determines number of iterations of loop whose ending condition
726    is IV <> FINAL.  TYPE is the type of the iv.  The number of
727    iterations is stored to NITER.  EXIT_MUST_BE_TAKEN is true if
728    we know that the exit must be taken eventually, i.e., that the IV
729    ever reaches the value FINAL (we derived this earlier, and possibly set
730    NITER->assumptions to make sure this is the case).  BNDS contains the
731    bounds on the difference FINAL - IV->base.  */
732
733 static bool
734 number_of_iterations_ne (tree type, affine_iv *iv, tree final,
735                          struct tree_niter_desc *niter, bool exit_must_be_taken,
736                          bounds *bnds)
737 {
738   tree niter_type = unsigned_type_for (type);
739   tree s, c, d, bits, assumption, tmp, bound;
740   mpz_t max;
741
742   niter->control = *iv;
743   niter->bound = final;
744   niter->cmp = NE_EXPR;
745
746   /* Rearrange the terms so that we get inequality S * i <> C, with S
747      positive.  Also cast everything to the unsigned type.  If IV does
748      not overflow, BNDS bounds the value of C.  Also, this is the
749      case if the computation |FINAL - IV->base| does not overflow, i.e.,
750      if BNDS->below in the result is nonnegative.  */
751   if (tree_int_cst_sign_bit (iv->step))
752     {
753       s = fold_convert (niter_type,
754                         fold_build1 (NEGATE_EXPR, type, iv->step));
755       c = fold_build2 (MINUS_EXPR, niter_type,
756                        fold_convert (niter_type, iv->base),
757                        fold_convert (niter_type, final));
758       bounds_negate (bnds);
759     }
760   else
761     {
762       s = fold_convert (niter_type, iv->step);
763       c = fold_build2 (MINUS_EXPR, niter_type,
764                        fold_convert (niter_type, final),
765                        fold_convert (niter_type, iv->base));
766     }
767
768   mpz_init (max);
769   number_of_iterations_ne_max (max, iv->no_overflow, c, s, bnds,
770                                exit_must_be_taken);
771   niter->max = widest_int::from (wi::from_mpz (niter_type, max, false),
772                                  TYPE_SIGN (niter_type));
773   mpz_clear (max);
774
775   /* First the trivial cases -- when the step is 1.  */
776   if (integer_onep (s))
777     {
778       niter->niter = c;
779       return true;
780     }
781
782   /* Let nsd (step, size of mode) = d.  If d does not divide c, the loop
783      is infinite.  Otherwise, the number of iterations is
784      (inverse(s/d) * (c/d)) mod (size of mode/d).  */
785   bits = num_ending_zeros (s);
786   bound = build_low_bits_mask (niter_type,
787                                (TYPE_PRECISION (niter_type)
788                                 - tree_to_uhwi (bits)));
789
790   d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
791                                build_int_cst (niter_type, 1), bits);
792   s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
793
794   if (!exit_must_be_taken)
795     {
796       /* If we cannot assume that the exit is taken eventually, record the
797          assumptions for divisibility of c.  */
798       assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
799       assumption = fold_build2 (EQ_EXPR, boolean_type_node,
800                                 assumption, build_int_cst (niter_type, 0));
801       if (!integer_nonzerop (assumption))
802         niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
803                                           niter->assumptions, assumption);
804     }
805
806   c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
807   tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
808   niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
809   return true;
810 }
811
812 /* Checks whether we can determine the final value of the control variable
813    of the loop with ending condition IV0 < IV1 (computed in TYPE).
814    DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
815    of the step.  The assumptions necessary to ensure that the computation
816    of the final value does not overflow are recorded in NITER.  If we
817    find the final value, we adjust DELTA and return TRUE.  Otherwise
818    we return false.  BNDS bounds the value of IV1->base - IV0->base,
819    and will be updated by the same amount as DELTA.  EXIT_MUST_BE_TAKEN is
820    true if we know that the exit must be taken eventually.  */
821
822 static bool
823 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
824                                struct tree_niter_desc *niter,
825                                tree *delta, tree step,
826                                bool exit_must_be_taken, bounds *bnds)
827 {
828   tree niter_type = TREE_TYPE (step);
829   tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
830   tree tmod;
831   mpz_t mmod;
832   tree assumption = boolean_true_node, bound, noloop;
833   bool ret = false, fv_comp_no_overflow;
834   tree type1 = type;
835   if (POINTER_TYPE_P (type))
836     type1 = sizetype;
837
838   if (TREE_CODE (mod) != INTEGER_CST)
839     return false;
840   if (integer_nonzerop (mod))
841     mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
842   tmod = fold_convert (type1, mod);
843
844   mpz_init (mmod);
845   wi::to_mpz (mod, mmod, UNSIGNED);
846   mpz_neg (mmod, mmod);
847
848   /* If the induction variable does not overflow and the exit is taken,
849      then the computation of the final value does not overflow.  This is
850      also obviously the case if the new final value is equal to the
851      current one.  Finally, we postulate this for pointer type variables,
852      as the code cannot rely on the object to that the pointer points being
853      placed at the end of the address space (and more pragmatically,
854      TYPE_{MIN,MAX}_VALUE is not defined for pointers).  */
855   if (integer_zerop (mod) || POINTER_TYPE_P (type))
856     fv_comp_no_overflow = true;
857   else if (!exit_must_be_taken)
858     fv_comp_no_overflow = false;
859   else
860     fv_comp_no_overflow =
861             (iv0->no_overflow && integer_nonzerop (iv0->step))
862             || (iv1->no_overflow && integer_nonzerop (iv1->step));
863
864   if (integer_nonzerop (iv0->step))
865     {
866       /* The final value of the iv is iv1->base + MOD, assuming that this
867          computation does not overflow, and that
868          iv0->base <= iv1->base + MOD.  */
869       if (!fv_comp_no_overflow)
870         {
871           bound = fold_build2 (MINUS_EXPR, type1,
872                                TYPE_MAX_VALUE (type1), tmod);
873           assumption = fold_build2 (LE_EXPR, boolean_type_node,
874                                     iv1->base, bound);
875           if (integer_zerop (assumption))
876             goto end;
877         }
878       if (mpz_cmp (mmod, bnds->below) < 0)
879         noloop = boolean_false_node;
880       else if (POINTER_TYPE_P (type))
881         noloop = fold_build2 (GT_EXPR, boolean_type_node,
882                               iv0->base,
883                               fold_build_pointer_plus (iv1->base, tmod));
884       else
885         noloop = fold_build2 (GT_EXPR, boolean_type_node,
886                               iv0->base,
887                               fold_build2 (PLUS_EXPR, type1,
888                                            iv1->base, tmod));
889     }
890   else
891     {
892       /* The final value of the iv is iv0->base - MOD, assuming that this
893          computation does not overflow, and that
894          iv0->base - MOD <= iv1->base. */
895       if (!fv_comp_no_overflow)
896         {
897           bound = fold_build2 (PLUS_EXPR, type1,
898                                TYPE_MIN_VALUE (type1), tmod);
899           assumption = fold_build2 (GE_EXPR, boolean_type_node,
900                                     iv0->base, bound);
901           if (integer_zerop (assumption))
902             goto end;
903         }
904       if (mpz_cmp (mmod, bnds->below) < 0)
905         noloop = boolean_false_node;
906       else if (POINTER_TYPE_P (type))
907         noloop = fold_build2 (GT_EXPR, boolean_type_node,
908                               fold_build_pointer_plus (iv0->base,
909                                                        fold_build1 (NEGATE_EXPR,
910                                                                     type1, tmod)),
911                               iv1->base);
912       else
913         noloop = fold_build2 (GT_EXPR, boolean_type_node,
914                               fold_build2 (MINUS_EXPR, type1,
915                                            iv0->base, tmod),
916                               iv1->base);
917     }
918
919   if (!integer_nonzerop (assumption))
920     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
921                                       niter->assumptions,
922                                       assumption);
923   if (!integer_zerop (noloop))
924     niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
925                                       niter->may_be_zero,
926                                       noloop);
927   bounds_add (bnds, wi::to_widest (mod), type);
928   *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
929
930   ret = true;
931 end:
932   mpz_clear (mmod);
933   return ret;
934 }
935
936 /* Add assertions to NITER that ensure that the control variable of the loop
937    with ending condition IV0 < IV1 does not overflow.  Types of IV0 and IV1
938    are TYPE.  Returns false if we can prove that there is an overflow, true
939    otherwise.  STEP is the absolute value of the step.  */
940
941 static bool
942 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
943                        struct tree_niter_desc *niter, tree step)
944 {
945   tree bound, d, assumption, diff;
946   tree niter_type = TREE_TYPE (step);
947
948   if (integer_nonzerop (iv0->step))
949     {
950       /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
951       if (iv0->no_overflow)
952         return true;
953
954       /* If iv0->base is a constant, we can determine the last value before
955          overflow precisely; otherwise we conservatively assume
956          MAX - STEP + 1.  */
957
958       if (TREE_CODE (iv0->base) == INTEGER_CST)
959         {
960           d = fold_build2 (MINUS_EXPR, niter_type,
961                            fold_convert (niter_type, TYPE_MAX_VALUE (type)),
962                            fold_convert (niter_type, iv0->base));
963           diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
964         }
965       else
966         diff = fold_build2 (MINUS_EXPR, niter_type, step,
967                             build_int_cst (niter_type, 1));
968       bound = fold_build2 (MINUS_EXPR, type,
969                            TYPE_MAX_VALUE (type), fold_convert (type, diff));
970       assumption = fold_build2 (LE_EXPR, boolean_type_node,
971                                 iv1->base, bound);
972     }
973   else
974     {
975       /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
976       if (iv1->no_overflow)
977         return true;
978
979       if (TREE_CODE (iv1->base) == INTEGER_CST)
980         {
981           d = fold_build2 (MINUS_EXPR, niter_type,
982                            fold_convert (niter_type, iv1->base),
983                            fold_convert (niter_type, TYPE_MIN_VALUE (type)));
984           diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
985         }
986       else
987         diff = fold_build2 (MINUS_EXPR, niter_type, step,
988                             build_int_cst (niter_type, 1));
989       bound = fold_build2 (PLUS_EXPR, type,
990                            TYPE_MIN_VALUE (type), fold_convert (type, diff));
991       assumption = fold_build2 (GE_EXPR, boolean_type_node,
992                                 iv0->base, bound);
993     }
994
995   if (integer_zerop (assumption))
996     return false;
997   if (!integer_nonzerop (assumption))
998     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
999                                       niter->assumptions, assumption);
1000
1001   iv0->no_overflow = true;
1002   iv1->no_overflow = true;
1003   return true;
1004 }
1005
1006 /* Add an assumption to NITER that a loop whose ending condition
1007    is IV0 < IV1 rolls.  TYPE is the type of the control iv.  BNDS
1008    bounds the value of IV1->base - IV0->base.  */
1009
1010 static void
1011 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1012                       struct tree_niter_desc *niter, bounds *bnds)
1013 {
1014   tree assumption = boolean_true_node, bound, diff;
1015   tree mbz, mbzl, mbzr, type1;
1016   bool rolls_p, no_overflow_p;
1017   widest_int dstep;
1018   mpz_t mstep, max;
1019
1020   /* We are going to compute the number of iterations as
1021      (iv1->base - iv0->base + step - 1) / step, computed in the unsigned
1022      variant of TYPE.  This formula only works if
1023
1024      -step + 1 <= (iv1->base - iv0->base) <= MAX - step + 1
1025
1026      (where MAX is the maximum value of the unsigned variant of TYPE, and
1027      the computations in this formula are performed in full precision,
1028      i.e., without overflows).
1029
1030      Usually, for loops with exit condition iv0->base + step * i < iv1->base,
1031      we have a condition of the form iv0->base - step < iv1->base before the loop,
1032      and for loops iv0->base < iv1->base - step * i the condition
1033      iv0->base < iv1->base + step, due to loop header copying, which enable us
1034      to prove the lower bound.
1035
1036      The upper bound is more complicated.  Unless the expressions for initial
1037      and final value themselves contain enough information, we usually cannot
1038      derive it from the context.  */
1039
1040   /* First check whether the answer does not follow from the bounds we gathered
1041      before.  */
1042   if (integer_nonzerop (iv0->step))
1043     dstep = wi::to_widest (iv0->step);
1044   else
1045     {
1046       dstep = wi::sext (wi::to_widest (iv1->step), TYPE_PRECISION (type));
1047       dstep = -dstep;
1048     }
1049
1050   mpz_init (mstep);
1051   wi::to_mpz (dstep, mstep, UNSIGNED);
1052   mpz_neg (mstep, mstep);
1053   mpz_add_ui (mstep, mstep, 1);
1054
1055   rolls_p = mpz_cmp (mstep, bnds->below) <= 0;
1056
1057   mpz_init (max);
1058   wi::to_mpz (wi::minus_one (TYPE_PRECISION (type)), max, UNSIGNED);
1059   mpz_add (max, max, mstep);
1060   no_overflow_p = (mpz_cmp (bnds->up, max) <= 0
1061                    /* For pointers, only values lying inside a single object
1062                       can be compared or manipulated by pointer arithmetics.
1063                       Gcc in general does not allow or handle objects larger
1064                       than half of the address space, hence the upper bound
1065                       is satisfied for pointers.  */
1066                    || POINTER_TYPE_P (type));
1067   mpz_clear (mstep);
1068   mpz_clear (max);
1069
1070   if (rolls_p && no_overflow_p)
1071     return;
1072
1073   type1 = type;
1074   if (POINTER_TYPE_P (type))
1075     type1 = sizetype;
1076
1077   /* Now the hard part; we must formulate the assumption(s) as expressions, and
1078      we must be careful not to introduce overflow.  */
1079
1080   if (integer_nonzerop (iv0->step))
1081     {
1082       diff = fold_build2 (MINUS_EXPR, type1,
1083                           iv0->step, build_int_cst (type1, 1));
1084
1085       /* We need to know that iv0->base >= MIN + iv0->step - 1.  Since
1086          0 address never belongs to any object, we can assume this for
1087          pointers.  */
1088       if (!POINTER_TYPE_P (type))
1089         {
1090           bound = fold_build2 (PLUS_EXPR, type1,
1091                                TYPE_MIN_VALUE (type), diff);
1092           assumption = fold_build2 (GE_EXPR, boolean_type_node,
1093                                     iv0->base, bound);
1094         }
1095
1096       /* And then we can compute iv0->base - diff, and compare it with
1097          iv1->base.  */
1098       mbzl = fold_build2 (MINUS_EXPR, type1,
1099                           fold_convert (type1, iv0->base), diff);
1100       mbzr = fold_convert (type1, iv1->base);
1101     }
1102   else
1103     {
1104       diff = fold_build2 (PLUS_EXPR, type1,
1105                           iv1->step, build_int_cst (type1, 1));
1106
1107       if (!POINTER_TYPE_P (type))
1108         {
1109           bound = fold_build2 (PLUS_EXPR, type1,
1110                                TYPE_MAX_VALUE (type), diff);
1111           assumption = fold_build2 (LE_EXPR, boolean_type_node,
1112                                     iv1->base, bound);
1113         }
1114
1115       mbzl = fold_convert (type1, iv0->base);
1116       mbzr = fold_build2 (MINUS_EXPR, type1,
1117                           fold_convert (type1, iv1->base), diff);
1118     }
1119
1120   if (!integer_nonzerop (assumption))
1121     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1122                                       niter->assumptions, assumption);
1123   if (!rolls_p)
1124     {
1125       mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
1126       niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
1127                                         niter->may_be_zero, mbz);
1128     }
1129 }
1130
1131 /* Determines number of iterations of loop whose ending condition
1132    is IV0 < IV1.  TYPE is the type of the iv.  The number of
1133    iterations is stored to NITER.  BNDS bounds the difference
1134    IV1->base - IV0->base.  EXIT_MUST_BE_TAKEN is true if we know
1135    that the exit must be taken eventually.  */
1136
1137 static bool
1138 number_of_iterations_lt (tree type, affine_iv *iv0, affine_iv *iv1,
1139                          struct tree_niter_desc *niter,
1140                          bool exit_must_be_taken, bounds *bnds)
1141 {
1142   tree niter_type = unsigned_type_for (type);
1143   tree delta, step, s;
1144   mpz_t mstep, tmp;
1145
1146   if (integer_nonzerop (iv0->step))
1147     {
1148       niter->control = *iv0;
1149       niter->cmp = LT_EXPR;
1150       niter->bound = iv1->base;
1151     }
1152   else
1153     {
1154       niter->control = *iv1;
1155       niter->cmp = GT_EXPR;
1156       niter->bound = iv0->base;
1157     }
1158
1159   delta = fold_build2 (MINUS_EXPR, niter_type,
1160                        fold_convert (niter_type, iv1->base),
1161                        fold_convert (niter_type, iv0->base));
1162
1163   /* First handle the special case that the step is +-1.  */
1164   if ((integer_onep (iv0->step) && integer_zerop (iv1->step))
1165       || (integer_all_onesp (iv1->step) && integer_zerop (iv0->step)))
1166     {
1167       /* for (i = iv0->base; i < iv1->base; i++)
1168
1169          or
1170
1171          for (i = iv1->base; i > iv0->base; i--).
1172
1173          In both cases # of iterations is iv1->base - iv0->base, assuming that
1174          iv1->base >= iv0->base.
1175
1176          First try to derive a lower bound on the value of
1177          iv1->base - iv0->base, computed in full precision.  If the difference
1178          is nonnegative, we are done, otherwise we must record the
1179          condition.  */
1180
1181       if (mpz_sgn (bnds->below) < 0)
1182         niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
1183                                           iv1->base, iv0->base);
1184       niter->niter = delta;
1185       niter->max = widest_int::from (wi::from_mpz (niter_type, bnds->up, false),
1186                                      TYPE_SIGN (niter_type));
1187       return true;
1188     }
1189
1190   if (integer_nonzerop (iv0->step))
1191     step = fold_convert (niter_type, iv0->step);
1192   else
1193     step = fold_convert (niter_type,
1194                          fold_build1 (NEGATE_EXPR, type, iv1->step));
1195
1196   /* If we can determine the final value of the control iv exactly, we can
1197      transform the condition to != comparison.  In particular, this will be
1198      the case if DELTA is constant.  */
1199   if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step,
1200                                      exit_must_be_taken, bnds))
1201     {
1202       affine_iv zps;
1203
1204       zps.base = build_int_cst (niter_type, 0);
1205       zps.step = step;
1206       /* number_of_iterations_lt_to_ne will add assumptions that ensure that
1207          zps does not overflow.  */
1208       zps.no_overflow = true;
1209
1210       return number_of_iterations_ne (type, &zps, delta, niter, true, bnds);
1211     }
1212
1213   /* Make sure that the control iv does not overflow.  */
1214   if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
1215     return false;
1216
1217   /* We determine the number of iterations as (delta + step - 1) / step.  For
1218      this to work, we must know that iv1->base >= iv0->base - step + 1,
1219      otherwise the loop does not roll.  */
1220   assert_loop_rolls_lt (type, iv0, iv1, niter, bnds);
1221
1222   s = fold_build2 (MINUS_EXPR, niter_type,
1223                    step, build_int_cst (niter_type, 1));
1224   delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
1225   niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
1226
1227   mpz_init (mstep);
1228   mpz_init (tmp);
1229   wi::to_mpz (step, mstep, UNSIGNED);
1230   mpz_add (tmp, bnds->up, mstep);
1231   mpz_sub_ui (tmp, tmp, 1);
1232   mpz_fdiv_q (tmp, tmp, mstep);
1233   niter->max = widest_int::from (wi::from_mpz (niter_type, tmp, false),
1234                                  TYPE_SIGN (niter_type));
1235   mpz_clear (mstep);
1236   mpz_clear (tmp);
1237
1238   return true;
1239 }
1240
1241 /* Determines number of iterations of loop whose ending condition
1242    is IV0 <= IV1.  TYPE is the type of the iv.  The number of
1243    iterations is stored to NITER.  EXIT_MUST_BE_TAKEN is true if
1244    we know that this condition must eventually become false (we derived this
1245    earlier, and possibly set NITER->assumptions to make sure this
1246    is the case).  BNDS bounds the difference IV1->base - IV0->base.  */
1247
1248 static bool
1249 number_of_iterations_le (tree type, affine_iv *iv0, affine_iv *iv1,
1250                          struct tree_niter_desc *niter, bool exit_must_be_taken,
1251                          bounds *bnds)
1252 {
1253   tree assumption;
1254   tree type1 = type;
1255   if (POINTER_TYPE_P (type))
1256     type1 = sizetype;
1257
1258   /* Say that IV0 is the control variable.  Then IV0 <= IV1 iff
1259      IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
1260      value of the type.  This we must know anyway, since if it is
1261      equal to this value, the loop rolls forever.  We do not check
1262      this condition for pointer type ivs, as the code cannot rely on
1263      the object to that the pointer points being placed at the end of
1264      the address space (and more pragmatically, TYPE_{MIN,MAX}_VALUE is
1265      not defined for pointers).  */
1266
1267   if (!exit_must_be_taken && !POINTER_TYPE_P (type))
1268     {
1269       if (integer_nonzerop (iv0->step))
1270         assumption = fold_build2 (NE_EXPR, boolean_type_node,
1271                                   iv1->base, TYPE_MAX_VALUE (type));
1272       else
1273         assumption = fold_build2 (NE_EXPR, boolean_type_node,
1274                                   iv0->base, TYPE_MIN_VALUE (type));
1275
1276       if (integer_zerop (assumption))
1277         return false;
1278       if (!integer_nonzerop (assumption))
1279         niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1280                                           niter->assumptions, assumption);
1281     }
1282
1283   if (integer_nonzerop (iv0->step))
1284     {
1285       if (POINTER_TYPE_P (type))
1286         iv1->base = fold_build_pointer_plus_hwi (iv1->base, 1);
1287       else
1288         iv1->base = fold_build2 (PLUS_EXPR, type1, iv1->base,
1289                                  build_int_cst (type1, 1));
1290     }
1291   else if (POINTER_TYPE_P (type))
1292     iv0->base = fold_build_pointer_plus_hwi (iv0->base, -1);
1293   else
1294     iv0->base = fold_build2 (MINUS_EXPR, type1,
1295                              iv0->base, build_int_cst (type1, 1));
1296
1297   bounds_add (bnds, 1, type1);
1298
1299   return number_of_iterations_lt (type, iv0, iv1, niter, exit_must_be_taken,
1300                                   bnds);
1301 }
1302
1303 /* Dumps description of affine induction variable IV to FILE.  */
1304
1305 static void
1306 dump_affine_iv (FILE *file, affine_iv *iv)
1307 {
1308   if (!integer_zerop (iv->step))
1309     fprintf (file, "[");
1310
1311   print_generic_expr (dump_file, iv->base, TDF_SLIM);
1312
1313   if (!integer_zerop (iv->step))
1314     {
1315       fprintf (file, ", + , ");
1316       print_generic_expr (dump_file, iv->step, TDF_SLIM);
1317       fprintf (file, "]%s", iv->no_overflow ? "(no_overflow)" : "");
1318     }
1319 }
1320
1321 /* Determine the number of iterations according to condition (for staying
1322    inside loop) which compares two induction variables using comparison
1323    operator CODE.  The induction variable on left side of the comparison
1324    is IV0, the right-hand side is IV1.  Both induction variables must have
1325    type TYPE, which must be an integer or pointer type.  The steps of the
1326    ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
1327
1328    LOOP is the loop whose number of iterations we are determining.
1329
1330    ONLY_EXIT is true if we are sure this is the only way the loop could be
1331    exited (including possibly non-returning function calls, exceptions, etc.)
1332    -- in this case we can use the information whether the control induction
1333    variables can overflow or not in a more efficient way.
1334
1335    if EVERY_ITERATION is true, we know the test is executed on every iteration.
1336
1337    The results (number of iterations and assumptions as described in
1338    comments at struct tree_niter_desc in tree-ssa-loop.h) are stored to NITER.
1339    Returns false if it fails to determine number of iterations, true if it
1340    was determined (possibly with some assumptions).  */
1341
1342 static bool
1343 number_of_iterations_cond (struct loop *loop,
1344                            tree type, affine_iv *iv0, enum tree_code code,
1345                            affine_iv *iv1, struct tree_niter_desc *niter,
1346                            bool only_exit, bool every_iteration)
1347 {
1348   bool exit_must_be_taken = false, ret;
1349   bounds bnds;
1350
1351   /* If the test is not executed every iteration, wrapping may make the test
1352      to pass again. 
1353      TODO: the overflow case can be still used as unreliable estimate of upper
1354      bound.  But we have no API to pass it down to number of iterations code
1355      and, at present, it will not use it anyway.  */
1356   if (!every_iteration
1357       && (!iv0->no_overflow || !iv1->no_overflow
1358           || code == NE_EXPR || code == EQ_EXPR))
1359     return false;
1360
1361   /* The meaning of these assumptions is this:
1362      if !assumptions
1363        then the rest of information does not have to be valid
1364      if may_be_zero then the loop does not roll, even if
1365        niter != 0.  */
1366   niter->assumptions = boolean_true_node;
1367   niter->may_be_zero = boolean_false_node;
1368   niter->niter = NULL_TREE;
1369   niter->max = 0;
1370   niter->bound = NULL_TREE;
1371   niter->cmp = ERROR_MARK;
1372
1373   /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
1374      the control variable is on lhs.  */
1375   if (code == GE_EXPR || code == GT_EXPR
1376       || (code == NE_EXPR && integer_zerop (iv0->step)))
1377     {
1378       SWAP (iv0, iv1);
1379       code = swap_tree_comparison (code);
1380     }
1381
1382   if (POINTER_TYPE_P (type))
1383     {
1384       /* Comparison of pointers is undefined unless both iv0 and iv1 point
1385          to the same object.  If they do, the control variable cannot wrap
1386          (as wrap around the bounds of memory will never return a pointer
1387          that would be guaranteed to point to the same object, even if we
1388          avoid undefined behavior by casting to size_t and back).  */
1389       iv0->no_overflow = true;
1390       iv1->no_overflow = true;
1391     }
1392
1393   /* If the control induction variable does not overflow and the only exit
1394      from the loop is the one that we analyze, we know it must be taken
1395      eventually.  */
1396   if (only_exit)
1397     {
1398       if (!integer_zerop (iv0->step) && iv0->no_overflow)
1399         exit_must_be_taken = true;
1400       else if (!integer_zerop (iv1->step) && iv1->no_overflow)
1401         exit_must_be_taken = true;
1402     }
1403
1404   /* We can handle the case when neither of the sides of the comparison is
1405      invariant, provided that the test is NE_EXPR.  This rarely occurs in
1406      practice, but it is simple enough to manage.  */
1407   if (!integer_zerop (iv0->step) && !integer_zerop (iv1->step))
1408     {
1409       tree step_type = POINTER_TYPE_P (type) ? sizetype : type;
1410       if (code != NE_EXPR)
1411         return false;
1412
1413       iv0->step = fold_binary_to_constant (MINUS_EXPR, step_type,
1414                                            iv0->step, iv1->step);
1415       iv0->no_overflow = false;
1416       iv1->step = build_int_cst (step_type, 0);
1417       iv1->no_overflow = true;
1418     }
1419
1420   /* If the result of the comparison is a constant,  the loop is weird.  More
1421      precise handling would be possible, but the situation is not common enough
1422      to waste time on it.  */
1423   if (integer_zerop (iv0->step) && integer_zerop (iv1->step))
1424     return false;
1425
1426   /* Ignore loops of while (i-- < 10) type.  */
1427   if (code != NE_EXPR)
1428     {
1429       if (iv0->step && tree_int_cst_sign_bit (iv0->step))
1430         return false;
1431
1432       if (!integer_zerop (iv1->step) && !tree_int_cst_sign_bit (iv1->step))
1433         return false;
1434     }
1435
1436   /* If the loop exits immediately, there is nothing to do.  */
1437   tree tem = fold_binary (code, boolean_type_node, iv0->base, iv1->base);
1438   if (tem && integer_zerop (tem))
1439     {
1440       niter->niter = build_int_cst (unsigned_type_for (type), 0);
1441       niter->max = 0;
1442       return true;
1443     }
1444
1445   /* OK, now we know we have a senseful loop.  Handle several cases, depending
1446      on what comparison operator is used.  */
1447   bound_difference (loop, iv1->base, iv0->base, &bnds);
1448
1449   if (dump_file && (dump_flags & TDF_DETAILS))
1450     {
1451       fprintf (dump_file,
1452                "Analyzing # of iterations of loop %d\n", loop->num);
1453
1454       fprintf (dump_file, "  exit condition ");
1455       dump_affine_iv (dump_file, iv0);
1456       fprintf (dump_file, " %s ",
1457                code == NE_EXPR ? "!="
1458                : code == LT_EXPR ? "<"
1459                : "<=");
1460       dump_affine_iv (dump_file, iv1);
1461       fprintf (dump_file, "\n");
1462
1463       fprintf (dump_file, "  bounds on difference of bases: ");
1464       mpz_out_str (dump_file, 10, bnds.below);
1465       fprintf (dump_file, " ... ");
1466       mpz_out_str (dump_file, 10, bnds.up);
1467       fprintf (dump_file, "\n");
1468     }
1469
1470   switch (code)
1471     {
1472     case NE_EXPR:
1473       gcc_assert (integer_zerop (iv1->step));
1474       ret = number_of_iterations_ne (type, iv0, iv1->base, niter,
1475                                      exit_must_be_taken, &bnds);
1476       break;
1477
1478     case LT_EXPR:
1479       ret = number_of_iterations_lt (type, iv0, iv1, niter, exit_must_be_taken,
1480                                      &bnds);
1481       break;
1482
1483     case LE_EXPR:
1484       ret = number_of_iterations_le (type, iv0, iv1, niter, exit_must_be_taken,
1485                                      &bnds);
1486       break;
1487
1488     default:
1489       gcc_unreachable ();
1490     }
1491
1492   mpz_clear (bnds.up);
1493   mpz_clear (bnds.below);
1494
1495   if (dump_file && (dump_flags & TDF_DETAILS))
1496     {
1497       if (ret)
1498         {
1499           fprintf (dump_file, "  result:\n");
1500           if (!integer_nonzerop (niter->assumptions))
1501             {
1502               fprintf (dump_file, "    under assumptions ");
1503               print_generic_expr (dump_file, niter->assumptions, TDF_SLIM);
1504               fprintf (dump_file, "\n");
1505             }
1506
1507           if (!integer_zerop (niter->may_be_zero))
1508             {
1509               fprintf (dump_file, "    zero if ");
1510               print_generic_expr (dump_file, niter->may_be_zero, TDF_SLIM);
1511               fprintf (dump_file, "\n");
1512             }
1513
1514           fprintf (dump_file, "    # of iterations ");
1515           print_generic_expr (dump_file, niter->niter, TDF_SLIM);
1516           fprintf (dump_file, ", bounded by ");
1517           print_decu (niter->max, dump_file);
1518           fprintf (dump_file, "\n");
1519         }
1520       else
1521         fprintf (dump_file, "  failed\n\n");
1522     }
1523   return ret;
1524 }
1525
1526 /* Substitute NEW for OLD in EXPR and fold the result.  */
1527
1528 static tree
1529 simplify_replace_tree (tree expr, tree old, tree new_tree)
1530 {
1531   unsigned i, n;
1532   tree ret = NULL_TREE, e, se;
1533
1534   if (!expr)
1535     return NULL_TREE;
1536
1537   /* Do not bother to replace constants.  */
1538   if (CONSTANT_CLASS_P (old))
1539     return expr;
1540
1541   if (expr == old
1542       || operand_equal_p (expr, old, 0))
1543     return unshare_expr (new_tree);
1544
1545   if (!EXPR_P (expr))
1546     return expr;
1547
1548   n = TREE_OPERAND_LENGTH (expr);
1549   for (i = 0; i < n; i++)
1550     {
1551       e = TREE_OPERAND (expr, i);
1552       se = simplify_replace_tree (e, old, new_tree);
1553       if (e == se)
1554         continue;
1555
1556       if (!ret)
1557         ret = copy_node (expr);
1558
1559       TREE_OPERAND (ret, i) = se;
1560     }
1561
1562   return (ret ? fold (ret) : expr);
1563 }
1564
1565 /* Expand definitions of ssa names in EXPR as long as they are simple
1566    enough, and return the new expression.  */
1567
1568 tree
1569 expand_simple_operations (tree expr)
1570 {
1571   unsigned i, n;
1572   tree ret = NULL_TREE, e, ee, e1;
1573   enum tree_code code;
1574   gimple stmt;
1575
1576   if (expr == NULL_TREE)
1577     return expr;
1578
1579   if (is_gimple_min_invariant (expr))
1580     return expr;
1581
1582   code = TREE_CODE (expr);
1583   if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
1584     {
1585       n = TREE_OPERAND_LENGTH (expr);
1586       for (i = 0; i < n; i++)
1587         {
1588           e = TREE_OPERAND (expr, i);
1589           ee = expand_simple_operations (e);
1590           if (e == ee)
1591             continue;
1592
1593           if (!ret)
1594             ret = copy_node (expr);
1595
1596           TREE_OPERAND (ret, i) = ee;
1597         }
1598
1599       if (!ret)
1600         return expr;
1601
1602       fold_defer_overflow_warnings ();
1603       ret = fold (ret);
1604       fold_undefer_and_ignore_overflow_warnings ();
1605       return ret;
1606     }
1607
1608   if (TREE_CODE (expr) != SSA_NAME)
1609     return expr;
1610
1611   stmt = SSA_NAME_DEF_STMT (expr);
1612   if (gimple_code (stmt) == GIMPLE_PHI)
1613     {
1614       basic_block src, dest;
1615
1616       if (gimple_phi_num_args (stmt) != 1)
1617         return expr;
1618       e = PHI_ARG_DEF (stmt, 0);
1619
1620       /* Avoid propagating through loop exit phi nodes, which
1621          could break loop-closed SSA form restrictions.  */
1622       dest = gimple_bb (stmt);
1623       src = single_pred (dest);
1624       if (TREE_CODE (e) == SSA_NAME
1625           && src->loop_father != dest->loop_father)
1626         return expr;
1627
1628       return expand_simple_operations (e);
1629     }
1630   if (gimple_code (stmt) != GIMPLE_ASSIGN)
1631     return expr;
1632
1633   /* Avoid expanding to expressions that contain SSA names that need
1634      to take part in abnormal coalescing.  */
1635   ssa_op_iter iter;
1636   FOR_EACH_SSA_TREE_OPERAND (e, stmt, iter, SSA_OP_USE)
1637     if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (e))
1638       return expr;
1639
1640   e = gimple_assign_rhs1 (stmt);
1641   code = gimple_assign_rhs_code (stmt);
1642   if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
1643     {
1644       if (is_gimple_min_invariant (e))
1645         return e;
1646
1647       if (code == SSA_NAME)
1648         return expand_simple_operations (e);
1649
1650       return expr;
1651     }
1652
1653   switch (code)
1654     {
1655     CASE_CONVERT:
1656       /* Casts are simple.  */
1657       ee = expand_simple_operations (e);
1658       return fold_build1 (code, TREE_TYPE (expr), ee);
1659
1660     case PLUS_EXPR:
1661     case MINUS_EXPR:
1662       if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (expr))
1663           && TYPE_OVERFLOW_TRAPS (TREE_TYPE (expr)))
1664         return expr;
1665       /* Fallthru.  */
1666     case POINTER_PLUS_EXPR:
1667       /* And increments and decrements by a constant are simple.  */
1668       e1 = gimple_assign_rhs2 (stmt);
1669       if (!is_gimple_min_invariant (e1))
1670         return expr;
1671
1672       ee = expand_simple_operations (e);
1673       return fold_build2 (code, TREE_TYPE (expr), ee, e1);
1674
1675     default:
1676       return expr;
1677     }
1678 }
1679
1680 /* Tries to simplify EXPR using the condition COND.  Returns the simplified
1681    expression (or EXPR unchanged, if no simplification was possible).  */
1682
1683 static tree
1684 tree_simplify_using_condition_1 (tree cond, tree expr)
1685 {
1686   bool changed;
1687   tree e, te, e0, e1, e2, notcond;
1688   enum tree_code code = TREE_CODE (expr);
1689
1690   if (code == INTEGER_CST)
1691     return expr;
1692
1693   if (code == TRUTH_OR_EXPR
1694       || code == TRUTH_AND_EXPR
1695       || code == COND_EXPR)
1696     {
1697       changed = false;
1698
1699       e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
1700       if (TREE_OPERAND (expr, 0) != e0)
1701         changed = true;
1702
1703       e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
1704       if (TREE_OPERAND (expr, 1) != e1)
1705         changed = true;
1706
1707       if (code == COND_EXPR)
1708         {
1709           e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
1710           if (TREE_OPERAND (expr, 2) != e2)
1711             changed = true;
1712         }
1713       else
1714         e2 = NULL_TREE;
1715
1716       if (changed)
1717         {
1718           if (code == COND_EXPR)
1719             expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
1720           else
1721             expr = fold_build2 (code, boolean_type_node, e0, e1);
1722         }
1723
1724       return expr;
1725     }
1726
1727   /* In case COND is equality, we may be able to simplify EXPR by copy/constant
1728      propagation, and vice versa.  Fold does not handle this, since it is
1729      considered too expensive.  */
1730   if (TREE_CODE (cond) == EQ_EXPR)
1731     {
1732       e0 = TREE_OPERAND (cond, 0);
1733       e1 = TREE_OPERAND (cond, 1);
1734
1735       /* We know that e0 == e1.  Check whether we cannot simplify expr
1736          using this fact.  */
1737       e = simplify_replace_tree (expr, e0, e1);
1738       if (integer_zerop (e) || integer_nonzerop (e))
1739         return e;
1740
1741       e = simplify_replace_tree (expr, e1, e0);
1742       if (integer_zerop (e) || integer_nonzerop (e))
1743         return e;
1744     }
1745   if (TREE_CODE (expr) == EQ_EXPR)
1746     {
1747       e0 = TREE_OPERAND (expr, 0);
1748       e1 = TREE_OPERAND (expr, 1);
1749
1750       /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true.  */
1751       e = simplify_replace_tree (cond, e0, e1);
1752       if (integer_zerop (e))
1753         return e;
1754       e = simplify_replace_tree (cond, e1, e0);
1755       if (integer_zerop (e))
1756         return e;
1757     }
1758   if (TREE_CODE (expr) == NE_EXPR)
1759     {
1760       e0 = TREE_OPERAND (expr, 0);
1761       e1 = TREE_OPERAND (expr, 1);
1762
1763       /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true.  */
1764       e = simplify_replace_tree (cond, e0, e1);
1765       if (integer_zerop (e))
1766         return boolean_true_node;
1767       e = simplify_replace_tree (cond, e1, e0);
1768       if (integer_zerop (e))
1769         return boolean_true_node;
1770     }
1771
1772   te = expand_simple_operations (expr);
1773
1774   /* Check whether COND ==> EXPR.  */
1775   notcond = invert_truthvalue (cond);
1776   e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, te);
1777   if (e && integer_nonzerop (e))
1778     return e;
1779
1780   /* Check whether COND ==> not EXPR.  */
1781   e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, te);
1782   if (e && integer_zerop (e))
1783     return e;
1784
1785   return expr;
1786 }
1787
1788 /* Tries to simplify EXPR using the condition COND.  Returns the simplified
1789    expression (or EXPR unchanged, if no simplification was possible).
1790    Wrapper around tree_simplify_using_condition_1 that ensures that chains
1791    of simple operations in definitions of ssa names in COND are expanded,
1792    so that things like casts or incrementing the value of the bound before
1793    the loop do not cause us to fail.  */
1794
1795 static tree
1796 tree_simplify_using_condition (tree cond, tree expr)
1797 {
1798   cond = expand_simple_operations (cond);
1799
1800   return tree_simplify_using_condition_1 (cond, expr);
1801 }
1802
1803 /* Tries to simplify EXPR using the conditions on entry to LOOP.
1804    Returns the simplified expression (or EXPR unchanged, if no
1805    simplification was possible).*/
1806
1807 static tree
1808 simplify_using_initial_conditions (struct loop *loop, tree expr)
1809 {
1810   edge e;
1811   basic_block bb;
1812   gimple stmt;
1813   tree cond;
1814   int cnt = 0;
1815
1816   if (TREE_CODE (expr) == INTEGER_CST)
1817     return expr;
1818
1819   /* Limit walking the dominators to avoid quadraticness in
1820      the number of BBs times the number of loops in degenerate
1821      cases.  */
1822   for (bb = loop->header;
1823        bb != ENTRY_BLOCK_PTR_FOR_FN (cfun) && cnt < MAX_DOMINATORS_TO_WALK;
1824        bb = get_immediate_dominator (CDI_DOMINATORS, bb))
1825     {
1826       if (!single_pred_p (bb))
1827         continue;
1828       e = single_pred_edge (bb);
1829
1830       if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
1831         continue;
1832
1833       stmt = last_stmt (e->src);
1834       cond = fold_build2 (gimple_cond_code (stmt),
1835                           boolean_type_node,
1836                           gimple_cond_lhs (stmt),
1837                           gimple_cond_rhs (stmt));
1838       if (e->flags & EDGE_FALSE_VALUE)
1839         cond = invert_truthvalue (cond);
1840       expr = tree_simplify_using_condition (cond, expr);
1841       ++cnt;
1842     }
1843
1844   return expr;
1845 }
1846
1847 /* Tries to simplify EXPR using the evolutions of the loop invariants
1848    in the superloops of LOOP.  Returns the simplified expression
1849    (or EXPR unchanged, if no simplification was possible).  */
1850
1851 static tree
1852 simplify_using_outer_evolutions (struct loop *loop, tree expr)
1853 {
1854   enum tree_code code = TREE_CODE (expr);
1855   bool changed;
1856   tree e, e0, e1, e2;
1857
1858   if (is_gimple_min_invariant (expr))
1859     return expr;
1860
1861   if (code == TRUTH_OR_EXPR
1862       || code == TRUTH_AND_EXPR
1863       || code == COND_EXPR)
1864     {
1865       changed = false;
1866
1867       e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
1868       if (TREE_OPERAND (expr, 0) != e0)
1869         changed = true;
1870
1871       e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
1872       if (TREE_OPERAND (expr, 1) != e1)
1873         changed = true;
1874
1875       if (code == COND_EXPR)
1876         {
1877           e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
1878           if (TREE_OPERAND (expr, 2) != e2)
1879             changed = true;
1880         }
1881       else
1882         e2 = NULL_TREE;
1883
1884       if (changed)
1885         {
1886           if (code == COND_EXPR)
1887             expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
1888           else
1889             expr = fold_build2 (code, boolean_type_node, e0, e1);
1890         }
1891
1892       return expr;
1893     }
1894
1895   e = instantiate_parameters (loop, expr);
1896   if (is_gimple_min_invariant (e))
1897     return e;
1898
1899   return expr;
1900 }
1901
1902 /* Returns true if EXIT is the only possible exit from LOOP.  */
1903
1904 bool
1905 loop_only_exit_p (const struct loop *loop, const_edge exit)
1906 {
1907   basic_block *body;
1908   gimple_stmt_iterator bsi;
1909   unsigned i;
1910   gimple call;
1911
1912   if (exit != single_exit (loop))
1913     return false;
1914
1915   body = get_loop_body (loop);
1916   for (i = 0; i < loop->num_nodes; i++)
1917     {
1918       for (bsi = gsi_start_bb (body[i]); !gsi_end_p (bsi); gsi_next (&bsi))
1919         {
1920           call = gsi_stmt (bsi);
1921           if (gimple_code (call) != GIMPLE_CALL)
1922             continue;
1923
1924           if (gimple_has_side_effects (call))
1925             {
1926               free (body);
1927               return false;
1928             }
1929         }
1930     }
1931
1932   free (body);
1933   return true;
1934 }
1935
1936 /* Stores description of number of iterations of LOOP derived from
1937    EXIT (an exit edge of the LOOP) in NITER.  Returns true if some
1938    useful information could be derived (and fields of NITER has
1939    meaning described in comments at struct tree_niter_desc
1940    declaration), false otherwise.  If WARN is true and
1941    -Wunsafe-loop-optimizations was given, warn if the optimizer is going to use
1942    potentially unsafe assumptions.  
1943    When EVERY_ITERATION is true, only tests that are known to be executed
1944    every iteration are considered (i.e. only test that alone bounds the loop). 
1945  */
1946
1947 bool
1948 number_of_iterations_exit (struct loop *loop, edge exit,
1949                            struct tree_niter_desc *niter,
1950                            bool warn, bool every_iteration)
1951 {
1952   gimple last;
1953   gcond *stmt;
1954   tree type;
1955   tree op0, op1;
1956   enum tree_code code;
1957   affine_iv iv0, iv1;
1958   bool safe;
1959
1960   safe = dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src);
1961
1962   if (every_iteration && !safe)
1963     return false;
1964
1965   niter->assumptions = boolean_false_node;
1966   last = last_stmt (exit->src);
1967   if (!last)
1968     return false;
1969   stmt = dyn_cast <gcond *> (last);
1970   if (!stmt)
1971     return false;
1972
1973   /* We want the condition for staying inside loop.  */
1974   code = gimple_cond_code (stmt);
1975   if (exit->flags & EDGE_TRUE_VALUE)
1976     code = invert_tree_comparison (code, false);
1977
1978   switch (code)
1979     {
1980     case GT_EXPR:
1981     case GE_EXPR:
1982     case LT_EXPR:
1983     case LE_EXPR:
1984     case NE_EXPR:
1985       break;
1986
1987     default:
1988       return false;
1989     }
1990
1991   op0 = gimple_cond_lhs (stmt);
1992   op1 = gimple_cond_rhs (stmt);
1993   type = TREE_TYPE (op0);
1994
1995   if (TREE_CODE (type) != INTEGER_TYPE
1996       && !POINTER_TYPE_P (type))
1997     return false;
1998
1999   if (!simple_iv (loop, loop_containing_stmt (stmt), op0, &iv0, false))
2000     return false;
2001   if (!simple_iv (loop, loop_containing_stmt (stmt), op1, &iv1, false))
2002     return false;
2003
2004   /* We don't want to see undefined signed overflow warnings while
2005      computing the number of iterations.  */
2006   fold_defer_overflow_warnings ();
2007
2008   iv0.base = expand_simple_operations (iv0.base);
2009   iv1.base = expand_simple_operations (iv1.base);
2010   if (!number_of_iterations_cond (loop, type, &iv0, code, &iv1, niter,
2011                                   loop_only_exit_p (loop, exit), safe))
2012     {
2013       fold_undefer_and_ignore_overflow_warnings ();
2014       return false;
2015     }
2016
2017   if (optimize >= 3)
2018     {
2019       niter->assumptions = simplify_using_outer_evolutions (loop,
2020                                                             niter->assumptions);
2021       niter->may_be_zero = simplify_using_outer_evolutions (loop,
2022                                                             niter->may_be_zero);
2023       niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
2024     }
2025
2026   niter->assumptions
2027           = simplify_using_initial_conditions (loop,
2028                                                niter->assumptions);
2029   niter->may_be_zero
2030           = simplify_using_initial_conditions (loop,
2031                                                niter->may_be_zero);
2032
2033   fold_undefer_and_ignore_overflow_warnings ();
2034
2035   /* If NITER has simplified into a constant, update MAX.  */
2036   if (TREE_CODE (niter->niter) == INTEGER_CST)
2037     niter->max = wi::to_widest (niter->niter);
2038
2039   if (integer_onep (niter->assumptions))
2040     return true;
2041
2042   /* With -funsafe-loop-optimizations we assume that nothing bad can happen.
2043      But if we can prove that there is overflow or some other source of weird
2044      behavior, ignore the loop even with -funsafe-loop-optimizations.  */
2045   if (integer_zerop (niter->assumptions) || !single_exit (loop))
2046     return false;
2047
2048   if (flag_unsafe_loop_optimizations)
2049     niter->assumptions = boolean_true_node;
2050
2051   if (warn)
2052     {
2053       const char *wording;
2054       location_t loc = gimple_location (stmt);
2055
2056       /* We can provide a more specific warning if one of the operator is
2057          constant and the other advances by +1 or -1.  */
2058       if (!integer_zerop (iv1.step)
2059           ? (integer_zerop (iv0.step)
2060              && (integer_onep (iv1.step) || integer_all_onesp (iv1.step)))
2061           : (integer_onep (iv0.step) || integer_all_onesp (iv0.step)))
2062         wording =
2063           flag_unsafe_loop_optimizations
2064           ? N_("assuming that the loop is not infinite")
2065           : N_("cannot optimize possibly infinite loops");
2066       else
2067         wording =
2068           flag_unsafe_loop_optimizations
2069           ? N_("assuming that the loop counter does not overflow")
2070           : N_("cannot optimize loop, the loop counter may overflow");
2071
2072       warning_at ((LOCATION_LINE (loc) > 0) ? loc : input_location,
2073                   OPT_Wunsafe_loop_optimizations, "%s", gettext (wording));
2074     }
2075
2076   return flag_unsafe_loop_optimizations;
2077 }
2078
2079 /* Try to determine the number of iterations of LOOP.  If we succeed,
2080    expression giving number of iterations is returned and *EXIT is
2081    set to the edge from that the information is obtained.  Otherwise
2082    chrec_dont_know is returned.  */
2083
2084 tree
2085 find_loop_niter (struct loop *loop, edge *exit)
2086 {
2087   unsigned i;
2088   vec<edge> exits = get_loop_exit_edges (loop);
2089   edge ex;
2090   tree niter = NULL_TREE, aniter;
2091   struct tree_niter_desc desc;
2092
2093   *exit = NULL;
2094   FOR_EACH_VEC_ELT (exits, i, ex)
2095     {
2096       if (!number_of_iterations_exit (loop, ex, &desc, false))
2097         continue;
2098
2099       if (integer_nonzerop (desc.may_be_zero))
2100         {
2101           /* We exit in the first iteration through this exit.
2102              We won't find anything better.  */
2103           niter = build_int_cst (unsigned_type_node, 0);
2104           *exit = ex;
2105           break;
2106         }
2107
2108       if (!integer_zerop (desc.may_be_zero))
2109         continue;
2110
2111       aniter = desc.niter;
2112
2113       if (!niter)
2114         {
2115           /* Nothing recorded yet.  */
2116           niter = aniter;
2117           *exit = ex;
2118           continue;
2119         }
2120
2121       /* Prefer constants, the lower the better.  */
2122       if (TREE_CODE (aniter) != INTEGER_CST)
2123         continue;
2124
2125       if (TREE_CODE (niter) != INTEGER_CST)
2126         {
2127           niter = aniter;
2128           *exit = ex;
2129           continue;
2130         }
2131
2132       if (tree_int_cst_lt (aniter, niter))
2133         {
2134           niter = aniter;
2135           *exit = ex;
2136           continue;
2137         }
2138     }
2139   exits.release ();
2140
2141   return niter ? niter : chrec_dont_know;
2142 }
2143
2144 /* Return true if loop is known to have bounded number of iterations.  */
2145
2146 bool
2147 finite_loop_p (struct loop *loop)
2148 {
2149   widest_int nit;
2150   int flags;
2151
2152   if (flag_unsafe_loop_optimizations)
2153     return true;
2154   flags = flags_from_decl_or_type (current_function_decl);
2155   if ((flags & (ECF_CONST|ECF_PURE)) && !(flags & ECF_LOOPING_CONST_OR_PURE))
2156     {
2157       if (dump_file && (dump_flags & TDF_DETAILS))
2158         fprintf (dump_file, "Found loop %i to be finite: it is within pure or const function.\n",
2159                  loop->num);
2160       return true;
2161     }
2162
2163   if (loop->any_upper_bound
2164       || max_loop_iterations (loop, &nit))
2165     {
2166       if (dump_file && (dump_flags & TDF_DETAILS))
2167         fprintf (dump_file, "Found loop %i to be finite: upper bound found.\n",
2168                  loop->num);
2169       return true;
2170     }
2171   return false;
2172 }
2173
2174 /*
2175
2176    Analysis of a number of iterations of a loop by a brute-force evaluation.
2177
2178 */
2179
2180 /* Bound on the number of iterations we try to evaluate.  */
2181
2182 #define MAX_ITERATIONS_TO_TRACK \
2183   ((unsigned) PARAM_VALUE (PARAM_MAX_ITERATIONS_TO_TRACK))
2184
2185 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
2186    result by a chain of operations such that all but exactly one of their
2187    operands are constants.  */
2188
2189 static gphi *
2190 chain_of_csts_start (struct loop *loop, tree x)
2191 {
2192   gimple stmt = SSA_NAME_DEF_STMT (x);
2193   tree use;
2194   basic_block bb = gimple_bb (stmt);
2195   enum tree_code code;
2196
2197   if (!bb
2198       || !flow_bb_inside_loop_p (loop, bb))
2199     return NULL;
2200
2201   if (gimple_code (stmt) == GIMPLE_PHI)
2202     {
2203       if (bb == loop->header)
2204         return as_a <gphi *> (stmt);
2205
2206       return NULL;
2207     }
2208
2209   if (gimple_code (stmt) != GIMPLE_ASSIGN
2210       || gimple_assign_rhs_class (stmt) == GIMPLE_TERNARY_RHS)
2211     return NULL;
2212
2213   code = gimple_assign_rhs_code (stmt);
2214   if (gimple_references_memory_p (stmt)
2215       || TREE_CODE_CLASS (code) == tcc_reference
2216       || (code == ADDR_EXPR
2217           && !is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
2218     return NULL;
2219
2220   use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
2221   if (use == NULL_TREE)
2222     return NULL;
2223
2224   return chain_of_csts_start (loop, use);
2225 }
2226
2227 /* Determines whether the expression X is derived from a result of a phi node
2228    in header of LOOP such that
2229
2230    * the derivation of X consists only from operations with constants
2231    * the initial value of the phi node is constant
2232    * the value of the phi node in the next iteration can be derived from the
2233      value in the current iteration by a chain of operations with constants.
2234
2235    If such phi node exists, it is returned, otherwise NULL is returned.  */
2236
2237 static gphi *
2238 get_base_for (struct loop *loop, tree x)
2239 {
2240   gphi *phi;
2241   tree init, next;
2242
2243   if (is_gimple_min_invariant (x))
2244     return NULL;
2245
2246   phi = chain_of_csts_start (loop, x);
2247   if (!phi)
2248     return NULL;
2249
2250   init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2251   next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2252
2253   if (TREE_CODE (next) != SSA_NAME)
2254     return NULL;
2255
2256   if (!is_gimple_min_invariant (init))
2257     return NULL;
2258
2259   if (chain_of_csts_start (loop, next) != phi)
2260     return NULL;
2261
2262   return phi;
2263 }
2264
2265 /* Given an expression X, then
2266
2267    * if X is NULL_TREE, we return the constant BASE.
2268    * otherwise X is a SSA name, whose value in the considered loop is derived
2269      by a chain of operations with constant from a result of a phi node in
2270      the header of the loop.  Then we return value of X when the value of the
2271      result of this phi node is given by the constant BASE.  */
2272
2273 static tree
2274 get_val_for (tree x, tree base)
2275 {
2276   gimple stmt;
2277
2278   gcc_checking_assert (is_gimple_min_invariant (base));
2279
2280   if (!x)
2281     return base;
2282
2283   stmt = SSA_NAME_DEF_STMT (x);
2284   if (gimple_code (stmt) == GIMPLE_PHI)
2285     return base;
2286
2287   gcc_checking_assert (is_gimple_assign (stmt));
2288
2289   /* STMT must be either an assignment of a single SSA name or an
2290      expression involving an SSA name and a constant.  Try to fold that
2291      expression using the value for the SSA name.  */
2292   if (gimple_assign_ssa_name_copy_p (stmt))
2293     return get_val_for (gimple_assign_rhs1 (stmt), base);
2294   else if (gimple_assign_rhs_class (stmt) == GIMPLE_UNARY_RHS
2295            && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
2296     {
2297       return fold_build1 (gimple_assign_rhs_code (stmt),
2298                           gimple_expr_type (stmt),
2299                           get_val_for (gimple_assign_rhs1 (stmt), base));
2300     }
2301   else if (gimple_assign_rhs_class (stmt) == GIMPLE_BINARY_RHS)
2302     {
2303       tree rhs1 = gimple_assign_rhs1 (stmt);
2304       tree rhs2 = gimple_assign_rhs2 (stmt);
2305       if (TREE_CODE (rhs1) == SSA_NAME)
2306         rhs1 = get_val_for (rhs1, base);
2307       else if (TREE_CODE (rhs2) == SSA_NAME)
2308         rhs2 = get_val_for (rhs2, base);
2309       else
2310         gcc_unreachable ();
2311       return fold_build2 (gimple_assign_rhs_code (stmt),
2312                           gimple_expr_type (stmt), rhs1, rhs2);
2313     }
2314   else
2315     gcc_unreachable ();
2316 }
2317
2318
2319 /* Tries to count the number of iterations of LOOP till it exits by EXIT
2320    by brute force -- i.e. by determining the value of the operands of the
2321    condition at EXIT in first few iterations of the loop (assuming that
2322    these values are constant) and determining the first one in that the
2323    condition is not satisfied.  Returns the constant giving the number
2324    of the iterations of LOOP if successful, chrec_dont_know otherwise.  */
2325
2326 tree
2327 loop_niter_by_eval (struct loop *loop, edge exit)
2328 {
2329   tree acnd;
2330   tree op[2], val[2], next[2], aval[2];
2331   gphi *phi;
2332   gimple cond;
2333   unsigned i, j;
2334   enum tree_code cmp;
2335
2336   cond = last_stmt (exit->src);
2337   if (!cond || gimple_code (cond) != GIMPLE_COND)
2338     return chrec_dont_know;
2339
2340   cmp = gimple_cond_code (cond);
2341   if (exit->flags & EDGE_TRUE_VALUE)
2342     cmp = invert_tree_comparison (cmp, false);
2343
2344   switch (cmp)
2345     {
2346     case EQ_EXPR:
2347     case NE_EXPR:
2348     case GT_EXPR:
2349     case GE_EXPR:
2350     case LT_EXPR:
2351     case LE_EXPR:
2352       op[0] = gimple_cond_lhs (cond);
2353       op[1] = gimple_cond_rhs (cond);
2354       break;
2355
2356     default:
2357       return chrec_dont_know;
2358     }
2359
2360   for (j = 0; j < 2; j++)
2361     {
2362       if (is_gimple_min_invariant (op[j]))
2363         {
2364           val[j] = op[j];
2365           next[j] = NULL_TREE;
2366           op[j] = NULL_TREE;
2367         }
2368       else
2369         {
2370           phi = get_base_for (loop, op[j]);
2371           if (!phi)
2372             return chrec_dont_know;
2373           val[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
2374           next[j] = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
2375         }
2376     }
2377
2378   /* Don't issue signed overflow warnings.  */
2379   fold_defer_overflow_warnings ();
2380
2381   for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
2382     {
2383       for (j = 0; j < 2; j++)
2384         aval[j] = get_val_for (op[j], val[j]);
2385
2386       acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
2387       if (acnd && integer_zerop (acnd))
2388         {
2389           fold_undefer_and_ignore_overflow_warnings ();
2390           if (dump_file && (dump_flags & TDF_DETAILS))
2391             fprintf (dump_file,
2392                      "Proved that loop %d iterates %d times using brute force.\n",
2393                      loop->num, i);
2394           return build_int_cst (unsigned_type_node, i);
2395         }
2396
2397       for (j = 0; j < 2; j++)
2398         {
2399           val[j] = get_val_for (next[j], val[j]);
2400           if (!is_gimple_min_invariant (val[j]))
2401             {
2402               fold_undefer_and_ignore_overflow_warnings ();
2403               return chrec_dont_know;
2404             }
2405         }
2406     }
2407
2408   fold_undefer_and_ignore_overflow_warnings ();
2409
2410   return chrec_dont_know;
2411 }
2412
2413 /* Finds the exit of the LOOP by that the loop exits after a constant
2414    number of iterations and stores the exit edge to *EXIT.  The constant
2415    giving the number of iterations of LOOP is returned.  The number of
2416    iterations is determined using loop_niter_by_eval (i.e. by brute force
2417    evaluation).  If we are unable to find the exit for that loop_niter_by_eval
2418    determines the number of iterations, chrec_dont_know is returned.  */
2419
2420 tree
2421 find_loop_niter_by_eval (struct loop *loop, edge *exit)
2422 {
2423   unsigned i;
2424   vec<edge> exits = get_loop_exit_edges (loop);
2425   edge ex;
2426   tree niter = NULL_TREE, aniter;
2427
2428   *exit = NULL;
2429
2430   /* Loops with multiple exits are expensive to handle and less important.  */
2431   if (!flag_expensive_optimizations
2432       && exits.length () > 1)
2433     {
2434       exits.release ();
2435       return chrec_dont_know;
2436     }
2437
2438   FOR_EACH_VEC_ELT (exits, i, ex)
2439     {
2440       if (!just_once_each_iteration_p (loop, ex->src))
2441         continue;
2442
2443       aniter = loop_niter_by_eval (loop, ex);
2444       if (chrec_contains_undetermined (aniter))
2445         continue;
2446
2447       if (niter
2448           && !tree_int_cst_lt (aniter, niter))
2449         continue;
2450
2451       niter = aniter;
2452       *exit = ex;
2453     }
2454   exits.release ();
2455
2456   return niter ? niter : chrec_dont_know;
2457 }
2458
2459 /*
2460
2461    Analysis of upper bounds on number of iterations of a loop.
2462
2463 */
2464
2465 static widest_int derive_constant_upper_bound_ops (tree, tree,
2466                                                    enum tree_code, tree);
2467
2468 /* Returns a constant upper bound on the value of the right-hand side of
2469    an assignment statement STMT.  */
2470
2471 static widest_int
2472 derive_constant_upper_bound_assign (gimple stmt)
2473 {
2474   enum tree_code code = gimple_assign_rhs_code (stmt);
2475   tree op0 = gimple_assign_rhs1 (stmt);
2476   tree op1 = gimple_assign_rhs2 (stmt);
2477
2478   return derive_constant_upper_bound_ops (TREE_TYPE (gimple_assign_lhs (stmt)),
2479                                           op0, code, op1);
2480 }
2481
2482 /* Returns a constant upper bound on the value of expression VAL.  VAL
2483    is considered to be unsigned.  If its type is signed, its value must
2484    be nonnegative.  */
2485
2486 static widest_int
2487 derive_constant_upper_bound (tree val)
2488 {
2489   enum tree_code code;
2490   tree op0, op1;
2491
2492   extract_ops_from_tree (val, &code, &op0, &op1);
2493   return derive_constant_upper_bound_ops (TREE_TYPE (val), op0, code, op1);
2494 }
2495
2496 /* Returns a constant upper bound on the value of expression OP0 CODE OP1,
2497    whose type is TYPE.  The expression is considered to be unsigned.  If
2498    its type is signed, its value must be nonnegative.  */
2499
2500 static widest_int
2501 derive_constant_upper_bound_ops (tree type, tree op0,
2502                                  enum tree_code code, tree op1)
2503 {
2504   tree subtype, maxt;
2505   widest_int bnd, max, mmax, cst;
2506   gimple stmt;
2507
2508   if (INTEGRAL_TYPE_P (type))
2509     maxt = TYPE_MAX_VALUE (type);
2510   else
2511     maxt = upper_bound_in_type (type, type);
2512
2513   max = wi::to_widest (maxt);
2514
2515   switch (code)
2516     {
2517     case INTEGER_CST:
2518       return wi::to_widest (op0);
2519
2520     CASE_CONVERT:
2521       subtype = TREE_TYPE (op0);
2522       if (!TYPE_UNSIGNED (subtype)
2523           /* If TYPE is also signed, the fact that VAL is nonnegative implies
2524              that OP0 is nonnegative.  */
2525           && TYPE_UNSIGNED (type)
2526           && !tree_expr_nonnegative_p (op0))
2527         {
2528           /* If we cannot prove that the casted expression is nonnegative,
2529              we cannot establish more useful upper bound than the precision
2530              of the type gives us.  */
2531           return max;
2532         }
2533
2534       /* We now know that op0 is an nonnegative value.  Try deriving an upper
2535          bound for it.  */
2536       bnd = derive_constant_upper_bound (op0);
2537
2538       /* If the bound does not fit in TYPE, max. value of TYPE could be
2539          attained.  */
2540       if (wi::ltu_p (max, bnd))
2541         return max;
2542
2543       return bnd;
2544
2545     case PLUS_EXPR:
2546     case POINTER_PLUS_EXPR:
2547     case MINUS_EXPR:
2548       if (TREE_CODE (op1) != INTEGER_CST
2549           || !tree_expr_nonnegative_p (op0))
2550         return max;
2551
2552       /* Canonicalize to OP0 - CST.  Consider CST to be signed, in order to
2553          choose the most logical way how to treat this constant regardless
2554          of the signedness of the type.  */
2555       cst = wi::sext (wi::to_widest (op1), TYPE_PRECISION (type));
2556       if (code != MINUS_EXPR)
2557         cst = -cst;
2558
2559       bnd = derive_constant_upper_bound (op0);
2560
2561       if (wi::neg_p (cst))
2562         {
2563           cst = -cst;
2564           /* Avoid CST == 0x80000...  */
2565           if (wi::neg_p (cst))
2566             return max;;
2567
2568           /* OP0 + CST.  We need to check that
2569              BND <= MAX (type) - CST.  */
2570
2571           mmax -= cst;
2572           if (wi::ltu_p (bnd, max))
2573             return max;
2574
2575           return bnd + cst;
2576         }
2577       else
2578         {
2579           /* OP0 - CST, where CST >= 0.
2580
2581              If TYPE is signed, we have already verified that OP0 >= 0, and we
2582              know that the result is nonnegative.  This implies that
2583              VAL <= BND - CST.
2584
2585              If TYPE is unsigned, we must additionally know that OP0 >= CST,
2586              otherwise the operation underflows.
2587            */
2588
2589           /* This should only happen if the type is unsigned; however, for
2590              buggy programs that use overflowing signed arithmetics even with
2591              -fno-wrapv, this condition may also be true for signed values.  */
2592           if (wi::ltu_p (bnd, cst))
2593             return max;
2594
2595           if (TYPE_UNSIGNED (type))
2596             {
2597               tree tem = fold_binary (GE_EXPR, boolean_type_node, op0,
2598                                       wide_int_to_tree (type, cst));
2599               if (!tem || integer_nonzerop (tem))
2600                 return max;
2601             }
2602
2603           bnd -= cst;
2604         }
2605
2606       return bnd;
2607
2608     case FLOOR_DIV_EXPR:
2609     case EXACT_DIV_EXPR:
2610       if (TREE_CODE (op1) != INTEGER_CST
2611           || tree_int_cst_sign_bit (op1))
2612         return max;
2613
2614       bnd = derive_constant_upper_bound (op0);
2615       return wi::udiv_floor (bnd, wi::to_widest (op1));
2616
2617     case BIT_AND_EXPR:
2618       if (TREE_CODE (op1) != INTEGER_CST
2619           || tree_int_cst_sign_bit (op1))
2620         return max;
2621       return wi::to_widest (op1);
2622
2623     case SSA_NAME:
2624       stmt = SSA_NAME_DEF_STMT (op0);
2625       if (gimple_code (stmt) != GIMPLE_ASSIGN
2626           || gimple_assign_lhs (stmt) != op0)
2627         return max;
2628       return derive_constant_upper_bound_assign (stmt);
2629
2630     default:
2631       return max;
2632     }
2633 }
2634
2635 /* Emit a -Waggressive-loop-optimizations warning if needed.  */
2636
2637 static void
2638 do_warn_aggressive_loop_optimizations (struct loop *loop,
2639                                        widest_int i_bound, gimple stmt)
2640 {
2641   /* Don't warn if the loop doesn't have known constant bound.  */
2642   if (!loop->nb_iterations
2643       || TREE_CODE (loop->nb_iterations) != INTEGER_CST
2644       || !warn_aggressive_loop_optimizations
2645       /* To avoid warning multiple times for the same loop,
2646          only start warning when we preserve loops.  */
2647       || (cfun->curr_properties & PROP_loops) == 0
2648       /* Only warn once per loop.  */
2649       || loop->warned_aggressive_loop_optimizations
2650       /* Only warn if undefined behavior gives us lower estimate than the
2651          known constant bound.  */
2652       || wi::cmpu (i_bound, wi::to_widest (loop->nb_iterations)) >= 0
2653       /* And undefined behavior happens unconditionally.  */
2654       || !dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (stmt)))
2655     return;
2656
2657   edge e = single_exit (loop);
2658   if (e == NULL)
2659     return;
2660
2661   gimple estmt = last_stmt (e->src);
2662   if (warning_at (gimple_location (stmt), OPT_Waggressive_loop_optimizations,
2663                   "iteration %E invokes undefined behavior",
2664                   wide_int_to_tree (TREE_TYPE (loop->nb_iterations),
2665                                     i_bound)))
2666     inform (gimple_location (estmt), "containing loop");
2667   loop->warned_aggressive_loop_optimizations = true;
2668 }
2669
2670 /* Records that AT_STMT is executed at most BOUND + 1 times in LOOP.  IS_EXIT
2671    is true if the loop is exited immediately after STMT, and this exit
2672    is taken at last when the STMT is executed BOUND + 1 times.
2673    REALISTIC is true if BOUND is expected to be close to the real number
2674    of iterations.  UPPER is true if we are sure the loop iterates at most
2675    BOUND times.  I_BOUND is a widest_int upper estimate on BOUND.  */
2676
2677 static void
2678 record_estimate (struct loop *loop, tree bound, const widest_int &i_bound,
2679                  gimple at_stmt, bool is_exit, bool realistic, bool upper)
2680 {
2681   widest_int delta;
2682
2683   if (dump_file && (dump_flags & TDF_DETAILS))
2684     {
2685       fprintf (dump_file, "Statement %s", is_exit ? "(exit)" : "");
2686       print_gimple_stmt (dump_file, at_stmt, 0, TDF_SLIM);
2687       fprintf (dump_file, " is %sexecuted at most ",
2688                upper ? "" : "probably ");
2689       print_generic_expr (dump_file, bound, TDF_SLIM);
2690       fprintf (dump_file, " (bounded by ");
2691       print_decu (i_bound, dump_file);
2692       fprintf (dump_file, ") + 1 times in loop %d.\n", loop->num);
2693     }
2694
2695   /* If the I_BOUND is just an estimate of BOUND, it rarely is close to the
2696      real number of iterations.  */
2697   if (TREE_CODE (bound) != INTEGER_CST)
2698     realistic = false;
2699   else
2700     gcc_checking_assert (i_bound == wi::to_widest (bound));
2701   if (!upper && !realistic)
2702     return;
2703
2704   /* If we have a guaranteed upper bound, record it in the appropriate
2705      list, unless this is an !is_exit bound (i.e. undefined behavior in
2706      at_stmt) in a loop with known constant number of iterations.  */
2707   if (upper
2708       && (is_exit
2709           || loop->nb_iterations == NULL_TREE
2710           || TREE_CODE (loop->nb_iterations) != INTEGER_CST))
2711     {
2712       struct nb_iter_bound *elt = ggc_alloc<nb_iter_bound> ();
2713
2714       elt->bound = i_bound;
2715       elt->stmt = at_stmt;
2716       elt->is_exit = is_exit;
2717       elt->next = loop->bounds;
2718       loop->bounds = elt;
2719     }
2720
2721   /* If statement is executed on every path to the loop latch, we can directly
2722      infer the upper bound on the # of iterations of the loop.  */
2723   if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (at_stmt)))
2724     return;
2725
2726   /* Update the number of iteration estimates according to the bound.
2727      If at_stmt is an exit then the loop latch is executed at most BOUND times,
2728      otherwise it can be executed BOUND + 1 times.  We will lower the estimate
2729      later if such statement must be executed on last iteration  */
2730   if (is_exit)
2731     delta = 0;
2732   else
2733     delta = 1;
2734   widest_int new_i_bound = i_bound + delta;
2735
2736   /* If an overflow occurred, ignore the result.  */
2737   if (wi::ltu_p (new_i_bound, delta))
2738     return;
2739
2740   if (upper && !is_exit)
2741     do_warn_aggressive_loop_optimizations (loop, new_i_bound, at_stmt);
2742   record_niter_bound (loop, new_i_bound, realistic, upper);
2743 }
2744
2745 /* Record the estimate on number of iterations of LOOP based on the fact that
2746    the induction variable BASE + STEP * i evaluated in STMT does not wrap and
2747    its values belong to the range <LOW, HIGH>.  REALISTIC is true if the
2748    estimated number of iterations is expected to be close to the real one.
2749    UPPER is true if we are sure the induction variable does not wrap.  */
2750
2751 static void
2752 record_nonwrapping_iv (struct loop *loop, tree base, tree step, gimple stmt,
2753                        tree low, tree high, bool realistic, bool upper)
2754 {
2755   tree niter_bound, extreme, delta;
2756   tree type = TREE_TYPE (base), unsigned_type;
2757   tree orig_base = base;
2758
2759   if (TREE_CODE (step) != INTEGER_CST || integer_zerop (step))
2760     return;
2761
2762   if (dump_file && (dump_flags & TDF_DETAILS))
2763     {
2764       fprintf (dump_file, "Induction variable (");
2765       print_generic_expr (dump_file, TREE_TYPE (base), TDF_SLIM);
2766       fprintf (dump_file, ") ");
2767       print_generic_expr (dump_file, base, TDF_SLIM);
2768       fprintf (dump_file, " + ");
2769       print_generic_expr (dump_file, step, TDF_SLIM);
2770       fprintf (dump_file, " * iteration does not wrap in statement ");
2771       print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2772       fprintf (dump_file, " in loop %d.\n", loop->num);
2773     }
2774
2775   unsigned_type = unsigned_type_for (type);
2776   base = fold_convert (unsigned_type, base);
2777   step = fold_convert (unsigned_type, step);
2778
2779   if (tree_int_cst_sign_bit (step))
2780     {
2781       wide_int min, max;
2782       extreme = fold_convert (unsigned_type, low);
2783       if (TREE_CODE (orig_base) == SSA_NAME
2784           && TREE_CODE (high) == INTEGER_CST
2785           && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
2786           && get_range_info (orig_base, &min, &max) == VR_RANGE
2787           && wi::gts_p (high, max))
2788         base = wide_int_to_tree (unsigned_type, max);
2789       else if (TREE_CODE (base) != INTEGER_CST)
2790         base = fold_convert (unsigned_type, high);
2791       delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
2792       step = fold_build1 (NEGATE_EXPR, unsigned_type, step);
2793     }
2794   else
2795     {
2796       wide_int min, max;
2797       extreme = fold_convert (unsigned_type, high);
2798       if (TREE_CODE (orig_base) == SSA_NAME
2799           && TREE_CODE (low) == INTEGER_CST
2800           && INTEGRAL_TYPE_P (TREE_TYPE (orig_base))
2801           && get_range_info (orig_base, &min, &max) == VR_RANGE
2802           && wi::gts_p (min, low))
2803         base = wide_int_to_tree (unsigned_type, min);
2804       else if (TREE_CODE (base) != INTEGER_CST)
2805         base = fold_convert (unsigned_type, low);
2806       delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
2807     }
2808
2809   /* STMT is executed at most NITER_BOUND + 1 times, since otherwise the value
2810      would get out of the range.  */
2811   niter_bound = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step);
2812   widest_int max = derive_constant_upper_bound (niter_bound);
2813   record_estimate (loop, niter_bound, max, stmt, false, realistic, upper);
2814 }
2815
2816 /* Determine information about number of iterations a LOOP from the index
2817    IDX of a data reference accessed in STMT.  RELIABLE is true if STMT is
2818    guaranteed to be executed in every iteration of LOOP.  Callback for
2819    for_each_index.  */
2820
2821 struct ilb_data
2822 {
2823   struct loop *loop;
2824   gimple stmt;
2825 };
2826
2827 static bool
2828 idx_infer_loop_bounds (tree base, tree *idx, void *dta)
2829 {
2830   struct ilb_data *data = (struct ilb_data *) dta;
2831   tree ev, init, step;
2832   tree low, high, type, next;
2833   bool sign, upper = true, at_end = false;
2834   struct loop *loop = data->loop;
2835   bool reliable = true;
2836
2837   if (TREE_CODE (base) != ARRAY_REF)
2838     return true;
2839
2840   /* For arrays at the end of the structure, we are not guaranteed that they
2841      do not really extend over their declared size.  However, for arrays of
2842      size greater than one, this is unlikely to be intended.  */
2843   if (array_at_struct_end_p (base))
2844     {
2845       at_end = true;
2846       upper = false;
2847     }
2848
2849   struct loop *dloop = loop_containing_stmt (data->stmt);
2850   if (!dloop)
2851     return true;
2852
2853   ev = analyze_scalar_evolution (dloop, *idx);
2854   ev = instantiate_parameters (loop, ev);
2855   init = initial_condition (ev);
2856   step = evolution_part_in_loop_num (ev, loop->num);
2857
2858   if (!init
2859       || !step
2860       || TREE_CODE (step) != INTEGER_CST
2861       || integer_zerop (step)
2862       || tree_contains_chrecs (init, NULL)
2863       || chrec_contains_symbols_defined_in_loop (init, loop->num))
2864     return true;
2865
2866   low = array_ref_low_bound (base);
2867   high = array_ref_up_bound (base);
2868
2869   /* The case of nonconstant bounds could be handled, but it would be
2870      complicated.  */
2871   if (TREE_CODE (low) != INTEGER_CST
2872       || !high
2873       || TREE_CODE (high) != INTEGER_CST)
2874     return true;
2875   sign = tree_int_cst_sign_bit (step);
2876   type = TREE_TYPE (step);
2877
2878   /* The array of length 1 at the end of a structure most likely extends
2879      beyond its bounds.  */
2880   if (at_end
2881       && operand_equal_p (low, high, 0))
2882     return true;
2883
2884   /* In case the relevant bound of the array does not fit in type, or
2885      it does, but bound + step (in type) still belongs into the range of the
2886      array, the index may wrap and still stay within the range of the array
2887      (consider e.g. if the array is indexed by the full range of
2888      unsigned char).
2889
2890      To make things simpler, we require both bounds to fit into type, although
2891      there are cases where this would not be strictly necessary.  */
2892   if (!int_fits_type_p (high, type)
2893       || !int_fits_type_p (low, type))
2894     return true;
2895   low = fold_convert (type, low);
2896   high = fold_convert (type, high);
2897
2898   if (sign)
2899     next = fold_binary (PLUS_EXPR, type, low, step);
2900   else
2901     next = fold_binary (PLUS_EXPR, type, high, step);
2902
2903   if (tree_int_cst_compare (low, next) <= 0
2904       && tree_int_cst_compare (next, high) <= 0)
2905     return true;
2906
2907   /* If access is not executed on every iteration, we must ensure that overlow may
2908      not make the access valid later.  */
2909   if (!dominated_by_p (CDI_DOMINATORS, loop->latch, gimple_bb (data->stmt))
2910       && scev_probably_wraps_p (initial_condition_in_loop_num (ev, loop->num),
2911                                 step, data->stmt, loop, true))
2912     reliable = false;
2913
2914   record_nonwrapping_iv (loop, init, step, data->stmt, low, high, reliable, upper);
2915   return true;
2916 }
2917
2918 /* Determine information about number of iterations a LOOP from the bounds
2919    of arrays in the data reference REF accessed in STMT.  RELIABLE is true if
2920    STMT is guaranteed to be executed in every iteration of LOOP.*/
2921
2922 static void
2923 infer_loop_bounds_from_ref (struct loop *loop, gimple stmt, tree ref)
2924 {
2925   struct ilb_data data;
2926
2927   data.loop = loop;
2928   data.stmt = stmt;
2929   for_each_index (&ref, idx_infer_loop_bounds, &data);
2930 }
2931
2932 /* Determine information about number of iterations of a LOOP from the way
2933    arrays are used in STMT.  RELIABLE is true if STMT is guaranteed to be
2934    executed in every iteration of LOOP.  */
2935
2936 static void
2937 infer_loop_bounds_from_array (struct loop *loop, gimple stmt)
2938 {
2939   if (is_gimple_assign (stmt))
2940     {
2941       tree op0 = gimple_assign_lhs (stmt);
2942       tree op1 = gimple_assign_rhs1 (stmt);
2943
2944       /* For each memory access, analyze its access function
2945          and record a bound on the loop iteration domain.  */
2946       if (REFERENCE_CLASS_P (op0))
2947         infer_loop_bounds_from_ref (loop, stmt, op0);
2948
2949       if (REFERENCE_CLASS_P (op1))
2950         infer_loop_bounds_from_ref (loop, stmt, op1);
2951     }
2952   else if (is_gimple_call (stmt))
2953     {
2954       tree arg, lhs;
2955       unsigned i, n = gimple_call_num_args (stmt);
2956
2957       lhs = gimple_call_lhs (stmt);
2958       if (lhs && REFERENCE_CLASS_P (lhs))
2959         infer_loop_bounds_from_ref (loop, stmt, lhs);
2960
2961       for (i = 0; i < n; i++)
2962         {
2963           arg = gimple_call_arg (stmt, i);
2964           if (REFERENCE_CLASS_P (arg))
2965             infer_loop_bounds_from_ref (loop, stmt, arg);
2966         }
2967     }
2968 }
2969
2970 /* Determine information about number of iterations of a LOOP from the fact
2971    that pointer arithmetics in STMT does not overflow.  */
2972
2973 static void
2974 infer_loop_bounds_from_pointer_arith (struct loop *loop, gimple stmt)
2975 {
2976   tree def, base, step, scev, type, low, high;
2977   tree var, ptr;
2978
2979   if (!is_gimple_assign (stmt)
2980       || gimple_assign_rhs_code (stmt) != POINTER_PLUS_EXPR)
2981     return;
2982
2983   def = gimple_assign_lhs (stmt);
2984   if (TREE_CODE (def) != SSA_NAME)
2985     return;
2986
2987   type = TREE_TYPE (def);
2988   if (!nowrap_type_p (type))
2989     return;
2990
2991   ptr = gimple_assign_rhs1 (stmt);
2992   if (!expr_invariant_in_loop_p (loop, ptr))
2993     return;
2994
2995   var = gimple_assign_rhs2 (stmt);
2996   if (TYPE_PRECISION (type) != TYPE_PRECISION (TREE_TYPE (var)))
2997     return;
2998
2999   scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
3000   if (chrec_contains_undetermined (scev))
3001     return;
3002
3003   base = initial_condition_in_loop_num (scev, loop->num);
3004   step = evolution_part_in_loop_num (scev, loop->num);
3005
3006   if (!base || !step
3007       || TREE_CODE (step) != INTEGER_CST
3008       || tree_contains_chrecs (base, NULL)
3009       || chrec_contains_symbols_defined_in_loop (base, loop->num))
3010     return;
3011
3012   low = lower_bound_in_type (type, type);
3013   high = upper_bound_in_type (type, type);
3014
3015   /* In C, pointer arithmetic p + 1 cannot use a NULL pointer, and p - 1 cannot
3016      produce a NULL pointer.  The contrary would mean NULL points to an object,
3017      while NULL is supposed to compare unequal with the address of all objects.
3018      Furthermore, p + 1 cannot produce a NULL pointer and p - 1 cannot use a
3019      NULL pointer since that would mean wrapping, which we assume here not to
3020      happen.  So, we can exclude NULL from the valid range of pointer
3021      arithmetic.  */
3022   if (flag_delete_null_pointer_checks && int_cst_value (low) == 0)
3023     low = build_int_cstu (TREE_TYPE (low), TYPE_ALIGN_UNIT (TREE_TYPE (type)));
3024
3025   record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
3026 }
3027
3028 /* Determine information about number of iterations of a LOOP from the fact
3029    that signed arithmetics in STMT does not overflow.  */
3030
3031 static void
3032 infer_loop_bounds_from_signedness (struct loop *loop, gimple stmt)
3033 {
3034   tree def, base, step, scev, type, low, high;
3035
3036   if (gimple_code (stmt) != GIMPLE_ASSIGN)
3037     return;
3038
3039   def = gimple_assign_lhs (stmt);
3040
3041   if (TREE_CODE (def) != SSA_NAME)
3042     return;
3043
3044   type = TREE_TYPE (def);
3045   if (!INTEGRAL_TYPE_P (type)
3046       || !TYPE_OVERFLOW_UNDEFINED (type))
3047     return;
3048
3049   scev = instantiate_parameters (loop, analyze_scalar_evolution (loop, def));
3050   if (chrec_contains_undetermined (scev))
3051     return;
3052
3053   base = initial_condition_in_loop_num (scev, loop->num);
3054   step = evolution_part_in_loop_num (scev, loop->num);
3055
3056   if (!base || !step
3057       || TREE_CODE (step) != INTEGER_CST
3058       || tree_contains_chrecs (base, NULL)
3059       || chrec_contains_symbols_defined_in_loop (base, loop->num))
3060     return;
3061
3062   low = lower_bound_in_type (type, type);
3063   high = upper_bound_in_type (type, type);
3064
3065   record_nonwrapping_iv (loop, base, step, stmt, low, high, false, true);
3066 }
3067
3068 /* The following analyzers are extracting informations on the bounds
3069    of LOOP from the following undefined behaviors:
3070
3071    - data references should not access elements over the statically
3072      allocated size,
3073
3074    - signed variables should not overflow when flag_wrapv is not set.
3075 */
3076
3077 static void
3078 infer_loop_bounds_from_undefined (struct loop *loop)
3079 {
3080   unsigned i;
3081   basic_block *bbs;
3082   gimple_stmt_iterator bsi;
3083   basic_block bb;
3084   bool reliable;
3085
3086   bbs = get_loop_body (loop);
3087
3088   for (i = 0; i < loop->num_nodes; i++)
3089     {
3090       bb = bbs[i];
3091
3092       /* If BB is not executed in each iteration of the loop, we cannot
3093          use the operations in it to infer reliable upper bound on the
3094          # of iterations of the loop.  However, we can use it as a guess. 
3095          Reliable guesses come only from array bounds.  */
3096       reliable = dominated_by_p (CDI_DOMINATORS, loop->latch, bb);
3097
3098       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
3099         {
3100           gimple stmt = gsi_stmt (bsi);
3101
3102           infer_loop_bounds_from_array (loop, stmt);
3103
3104           if (reliable)
3105             {
3106               infer_loop_bounds_from_signedness (loop, stmt);
3107               infer_loop_bounds_from_pointer_arith (loop, stmt);
3108             }
3109         }
3110
3111     }
3112
3113   free (bbs);
3114 }
3115
3116 /* Compare wide ints, callback for qsort.  */
3117
3118 static int
3119 wide_int_cmp (const void *p1, const void *p2)
3120 {
3121   const widest_int *d1 = (const widest_int *) p1;
3122   const widest_int *d2 = (const widest_int *) p2;
3123   return wi::cmpu (*d1, *d2);
3124 }
3125
3126 /* Return index of BOUND in BOUNDS array sorted in increasing order.
3127    Lookup by binary search.  */
3128
3129 static int
3130 bound_index (vec<widest_int> bounds, const widest_int &bound)
3131 {
3132   unsigned int end = bounds.length ();
3133   unsigned int begin = 0;
3134
3135   /* Find a matching index by means of a binary search.  */
3136   while (begin != end)
3137     {
3138       unsigned int middle = (begin + end) / 2;
3139       widest_int index = bounds[middle];
3140
3141       if (index == bound)
3142         return middle;
3143       else if (wi::ltu_p (index, bound))
3144         begin = middle + 1;
3145       else
3146         end = middle;
3147     }
3148   gcc_unreachable ();
3149 }
3150
3151 /* We recorded loop bounds only for statements dominating loop latch (and thus
3152    executed each loop iteration).  If there are any bounds on statements not
3153    dominating the loop latch we can improve the estimate by walking the loop
3154    body and seeing if every path from loop header to loop latch contains
3155    some bounded statement.  */
3156
3157 static void
3158 discover_iteration_bound_by_body_walk (struct loop *loop)
3159 {
3160   struct nb_iter_bound *elt;
3161   vec<widest_int> bounds = vNULL;
3162   vec<vec<basic_block> > queues = vNULL;
3163   vec<basic_block> queue = vNULL;
3164   ptrdiff_t queue_index;
3165   ptrdiff_t latch_index = 0;
3166
3167   /* Discover what bounds may interest us.  */
3168   for (elt = loop->bounds; elt; elt = elt->next)
3169     {
3170       widest_int bound = elt->bound;
3171
3172       /* Exit terminates loop at given iteration, while non-exits produce undefined
3173          effect on the next iteration.  */
3174       if (!elt->is_exit)
3175         {
3176           bound += 1;
3177           /* If an overflow occurred, ignore the result.  */
3178           if (bound == 0)
3179             continue;
3180         }
3181
3182       if (!loop->any_upper_bound
3183           || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
3184         bounds.safe_push (bound);
3185     }
3186
3187   /* Exit early if there is nothing to do.  */
3188   if (!bounds.exists ())
3189     return;
3190
3191   if (dump_file && (dump_flags & TDF_DETAILS))
3192     fprintf (dump_file, " Trying to walk loop body to reduce the bound.\n");
3193
3194   /* Sort the bounds in decreasing order.  */
3195   bounds.qsort (wide_int_cmp);
3196
3197   /* For every basic block record the lowest bound that is guaranteed to
3198      terminate the loop.  */
3199
3200   hash_map<basic_block, ptrdiff_t> bb_bounds;
3201   for (elt = loop->bounds; elt; elt = elt->next)
3202     {
3203       widest_int bound = elt->bound;
3204       if (!elt->is_exit)
3205         {
3206           bound += 1;
3207           /* If an overflow occurred, ignore the result.  */
3208           if (bound == 0)
3209             continue;
3210         }
3211
3212       if (!loop->any_upper_bound
3213           || wi::ltu_p (bound, loop->nb_iterations_upper_bound))
3214         {
3215           ptrdiff_t index = bound_index (bounds, bound);
3216           ptrdiff_t *entry = bb_bounds.get (gimple_bb (elt->stmt));
3217           if (!entry)
3218             bb_bounds.put (gimple_bb (elt->stmt), index);
3219           else if ((ptrdiff_t)*entry > index)
3220             *entry = index;
3221         }
3222     }
3223
3224   hash_map<basic_block, ptrdiff_t> block_priority;
3225
3226   /* Perform shortest path discovery loop->header ... loop->latch.
3227
3228      The "distance" is given by the smallest loop bound of basic block
3229      present in the path and we look for path with largest smallest bound
3230      on it.
3231
3232      To avoid the need for fibonacci heap on double ints we simply compress
3233      double ints into indexes to BOUNDS array and then represent the queue
3234      as arrays of queues for every index.
3235      Index of BOUNDS.length() means that the execution of given BB has
3236      no bounds determined.
3237
3238      VISITED is a pointer map translating basic block into smallest index
3239      it was inserted into the priority queue with.  */
3240   latch_index = -1;
3241
3242   /* Start walk in loop header with index set to infinite bound.  */
3243   queue_index = bounds.length ();
3244   queues.safe_grow_cleared (queue_index + 1);
3245   queue.safe_push (loop->header);
3246   queues[queue_index] = queue;
3247   block_priority.put (loop->header, queue_index);
3248
3249   for (; queue_index >= 0; queue_index--)
3250     {
3251       if (latch_index < queue_index)
3252         {
3253           while (queues[queue_index].length ())
3254             {
3255               basic_block bb;
3256               ptrdiff_t bound_index = queue_index;
3257               edge e;
3258               edge_iterator ei;
3259
3260               queue = queues[queue_index];
3261               bb = queue.pop ();
3262
3263               /* OK, we later inserted the BB with lower priority, skip it.  */
3264               if (*block_priority.get (bb) > queue_index)
3265                 continue;
3266
3267               /* See if we can improve the bound.  */
3268               ptrdiff_t *entry = bb_bounds.get (bb);
3269               if (entry && *entry < bound_index)
3270                 bound_index = *entry;
3271
3272               /* Insert succesors into the queue, watch for latch edge
3273                  and record greatest index we saw.  */
3274               FOR_EACH_EDGE (e, ei, bb->succs)
3275                 {
3276                   bool insert = false;
3277
3278                   if (loop_exit_edge_p (loop, e))
3279                     continue;
3280
3281                   if (e == loop_latch_edge (loop)
3282                       && latch_index < bound_index)
3283                     latch_index = bound_index;
3284                   else if (!(entry = block_priority.get (e->dest)))
3285                     {
3286                       insert = true;
3287                       block_priority.put (e->dest, bound_index);
3288                     }
3289                   else if (*entry < bound_index)
3290                     {
3291                       insert = true;
3292                       *entry = bound_index;
3293                     }
3294                     
3295                   if (insert)
3296                     queues[bound_index].safe_push (e->dest);
3297                 }
3298             }
3299         }
3300       queues[queue_index].release ();
3301     }
3302
3303   gcc_assert (latch_index >= 0);
3304   if ((unsigned)latch_index < bounds.length ())
3305     {
3306       if (dump_file && (dump_flags & TDF_DETAILS))
3307         {
3308           fprintf (dump_file, "Found better loop bound ");
3309           print_decu (bounds[latch_index], dump_file);
3310           fprintf (dump_file, "\n");
3311         }
3312       record_niter_bound (loop, bounds[latch_index], false, true);
3313     }
3314
3315   queues.release ();
3316   bounds.release ();
3317 }
3318
3319 /* See if every path cross the loop goes through a statement that is known
3320    to not execute at the last iteration. In that case we can decrese iteration
3321    count by 1.  */
3322
3323 static void
3324 maybe_lower_iteration_bound (struct loop *loop)
3325 {
3326   hash_set<gimple> *not_executed_last_iteration = NULL;
3327   struct nb_iter_bound *elt;
3328   bool found_exit = false;
3329   vec<basic_block> queue = vNULL;
3330   vec<gimple> problem_stmts = vNULL;
3331   bitmap visited;
3332
3333   /* Collect all statements with interesting (i.e. lower than
3334      nb_iterations_upper_bound) bound on them. 
3335
3336      TODO: Due to the way record_estimate choose estimates to store, the bounds
3337      will be always nb_iterations_upper_bound-1.  We can change this to record
3338      also statements not dominating the loop latch and update the walk bellow
3339      to the shortest path algorthm.  */
3340   for (elt = loop->bounds; elt; elt = elt->next)
3341     {
3342       if (!elt->is_exit
3343           && wi::ltu_p (elt->bound, loop->nb_iterations_upper_bound))
3344         {
3345           if (!not_executed_last_iteration)
3346             not_executed_last_iteration = new hash_set<gimple>;
3347           not_executed_last_iteration->add (elt->stmt);
3348         }
3349     }
3350   if (!not_executed_last_iteration)
3351     return;
3352
3353   /* Start DFS walk in the loop header and see if we can reach the
3354      loop latch or any of the exits (including statements with side
3355      effects that may terminate the loop otherwise) without visiting
3356      any of the statements known to have undefined effect on the last
3357      iteration.  */
3358   queue.safe_push (loop->header);
3359   visited = BITMAP_ALLOC (NULL);
3360   bitmap_set_bit (visited, loop->header->index);
3361   found_exit = false;
3362
3363   do
3364     {
3365       basic_block bb = queue.pop ();
3366       gimple_stmt_iterator gsi;
3367       bool stmt_found = false;
3368
3369       /* Loop for possible exits and statements bounding the execution.  */
3370       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3371         {
3372           gimple stmt = gsi_stmt (gsi);
3373           if (not_executed_last_iteration->contains (stmt))
3374             {
3375               stmt_found = true;
3376               problem_stmts.safe_push (stmt);
3377               break;
3378             }
3379           if (gimple_has_side_effects (stmt))
3380             {
3381               found_exit = true;
3382               break;
3383             }
3384         }
3385       if (found_exit)
3386         break;
3387
3388       /* If no bounding statement is found, continue the walk.  */
3389       if (!stmt_found)
3390         {
3391           edge e;
3392           edge_iterator ei;
3393
3394           FOR_EACH_EDGE (e, ei, bb->succs)
3395             {
3396               if (loop_exit_edge_p (loop, e)
3397                   || e == loop_latch_edge (loop))
3398                 {
3399                   found_exit = true;
3400                   break;
3401                 }
3402               if (bitmap_set_bit (visited, e->dest->index))
3403                 queue.safe_push (e->dest);
3404             }
3405         }
3406     }
3407   while (queue.length () && !found_exit);
3408
3409   /* If every path through the loop reach bounding statement before exit,
3410      then we know the last iteration of the loop will have undefined effect
3411      and we can decrease number of iterations.  */
3412     
3413   if (!found_exit)
3414     {
3415       if (dump_file && (dump_flags & TDF_DETAILS))
3416         fprintf (dump_file, "Reducing loop iteration estimate by 1; "
3417                  "undefined statement must be executed at the last iteration.\n");
3418       record_niter_bound (loop, loop->nb_iterations_upper_bound - 1,
3419                           false, true);
3420
3421       if (warn_aggressive_loop_optimizations)
3422         {
3423           bool exit_warned = false;
3424           for (elt = loop->bounds; elt; elt = elt->next)
3425             {
3426               if (elt->is_exit
3427                   && wi::gtu_p (elt->bound, loop->nb_iterations_upper_bound))
3428                 {
3429                   basic_block bb = gimple_bb (elt->stmt);
3430                   edge exit_edge = EDGE_SUCC (bb, 0);
3431                   struct tree_niter_desc niter;
3432
3433                   if (!loop_exit_edge_p (loop, exit_edge))
3434                     exit_edge = EDGE_SUCC (bb, 1);
3435
3436                   if(number_of_iterations_exit (loop, exit_edge,
3437                                                 &niter, false, false)
3438                      && integer_onep (niter.assumptions)
3439                      && integer_zerop (niter.may_be_zero)
3440                      && niter.niter
3441                      && TREE_CODE (niter.niter) == INTEGER_CST
3442                      && wi::ltu_p (loop->nb_iterations_upper_bound,
3443                                    wi::to_widest (niter.niter)))
3444                    {
3445                      if (warning_at (gimple_location (elt->stmt),
3446                                      OPT_Waggressive_loop_optimizations,
3447                                      "loop exit may only be reached after undefined behavior"))
3448                        exit_warned = true;
3449                    }
3450                 }
3451             }
3452
3453           if (exit_warned && !problem_stmts.is_empty ())
3454             {
3455               gimple stmt;
3456               int index;
3457               FOR_EACH_VEC_ELT (problem_stmts, index, stmt)
3458                 inform (gimple_location (stmt),
3459                         "possible undefined statement is here");
3460             }
3461       }
3462     }
3463
3464   BITMAP_FREE (visited);
3465   queue.release ();
3466   problem_stmts.release ();
3467   delete not_executed_last_iteration;
3468 }
3469
3470 /* Records estimates on numbers of iterations of LOOP.  If USE_UNDEFINED_P
3471    is true also use estimates derived from undefined behavior.  */
3472
3473 static void
3474 estimate_numbers_of_iterations_loop (struct loop *loop)
3475 {
3476   vec<edge> exits;
3477   tree niter, type;
3478   unsigned i;
3479   struct tree_niter_desc niter_desc;
3480   edge ex;
3481   widest_int bound;
3482   edge likely_exit;
3483
3484   /* Give up if we already have tried to compute an estimation.  */
3485   if (loop->estimate_state != EST_NOT_COMPUTED)
3486     return;
3487
3488   loop->estimate_state = EST_AVAILABLE;
3489   /* Force estimate compuation but leave any existing upper bound in place.  */
3490   loop->any_estimate = false;
3491
3492   /* Ensure that loop->nb_iterations is computed if possible.  If it turns out
3493      to be constant, we avoid undefined behavior implied bounds and instead
3494      diagnose those loops with -Waggressive-loop-optimizations.  */
3495   number_of_latch_executions (loop);
3496
3497   exits = get_loop_exit_edges (loop);
3498   likely_exit = single_likely_exit (loop);
3499   FOR_EACH_VEC_ELT (exits, i, ex)
3500     {
3501       if (!number_of_iterations_exit (loop, ex, &niter_desc, false, false))
3502         continue;
3503
3504       niter = niter_desc.niter;
3505       type = TREE_TYPE (niter);
3506       if (TREE_CODE (niter_desc.may_be_zero) != INTEGER_CST)
3507         niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
3508                         build_int_cst (type, 0),
3509                         niter);
3510       record_estimate (loop, niter, niter_desc.max,
3511                        last_stmt (ex->src),
3512                        true, ex == likely_exit, true);
3513     }
3514   exits.release ();
3515
3516   if (flag_aggressive_loop_optimizations)
3517     infer_loop_bounds_from_undefined (loop);
3518
3519   discover_iteration_bound_by_body_walk (loop);
3520
3521   maybe_lower_iteration_bound (loop);
3522
3523   /* If we have a measured profile, use it to estimate the number of
3524      iterations.  */
3525   if (loop->header->count != 0)
3526     {
3527       gcov_type nit = expected_loop_iterations_unbounded (loop) + 1;
3528       bound = gcov_type_to_wide_int (nit);
3529       record_niter_bound (loop, bound, true, false);
3530     }
3531
3532   /* If we know the exact number of iterations of this loop, try to
3533      not break code with undefined behavior by not recording smaller
3534      maximum number of iterations.  */
3535   if (loop->nb_iterations
3536       && TREE_CODE (loop->nb_iterations) == INTEGER_CST)
3537     {
3538       loop->any_upper_bound = true;
3539       loop->nb_iterations_upper_bound = wi::to_widest (loop->nb_iterations);
3540     }
3541 }
3542
3543 /* Sets NIT to the estimated number of executions of the latch of the
3544    LOOP.  If CONSERVATIVE is true, we must be sure that NIT is at least as
3545    large as the number of iterations.  If we have no reliable estimate,
3546    the function returns false, otherwise returns true.  */
3547
3548 bool
3549 estimated_loop_iterations (struct loop *loop, widest_int *nit)
3550 {
3551   /* When SCEV information is available, try to update loop iterations
3552      estimate.  Otherwise just return whatever we recorded earlier.  */
3553   if (scev_initialized_p ())
3554     estimate_numbers_of_iterations_loop (loop);
3555
3556   return (get_estimated_loop_iterations (loop, nit));
3557 }
3558
3559 /* Similar to estimated_loop_iterations, but returns the estimate only
3560    if it fits to HOST_WIDE_INT.  If this is not the case, or the estimate
3561    on the number of iterations of LOOP could not be derived, returns -1.  */
3562
3563 HOST_WIDE_INT
3564 estimated_loop_iterations_int (struct loop *loop)
3565 {
3566   widest_int nit;
3567   HOST_WIDE_INT hwi_nit;
3568
3569   if (!estimated_loop_iterations (loop, &nit))
3570     return -1;
3571
3572   if (!wi::fits_shwi_p (nit))
3573     return -1;
3574   hwi_nit = nit.to_shwi ();
3575
3576   return hwi_nit < 0 ? -1 : hwi_nit;
3577 }
3578
3579
3580 /* Sets NIT to an upper bound for the maximum number of executions of the
3581    latch of the LOOP.  If we have no reliable estimate, the function returns
3582    false, otherwise returns true.  */
3583
3584 bool
3585 max_loop_iterations (struct loop *loop, widest_int *nit)
3586 {
3587   /* When SCEV information is available, try to update loop iterations
3588      estimate.  Otherwise just return whatever we recorded earlier.  */
3589   if (scev_initialized_p ())
3590     estimate_numbers_of_iterations_loop (loop);
3591
3592   return get_max_loop_iterations (loop, nit);
3593 }
3594
3595 /* Similar to max_loop_iterations, but returns the estimate only
3596    if it fits to HOST_WIDE_INT.  If this is not the case, or the estimate
3597    on the number of iterations of LOOP could not be derived, returns -1.  */
3598
3599 HOST_WIDE_INT
3600 max_loop_iterations_int (struct loop *loop)
3601 {
3602   widest_int nit;
3603   HOST_WIDE_INT hwi_nit;
3604
3605   if (!max_loop_iterations (loop, &nit))
3606     return -1;
3607
3608   if (!wi::fits_shwi_p (nit))
3609     return -1;
3610   hwi_nit = nit.to_shwi ();
3611
3612   return hwi_nit < 0 ? -1 : hwi_nit;
3613 }
3614
3615 /* Returns an estimate for the number of executions of statements
3616    in the LOOP.  For statements before the loop exit, this exceeds
3617    the number of execution of the latch by one.  */
3618
3619 HOST_WIDE_INT
3620 estimated_stmt_executions_int (struct loop *loop)
3621 {
3622   HOST_WIDE_INT nit = estimated_loop_iterations_int (loop);
3623   HOST_WIDE_INT snit;
3624
3625   if (nit == -1)
3626     return -1;
3627
3628   snit = (HOST_WIDE_INT) ((unsigned HOST_WIDE_INT) nit + 1);
3629
3630   /* If the computation overflows, return -1.  */
3631   return snit < 0 ? -1 : snit;
3632 }
3633
3634 /* Sets NIT to the estimated maximum number of executions of the latch of the
3635    LOOP, plus one.  If we have no reliable estimate, the function returns
3636    false, otherwise returns true.  */
3637
3638 bool
3639 max_stmt_executions (struct loop *loop, widest_int *nit)
3640 {
3641   widest_int nit_minus_one;
3642
3643   if (!max_loop_iterations (loop, nit))
3644     return false;
3645
3646   nit_minus_one = *nit;
3647
3648   *nit += 1;
3649
3650   return wi::gtu_p (*nit, nit_minus_one);
3651 }
3652
3653 /* Sets NIT to the estimated number of executions of the latch of the
3654    LOOP, plus one.  If we have no reliable estimate, the function returns
3655    false, otherwise returns true.  */
3656
3657 bool
3658 estimated_stmt_executions (struct loop *loop, widest_int *nit)
3659 {
3660   widest_int nit_minus_one;
3661
3662   if (!estimated_loop_iterations (loop, nit))
3663     return false;
3664
3665   nit_minus_one = *nit;
3666
3667   *nit += 1;
3668
3669   return wi::gtu_p (*nit, nit_minus_one);
3670 }
3671
3672 /* Records estimates on numbers of iterations of loops.  */
3673
3674 void
3675 estimate_numbers_of_iterations (void)
3676 {
3677   struct loop *loop;
3678
3679   /* We don't want to issue signed overflow warnings while getting
3680      loop iteration estimates.  */
3681   fold_defer_overflow_warnings ();
3682
3683   FOR_EACH_LOOP (loop, 0)
3684     {
3685       estimate_numbers_of_iterations_loop (loop);
3686     }
3687
3688   fold_undefer_and_ignore_overflow_warnings ();
3689 }
3690
3691 /* Returns true if statement S1 dominates statement S2.  */
3692
3693 bool
3694 stmt_dominates_stmt_p (gimple s1, gimple s2)
3695 {
3696   basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
3697
3698   if (!bb1
3699       || s1 == s2)
3700     return true;
3701
3702   if (bb1 == bb2)
3703     {
3704       gimple_stmt_iterator bsi;
3705
3706       if (gimple_code (s2) == GIMPLE_PHI)
3707         return false;
3708
3709       if (gimple_code (s1) == GIMPLE_PHI)
3710         return true;
3711
3712       for (bsi = gsi_start_bb (bb1); gsi_stmt (bsi) != s2; gsi_next (&bsi))
3713         if (gsi_stmt (bsi) == s1)
3714           return true;
3715
3716       return false;
3717     }
3718
3719   return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
3720 }
3721
3722 /* Returns true when we can prove that the number of executions of
3723    STMT in the loop is at most NITER, according to the bound on
3724    the number of executions of the statement NITER_BOUND->stmt recorded in
3725    NITER_BOUND and fact that NITER_BOUND->stmt dominate STMT.
3726
3727    ??? This code can become quite a CPU hog - we can have many bounds,
3728    and large basic block forcing stmt_dominates_stmt_p to be queried
3729    many times on a large basic blocks, so the whole thing is O(n^2)
3730    for scev_probably_wraps_p invocation (that can be done n times).
3731
3732    It would make more sense (and give better answers) to remember BB
3733    bounds computed by discover_iteration_bound_by_body_walk.  */
3734
3735 static bool
3736 n_of_executions_at_most (gimple stmt,
3737                          struct nb_iter_bound *niter_bound,
3738                          tree niter)
3739 {
3740   widest_int bound = niter_bound->bound;
3741   tree nit_type = TREE_TYPE (niter), e;
3742   enum tree_code cmp;
3743
3744   gcc_assert (TYPE_UNSIGNED (nit_type));
3745
3746   /* If the bound does not even fit into NIT_TYPE, it cannot tell us that
3747      the number of iterations is small.  */
3748   if (!wi::fits_to_tree_p (bound, nit_type))
3749     return false;
3750
3751   /* We know that NITER_BOUND->stmt is executed at most NITER_BOUND->bound + 1
3752      times.  This means that:
3753
3754      -- if NITER_BOUND->is_exit is true, then everything after
3755         it at most NITER_BOUND->bound times.
3756
3757      -- If NITER_BOUND->is_exit is false, then if we can prove that when STMT
3758         is executed, then NITER_BOUND->stmt is executed as well in the same
3759         iteration then STMT is executed at most NITER_BOUND->bound + 1 times. 
3760
3761         If we can determine that NITER_BOUND->stmt is always executed
3762         after STMT, then STMT is executed at most NITER_BOUND->bound + 2 times.
3763         We conclude that if both statements belong to the same
3764         basic block and STMT is before NITER_BOUND->stmt and there are no
3765         statements with side effects in between.  */
3766
3767   if (niter_bound->is_exit)
3768     {
3769       if (stmt == niter_bound->stmt
3770           || !stmt_dominates_stmt_p (niter_bound->stmt, stmt))
3771         return false;
3772       cmp = GE_EXPR;
3773     }
3774   else
3775     {
3776       if (!stmt_dominates_stmt_p (niter_bound->stmt, stmt))
3777         {
3778           gimple_stmt_iterator bsi;
3779           if (gimple_bb (stmt) != gimple_bb (niter_bound->stmt)
3780               || gimple_code (stmt) == GIMPLE_PHI
3781               || gimple_code (niter_bound->stmt) == GIMPLE_PHI)
3782             return false;
3783
3784           /* By stmt_dominates_stmt_p we already know that STMT appears
3785              before NITER_BOUND->STMT.  Still need to test that the loop
3786              can not be terinated by a side effect in between.  */
3787           for (bsi = gsi_for_stmt (stmt); gsi_stmt (bsi) != niter_bound->stmt;
3788                gsi_next (&bsi))
3789             if (gimple_has_side_effects (gsi_stmt (bsi)))
3790                return false;
3791           bound += 1;
3792           if (bound == 0
3793               || !wi::fits_to_tree_p (bound, nit_type))
3794             return false;
3795         }
3796       cmp = GT_EXPR;
3797     }
3798
3799   e = fold_binary (cmp, boolean_type_node,
3800                    niter, wide_int_to_tree (nit_type, bound));
3801   return e && integer_nonzerop (e);
3802 }
3803
3804 /* Returns true if the arithmetics in TYPE can be assumed not to wrap.  */
3805
3806 bool
3807 nowrap_type_p (tree type)
3808 {
3809   if (INTEGRAL_TYPE_P (type)
3810       && TYPE_OVERFLOW_UNDEFINED (type))
3811     return true;
3812
3813   if (POINTER_TYPE_P (type))
3814     return true;
3815
3816   return false;
3817 }
3818
3819 /* Return false only when the induction variable BASE + STEP * I is
3820    known to not overflow: i.e. when the number of iterations is small
3821    enough with respect to the step and initial condition in order to
3822    keep the evolution confined in TYPEs bounds.  Return true when the
3823    iv is known to overflow or when the property is not computable.
3824
3825    USE_OVERFLOW_SEMANTICS is true if this function should assume that
3826    the rules for overflow of the given language apply (e.g., that signed
3827    arithmetics in C does not overflow).  */
3828
3829 bool
3830 scev_probably_wraps_p (tree base, tree step,
3831                        gimple at_stmt, struct loop *loop,
3832                        bool use_overflow_semantics)
3833 {
3834   tree delta, step_abs;
3835   tree unsigned_type, valid_niter;
3836   tree type = TREE_TYPE (step);
3837   tree e;
3838   widest_int niter;
3839   struct nb_iter_bound *bound;
3840
3841   /* FIXME: We really need something like
3842      http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html.
3843
3844      We used to test for the following situation that frequently appears
3845      during address arithmetics:
3846
3847        D.1621_13 = (long unsigned intD.4) D.1620_12;
3848        D.1622_14 = D.1621_13 * 8;
3849        D.1623_15 = (doubleD.29 *) D.1622_14;
3850
3851      And derived that the sequence corresponding to D_14
3852      can be proved to not wrap because it is used for computing a
3853      memory access; however, this is not really the case -- for example,
3854      if D_12 = (unsigned char) [254,+,1], then D_14 has values
3855      2032, 2040, 0, 8, ..., but the code is still legal.  */
3856
3857   if (chrec_contains_undetermined (base)
3858       || chrec_contains_undetermined (step))
3859     return true;
3860
3861   if (integer_zerop (step))
3862     return false;
3863
3864   /* If we can use the fact that signed and pointer arithmetics does not
3865      wrap, we are done.  */
3866   if (use_overflow_semantics && nowrap_type_p (TREE_TYPE (base)))
3867     return false;
3868
3869   /* To be able to use estimates on number of iterations of the loop,
3870      we must have an upper bound on the absolute value of the step.  */
3871   if (TREE_CODE (step) != INTEGER_CST)
3872     return true;
3873
3874   /* Don't issue signed overflow warnings.  */
3875   fold_defer_overflow_warnings ();
3876
3877   /* Otherwise, compute the number of iterations before we reach the
3878      bound of the type, and verify that the loop is exited before this
3879      occurs.  */
3880   unsigned_type = unsigned_type_for (type);
3881   base = fold_convert (unsigned_type, base);
3882
3883   if (tree_int_cst_sign_bit (step))
3884     {
3885       tree extreme = fold_convert (unsigned_type,
3886                                    lower_bound_in_type (type, type));
3887       delta = fold_build2 (MINUS_EXPR, unsigned_type, base, extreme);
3888       step_abs = fold_build1 (NEGATE_EXPR, unsigned_type,
3889                               fold_convert (unsigned_type, step));
3890     }
3891   else
3892     {
3893       tree extreme = fold_convert (unsigned_type,
3894                                    upper_bound_in_type (type, type));
3895       delta = fold_build2 (MINUS_EXPR, unsigned_type, extreme, base);
3896       step_abs = fold_convert (unsigned_type, step);
3897     }
3898
3899   valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
3900
3901   estimate_numbers_of_iterations_loop (loop);
3902
3903   if (max_loop_iterations (loop, &niter)
3904       && wi::fits_to_tree_p (niter, TREE_TYPE (valid_niter))
3905       && (e = fold_binary (GT_EXPR, boolean_type_node, valid_niter,
3906                            wide_int_to_tree (TREE_TYPE (valid_niter),
3907                                              niter))) != NULL
3908       && integer_nonzerop (e))
3909     {
3910       fold_undefer_and_ignore_overflow_warnings ();
3911       return false;
3912     }
3913   if (at_stmt)
3914     for (bound = loop->bounds; bound; bound = bound->next)
3915       {
3916         if (n_of_executions_at_most (at_stmt, bound, valid_niter))
3917           {
3918             fold_undefer_and_ignore_overflow_warnings ();
3919             return false;
3920           }
3921       }
3922
3923   fold_undefer_and_ignore_overflow_warnings ();
3924
3925   /* At this point we still don't have a proof that the iv does not
3926      overflow: give up.  */
3927   return true;
3928 }
3929
3930 /* Frees the information on upper bounds on numbers of iterations of LOOP.  */
3931
3932 void
3933 free_numbers_of_iterations_estimates_loop (struct loop *loop)
3934 {
3935   struct nb_iter_bound *bound, *next;
3936
3937   loop->nb_iterations = NULL;
3938   loop->estimate_state = EST_NOT_COMPUTED;
3939   for (bound = loop->bounds; bound; bound = next)
3940     {
3941       next = bound->next;
3942       ggc_free (bound);
3943     }
3944
3945   loop->bounds = NULL;
3946 }
3947
3948 /* Frees the information on upper bounds on numbers of iterations of loops.  */
3949
3950 void
3951 free_numbers_of_iterations_estimates (void)
3952 {
3953   struct loop *loop;
3954
3955   FOR_EACH_LOOP (loop, 0)
3956     {
3957       free_numbers_of_iterations_estimates_loop (loop);
3958     }
3959 }
3960
3961 /* Substitute value VAL for ssa name NAME inside expressions held
3962    at LOOP.  */
3963
3964 void
3965 substitute_in_loop_info (struct loop *loop, tree name, tree val)
3966 {
3967   loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);
3968 }