OSDN Git Service

2006-01-19 Paolo Bonzini <bonzini@gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-niter.c
1 /* Functions to determine/estimate number of iterations of a loop.
2    Copyright (C) 2004, 2005 Free Software Foundation, Inc.
3    
4 This file is part of GCC.
5    
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10    
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15    
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING.  If not, write to the Free
18 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "hard-reg-set.h"
29 #include "basic-block.h"
30 #include "output.h"
31 #include "diagnostic.h"
32 #include "intl.h"
33 #include "tree-flow.h"
34 #include "tree-dump.h"
35 #include "cfgloop.h"
36 #include "tree-pass.h"
37 #include "ggc.h"
38 #include "tree-chrec.h"
39 #include "tree-scalar-evolution.h"
40 #include "tree-data-ref.h"
41 #include "params.h"
42 #include "flags.h"
43 #include "toplev.h"
44 #include "tree-inline.h"
45
46 #define SWAP(X, Y) do { void *tmp = (X); (X) = (Y); (Y) = tmp; } while (0)
47
48
49 /*
50
51    Analysis of number of iterations of an affine exit test.
52
53 */
54
55 /* Returns true if ARG is either NULL_TREE or constant zero.  Unlike
56    integer_zerop, it does not care about overflow flags.  */
57
58 bool
59 zero_p (tree arg)
60 {
61   if (!arg)
62     return true;
63
64   if (TREE_CODE (arg) != INTEGER_CST)
65     return false;
66
67   return (TREE_INT_CST_LOW (arg) == 0 && TREE_INT_CST_HIGH (arg) == 0);
68 }
69
70 /* Returns true if ARG a nonzero constant.  Unlike integer_nonzerop, it does
71    not care about overflow flags.  */
72
73 static bool
74 nonzero_p (tree arg)
75 {
76   if (!arg)
77     return false;
78
79   if (TREE_CODE (arg) != INTEGER_CST)
80     return false;
81
82   return (TREE_INT_CST_LOW (arg) != 0 || TREE_INT_CST_HIGH (arg) != 0);
83 }
84
85 /* Returns inverse of X modulo 2^s, where MASK = 2^s-1.  */
86
87 static tree
88 inverse (tree x, tree mask)
89 {
90   tree type = TREE_TYPE (x);
91   tree rslt;
92   unsigned ctr = tree_floor_log2 (mask);
93
94   if (TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT)
95     {
96       unsigned HOST_WIDE_INT ix;
97       unsigned HOST_WIDE_INT imask;
98       unsigned HOST_WIDE_INT irslt = 1;
99
100       gcc_assert (cst_and_fits_in_hwi (x));
101       gcc_assert (cst_and_fits_in_hwi (mask));
102
103       ix = int_cst_value (x);
104       imask = int_cst_value (mask);
105
106       for (; ctr; ctr--)
107         {
108           irslt *= ix;
109           ix *= ix;
110         }
111       irslt &= imask;
112
113       rslt = build_int_cst_type (type, irslt);
114     }
115   else
116     {
117       rslt = build_int_cst_type (type, 1);
118       for (; ctr; ctr--)
119         {
120           rslt = int_const_binop (MULT_EXPR, rslt, x, 0);
121           x = int_const_binop (MULT_EXPR, x, x, 0);
122         }
123       rslt = int_const_binop (BIT_AND_EXPR, rslt, mask, 0);
124     }
125
126   return rslt;
127 }
128
129 /* Determines number of iterations of loop whose ending condition
130    is IV <> FINAL.  TYPE is the type of the iv.  The number of
131    iterations is stored to NITER.  NEVER_INFINITE is true if
132    we know that the loop cannot be infinite (we derived this
133    earlier, and possibly set NITER->assumptions to make sure this
134    is the case.  */
135
136 static bool
137 number_of_iterations_ne (tree type, affine_iv *iv, tree final,
138                          struct tree_niter_desc *niter, bool never_infinite)
139 {
140   tree niter_type = unsigned_type_for (type);
141   tree s, c, d, bits, assumption, tmp, bound;
142
143   /* Rearrange the terms so that we get inequality s * i <> c, with s
144      positive.  Also cast everything to the unsigned type.  */
145   if (tree_int_cst_sign_bit (iv->step))
146     {
147       s = fold_convert (niter_type,
148                         fold_build1 (NEGATE_EXPR, type, iv->step));
149       c = fold_build2 (MINUS_EXPR, niter_type,
150                        fold_convert (niter_type, iv->base),
151                        fold_convert (niter_type, final));
152     }
153   else
154     {
155       s = fold_convert (niter_type, iv->step);
156       c = fold_build2 (MINUS_EXPR, niter_type,
157                        fold_convert (niter_type, final),
158                        fold_convert (niter_type, iv->base));
159     }
160
161   /* First the trivial cases -- when the step is 1.  */
162   if (integer_onep (s))
163     {
164       niter->niter = c;
165       return true;
166     }
167
168   /* Let nsd (step, size of mode) = d.  If d does not divide c, the loop
169      is infinite.  Otherwise, the number of iterations is
170      (inverse(s/d) * (c/d)) mod (size of mode/d).  */
171   bits = num_ending_zeros (s);
172   bound = build_low_bits_mask (niter_type,
173                                (TYPE_PRECISION (niter_type)
174                                 - tree_low_cst (bits, 1)));
175
176   d = fold_binary_to_constant (LSHIFT_EXPR, niter_type,
177                                build_int_cst_type (niter_type, 1), bits);
178   s = fold_binary_to_constant (RSHIFT_EXPR, niter_type, s, bits);
179
180   if (!never_infinite)
181     {
182       /* If we cannot assume that the loop is not infinite, record the
183          assumptions for divisibility of c.  */
184       assumption = fold_build2 (FLOOR_MOD_EXPR, niter_type, c, d);
185       assumption = fold_build2 (EQ_EXPR, boolean_type_node,
186                                 assumption, build_int_cst (niter_type, 0));
187       if (!nonzero_p (assumption))
188         niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
189                                           niter->assumptions, assumption);
190     }
191       
192   c = fold_build2 (EXACT_DIV_EXPR, niter_type, c, d);
193   tmp = fold_build2 (MULT_EXPR, niter_type, c, inverse (s, bound));
194   niter->niter = fold_build2 (BIT_AND_EXPR, niter_type, tmp, bound);
195   return true;
196 }
197
198 /* Checks whether we can determine the final value of the control variable
199    of the loop with ending condition IV0 < IV1 (computed in TYPE).
200    DELTA is the difference IV1->base - IV0->base, STEP is the absolute value
201    of the step.  The assumptions necessary to ensure that the computation
202    of the final value does not overflow are recorded in NITER.  If we
203    find the final value, we adjust DELTA and return TRUE.  Otherwise
204    we return false.  */
205
206 static bool
207 number_of_iterations_lt_to_ne (tree type, affine_iv *iv0, affine_iv *iv1,
208                                struct tree_niter_desc *niter,
209                                tree *delta, tree step)
210 {
211   tree niter_type = TREE_TYPE (step);
212   tree mod = fold_build2 (FLOOR_MOD_EXPR, niter_type, *delta, step);
213   tree tmod;
214   tree assumption = boolean_true_node, bound, noloop;
215
216   if (TREE_CODE (mod) != INTEGER_CST)
217     return false;
218   if (nonzero_p (mod))
219     mod = fold_build2 (MINUS_EXPR, niter_type, step, mod);
220   tmod = fold_convert (type, mod);
221
222   if (nonzero_p (iv0->step))
223     {
224       /* The final value of the iv is iv1->base + MOD, assuming that this
225          computation does not overflow, and that
226          iv0->base <= iv1->base + MOD.  */
227       if (!iv1->no_overflow && !zero_p (mod))
228         {
229           bound = fold_build2 (MINUS_EXPR, type,
230                                TYPE_MAX_VALUE (type), tmod);
231           assumption = fold_build2 (LE_EXPR, boolean_type_node,
232                                     iv1->base, bound);
233           if (zero_p (assumption))
234             return false;
235         }
236       noloop = fold_build2 (GT_EXPR, boolean_type_node,
237                             iv0->base,
238                             fold_build2 (PLUS_EXPR, type,
239                                          iv1->base, tmod));
240     }
241   else
242     {
243       /* The final value of the iv is iv0->base - MOD, assuming that this
244          computation does not overflow, and that
245          iv0->base - MOD <= iv1->base. */
246       if (!iv0->no_overflow && !zero_p (mod))
247         {
248           bound = fold_build2 (PLUS_EXPR, type,
249                                TYPE_MIN_VALUE (type), tmod);
250           assumption = fold_build2 (GE_EXPR, boolean_type_node,
251                                     iv0->base, bound);
252           if (zero_p (assumption))
253             return false;
254         }
255       noloop = fold_build2 (GT_EXPR, boolean_type_node,
256                             fold_build2 (MINUS_EXPR, type,
257                                          iv0->base, tmod),
258                             iv1->base);
259     }
260
261   if (!nonzero_p (assumption))
262     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
263                                       niter->assumptions,
264                                       assumption);
265   if (!zero_p (noloop))
266     niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
267                                       niter->may_be_zero,
268                                       noloop);
269   *delta = fold_build2 (PLUS_EXPR, niter_type, *delta, mod);
270   return true;
271 }
272
273 /* Add assertions to NITER that ensure that the control variable of the loop
274    with ending condition IV0 < IV1 does not overflow.  Types of IV0 and IV1
275    are TYPE.  Returns false if we can prove that there is an overflow, true
276    otherwise.  STEP is the absolute value of the step.  */
277
278 static bool
279 assert_no_overflow_lt (tree type, affine_iv *iv0, affine_iv *iv1,
280                        struct tree_niter_desc *niter, tree step)
281 {
282   tree bound, d, assumption, diff;
283   tree niter_type = TREE_TYPE (step);
284
285   if (nonzero_p (iv0->step))
286     {
287       /* for (i = iv0->base; i < iv1->base; i += iv0->step) */
288       if (iv0->no_overflow)
289         return true;
290
291       /* If iv0->base is a constant, we can determine the last value before
292          overflow precisely; otherwise we conservatively assume
293          MAX - STEP + 1.  */
294
295       if (TREE_CODE (iv0->base) == INTEGER_CST)
296         {
297           d = fold_build2 (MINUS_EXPR, niter_type,
298                            fold_convert (niter_type, TYPE_MAX_VALUE (type)),
299                            fold_convert (niter_type, iv0->base));
300           diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
301         }
302       else
303         diff = fold_build2 (MINUS_EXPR, niter_type, step,
304                             build_int_cst_type (niter_type, 1));
305       bound = fold_build2 (MINUS_EXPR, type,
306                            TYPE_MAX_VALUE (type), fold_convert (type, diff));
307       assumption = fold_build2 (LE_EXPR, boolean_type_node,
308                                 iv1->base, bound);
309     }
310   else
311     {
312       /* for (i = iv1->base; i > iv0->base; i += iv1->step) */
313       if (iv1->no_overflow)
314         return true;
315
316       if (TREE_CODE (iv1->base) == INTEGER_CST)
317         {
318           d = fold_build2 (MINUS_EXPR, niter_type,
319                            fold_convert (niter_type, iv1->base),
320                            fold_convert (niter_type, TYPE_MIN_VALUE (type)));
321           diff = fold_build2 (FLOOR_MOD_EXPR, niter_type, d, step);
322         }
323       else
324         diff = fold_build2 (MINUS_EXPR, niter_type, step,
325                             build_int_cst_type (niter_type, 1));
326       bound = fold_build2 (PLUS_EXPR, type,
327                            TYPE_MIN_VALUE (type), fold_convert (type, diff));
328       assumption = fold_build2 (GE_EXPR, boolean_type_node,
329                                 iv0->base, bound);
330     }
331
332   if (zero_p (assumption))
333     return false;
334   if (!nonzero_p (assumption))
335     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
336                                       niter->assumptions, assumption);
337     
338   iv0->no_overflow = true;
339   iv1->no_overflow = true;
340   return true;
341 }
342
343 /* Add an assumption to NITER that a loop whose ending condition
344    is IV0 < IV1 rolls.  TYPE is the type of the control iv.  */
345
346 static void
347 assert_loop_rolls_lt (tree type, affine_iv *iv0, affine_iv *iv1,
348                       struct tree_niter_desc *niter)
349 {
350   tree assumption = boolean_true_node, bound, diff;
351   tree mbz, mbzl, mbzr;
352
353   if (nonzero_p (iv0->step))
354     {
355       diff = fold_build2 (MINUS_EXPR, type,
356                           iv0->step, build_int_cst_type (type, 1));
357
358       /* We need to know that iv0->base >= MIN + iv0->step - 1.  Since
359          0 address never belongs to any object, we can assume this for
360          pointers.  */
361       if (!POINTER_TYPE_P (type))
362         {
363           bound = fold_build2 (PLUS_EXPR, type,
364                                TYPE_MIN_VALUE (type), diff);
365           assumption = fold_build2 (GE_EXPR, boolean_type_node,
366                                     iv0->base, bound);
367         }
368
369       /* And then we can compute iv0->base - diff, and compare it with
370          iv1->base.  */      
371       mbzl = fold_build2 (MINUS_EXPR, type, iv0->base, diff);
372       mbzr = iv1->base;
373     }
374   else
375     {
376       diff = fold_build2 (PLUS_EXPR, type,
377                           iv1->step, build_int_cst_type (type, 1));
378
379       if (!POINTER_TYPE_P (type))
380         {
381           bound = fold_build2 (PLUS_EXPR, type,
382                                TYPE_MAX_VALUE (type), diff);
383           assumption = fold_build2 (LE_EXPR, boolean_type_node,
384                                     iv1->base, bound);
385         }
386
387       mbzl = iv0->base;
388       mbzr = fold_build2 (MINUS_EXPR, type, iv1->base, diff);
389     }
390
391   mbz = fold_build2 (GT_EXPR, boolean_type_node, mbzl, mbzr);
392
393   if (!nonzero_p (assumption))
394     niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
395                                       niter->assumptions, assumption);
396   if (!zero_p (mbz))
397     niter->may_be_zero = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
398                                       niter->may_be_zero, mbz);
399 }
400
401 /* Determines number of iterations of loop whose ending condition
402    is IV0 < IV1.  TYPE is the type of the iv.  The number of
403    iterations is stored to NITER.  */
404
405 static bool
406 number_of_iterations_lt (tree type, affine_iv *iv0, affine_iv *iv1,
407                          struct tree_niter_desc *niter,
408                          bool never_infinite ATTRIBUTE_UNUSED)
409 {
410   tree niter_type = unsigned_type_for (type);
411   tree delta, step, s;
412
413   delta = fold_build2 (MINUS_EXPR, niter_type,
414                        fold_convert (niter_type, iv1->base),
415                        fold_convert (niter_type, iv0->base));
416
417   /* First handle the special case that the step is +-1.  */
418   if ((iv0->step && integer_onep (iv0->step)
419        && zero_p (iv1->step))
420       || (iv1->step && integer_all_onesp (iv1->step)
421           && zero_p (iv0->step)))
422     {
423       /* for (i = iv0->base; i < iv1->base; i++)
424
425          or
426
427          for (i = iv1->base; i > iv0->base; i--).
428              
429          In both cases # of iterations is iv1->base - iv0->base, assuming that
430          iv1->base >= iv0->base.  */
431       niter->may_be_zero = fold_build2 (LT_EXPR, boolean_type_node,
432                                         iv1->base, iv0->base);
433       niter->niter = delta;
434       return true;
435     }
436
437   if (nonzero_p (iv0->step))
438     step = fold_convert (niter_type, iv0->step);
439   else
440     step = fold_convert (niter_type,
441                          fold_build1 (NEGATE_EXPR, type, iv1->step));
442
443   /* If we can determine the final value of the control iv exactly, we can
444      transform the condition to != comparison.  In particular, this will be
445      the case if DELTA is constant.  */
446   if (number_of_iterations_lt_to_ne (type, iv0, iv1, niter, &delta, step))
447     {
448       affine_iv zps;
449
450       zps.base = build_int_cst_type (niter_type, 0);
451       zps.step = step;
452       /* number_of_iterations_lt_to_ne will add assumptions that ensure that
453          zps does not overflow.  */
454       zps.no_overflow = true;
455
456       return number_of_iterations_ne (type, &zps, delta, niter, true);
457     }
458
459   /* Make sure that the control iv does not overflow.  */
460   if (!assert_no_overflow_lt (type, iv0, iv1, niter, step))
461     return false;
462
463   /* We determine the number of iterations as (delta + step - 1) / step.  For
464      this to work, we must know that iv1->base >= iv0->base - step + 1,
465      otherwise the loop does not roll.  */
466   assert_loop_rolls_lt (type, iv0, iv1, niter);
467
468   s = fold_build2 (MINUS_EXPR, niter_type,
469                    step, build_int_cst_type (niter_type, 1));
470   delta = fold_build2 (PLUS_EXPR, niter_type, delta, s);
471   niter->niter = fold_build2 (FLOOR_DIV_EXPR, niter_type, delta, step);
472   return true;
473 }
474
475 /* Determines number of iterations of loop whose ending condition
476    is IV0 <= IV1.  TYPE is the type of the iv.  The number of
477    iterations is stored to NITER.  NEVER_INFINITE is true if
478    we know that the loop cannot be infinite (we derived this
479    earlier, and possibly set NITER->assumptions to make sure this
480    is the case.  */
481
482 static bool
483 number_of_iterations_le (tree type, affine_iv *iv0, affine_iv *iv1,
484                          struct tree_niter_desc *niter, bool never_infinite)
485 {
486   tree assumption;
487
488   /* Say that IV0 is the control variable.  Then IV0 <= IV1 iff
489      IV0 < IV1 + 1, assuming that IV1 is not equal to the greatest
490      value of the type.  This we must know anyway, since if it is
491      equal to this value, the loop rolls forever.  */
492
493   if (!never_infinite)
494     {
495       if (nonzero_p (iv0->step))
496         assumption = fold_build2 (NE_EXPR, boolean_type_node,
497                                   iv1->base, TYPE_MAX_VALUE (type));
498       else
499         assumption = fold_build2 (NE_EXPR, boolean_type_node,
500                                   iv0->base, TYPE_MIN_VALUE (type));
501
502       if (zero_p (assumption))
503         return false;
504       if (!nonzero_p (assumption))
505         niter->assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
506                                           niter->assumptions, assumption);
507     }
508
509   if (nonzero_p (iv0->step))
510     iv1->base = fold_build2 (PLUS_EXPR, type,
511                              iv1->base, build_int_cst_type (type, 1));
512   else
513     iv0->base = fold_build2 (MINUS_EXPR, type,
514                              iv0->base, build_int_cst_type (type, 1));
515   return number_of_iterations_lt (type, iv0, iv1, niter, never_infinite);
516 }
517
518 /* Determine the number of iterations according to condition (for staying
519    inside loop) which compares two induction variables using comparison
520    operator CODE.  The induction variable on left side of the comparison
521    is IV0, the right-hand side is IV1.  Both induction variables must have
522    type TYPE, which must be an integer or pointer type.  The steps of the
523    ivs must be constants (or NULL_TREE, which is interpreted as constant zero).
524    
525    The results (number of iterations and assumptions as described in
526    comments at struct tree_niter_desc in tree-flow.h) are stored to NITER.
527    Returns false if it fails to determine number of iterations, true if it
528    was determined (possibly with some assumptions).  */
529
530 static bool
531 number_of_iterations_cond (tree type, affine_iv *iv0, enum tree_code code,
532                            affine_iv *iv1, struct tree_niter_desc *niter)
533 {
534   bool never_infinite;
535
536   /* The meaning of these assumptions is this:
537      if !assumptions
538        then the rest of information does not have to be valid
539      if may_be_zero then the loop does not roll, even if
540        niter != 0.  */
541   niter->assumptions = boolean_true_node;
542   niter->may_be_zero = boolean_false_node;
543   niter->niter = NULL_TREE;
544   niter->additional_info = boolean_true_node;
545
546   /* Make < comparison from > ones, and for NE_EXPR comparisons, ensure that
547      the control variable is on lhs.  */
548   if (code == GE_EXPR || code == GT_EXPR
549       || (code == NE_EXPR && zero_p (iv0->step)))
550     {
551       SWAP (iv0, iv1);
552       code = swap_tree_comparison (code);
553     }
554
555   if (POINTER_TYPE_P (type))
556     {
557       /* Comparison of pointers is undefined unless both iv0 and iv1 point
558          to the same object.  If they do, the control variable cannot wrap
559          (as wrap around the bounds of memory will never return a pointer
560          that would be guaranteed to point to the same object, even if we
561          avoid undefined behavior by casting to size_t and back).  */
562       iv0->no_overflow = true;
563       iv1->no_overflow = true;
564     }
565
566   /* If the control induction variable does not overflow, the loop obviously
567      cannot be infinite.  */
568   if (!zero_p (iv0->step) && iv0->no_overflow)
569     never_infinite = true;
570   else if (!zero_p (iv1->step) && iv1->no_overflow)
571     never_infinite = true;
572   else
573     never_infinite = false;
574
575   /* We can handle the case when neither of the sides of the comparison is
576      invariant, provided that the test is NE_EXPR.  This rarely occurs in
577      practice, but it is simple enough to manage.  */
578   if (!zero_p (iv0->step) && !zero_p (iv1->step))
579     {
580       if (code != NE_EXPR)
581         return false;
582
583       iv0->step = fold_binary_to_constant (MINUS_EXPR, type,
584                                            iv0->step, iv1->step);
585       iv0->no_overflow = false;
586       iv1->step = NULL_TREE;
587       iv1->no_overflow = true;
588     }
589
590   /* If the result of the comparison is a constant,  the loop is weird.  More
591      precise handling would be possible, but the situation is not common enough
592      to waste time on it.  */
593   if (zero_p (iv0->step) && zero_p (iv1->step))
594     return false;
595
596   /* Ignore loops of while (i-- < 10) type.  */
597   if (code != NE_EXPR)
598     {
599       if (iv0->step && tree_int_cst_sign_bit (iv0->step))
600         return false;
601
602       if (!zero_p (iv1->step) && !tree_int_cst_sign_bit (iv1->step))
603         return false;
604     }
605
606   /* If the loop exits immediatelly, there is nothing to do.  */
607   if (zero_p (fold_build2 (code, boolean_type_node, iv0->base, iv1->base)))
608     {
609       niter->niter = build_int_cst_type (unsigned_type_for (type), 0);
610       return true;
611     }
612
613   /* OK, now we know we have a senseful loop.  Handle several cases, depending
614      on what comparison operator is used.  */
615   switch (code)
616     {
617     case NE_EXPR:
618       gcc_assert (zero_p (iv1->step));
619       return number_of_iterations_ne (type, iv0, iv1->base, niter, never_infinite);
620     case LT_EXPR:
621       return number_of_iterations_lt (type, iv0, iv1, niter, never_infinite);
622     case LE_EXPR:
623       return number_of_iterations_le (type, iv0, iv1, niter, never_infinite);
624     default:
625       gcc_unreachable ();
626     }
627 }
628
629 /* Substitute NEW for OLD in EXPR and fold the result.  */
630
631 static tree
632 simplify_replace_tree (tree expr, tree old, tree new)
633 {
634   unsigned i, n;
635   tree ret = NULL_TREE, e, se;
636
637   if (!expr)
638     return NULL_TREE;
639
640   if (expr == old
641       || operand_equal_p (expr, old, 0))
642     return unshare_expr (new);
643
644   if (!EXPR_P (expr))
645     return expr;
646
647   n = TREE_CODE_LENGTH (TREE_CODE (expr));
648   for (i = 0; i < n; i++)
649     {
650       e = TREE_OPERAND (expr, i);
651       se = simplify_replace_tree (e, old, new);
652       if (e == se)
653         continue;
654
655       if (!ret)
656         ret = copy_node (expr);
657
658       TREE_OPERAND (ret, i) = se;
659     }
660
661   return (ret ? fold (ret) : expr);
662 }
663
664 /* Expand definitions of ssa names in EXPR as long as they are simple
665    enough, and return the new expression.  */
666
667 tree
668 expand_simple_operations (tree expr)
669 {
670   unsigned i, n;
671   tree ret = NULL_TREE, e, ee, stmt;
672   enum tree_code code;
673
674   if (expr == NULL_TREE)
675     return expr;
676
677   if (is_gimple_min_invariant (expr))
678     return expr;
679
680   code = TREE_CODE (expr);
681   if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (code)))
682     {
683       n = TREE_CODE_LENGTH (code);
684       for (i = 0; i < n; i++)
685         {
686           e = TREE_OPERAND (expr, i);
687           ee = expand_simple_operations (e);
688           if (e == ee)
689             continue;
690
691           if (!ret)
692             ret = copy_node (expr);
693
694           TREE_OPERAND (ret, i) = ee;
695         }
696
697       return (ret ? fold (ret) : expr);
698     }
699
700   if (TREE_CODE (expr) != SSA_NAME)
701     return expr;
702
703   stmt = SSA_NAME_DEF_STMT (expr);
704   if (TREE_CODE (stmt) != MODIFY_EXPR)
705     return expr;
706
707   e = TREE_OPERAND (stmt, 1);
708   if (/* Casts are simple.  */
709       TREE_CODE (e) != NOP_EXPR
710       && TREE_CODE (e) != CONVERT_EXPR
711       /* Copies are simple.  */
712       && TREE_CODE (e) != SSA_NAME
713       /* Assignments of invariants are simple.  */
714       && !is_gimple_min_invariant (e)
715       /* And increments and decrements by a constant are simple.  */
716       && !((TREE_CODE (e) == PLUS_EXPR
717             || TREE_CODE (e) == MINUS_EXPR)
718            && is_gimple_min_invariant (TREE_OPERAND (e, 1))))
719     return expr;
720
721   return expand_simple_operations (e);
722 }
723
724 /* Tries to simplify EXPR using the condition COND.  Returns the simplified
725    expression (or EXPR unchanged, if no simplification was possible).  */
726
727 static tree
728 tree_simplify_using_condition_1 (tree cond, tree expr)
729 {
730   bool changed;
731   tree e, te, e0, e1, e2, notcond;
732   enum tree_code code = TREE_CODE (expr);
733
734   if (code == INTEGER_CST)
735     return expr;
736
737   if (code == TRUTH_OR_EXPR
738       || code == TRUTH_AND_EXPR
739       || code == COND_EXPR)
740     {
741       changed = false;
742
743       e0 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 0));
744       if (TREE_OPERAND (expr, 0) != e0)
745         changed = true;
746
747       e1 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 1));
748       if (TREE_OPERAND (expr, 1) != e1)
749         changed = true;
750
751       if (code == COND_EXPR)
752         {
753           e2 = tree_simplify_using_condition_1 (cond, TREE_OPERAND (expr, 2));
754           if (TREE_OPERAND (expr, 2) != e2)
755             changed = true;
756         }
757       else
758         e2 = NULL_TREE;
759
760       if (changed)
761         {
762           if (code == COND_EXPR)
763             expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
764           else
765             expr = fold_build2 (code, boolean_type_node, e0, e1);
766         }
767
768       return expr;
769     }
770
771   /* In case COND is equality, we may be able to simplify EXPR by copy/constant
772      propagation, and vice versa.  Fold does not handle this, since it is
773      considered too expensive.  */
774   if (TREE_CODE (cond) == EQ_EXPR)
775     {
776       e0 = TREE_OPERAND (cond, 0);
777       e1 = TREE_OPERAND (cond, 1);
778
779       /* We know that e0 == e1.  Check whether we cannot simplify expr
780          using this fact.  */
781       e = simplify_replace_tree (expr, e0, e1);
782       if (zero_p (e) || nonzero_p (e))
783         return e;
784
785       e = simplify_replace_tree (expr, e1, e0);
786       if (zero_p (e) || nonzero_p (e))
787         return e;
788     }
789   if (TREE_CODE (expr) == EQ_EXPR)
790     {
791       e0 = TREE_OPERAND (expr, 0);
792       e1 = TREE_OPERAND (expr, 1);
793
794       /* If e0 == e1 (EXPR) implies !COND, then EXPR cannot be true.  */
795       e = simplify_replace_tree (cond, e0, e1);
796       if (zero_p (e))
797         return e;
798       e = simplify_replace_tree (cond, e1, e0);
799       if (zero_p (e))
800         return e;
801     }
802   if (TREE_CODE (expr) == NE_EXPR)
803     {
804       e0 = TREE_OPERAND (expr, 0);
805       e1 = TREE_OPERAND (expr, 1);
806
807       /* If e0 == e1 (!EXPR) implies !COND, then EXPR must be true.  */
808       e = simplify_replace_tree (cond, e0, e1);
809       if (zero_p (e))
810         return boolean_true_node;
811       e = simplify_replace_tree (cond, e1, e0);
812       if (zero_p (e))
813         return boolean_true_node;
814     }
815
816   te = expand_simple_operations (expr);
817
818   /* Check whether COND ==> EXPR.  */
819   notcond = invert_truthvalue (cond);
820   e = fold_binary (TRUTH_OR_EXPR, boolean_type_node, notcond, te);
821   if (nonzero_p (e))
822     return e;
823
824   /* Check whether COND ==> not EXPR.  */
825   e = fold_binary (TRUTH_AND_EXPR, boolean_type_node, cond, te);
826   if (e && zero_p (e))
827     return e;
828
829   return expr;
830 }
831
832 /* Tries to simplify EXPR using the condition COND.  Returns the simplified
833    expression (or EXPR unchanged, if no simplification was possible).
834    Wrapper around tree_simplify_using_condition_1 that ensures that chains
835    of simple operations in definitions of ssa names in COND are expanded,
836    so that things like casts or incrementing the value of the bound before
837    the loop do not cause us to fail.  */
838
839 static tree
840 tree_simplify_using_condition (tree cond, tree expr)
841 {
842   cond = expand_simple_operations (cond);
843
844   return tree_simplify_using_condition_1 (cond, expr);
845 }
846      
847 /* Tries to simplify EXPR using the conditions on entry to LOOP.
848    Record the conditions used for simplification to CONDS_USED.
849    Returns the simplified expression (or EXPR unchanged, if no
850    simplification was possible).*/
851
852 static tree
853 simplify_using_initial_conditions (struct loop *loop, tree expr,
854                                    tree *conds_used)
855 {
856   edge e;
857   basic_block bb;
858   tree exp, cond;
859
860   if (TREE_CODE (expr) == INTEGER_CST)
861     return expr;
862
863   for (bb = loop->header;
864        bb != ENTRY_BLOCK_PTR;
865        bb = get_immediate_dominator (CDI_DOMINATORS, bb))
866     {
867       if (!single_pred_p (bb))
868         continue;
869       e = single_pred_edge (bb);
870
871       if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
872         continue;
873
874       cond = COND_EXPR_COND (last_stmt (e->src));
875       if (e->flags & EDGE_FALSE_VALUE)
876         cond = invert_truthvalue (cond);
877       exp = tree_simplify_using_condition (cond, expr);
878
879       if (exp != expr)
880         *conds_used = fold_build2 (TRUTH_AND_EXPR,
881                                    boolean_type_node,
882                                    *conds_used,
883                                    cond);
884
885       expr = exp;
886     }
887
888   return expr;
889 }
890
891 /* Tries to simplify EXPR using the evolutions of the loop invariants
892    in the superloops of LOOP.  Returns the simplified expression
893    (or EXPR unchanged, if no simplification was possible).  */
894
895 static tree
896 simplify_using_outer_evolutions (struct loop *loop, tree expr)
897 {
898   enum tree_code code = TREE_CODE (expr);
899   bool changed;
900   tree e, e0, e1, e2;
901
902   if (is_gimple_min_invariant (expr))
903     return expr;
904
905   if (code == TRUTH_OR_EXPR
906       || code == TRUTH_AND_EXPR
907       || code == COND_EXPR)
908     {
909       changed = false;
910
911       e0 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 0));
912       if (TREE_OPERAND (expr, 0) != e0)
913         changed = true;
914
915       e1 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 1));
916       if (TREE_OPERAND (expr, 1) != e1)
917         changed = true;
918
919       if (code == COND_EXPR)
920         {
921           e2 = simplify_using_outer_evolutions (loop, TREE_OPERAND (expr, 2));
922           if (TREE_OPERAND (expr, 2) != e2)
923             changed = true;
924         }
925       else
926         e2 = NULL_TREE;
927
928       if (changed)
929         {
930           if (code == COND_EXPR)
931             expr = fold_build3 (code, boolean_type_node, e0, e1, e2);
932           else
933             expr = fold_build2 (code, boolean_type_node, e0, e1);
934         }
935
936       return expr;
937     }
938
939   e = instantiate_parameters (loop, expr);
940   if (is_gimple_min_invariant (e))
941     return e;
942
943   return expr;
944 }
945
946 /* Stores description of number of iterations of LOOP derived from
947    EXIT (an exit edge of the LOOP) in NITER.  Returns true if some
948    useful information could be derived (and fields of NITER has
949    meaning described in comments at struct tree_niter_desc
950    declaration), false otherwise.  If WARN is true and
951    -Wunsafe-loop-optimizations was given, warn if the optimizer is going to use
952    potentially unsafe assumptions.  */
953
954 bool
955 number_of_iterations_exit (struct loop *loop, edge exit,
956                            struct tree_niter_desc *niter,
957                            bool warn)
958 {
959   tree stmt, cond, type;
960   tree op0, op1;
961   enum tree_code code;
962   affine_iv iv0, iv1;
963
964   if (!dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src))
965     return false;
966
967   niter->assumptions = boolean_false_node;
968   stmt = last_stmt (exit->src);
969   if (!stmt || TREE_CODE (stmt) != COND_EXPR)
970     return false;
971
972   /* We want the condition for staying inside loop.  */
973   cond = COND_EXPR_COND (stmt);
974   if (exit->flags & EDGE_TRUE_VALUE)
975     cond = invert_truthvalue (cond);
976
977   code = TREE_CODE (cond);
978   switch (code)
979     {
980     case GT_EXPR:
981     case GE_EXPR:
982     case NE_EXPR:
983     case LT_EXPR:
984     case LE_EXPR:
985       break;
986
987     default:
988       return false;
989     }
990   
991   op0 = TREE_OPERAND (cond, 0);
992   op1 = TREE_OPERAND (cond, 1);
993   type = TREE_TYPE (op0);
994
995   if (TREE_CODE (type) != INTEGER_TYPE
996       && !POINTER_TYPE_P (type))
997     return false;
998      
999   if (!simple_iv (loop, stmt, op0, &iv0, false))
1000     return false;
1001   if (!simple_iv (loop, stmt, op1, &iv1, false))
1002     return false;
1003
1004   iv0.base = expand_simple_operations (iv0.base);
1005   iv1.base = expand_simple_operations (iv1.base);
1006   if (!number_of_iterations_cond (type, &iv0, code, &iv1, niter))
1007     return false;
1008
1009   if (optimize >= 3)
1010     {
1011       niter->assumptions = simplify_using_outer_evolutions (loop,
1012                                                             niter->assumptions);
1013       niter->may_be_zero = simplify_using_outer_evolutions (loop,
1014                                                             niter->may_be_zero);
1015       niter->niter = simplify_using_outer_evolutions (loop, niter->niter);
1016     }
1017
1018   niter->additional_info = boolean_true_node;
1019   niter->assumptions
1020           = simplify_using_initial_conditions (loop,
1021                                                niter->assumptions,
1022                                                &niter->additional_info);
1023   niter->may_be_zero
1024           = simplify_using_initial_conditions (loop,
1025                                                niter->may_be_zero,
1026                                                &niter->additional_info);
1027
1028   if (integer_onep (niter->assumptions))
1029     return true;
1030
1031   /* With -funsafe-loop-optimizations we assume that nothing bad can happen.
1032      But if we can prove that there is overflow or some other source of weird
1033      behavior, ignore the loop even with -funsafe-loop-optimizations.  */
1034   if (integer_zerop (niter->assumptions))
1035     return false;
1036
1037   if (flag_unsafe_loop_optimizations)
1038     niter->assumptions = boolean_true_node;
1039
1040   if (warn)
1041     {
1042       const char *wording;
1043       location_t loc = EXPR_LOCATION (stmt);
1044   
1045       /* We can provide a more specific warning if one of the operator is
1046          constant and the other advances by +1 or -1.  */
1047       if (!zero_p (iv1.step)
1048           ? (zero_p (iv0.step)
1049              && (integer_onep (iv1.step) || integer_all_onesp (iv1.step)))
1050           : (iv0.step
1051              && (integer_onep (iv0.step) || integer_all_onesp (iv0.step))))
1052         wording =
1053           flag_unsafe_loop_optimizations
1054           ? N_("assuming that the loop is not infinite")
1055           : N_("cannot optimize possibly infinite loops");
1056       else
1057         wording = 
1058           flag_unsafe_loop_optimizations
1059           ? N_("assuming that the loop counter does not overflow")
1060           : N_("cannot optimize loop, the loop counter may overflow");
1061
1062       if (LOCATION_LINE (loc) > 0)
1063         warning (OPT_Wunsafe_loop_optimizations, "%H%s", &loc, gettext (wording));
1064       else
1065         warning (OPT_Wunsafe_loop_optimizations, "%s", gettext (wording));
1066     }
1067
1068   return flag_unsafe_loop_optimizations;
1069 }
1070
1071 /* Try to determine the number of iterations of LOOP.  If we succeed,
1072    expression giving number of iterations is returned and *EXIT is
1073    set to the edge from that the information is obtained.  Otherwise
1074    chrec_dont_know is returned.  */
1075
1076 tree
1077 find_loop_niter (struct loop *loop, edge *exit)
1078 {
1079   unsigned n_exits, i;
1080   edge *exits = get_loop_exit_edges (loop, &n_exits);
1081   edge ex;
1082   tree niter = NULL_TREE, aniter;
1083   struct tree_niter_desc desc;
1084
1085   *exit = NULL;
1086   for (i = 0; i < n_exits; i++)
1087     {
1088       ex = exits[i];
1089       if (!just_once_each_iteration_p (loop, ex->src))
1090         continue;
1091
1092       if (!number_of_iterations_exit (loop, ex, &desc, false))
1093         continue;
1094
1095       if (nonzero_p (desc.may_be_zero))
1096         {
1097           /* We exit in the first iteration through this exit.
1098              We won't find anything better.  */
1099           niter = build_int_cst_type (unsigned_type_node, 0);
1100           *exit = ex;
1101           break;
1102         }
1103
1104       if (!zero_p (desc.may_be_zero))
1105         continue;
1106
1107       aniter = desc.niter;
1108
1109       if (!niter)
1110         {
1111           /* Nothing recorded yet.  */
1112           niter = aniter;
1113           *exit = ex;
1114           continue;
1115         }
1116
1117       /* Prefer constants, the lower the better.  */
1118       if (TREE_CODE (aniter) != INTEGER_CST)
1119         continue;
1120
1121       if (TREE_CODE (niter) != INTEGER_CST)
1122         {
1123           niter = aniter;
1124           *exit = ex;
1125           continue;
1126         }
1127
1128       if (tree_int_cst_lt (aniter, niter))
1129         {
1130           niter = aniter;
1131           *exit = ex;
1132           continue;
1133         }
1134     }
1135   free (exits);
1136
1137   return niter ? niter : chrec_dont_know;
1138 }
1139
1140 /*
1141
1142    Analysis of a number of iterations of a loop by a brute-force evaluation.
1143
1144 */
1145
1146 /* Bound on the number of iterations we try to evaluate.  */
1147
1148 #define MAX_ITERATIONS_TO_TRACK \
1149   ((unsigned) PARAM_VALUE (PARAM_MAX_ITERATIONS_TO_TRACK))
1150
1151 /* Returns the loop phi node of LOOP such that ssa name X is derived from its
1152    result by a chain of operations such that all but exactly one of their
1153    operands are constants.  */
1154
1155 static tree
1156 chain_of_csts_start (struct loop *loop, tree x)
1157 {
1158   tree stmt = SSA_NAME_DEF_STMT (x);
1159   tree use;
1160   basic_block bb = bb_for_stmt (stmt);
1161
1162   if (!bb
1163       || !flow_bb_inside_loop_p (loop, bb))
1164     return NULL_TREE;
1165   
1166   if (TREE_CODE (stmt) == PHI_NODE)
1167     {
1168       if (bb == loop->header)
1169         return stmt;
1170
1171       return NULL_TREE;
1172     }
1173
1174   if (TREE_CODE (stmt) != MODIFY_EXPR)
1175     return NULL_TREE;
1176
1177   if (!ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
1178     return NULL_TREE;
1179   if (SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_DEF) == NULL_DEF_OPERAND_P)
1180     return NULL_TREE;
1181
1182   use = SINGLE_SSA_TREE_OPERAND (stmt, SSA_OP_USE);
1183   if (use == NULL_USE_OPERAND_P)
1184     return NULL_TREE;
1185
1186   return chain_of_csts_start (loop, use);
1187 }
1188
1189 /* Determines whether the expression X is derived from a result of a phi node
1190    in header of LOOP such that
1191
1192    * the derivation of X consists only from operations with constants
1193    * the initial value of the phi node is constant
1194    * the value of the phi node in the next iteration can be derived from the
1195      value in the current iteration by a chain of operations with constants.
1196    
1197    If such phi node exists, it is returned.  If X is a constant, X is returned
1198    unchanged.  Otherwise NULL_TREE is returned.  */
1199
1200 static tree
1201 get_base_for (struct loop *loop, tree x)
1202 {
1203   tree phi, init, next;
1204
1205   if (is_gimple_min_invariant (x))
1206     return x;
1207
1208   phi = chain_of_csts_start (loop, x);
1209   if (!phi)
1210     return NULL_TREE;
1211
1212   init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1213   next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1214
1215   if (TREE_CODE (next) != SSA_NAME)
1216     return NULL_TREE;
1217
1218   if (!is_gimple_min_invariant (init))
1219     return NULL_TREE;
1220
1221   if (chain_of_csts_start (loop, next) != phi)
1222     return NULL_TREE;
1223
1224   return phi;
1225 }
1226
1227 /* Given an expression X, then 
1228  
1229    * if BASE is NULL_TREE, X must be a constant and we return X.
1230    * otherwise X is a SSA name, whose value in the considered loop is derived
1231      by a chain of operations with constant from a result of a phi node in
1232      the header of the loop.  Then we return value of X when the value of the
1233      result of this phi node is given by the constant BASE.  */
1234
1235 static tree
1236 get_val_for (tree x, tree base)
1237 {
1238   tree stmt, nx, val;
1239   use_operand_p op;
1240   ssa_op_iter iter;
1241
1242   if (!x)
1243     return base;
1244
1245   stmt = SSA_NAME_DEF_STMT (x);
1246   if (TREE_CODE (stmt) == PHI_NODE)
1247     return base;
1248
1249   FOR_EACH_SSA_USE_OPERAND (op, stmt, iter, SSA_OP_USE)
1250     {
1251       nx = USE_FROM_PTR (op);
1252       val = get_val_for (nx, base);
1253       SET_USE (op, val);
1254       val = fold (TREE_OPERAND (stmt, 1));
1255       SET_USE (op, nx);
1256       /* only iterate loop once.  */
1257       return val;
1258     }
1259
1260   /* Should never reach here.  */
1261   gcc_unreachable();
1262 }
1263
1264 /* Tries to count the number of iterations of LOOP till it exits by EXIT
1265    by brute force -- i.e. by determining the value of the operands of the
1266    condition at EXIT in first few iterations of the loop (assuming that
1267    these values are constant) and determining the first one in that the
1268    condition is not satisfied.  Returns the constant giving the number
1269    of the iterations of LOOP if successful, chrec_dont_know otherwise.  */
1270
1271 tree
1272 loop_niter_by_eval (struct loop *loop, edge exit)
1273 {
1274   tree cond, cnd, acnd;
1275   tree op[2], val[2], next[2], aval[2], phi[2];
1276   unsigned i, j;
1277   enum tree_code cmp;
1278
1279   cond = last_stmt (exit->src);
1280   if (!cond || TREE_CODE (cond) != COND_EXPR)
1281     return chrec_dont_know;
1282
1283   cnd = COND_EXPR_COND (cond);
1284   if (exit->flags & EDGE_TRUE_VALUE)
1285     cnd = invert_truthvalue (cnd);
1286
1287   cmp = TREE_CODE (cnd);
1288   switch (cmp)
1289     {
1290     case EQ_EXPR:
1291     case NE_EXPR:
1292     case GT_EXPR:
1293     case GE_EXPR:
1294     case LT_EXPR:
1295     case LE_EXPR:
1296       for (j = 0; j < 2; j++)
1297         op[j] = TREE_OPERAND (cnd, j);
1298       break;
1299
1300     default:
1301       return chrec_dont_know;
1302     }
1303
1304   for (j = 0; j < 2; j++)
1305     {
1306       phi[j] = get_base_for (loop, op[j]);
1307       if (!phi[j])
1308         return chrec_dont_know;
1309     }
1310
1311   for (j = 0; j < 2; j++)
1312     {
1313       if (TREE_CODE (phi[j]) == PHI_NODE)
1314         {
1315           val[j] = PHI_ARG_DEF_FROM_EDGE (phi[j], loop_preheader_edge (loop));
1316           next[j] = PHI_ARG_DEF_FROM_EDGE (phi[j], loop_latch_edge (loop));
1317         }
1318       else
1319         {
1320           val[j] = phi[j];
1321           next[j] = NULL_TREE;
1322           op[j] = NULL_TREE;
1323         }
1324     }
1325
1326   for (i = 0; i < MAX_ITERATIONS_TO_TRACK; i++)
1327     {
1328       for (j = 0; j < 2; j++)
1329         aval[j] = get_val_for (op[j], val[j]);
1330
1331       acnd = fold_binary (cmp, boolean_type_node, aval[0], aval[1]);
1332       if (acnd && zero_p (acnd))
1333         {
1334           if (dump_file && (dump_flags & TDF_DETAILS))
1335             fprintf (dump_file,
1336                      "Proved that loop %d iterates %d times using brute force.\n",
1337                      loop->num, i);
1338           return build_int_cst (unsigned_type_node, i);
1339         }
1340
1341       for (j = 0; j < 2; j++)
1342         val[j] = get_val_for (next[j], val[j]);
1343     }
1344
1345   return chrec_dont_know;
1346 }
1347
1348 /* Finds the exit of the LOOP by that the loop exits after a constant
1349    number of iterations and stores the exit edge to *EXIT.  The constant
1350    giving the number of iterations of LOOP is returned.  The number of
1351    iterations is determined using loop_niter_by_eval (i.e. by brute force
1352    evaluation).  If we are unable to find the exit for that loop_niter_by_eval
1353    determines the number of iterations, chrec_dont_know is returned.  */
1354
1355 tree
1356 find_loop_niter_by_eval (struct loop *loop, edge *exit)
1357 {
1358   unsigned n_exits, i;
1359   edge *exits = get_loop_exit_edges (loop, &n_exits);
1360   edge ex;
1361   tree niter = NULL_TREE, aniter;
1362
1363   *exit = NULL;
1364   for (i = 0; i < n_exits; i++)
1365     {
1366       ex = exits[i];
1367       if (!just_once_each_iteration_p (loop, ex->src))
1368         continue;
1369
1370       aniter = loop_niter_by_eval (loop, ex);
1371       if (chrec_contains_undetermined (aniter))
1372         continue;
1373
1374       if (niter
1375           && !tree_int_cst_lt (aniter, niter))
1376         continue;
1377
1378       niter = aniter;
1379       *exit = ex;
1380     }
1381   free (exits);
1382
1383   return niter ? niter : chrec_dont_know;
1384 }
1385
1386 /*
1387
1388    Analysis of upper bounds on number of iterations of a loop.
1389
1390 */
1391
1392 /* Records that AT_STMT is executed at most BOUND times in LOOP.  The
1393    additional condition ADDITIONAL is recorded with the bound.  */
1394
1395 void
1396 record_estimate (struct loop *loop, tree bound, tree additional, tree at_stmt)
1397 {
1398   struct nb_iter_bound *elt = xmalloc (sizeof (struct nb_iter_bound));
1399
1400   if (dump_file && (dump_flags & TDF_DETAILS))
1401     {
1402       fprintf (dump_file, "Statements after ");
1403       print_generic_expr (dump_file, at_stmt, TDF_SLIM);
1404       fprintf (dump_file, " are executed at most ");
1405       print_generic_expr (dump_file, bound, TDF_SLIM);
1406       fprintf (dump_file, " times in loop %d.\n", loop->num);
1407     }
1408
1409   elt->bound = bound;
1410   elt->at_stmt = at_stmt;
1411   elt->additional = additional;
1412   elt->next = loop->bounds;
1413   loop->bounds = elt;
1414 }
1415
1416 /* Initialize LOOP->ESTIMATED_NB_ITERATIONS with the lowest safe
1417    approximation of the number of iterations for LOOP.  */
1418
1419 static void
1420 compute_estimated_nb_iterations (struct loop *loop)
1421 {
1422   struct nb_iter_bound *bound;
1423   
1424   for (bound = loop->bounds; bound; bound = bound->next)
1425     if (TREE_CODE (bound->bound) == INTEGER_CST
1426         /* Update only when there is no previous estimation.  */
1427         && (chrec_contains_undetermined (loop->estimated_nb_iterations)
1428             /* Or when the current estimation is smaller.  */
1429             || tree_int_cst_lt (bound->bound, loop->estimated_nb_iterations)))
1430       loop->estimated_nb_iterations = bound->bound;
1431 }
1432
1433 /* The following analyzers are extracting informations on the bounds
1434    of LOOP from the following undefined behaviors:
1435
1436    - data references should not access elements over the statically
1437      allocated size,
1438
1439    - signed variables should not overflow when flag_wrapv is not set.
1440 */
1441
1442 static void
1443 infer_loop_bounds_from_undefined (struct loop *loop)
1444 {
1445   unsigned i;
1446   basic_block bb, *bbs;
1447   block_stmt_iterator bsi;
1448   
1449   bbs = get_loop_body (loop);
1450
1451   for (i = 0; i < loop->num_nodes; i++)
1452     {
1453       bb = bbs[i];
1454
1455       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1456         {
1457           tree stmt = bsi_stmt (bsi);
1458
1459           switch (TREE_CODE (stmt))
1460             {
1461             case MODIFY_EXPR:
1462               {
1463                 tree op0 = TREE_OPERAND (stmt, 0);
1464                 tree op1 = TREE_OPERAND (stmt, 1);
1465
1466                 /* For each array access, analyze its access function
1467                    and record a bound on the loop iteration domain.  */
1468                 if (TREE_CODE (op1) == ARRAY_REF 
1469                     && !array_ref_contains_indirect_ref (op1))
1470                   estimate_iters_using_array (stmt, op1);
1471
1472                 if (TREE_CODE (op0) == ARRAY_REF 
1473                     && !array_ref_contains_indirect_ref (op0))
1474                   estimate_iters_using_array (stmt, op0);
1475
1476                 /* For each signed type variable in LOOP, analyze its
1477                    scalar evolution and record a bound of the loop
1478                    based on the type's ranges.  */
1479                 else if (!flag_wrapv && TREE_CODE (op0) == SSA_NAME)
1480                   {
1481                     tree init, step, diff, estimation;
1482                     tree scev = instantiate_parameters 
1483                       (loop, analyze_scalar_evolution (loop, op0));
1484                     tree type = chrec_type (scev);
1485                     tree utype;
1486
1487                     if (chrec_contains_undetermined (scev)
1488                         || TYPE_UNSIGNED (type))
1489                       break;
1490
1491                     init = initial_condition_in_loop_num (scev, loop->num);
1492                     step = evolution_part_in_loop_num (scev, loop->num);
1493
1494                     if (init == NULL_TREE
1495                         || step == NULL_TREE
1496                         || TREE_CODE (init) != INTEGER_CST
1497                         || TREE_CODE (step) != INTEGER_CST
1498                         || TYPE_MIN_VALUE (type) == NULL_TREE
1499                         || TYPE_MAX_VALUE (type) == NULL_TREE)
1500                       break;
1501
1502                     utype = unsigned_type_for (type);
1503                     if (tree_int_cst_lt (step, integer_zero_node))
1504                       diff = fold_build2 (MINUS_EXPR, utype, init,
1505                                           TYPE_MIN_VALUE (type));
1506                     else
1507                       diff = fold_build2 (MINUS_EXPR, utype,
1508                                           TYPE_MAX_VALUE (type), init);
1509
1510                     estimation = fold_build2 (CEIL_DIV_EXPR, utype, diff,
1511                                               step);
1512                     record_estimate (loop, estimation, boolean_true_node, stmt);
1513                   }
1514
1515                 break;
1516               }
1517
1518             case CALL_EXPR:
1519               {
1520                 tree args;
1521
1522                 for (args = TREE_OPERAND (stmt, 1); args;
1523                      args = TREE_CHAIN (args))
1524                   if (TREE_CODE (TREE_VALUE (args)) == ARRAY_REF
1525                       && !array_ref_contains_indirect_ref (TREE_VALUE (args)))
1526                     estimate_iters_using_array (stmt, TREE_VALUE (args));
1527
1528                 break;
1529               }
1530
1531             default:
1532               break;
1533             }
1534         }
1535
1536       if (chrec_contains_undetermined (loop->estimated_nb_iterations))
1537         compute_estimated_nb_iterations (loop);
1538     }
1539
1540   free (bbs);
1541 }
1542
1543 /* Records estimates on numbers of iterations of LOOP.  */
1544
1545 static void
1546 estimate_numbers_of_iterations_loop (struct loop *loop)
1547 {
1548   edge *exits;
1549   tree niter, type;
1550   unsigned i, n_exits;
1551   struct tree_niter_desc niter_desc;
1552
1553   /* Give up if we already have tried to compute an estimation.  */
1554   if (loop->estimated_nb_iterations == chrec_dont_know
1555       /* Or when we already have an estimation.  */
1556       || (loop->estimated_nb_iterations != NULL_TREE
1557           && TREE_CODE (loop->estimated_nb_iterations) == INTEGER_CST))
1558     return;
1559   else
1560     loop->estimated_nb_iterations = chrec_dont_know;
1561
1562   exits = get_loop_exit_edges (loop, &n_exits);
1563   for (i = 0; i < n_exits; i++)
1564     {
1565       if (!number_of_iterations_exit (loop, exits[i], &niter_desc, false))
1566         continue;
1567
1568       niter = niter_desc.niter;
1569       type = TREE_TYPE (niter);
1570       if (!zero_p (niter_desc.may_be_zero)
1571           && !nonzero_p (niter_desc.may_be_zero))
1572         niter = build3 (COND_EXPR, type, niter_desc.may_be_zero,
1573                         build_int_cst_type (type, 0),
1574                         niter);
1575       record_estimate (loop, niter,
1576                        niter_desc.additional_info,
1577                        last_stmt (exits[i]->src));
1578     }
1579   free (exits);
1580   
1581   if (chrec_contains_undetermined (loop->estimated_nb_iterations))
1582     infer_loop_bounds_from_undefined (loop);
1583 }
1584
1585 /* Records estimates on numbers of iterations of LOOPS.  */
1586
1587 void
1588 estimate_numbers_of_iterations (struct loops *loops)
1589 {
1590   unsigned i;
1591   struct loop *loop;
1592
1593   for (i = 1; i < loops->num; i++)
1594     {
1595       loop = loops->parray[i];
1596       if (loop)
1597         estimate_numbers_of_iterations_loop (loop);
1598     }
1599 }
1600
1601 /* If A > B, returns -1.  If A == B, returns 0.  If A < B, returns 1.
1602    If neither of these relations can be proved, returns 2.  */
1603
1604 static int
1605 compare_trees (tree a, tree b)
1606 {
1607   tree typea = TREE_TYPE (a), typeb = TREE_TYPE (b);
1608   tree type;
1609
1610   if (TYPE_PRECISION (typea) > TYPE_PRECISION (typeb))
1611     type = typea;
1612   else
1613     type = typeb;
1614
1615   a = fold_convert (type, a);
1616   b = fold_convert (type, b);
1617
1618   if (nonzero_p (fold_binary (EQ_EXPR, boolean_type_node, a, b)))
1619     return 0;
1620   if (nonzero_p (fold_binary (LT_EXPR, boolean_type_node, a, b)))
1621     return 1;
1622   if (nonzero_p (fold_binary (GT_EXPR, boolean_type_node, a, b)))
1623     return -1;
1624
1625   return 2;
1626 }
1627
1628 /* Returns true if statement S1 dominates statement S2.  */
1629
1630 static bool
1631 stmt_dominates_stmt_p (tree s1, tree s2)
1632 {
1633   basic_block bb1 = bb_for_stmt (s1), bb2 = bb_for_stmt (s2);
1634
1635   if (!bb1
1636       || s1 == s2)
1637     return true;
1638
1639   if (bb1 == bb2)
1640     {
1641       block_stmt_iterator bsi;
1642
1643       for (bsi = bsi_start (bb1); bsi_stmt (bsi) != s2; bsi_next (&bsi))
1644         if (bsi_stmt (bsi) == s1)
1645           return true;
1646
1647       return false;
1648     }
1649
1650   return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
1651 }
1652
1653 /* Return true when it is possible to prove that the induction
1654    variable does not wrap: vary outside the type specified bounds.
1655    Checks whether BOUND < VALID_NITER that means in the context of iv
1656    conversion that all the iterations in the loop are safe: not
1657    producing wraps.
1658
1659    The statement NITER_BOUND->AT_STMT is executed at most
1660    NITER_BOUND->BOUND times in the loop.
1661    
1662    NITER_BOUND->ADDITIONAL is the additional condition recorded for
1663    operands of the bound.  This is useful in the following case,
1664    created by loop header copying:
1665
1666    i = 0;
1667    if (n > 0)
1668      do
1669        {
1670          something;
1671        } while (++i < n)
1672
1673    If the n > 0 condition is taken into account, the number of iterations of the
1674    loop can be expressed as n - 1.  If the type of n is signed, the ADDITIONAL
1675    assumption "n > 0" says us that the value of the number of iterations is at
1676    most MAX_TYPE - 1 (without this assumption, it might overflow).  */
1677
1678 static bool
1679 proved_non_wrapping_p (tree at_stmt,
1680                        struct nb_iter_bound *niter_bound, 
1681                        tree new_type,
1682                        tree valid_niter)
1683 {
1684   tree cond;
1685   tree bound = niter_bound->bound;
1686   enum tree_code cmp;
1687
1688   if (TYPE_PRECISION (new_type) > TYPE_PRECISION (TREE_TYPE (bound)))
1689     bound = fold_convert (unsigned_type_for (new_type), bound);
1690   else
1691     valid_niter = fold_convert (TREE_TYPE (bound), valid_niter);
1692
1693   /* Give up if BOUND was not folded to an INTEGER_CST, as in PR23434.  */
1694   if (TREE_CODE (bound) != INTEGER_CST)
1695     return false;
1696
1697   /* After the statement niter_bound->at_stmt we know that anything is
1698      executed at most BOUND times.  */
1699   if (at_stmt && stmt_dominates_stmt_p (niter_bound->at_stmt, at_stmt))
1700     cmp = GE_EXPR;
1701   /* Before the statement niter_bound->at_stmt we know that anything
1702      is executed at most BOUND + 1 times.  */
1703   else
1704     cmp = GT_EXPR;
1705
1706   cond = fold_binary (cmp, boolean_type_node, valid_niter, bound);
1707   if (nonzero_p (cond))
1708     return true;
1709
1710   cond = build2 (cmp, boolean_type_node, valid_niter, bound);
1711   /* Try taking additional conditions into account.  */
1712   cond = fold_binary (TRUTH_OR_EXPR, boolean_type_node,
1713                       invert_truthvalue (niter_bound->additional),
1714                       cond);
1715
1716   if (nonzero_p (cond))
1717     return true;
1718
1719   return false;
1720 }
1721
1722 /* Checks whether it is correct to count the induction variable BASE +
1723    STEP * I at AT_STMT in a wider type NEW_TYPE, using the bounds on
1724    numbers of iterations of a LOOP.  If it is possible, return the
1725    value of step of the induction variable in the NEW_TYPE, otherwise
1726    return NULL_TREE.  */
1727
1728 static tree
1729 convert_step_widening (struct loop *loop, tree new_type, tree base, tree step,
1730                        tree at_stmt)
1731 {
1732   struct nb_iter_bound *bound;
1733   tree base_in_new_type, base_plus_step_in_new_type, step_in_new_type;
1734   tree delta, step_abs;
1735   tree unsigned_type, valid_niter;
1736
1737   /* Compute the new step.  For example, {(uchar) 100, +, (uchar) 240}
1738      is converted to {(uint) 100, +, (uint) 0xfffffff0} in order to
1739      keep the values of the induction variable unchanged: 100, 84, 68,
1740      ...
1741
1742      Another example is: (uint) {(uchar)100, +, (uchar)3} is converted
1743      to {(uint)100, +, (uint)3}.  
1744
1745      Before returning the new step, verify that the number of
1746      iterations is less than DELTA / STEP_ABS (i.e. in the previous
1747      example (256 - 100) / 3) such that the iv does not wrap (in which
1748      case the operations are too difficult to be represented and
1749      handled: the values of the iv should be taken modulo 256 in the
1750      wider type; this is not implemented).  */
1751   base_in_new_type = fold_convert (new_type, base);
1752   base_plus_step_in_new_type = 
1753     fold_convert (new_type,
1754                   fold_build2 (PLUS_EXPR, TREE_TYPE (base), base, step));
1755   step_in_new_type = fold_build2 (MINUS_EXPR, new_type,
1756                                   base_plus_step_in_new_type,
1757                                   base_in_new_type);
1758
1759   if (TREE_CODE (step_in_new_type) != INTEGER_CST)
1760     return NULL_TREE;
1761
1762   switch (compare_trees (base_plus_step_in_new_type, base_in_new_type))
1763     {
1764     case -1:
1765       {
1766         tree extreme = upper_bound_in_type (new_type, TREE_TYPE (base));
1767         delta = fold_build2 (MINUS_EXPR, new_type, extreme,
1768                              base_in_new_type);
1769         step_abs = step_in_new_type;
1770         break;
1771       }
1772
1773     case 1:
1774       {
1775         tree extreme = lower_bound_in_type (new_type, TREE_TYPE (base));
1776         delta = fold_build2 (MINUS_EXPR, new_type, base_in_new_type,
1777                              extreme);
1778         step_abs = fold_build1 (NEGATE_EXPR, new_type, step_in_new_type);
1779         break;
1780       }
1781
1782     case 0:
1783       return step_in_new_type;
1784
1785     default:
1786       return NULL_TREE;
1787     }
1788
1789   unsigned_type = unsigned_type_for (new_type);
1790   delta = fold_convert (unsigned_type, delta);
1791   step_abs = fold_convert (unsigned_type, step_abs);
1792   valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type,
1793                              delta, step_abs);
1794
1795   estimate_numbers_of_iterations_loop (loop);
1796   for (bound = loop->bounds; bound; bound = bound->next)
1797     if (proved_non_wrapping_p (at_stmt, bound, new_type, valid_niter))
1798       return step_in_new_type;
1799
1800   /* Fail when the loop has no bound estimations, or when no bound can
1801      be used for verifying the conversion.  */
1802   return NULL_TREE;
1803 }
1804
1805 /* Returns true when VAR is used in pointer arithmetics.  DEPTH is
1806    used for limiting the search.  */
1807
1808 static bool
1809 used_in_pointer_arithmetic_p (tree var, int depth)
1810 {
1811   use_operand_p use_p;
1812   imm_use_iterator iter;
1813
1814   if (depth == 0
1815       || TREE_CODE (var) != SSA_NAME
1816       || !has_single_use (var))
1817     return false;
1818
1819   FOR_EACH_IMM_USE_FAST (use_p, iter, var)
1820     {
1821       tree stmt = USE_STMT (use_p);
1822
1823       if (stmt && TREE_CODE (stmt) == MODIFY_EXPR)
1824         {
1825           tree rhs = TREE_OPERAND (stmt, 1);
1826
1827           if (TREE_CODE (rhs) == NOP_EXPR
1828               || TREE_CODE (rhs) == CONVERT_EXPR)
1829             {
1830               if (POINTER_TYPE_P (TREE_TYPE (rhs)))
1831                 return true;
1832               return false;
1833             }
1834           else
1835             return used_in_pointer_arithmetic_p (TREE_OPERAND (stmt, 0),
1836                                                  depth - 1);
1837         }
1838     }
1839   return false;
1840 }
1841
1842 /* Return false only when the induction variable BASE + STEP * I is
1843    known to not overflow: i.e. when the number of iterations is small
1844    enough with respect to the step and initial condition in order to
1845    keep the evolution confined in TYPEs bounds.  Return true when the
1846    iv is known to overflow or when the property is not computable.
1847
1848    Initialize INIT_IS_MAX to true when the evolution goes from
1849    INIT_IS_MAX to LOWER_BOUND_IN_TYPE, false in the contrary case.
1850    When this property cannot be determined, UNKNOWN_MAX is set to
1851    true.  */
1852
1853 bool
1854 scev_probably_wraps_p (tree type, tree base, tree step, 
1855                        tree at_stmt, struct loop *loop,
1856                        bool *init_is_max, bool *unknown_max)
1857 {
1858   struct nb_iter_bound *bound;
1859   tree delta, step_abs;
1860   tree unsigned_type, valid_niter;
1861   tree base_plus_step, bpsps;
1862   int cps, cpsps;
1863
1864   /* FIXME: The following code will not be used anymore once
1865      http://gcc.gnu.org/ml/gcc-patches/2005-06/msg02025.html is
1866      committed.
1867
1868      If AT_STMT is a cast to unsigned that is later used for
1869      referencing a memory location, it is followed by a pointer
1870      conversion just after.  Because pointers do not wrap, the
1871      sequences that reference the memory do not wrap either.  In the
1872      following example, sequences corresponding to D_13 and to D_14
1873      can be proved to not wrap because they are used for computing a
1874      memory access:
1875          
1876        D.1621_13 = (long unsigned intD.4) D.1620_12;
1877        D.1622_14 = D.1621_13 * 8;
1878        D.1623_15 = (doubleD.29 *) D.1622_14;
1879   */
1880   if (at_stmt && TREE_CODE (at_stmt) == MODIFY_EXPR)
1881     {
1882       tree op0 = TREE_OPERAND (at_stmt, 0);
1883       tree op1 = TREE_OPERAND (at_stmt, 1);
1884       tree type_op1 = TREE_TYPE (op1);
1885
1886       if ((TYPE_UNSIGNED (type_op1)
1887            && used_in_pointer_arithmetic_p (op0, 2))
1888           || POINTER_TYPE_P (type_op1))
1889         {
1890           *unknown_max = true;
1891           return false;
1892         }
1893     }
1894
1895   if (chrec_contains_undetermined (base)
1896       || chrec_contains_undetermined (step)
1897       || TREE_CODE (base) == REAL_CST
1898       || TREE_CODE (step) == REAL_CST)
1899     {
1900       *unknown_max = true;
1901       return true;
1902     }
1903
1904   *unknown_max = false;
1905   base_plus_step = fold_build2 (PLUS_EXPR, type, base, step);
1906   bpsps = fold_build2 (PLUS_EXPR, type, base_plus_step, step);
1907   cps = compare_trees (base_plus_step, base);
1908   cpsps = compare_trees (bpsps, base_plus_step);
1909
1910   /* Check that the sequence is not wrapping in the first step: it
1911      should have the same monotonicity for the first two steps.  See
1912      PR23410.  */
1913   if (cps != cpsps)
1914     return true;
1915
1916   switch (cps)
1917     {
1918     case -1:
1919       {
1920         tree extreme = upper_bound_in_type (type, TREE_TYPE (base));
1921         delta = fold_build2 (MINUS_EXPR, type, extreme, base);
1922         step_abs = step;
1923         *init_is_max = false;
1924         break;
1925       }
1926
1927     case 1:
1928       {
1929         tree extreme = lower_bound_in_type (type, TREE_TYPE (base));
1930         delta = fold_build2 (MINUS_EXPR, type, base, extreme);
1931         step_abs = fold_build1 (NEGATE_EXPR, type, step);
1932         *init_is_max = true;
1933         break;
1934       }
1935
1936     case 0:
1937       /* This means step is equal to 0.  This should not happen.  It
1938          could happen in convert step, but not here.  Safely answer
1939          don't know as in the default case.  */
1940
1941     default:
1942       *unknown_max = true;
1943       return true;
1944     }
1945
1946   /* If AT_STMT represents a cast operation, we may not be able to
1947      take advantage of the undefinedness of signed type evolutions.
1948
1949      implement-c.texi states: "For conversion to a type of width
1950      N, the value is reduced modulo 2^N to be within range of the
1951      type;"
1952
1953      See PR 21959 for a test case.  Essentially, given a cast
1954      operation
1955                 unsigned char uc;
1956                 signed char sc;
1957                 ...
1958                 sc = (signed char) uc;
1959                 if (sc < 0)
1960                   ...
1961
1962      where uc and sc have the scev {0, +, 1}, we would consider uc to
1963      wrap around, but not sc, because it is of a signed type.  This
1964      causes VRP to erroneously fold the predicate above because it
1965      thinks that sc cannot be negative.  */
1966   if (at_stmt && TREE_CODE (at_stmt) == MODIFY_EXPR)
1967     {
1968       tree rhs = TREE_OPERAND (at_stmt, 1);
1969       tree outer_t = TREE_TYPE (rhs);
1970
1971       if (!TYPE_UNSIGNED (outer_t)
1972           && (TREE_CODE (rhs) == NOP_EXPR || TREE_CODE (rhs) == CONVERT_EXPR))
1973         {
1974           tree inner_t = TREE_TYPE (TREE_OPERAND (rhs, 0));
1975
1976           /* If the inner type is unsigned and its size and/or
1977              precision are smaller to that of the outer type, then the
1978              expression may wrap around.  */
1979           if (TYPE_UNSIGNED (inner_t)
1980               && (TYPE_SIZE (inner_t) <= TYPE_SIZE (outer_t)
1981                   || TYPE_PRECISION (inner_t) <= TYPE_PRECISION (outer_t)))
1982             {
1983               *unknown_max = true;
1984               return true;
1985             }
1986         }
1987     }
1988
1989   /* After having set INIT_IS_MAX, we can return false: when not using
1990      wrapping arithmetic, signed types don't wrap.  */
1991   if (!flag_wrapv && !TYPE_UNSIGNED (type))
1992     return false;
1993
1994   unsigned_type = unsigned_type_for (type);
1995   delta = fold_convert (unsigned_type, delta);
1996   step_abs = fold_convert (unsigned_type, step_abs);
1997   valid_niter = fold_build2 (FLOOR_DIV_EXPR, unsigned_type, delta, step_abs);
1998
1999   estimate_numbers_of_iterations_loop (loop);
2000   for (bound = loop->bounds; bound; bound = bound->next)
2001     if (proved_non_wrapping_p (at_stmt, bound, type, valid_niter))
2002       return false;
2003
2004   /* At this point we still don't have a proof that the iv does not
2005      overflow: give up.  */
2006   *unknown_max = true;
2007   return true;
2008 }
2009
2010 /* Return the conversion to NEW_TYPE of the STEP of an induction
2011    variable BASE + STEP * I at AT_STMT.  When it fails, return
2012    NULL_TREE.  */
2013
2014 tree
2015 convert_step (struct loop *loop, tree new_type, tree base, tree step,
2016               tree at_stmt)
2017 {
2018   tree base_type;
2019
2020   if (chrec_contains_undetermined (base)
2021       || chrec_contains_undetermined (step))
2022     return NULL_TREE;
2023
2024   base_type = TREE_TYPE (base);
2025
2026   /* When not using wrapping arithmetic, signed types don't wrap.  */
2027   if (!flag_wrapv && !TYPE_UNSIGNED (base_type))
2028     return fold_convert (new_type, step);
2029
2030   if (TYPE_PRECISION (new_type) > TYPE_PRECISION (base_type))
2031     return convert_step_widening (loop, new_type, base, step, at_stmt);
2032
2033   return fold_convert (new_type, step);
2034 }
2035
2036 /* Frees the information on upper bounds on numbers of iterations of LOOP.  */
2037
2038 void
2039 free_numbers_of_iterations_estimates_loop (struct loop *loop)
2040 {
2041   struct nb_iter_bound *bound, *next;
2042
2043   loop->nb_iterations = NULL;
2044   loop->estimated_nb_iterations = NULL;
2045   for (bound = loop->bounds; bound; bound = next)
2046     {
2047       next = bound->next;
2048       free (bound);
2049     }
2050
2051   loop->bounds = NULL;
2052 }
2053
2054 /* Frees the information on upper bounds on numbers of iterations of LOOPS.  */
2055
2056 void
2057 free_numbers_of_iterations_estimates (struct loops *loops)
2058 {
2059   unsigned i;
2060   struct loop *loop;
2061
2062   for (i = 1; i < loops->num; i++)
2063     {
2064       loop = loops->parray[i];
2065       if (loop)
2066         free_numbers_of_iterations_estimates_loop (loop);
2067     }
2068 }
2069
2070 /* Substitute value VAL for ssa name NAME inside expressions held
2071    at LOOP.  */
2072
2073 void
2074 substitute_in_loop_info (struct loop *loop, tree name, tree val)
2075 {
2076   struct nb_iter_bound *bound;
2077
2078   loop->nb_iterations = simplify_replace_tree (loop->nb_iterations, name, val);
2079   loop->estimated_nb_iterations
2080           = simplify_replace_tree (loop->estimated_nb_iterations, name, val);
2081   for (bound = loop->bounds; bound; bound = bound->next)
2082     {
2083       bound->bound = simplify_replace_tree (bound->bound, name, val);
2084       bound->additional = simplify_replace_tree (bound->additional, name, val);
2085     }
2086 }