LCOV - code coverage report
Current view: top level - gcc - tree-ssa-loop-niter.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 97.9 % 2484 2432
Test Date: 2026-09-19 16:22:48 Functions: 98.9 % 87 86
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.4-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.