LCOV - code coverage report
Current view: top level - gcc - tree-ssa-reassoc.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 92.9 % 3651 3391
Test Date: 2026-12-05 16:10:02 Functions: 96.1 % 103 99
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Reassociation for trees.
       2              :    Copyright (C) 2005-2026 Free Software Foundation, Inc.
       3              :    Contributed by Daniel Berlin <dan@dberlin.org>
       4              : 
       5              : This file is part of GCC.
       6              : 
       7              : GCC is free software; you can redistribute it and/or modify
       8              : it under the terms of the GNU General Public License as published by
       9              : the Free Software Foundation; either version 3, or (at your option)
      10              : any later version.
      11              : 
      12              : GCC is distributed in the hope that it will be useful,
      13              : but WITHOUT ANY WARRANTY; without even the implied warranty of
      14              : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      15              : GNU General Public License for more details.
      16              : 
      17              : You should have received a copy of the GNU General Public License
      18              : along with GCC; see the file COPYING3.  If not see
      19              : <http://www.gnu.org/licenses/>.  */
      20              : 
      21              : #include "config.h"
      22              : #include "system.h"
      23              : #include "coretypes.h"
      24              : #include "backend.h"
      25              : #include "target.h"
      26              : #include "rtl.h"
      27              : #include "tree.h"
      28              : #include "gimple.h"
      29              : #include "cfghooks.h"
      30              : #include "alloc-pool.h"
      31              : #include "tree-pass.h"
      32              : #include "memmodel.h"
      33              : #include "tm_p.h"
      34              : #include "ssa.h"
      35              : #include "optabs-tree.h"
      36              : #include "gimple-pretty-print.h"
      37              : #include "diagnostic-core.h"
      38              : #include "fold-const.h"
      39              : #include "stor-layout.h"
      40              : #include "cfganal.h"
      41              : #include "gimple-iterator.h"
      42              : #include "gimple-fold.h"
      43              : #include "tree-eh.h"
      44              : #include "gimplify-me.h"
      45              : #include "tree-cfg.h"
      46              : #include "tree-ssa-loop.h"
      47              : #include "flags.h"
      48              : #include "tree-ssa.h"
      49              : #include "langhooks.h"
      50              : #include "cfgloop.h"
      51              : #include "builtins.h"
      52              : #include "gimplify.h"
      53              : #include "case-cfn-macros.h"
      54              : #include "tree-ssa-reassoc.h"
      55              : #include "tree-ssa-math-opts.h"
      56              : #include "gimple-range.h"
      57              : #include "internal-fn.h"
      58              : 
      59              : /*  This is a simple global reassociation pass.  It is, in part, based
      60              :     on the LLVM pass of the same name (They do some things more/less
      61              :     than we do, in different orders, etc).
      62              : 
      63              :     It consists of five steps:
      64              : 
      65              :     1. Breaking up subtract operations into addition + negate, where
      66              :     it would promote the reassociation of adds.
      67              : 
      68              :     2. Left linearization of the expression trees, so that (A+B)+(C+D)
      69              :     becomes (((A+B)+C)+D), which is easier for us to rewrite later.
      70              :     During linearization, we place the operands of the binary
      71              :     expressions into a vector of operand_entry_*
      72              : 
      73              :     3. Optimization of the operand lists, eliminating things like a +
      74              :     -a, a & a, etc.
      75              : 
      76              :     3a. Combine repeated factors with the same occurrence counts
      77              :     into a __builtin_powi call that will later be optimized into
      78              :     an optimal number of multiplies.
      79              : 
      80              :     4. Rewrite the expression trees we linearized and optimized so
      81              :     they are in proper rank order.
      82              : 
      83              :     5. Repropagate negates, as nothing else will clean it up ATM.
      84              : 
      85              :     A bit of theory on #4, since nobody seems to write anything down
      86              :     about why it makes sense to do it the way they do it:
      87              : 
      88              :     We could do this much nicer theoretically, but don't (for reasons
      89              :     explained after how to do it theoretically nice :P).
      90              : 
      91              :     In order to promote the most redundancy elimination, you want
      92              :     binary expressions whose operands are the same rank (or
      93              :     preferably, the same value) exposed to the redundancy eliminator,
      94              :     for possible elimination.
      95              : 
      96              :     So the way to do this if we really cared, is to build the new op
      97              :     tree from the leaves to the roots, merging as you go, and putting the
      98              :     new op on the end of the worklist, until you are left with one
      99              :     thing on the worklist.
     100              : 
     101              :     IE if you have to rewrite the following set of operands (listed with
     102              :     rank in parentheses), with opcode PLUS_EXPR:
     103              : 
     104              :     a (1),  b (1),  c (1),  d (2), e (2)
     105              : 
     106              : 
     107              :     We start with our merge worklist empty, and the ops list with all of
     108              :     those on it.
     109              : 
     110              :     You want to first merge all leaves of the same rank, as much as
     111              :     possible.
     112              : 
     113              :     So first build a binary op of
     114              : 
     115              :     mergetmp = a + b, and put "mergetmp" on the merge worklist.
     116              : 
     117              :     Because there is no three operand form of PLUS_EXPR, c is not going to
     118              :     be exposed to redundancy elimination as a rank 1 operand.
     119              : 
     120              :     So you might as well throw it on the merge worklist (you could also
     121              :     consider it to now be a rank two operand, and merge it with d and e,
     122              :     but in this case, you then have evicted e from a binary op. So at
     123              :     least in this situation, you can't win.)
     124              : 
     125              :     Then build a binary op of d + e
     126              :     mergetmp2 = d + e
     127              : 
     128              :     and put mergetmp2 on the merge worklist.
     129              : 
     130              :     so merge worklist = {mergetmp, c, mergetmp2}
     131              : 
     132              :     Continue building binary ops of these operations until you have only
     133              :     one operation left on the worklist.
     134              : 
     135              :     So we have
     136              : 
     137              :     build binary op
     138              :     mergetmp3 = mergetmp + c
     139              : 
     140              :     worklist = {mergetmp2, mergetmp3}
     141              : 
     142              :     mergetmp4 = mergetmp2 + mergetmp3
     143              : 
     144              :     worklist = {mergetmp4}
     145              : 
     146              :     because we have one operation left, we can now just set the original
     147              :     statement equal to the result of that operation.
     148              : 
     149              :     This will at least expose a + b  and d + e to redundancy elimination
     150              :     as binary operations.
     151              : 
     152              :     For extra points, you can reuse the old statements to build the
     153              :     mergetmps, since you shouldn't run out.
     154              : 
     155              :     So why don't we do this?
     156              : 
     157              :     Because it's expensive, and rarely will help.  Most trees we are
     158              :     reassociating have 3 or less ops.  If they have 2 ops, they already
     159              :     will be written into a nice single binary op.  If you have 3 ops, a
     160              :     single simple check suffices to tell you whether the first two are of the
     161              :     same rank.  If so, you know to order it
     162              : 
     163              :     mergetmp = op1 + op2
     164              :     newstmt = mergetmp + op3
     165              : 
     166              :     instead of
     167              :     mergetmp = op2 + op3
     168              :     newstmt = mergetmp + op1
     169              : 
     170              :     If all three are of the same rank, you can't expose them all in a
     171              :     single binary operator anyway, so the above is *still* the best you
     172              :     can do.
     173              : 
     174              :     Thus, this is what we do.  When we have three ops left, we check to see
     175              :     what order to put them in, and call it a day.  As a nod to vector sum
     176              :     reduction, we check if any of the ops are really a phi node that is a
     177              :     destructive update for the associating op, and keep the destructive
     178              :     update together for vector sum reduction recognition.  */
     179              : 
     180              : /* Enable insertion of __builtin_powi calls during execute_reassoc.  See
     181              :    point 3a in the pass header comment.  */
     182              : static bool reassoc_insert_powi_p;
     183              : 
     184              : /* Enable biasing ranks of loop accumulators.  We don't want this before
     185              :    vectorization, since it interferes with reduction chains.  */
     186              : static bool reassoc_bias_loop_carried_phi_ranks_p;
     187              : 
     188              : /* Statistics */
     189              : static struct
     190              : {
     191              :   int linearized;
     192              :   int constants_eliminated;
     193              :   int ops_eliminated;
     194              :   int rewritten;
     195              :   int pows_encountered;
     196              :   int pows_created;
     197              : } reassociate_stats;
     198              : 
     199              : 
     200              : static object_allocator<operand_entry> operand_entry_pool
     201              :   ("operand entry pool");
     202              : 
     203              : /* This is used to assign a unique ID to each struct operand_entry
     204              :    so that qsort results are identical on different hosts.  */
     205              : static unsigned int next_operand_entry_id;
     206              : 
     207              : /* Starting rank number for a given basic block, so that we can rank
     208              :    operations using unmovable instructions in that BB based on the bb
     209              :    depth.  */
     210              : static int64_t *bb_rank;
     211              : 
     212              : /* Operand->rank hashtable.  */
     213              : static hash_map<tree, int64_t> *operand_rank;
     214              : 
     215              : /* SSA_NAMEs that are forms of loop accumulators and whose ranks need to be
     216              :    biased.  */
     217              : static auto_bitmap biased_names;
     218              : 
     219              : /* Vector of SSA_NAMEs on which after reassociate_bb is done with
     220              :    all basic blocks the CFG should be adjusted - basic blocks
     221              :    split right after that SSA_NAME's definition statement and before
     222              :    the only use, which must be a bit ior.  */
     223              : static vec<tree> reassoc_branch_fixups;
     224              : 
     225              : /* Forward decls.  */
     226              : static int64_t get_rank (tree);
     227              : static bool reassoc_stmt_dominates_stmt_p (gimple *, gimple *);
     228              : 
     229              : /* Wrapper around gsi_remove, which adjusts gimple_uid of debug stmts
     230              :    possibly added by gsi_remove.  */
     231              : 
     232              : static bool
     233       170642 : reassoc_remove_stmt (gimple_stmt_iterator *gsi)
     234              : {
     235       170642 :   gimple *stmt = gsi_stmt (*gsi);
     236              : 
     237       170642 :   if (!MAY_HAVE_DEBUG_BIND_STMTS || gimple_code (stmt) == GIMPLE_PHI)
     238        70232 :     return gsi_remove (gsi, true);
     239              : 
     240       100410 :   gimple_stmt_iterator prev = *gsi;
     241       100410 :   gsi_prev (&prev);
     242       100410 :   unsigned uid = gimple_uid (stmt);
     243       100410 :   basic_block bb = gimple_bb (stmt);
     244       100410 :   bool ret = gsi_remove (gsi, true);
     245       100410 :   if (!gsi_end_p (prev))
     246       100198 :     gsi_next (&prev);
     247              :   else
     248          424 :     prev = gsi_start_bb (bb);
     249       100410 :   gimple *end_stmt = gsi_stmt (*gsi);
     250       105098 :   while ((stmt = gsi_stmt (prev)) != end_stmt)
     251              :     {
     252         4688 :       gcc_assert (stmt && is_gimple_debug (stmt) && gimple_uid (stmt) == 0);
     253         4688 :       gimple_set_uid (stmt, uid);
     254         4688 :       gsi_next (&prev);
     255              :     }
     256              :   return ret;
     257              : }
     258              : 
     259              : /* Bias amount for loop-carried phis.  We want this to be larger than
     260              :    the depth of any reassociation tree we can see, but not larger than
     261              :    the rank difference between two blocks.  */
     262              : #define PHI_LOOP_BIAS (1 << 15)
     263              : 
     264              : /* Return TRUE iff PHI_LOOP_BIAS should be propagated from one of the STMT's
     265              :    operands to the STMT's left-hand side.  The goal is to preserve bias in code
     266              :    like this:
     267              : 
     268              :      x_1 = phi(x_0, x_2)
     269              :      a = x_1 | 1
     270              :      b = a ^ 2
     271              :      .MEM = b
     272              :      c = b + d
     273              :      x_2 = c + e
     274              : 
     275              :    That is, we need to preserve bias along single-use chains originating from
     276              :    loop-carried phis.  Only GIMPLE_ASSIGNs to SSA_NAMEs are considered to be
     277              :    uses, because only they participate in rank propagation.  */
     278              : static bool
     279      7251747 : propagate_bias_p (gimple *stmt)
     280              : {
     281      7251747 :   use_operand_p use;
     282      7251747 :   imm_use_iterator use_iter;
     283      7251747 :   gimple *single_use_stmt = NULL;
     284              : 
     285      7251747 :   if (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt)) == tcc_reference)
     286              :     return false;
     287              : 
     288     12946685 :   FOR_EACH_IMM_USE_FAST (use, use_iter, gimple_assign_lhs (stmt))
     289              :     {
     290     13817903 :       gassign *current_use_stmt = dyn_cast<gassign *> (USE_STMT (use));
     291              : 
     292      6335601 :       if (current_use_stmt
     293      6335601 :           && TREE_CODE (gimple_assign_lhs (current_use_stmt)) == SSA_NAME)
     294              :         {
     295      6241161 :           if (single_use_stmt != NULL && single_use_stmt != current_use_stmt)
     296       759621 :             return false;
     297              :           single_use_stmt = current_use_stmt;
     298              :         }
     299       759621 :     }
     300              : 
     301      4704762 :   if (single_use_stmt == NULL)
     302              :     return false;
     303              : 
     304      4704332 :   if (gimple_bb (stmt)->loop_father
     305      4704332 :       != gimple_bb (single_use_stmt)->loop_father)
     306       118901 :     return false;
     307              : 
     308              :   return true;
     309              : }
     310              : 
     311              : /* Rank assigned to a phi statement.  If STMT is a loop-carried phi of
     312              :    an innermost loop, and the phi has only a single use which is inside
     313              :    the loop, then the rank is the block rank of the loop latch plus an
     314              :    extra bias for the loop-carried dependence.  This causes expressions
     315              :    calculated into an accumulator variable to be independent for each
     316              :    iteration of the loop.  If STMT is some other phi, the rank is the
     317              :    block rank of its containing block.  */
     318              : static int64_t
     319      1516266 : phi_rank (gimple *stmt)
     320              : {
     321      1516266 :   basic_block bb = gimple_bb (stmt);
     322      1516266 :   class loop *father = bb->loop_father;
     323      1516266 :   tree res;
     324      1516266 :   unsigned i;
     325      1516266 :   use_operand_p use;
     326      1516266 :   gimple *use_stmt;
     327              : 
     328      1516266 :   if (!reassoc_bias_loop_carried_phi_ranks_p)
     329       576123 :     return bb_rank[bb->index];
     330              : 
     331              :   /* We only care about real loops (those with a latch).  */
     332       940143 :   if (!father->latch)
     333            0 :     return bb_rank[bb->index];
     334              : 
     335              :   /* Interesting phis must be in headers of innermost loops.  */
     336       940143 :   if (bb != father->header
     337       734058 :       || father->inner)
     338       378193 :     return bb_rank[bb->index];
     339              : 
     340              :   /* Ignore virtual SSA_NAMEs.  */
     341       561950 :   res = gimple_phi_result (stmt);
     342      1123900 :   if (virtual_operand_p (res))
     343            0 :     return bb_rank[bb->index];
     344              : 
     345              :   /* The phi definition must have a single use, and that use must be
     346              :      within the loop.  Otherwise this isn't an accumulator pattern.  */
     347       561950 :   if (!single_imm_use (res, &use, &use_stmt)
     348       561950 :       || gimple_bb (use_stmt)->loop_father != father)
     349       489529 :     return bb_rank[bb->index];
     350              : 
     351              :   /* Look for phi arguments from within the loop.  If found, bias this phi.  */
     352        82613 :   for (i = 0; i < gimple_phi_num_args (stmt); i++)
     353              :     {
     354        82332 :       tree arg = gimple_phi_arg_def (stmt, i);
     355        82332 :       if (TREE_CODE (arg) == SSA_NAME
     356        82332 :           && !SSA_NAME_IS_DEFAULT_DEF (arg))
     357              :         {
     358        76660 :           gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
     359        76660 :           if (gimple_bb (def_stmt)->loop_father == father)
     360        72140 :             return bb_rank[father->latch->index] + PHI_LOOP_BIAS;
     361              :         }
     362              :     }
     363              : 
     364              :   /* Must be an uninteresting phi.  */
     365          281 :   return bb_rank[bb->index];
     366              : }
     367              : 
     368              : /* Return the maximum of RANK and the rank that should be propagated
     369              :    from expression OP.  For most operands, this is just the rank of OP.
     370              :    For loop-carried phis, the value is zero to avoid undoing the bias
     371              :    in favor of the phi.  */
     372              : static int64_t
     373      7911807 : propagate_rank (int64_t rank, tree op, bool *maybe_biased_p)
     374              : {
     375      7911807 :   int64_t op_rank;
     376              : 
     377      7911807 :   op_rank = get_rank (op);
     378              : 
     379              :   /* Check whether op is biased after the get_rank () call, since it might have
     380              :      updated biased_names.  */
     381      7911807 :   if (TREE_CODE (op) == SSA_NAME
     382      7911807 :       && bitmap_bit_p (biased_names, SSA_NAME_VERSION (op)))
     383              :     {
     384        44871 :       if (maybe_biased_p == NULL)
     385              :         return rank;
     386        30441 :       *maybe_biased_p = true;
     387              :     }
     388              : 
     389      7897377 :   return MAX (rank, op_rank);
     390              : }
     391              : 
     392              : /* Look up the operand rank structure for expression E.  */
     393              : 
     394              : static inline int64_t
     395     14393419 : find_operand_rank (tree e)
     396              : {
     397     14393419 :   int64_t *slot = operand_rank->get (e);
     398     14393419 :   return slot ? *slot : -1;
     399              : }
     400              : 
     401              : /* Insert {E,RANK} into the operand rank hashtable.  */
     402              : 
     403              : static inline void
     404     15369396 : insert_operand_rank (tree e, int64_t rank)
     405              : {
     406     15369396 :   gcc_assert (rank > 0);
     407     15369396 :   bool existed = operand_rank->put (e, rank);
     408     15369396 :   gcc_assert (!existed);
     409     15369396 : }
     410              : 
     411              : /* Given an expression E, return the rank of the expression.  */
     412              : 
     413              : static int64_t
     414     17896086 : get_rank (tree e)
     415              : {
     416              :   /* SSA_NAME's have the rank of the expression they are the result
     417              :      of.
     418              :      For globals and uninitialized values, the rank is 0.
     419              :      For function arguments, use the pre-setup rank.
     420              :      For PHI nodes, stores, asm statements, etc, we use the rank of
     421              :      the BB.
     422              :      For simple operations, the rank is the maximum rank of any of
     423              :      its operands, or the bb_rank, whichever is less.
     424              :      I make no claims that this is optimal, however, it gives good
     425              :      results.  */
     426              : 
     427              :   /* We make an exception to the normal ranking system to break
     428              :      dependences of accumulator variables in loops.  Suppose we
     429              :      have a simple one-block loop containing:
     430              : 
     431              :        x_1 = phi(x_0, x_2)
     432              :        b = a + x_1
     433              :        c = b + d
     434              :        x_2 = c + e
     435              : 
     436              :      As shown, each iteration of the calculation into x is fully
     437              :      dependent upon the iteration before it.  We would prefer to
     438              :      see this in the form:
     439              : 
     440              :        x_1 = phi(x_0, x_2)
     441              :        b = a + d
     442              :        c = b + e
     443              :        x_2 = c + x_1
     444              : 
     445              :      If the loop is unrolled, the calculations of b and c from
     446              :      different iterations can be interleaved.
     447              : 
     448              :      To obtain this result during reassociation, we bias the rank
     449              :      of the phi definition x_1 upward, when it is recognized as an
     450              :      accumulator pattern.  The artificial rank causes it to be
     451              :      added last, providing the desired independence.  */
     452              : 
     453     17896086 :   if (TREE_CODE (e) == SSA_NAME)
     454              :     {
     455     14393419 :       ssa_op_iter iter;
     456     14393419 :       gimple *stmt;
     457     14393419 :       int64_t rank;
     458     14393419 :       tree op;
     459              : 
     460              :       /* If we already have a rank for this expression, use that.  */
     461     14393419 :       rank = find_operand_rank (e);
     462     14393419 :       if (rank != -1)
     463              :         return rank;
     464              : 
     465      9024825 :       stmt = SSA_NAME_DEF_STMT (e);
     466      9024825 :       if (gimple_code (stmt) == GIMPLE_PHI)
     467              :         {
     468      1516266 :           rank = phi_rank (stmt);
     469      1516266 :           if (rank != bb_rank[gimple_bb (stmt)->index])
     470        72140 :             bitmap_set_bit (biased_names, SSA_NAME_VERSION (e));
     471              :         }
     472              : 
     473      7508559 :       else if (!is_gimple_assign (stmt))
     474       256812 :         rank = bb_rank[gimple_bb (stmt)->index];
     475              : 
     476              :       else
     477              :         {
     478      7251747 :           bool biased_p = false;
     479      7251747 :           bool *maybe_biased_p = propagate_bias_p (stmt) ? &biased_p : NULL;
     480              : 
     481              :           /* Otherwise, find the maximum rank for the operands.  As an
     482              :              exception, remove the bias from loop-carried phis when propagating
     483              :              the rank so that dependent operations are not also biased.  */
     484              :           /* Simply walk over all SSA uses - this takes advantage of the
     485              :              fact that non-SSA operands are is_gimple_min_invariant and
     486              :              thus have rank 0.  */
     487      7251747 :           rank = 0;
     488     15163554 :           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
     489      7911807 :             rank = propagate_rank (rank, op, maybe_biased_p);
     490              : 
     491      7251747 :           rank += 1;
     492      7251747 :           if (biased_p)
     493        29142 :             bitmap_set_bit (biased_names, SSA_NAME_VERSION (e));
     494              :         }
     495              : 
     496      9024825 :       if (dump_file && (dump_flags & TDF_DETAILS))
     497              :         {
     498          205 :           fprintf (dump_file, "Rank for ");
     499          205 :           print_generic_expr (dump_file, e);
     500          205 :           fprintf (dump_file, " is %" PRId64 "\n", rank);
     501              :         }
     502              : 
     503              :       /* Note the rank in the hashtable so we don't recompute it.  */
     504      9024825 :       insert_operand_rank (e, rank);
     505      9024825 :       return rank;
     506              :     }
     507              : 
     508              :   /* Constants, globals, etc., are rank 0 */
     509              :   return 0;
     510              : }
     511              : 
     512              : 
     513              : /* We want integer ones to end up last no matter what, since they are
     514              :    the ones we can do the most with.  */
     515              : #define INTEGER_CONST_TYPE 1 << 4
     516              : #define FLOAT_ONE_CONST_TYPE 1 << 3
     517              : #define FLOAT_CONST_TYPE 1 << 2
     518              : #define OTHER_CONST_TYPE 1 << 1
     519              : 
     520              : /* Classify an invariant tree into integer, float, or other, so that
     521              :    we can sort them to be near other constants of the same type.  */
     522              : static inline int
     523       316808 : constant_type (tree t)
     524              : {
     525       316808 :   if (INTEGRAL_TYPE_P (TREE_TYPE (t)))
     526              :     return INTEGER_CONST_TYPE;
     527        10738 :   else if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (t)))
     528              :     {
     529              :       /* Sort -1.0 and 1.0 constants last, while in some cases
     530              :          const_binop can't optimize some inexact operations, multiplication
     531              :          by -1.0 or 1.0 can be always merged with others.  */
     532         6828 :       if (real_onep (t) || real_minus_onep (t))
     533          816 :         return FLOAT_ONE_CONST_TYPE;
     534              :       return FLOAT_CONST_TYPE;
     535              :     }
     536              :   else
     537              :     return OTHER_CONST_TYPE;
     538              : }
     539              : 
     540              : /* qsort comparison function to sort operand entries PA and PB by rank
     541              :    so that the sorted array is ordered by rank in decreasing order.  */
     542              : static int
     543     23935309 : sort_by_operand_rank (const void *pa, const void *pb)
     544              : {
     545     23935309 :   const operand_entry *oea = *(const operand_entry *const *)pa;
     546     23935309 :   const operand_entry *oeb = *(const operand_entry *const *)pb;
     547              : 
     548     23935309 :   if (oeb->rank != oea->rank)
     549     21487409 :     return oeb->rank > oea->rank ? 1 : -1;
     550              : 
     551              :   /* It's nicer for optimize_expression if constants that are likely
     552              :      to fold when added/multiplied/whatever are put next to each
     553              :      other.  Since all constants have rank 0, order them by type.  */
     554      2447900 :   if (oea->rank == 0)
     555              :     {
     556       158346 :       if (constant_type (oeb->op) != constant_type (oea->op))
     557           58 :         return constant_type (oea->op) - constant_type (oeb->op);
     558              :       else
     559              :         /* To make sorting result stable, we use unique IDs to determine
     560              :            order.  */
     561       158288 :         return oeb->id > oea->id ? 1 : -1;
     562              :     }
     563              : 
     564      2289554 :   if (TREE_CODE (oea->op) != SSA_NAME)
     565              :     {
     566            0 :       if (TREE_CODE (oeb->op) != SSA_NAME)
     567            0 :         return oeb->id > oea->id ? 1 : -1;
     568              :       else
     569              :         return 1;
     570              :     }
     571      2289554 :   else if (TREE_CODE (oeb->op) != SSA_NAME)
     572              :     return -1;
     573              : 
     574              :   /* Lastly, make sure the versions that are the same go next to each
     575              :      other.  */
     576      2289554 :   if (SSA_NAME_VERSION (oeb->op) != SSA_NAME_VERSION (oea->op))
     577              :     {
     578              :       /* As SSA_NAME_VERSION is assigned pretty randomly, because we reuse
     579              :          versions of removed SSA_NAMEs, so if possible, prefer to sort
     580              :          based on basic block and gimple_uid of the SSA_NAME_DEF_STMT.
     581              :          See PR60418.  */
     582      2233193 :       gimple *stmta = SSA_NAME_DEF_STMT (oea->op);
     583      2233193 :       gimple *stmtb = SSA_NAME_DEF_STMT (oeb->op);
     584      2233193 :       basic_block bba = gimple_bb (stmta);
     585      2233193 :       basic_block bbb = gimple_bb (stmtb);
     586      2233193 :       if (bbb != bba)
     587              :         {
     588              :           /* One of the SSA_NAMEs can be defined in oeN->stmt_to_insert
     589              :              but the other might not.  */
     590       154946 :           if (!bba)
     591              :             return 1;
     592       150600 :           if (!bbb)
     593              :             return -1;
     594              :           /* If neither is, compare bb_rank.  */
     595       144545 :           if (bb_rank[bbb->index] != bb_rank[bba->index])
     596       144545 :             return (bb_rank[bbb->index] >> 16) - (bb_rank[bba->index] >> 16);
     597              :         }
     598              : 
     599      2078247 :       bool da = reassoc_stmt_dominates_stmt_p (stmta, stmtb);
     600      2078247 :       bool db = reassoc_stmt_dominates_stmt_p (stmtb, stmta);
     601      2078247 :       if (da != db)
     602      2017446 :         return da ? 1 : -1;
     603              : 
     604        60801 :       return SSA_NAME_VERSION (oeb->op) > SSA_NAME_VERSION (oea->op) ? 1 : -1;
     605              :     }
     606              : 
     607        56361 :   return oeb->id > oea->id ? 1 : -1;
     608              : }
     609              : 
     610              : /* Add an operand entry to *OPS for the tree operand OP.  */
     611              : 
     612              : static void
     613      9983773 : add_to_ops_vec (vec<operand_entry *> *ops, tree op, gimple *stmt_to_insert = NULL)
     614              : {
     615      9983773 :   operand_entry *oe = operand_entry_pool.allocate ();
     616              : 
     617      9983773 :   oe->op = op;
     618      9983773 :   oe->rank = get_rank (op);
     619      9983773 :   oe->id = next_operand_entry_id++;
     620      9983773 :   oe->count = 1;
     621      9983773 :   oe->stmt_to_insert = stmt_to_insert;
     622      9983773 :   ops->safe_push (oe);
     623      9983773 : }
     624              : 
     625              : /* Add an operand entry to *OPS for the tree operand OP with repeat
     626              :    count REPEAT.  */
     627              : 
     628              : static void
     629           17 : add_repeat_to_ops_vec (vec<operand_entry *> *ops, tree op,
     630              :                        HOST_WIDE_INT repeat)
     631              : {
     632           17 :   operand_entry *oe = operand_entry_pool.allocate ();
     633              : 
     634           17 :   oe->op = op;
     635           17 :   oe->rank = get_rank (op);
     636           17 :   oe->id = next_operand_entry_id++;
     637           17 :   oe->count = repeat;
     638           17 :   oe->stmt_to_insert = NULL;
     639           17 :   ops->safe_push (oe);
     640              : 
     641           17 :   reassociate_stats.pows_encountered++;
     642           17 : }
     643              : 
     644              : /* Returns true if we can associate the SSA def OP.  */
     645              : 
     646              : static bool
     647     32636383 : can_reassociate_op_p (tree op)
     648              : {
     649     32636383 :   if (TREE_CODE (op) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op))
     650              :     return false;
     651              :   /* Uninitialized variables can't participate in reassociation. */
     652     32635487 :   if (TREE_CODE (op) == SSA_NAME && ssa_name_maybe_undef_p (op))
     653              :     return false;
     654              :   /* Make sure asm goto outputs do not participate in reassociation since
     655              :      we have no way to find an insertion place after asm goto.  */
     656     32630611 :   if (TREE_CODE (op) == SSA_NAME
     657     23988917 :       && gimple_code (SSA_NAME_DEF_STMT (op)) == GIMPLE_ASM
     658     32653504 :       && gimple_asm_nlabels (as_a <gasm *> (SSA_NAME_DEF_STMT (op))) != 0)
     659          100 :     return false;
     660              :   return true;
     661              : }
     662              : 
     663              : /* Returns true if we can reassociate operations of TYPE.
     664              :    That is for integral or non-saturating fixed-point types, and for
     665              :    floating point type when associative-math is enabled.  */
     666              : 
     667              : static bool
     668     59791280 : can_reassociate_type_p (tree type)
     669              : {
     670     59791280 :   if ((ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type))
     671     37101007 :       || NON_SAT_FIXED_POINT_TYPE_P (type)
     672     96892287 :       || (flag_associative_math && FLOAT_TYPE_P (type)))
     673     23084605 :     return true;
     674              :   return false;
     675              : }
     676              : 
     677              : /* Return true if STMT is reassociable operation containing a binary
     678              :    operation with tree code CODE, and is inside LOOP.  */
     679              : 
     680              : static bool
     681      7963724 : is_reassociable_op (gimple *stmt, enum tree_code code, class loop *loop)
     682              : {
     683      7963724 :   basic_block bb = gimple_bb (stmt);
     684              : 
     685      7963724 :   if (gimple_bb (stmt) == NULL)
     686              :     return false;
     687              : 
     688      7774467 :   if (!flow_bb_inside_loop_p (loop, bb))
     689              :     return false;
     690              : 
     691      7547972 :   auto a_stmt = dyn_cast<gassign *> (stmt);
     692      5994482 :   if (a_stmt
     693      5994482 :       && gimple_assign_rhs_code (a_stmt) == code
     694       850405 :       && has_single_use (gimple_assign_lhs (a_stmt)))
     695              :     {
     696       604816 :       tree rhs1 = gimple_assign_rhs1 (a_stmt);
     697       604816 :       tree rhs2 = gimple_assign_rhs2 (a_stmt);
     698       604816 :       if (!can_reassociate_op_p (rhs1)
     699       604816 :           || (rhs2 && !can_reassociate_op_p (rhs2)))
     700          526 :         return false;
     701              :       return true;
     702              :     }
     703              : 
     704              :   return false;
     705              : }
     706              : 
     707              : 
     708              : /* Return true if STMT is a nop-conversion.  */
     709              : 
     710              : static bool
     711      7901117 : gimple_nop_conversion_p (gimple *stmt)
     712              : {
     713      7901117 :   if (gassign *ass = dyn_cast <gassign *> (stmt))
     714              :     {
     715      9273675 :       if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (ass))
     716      6968001 :           && tree_nop_conversion_p (TREE_TYPE (gimple_assign_lhs (ass)),
     717      1554109 :                                     TREE_TYPE (gimple_assign_rhs1 (ass))))
     718              :         return true;
     719              :     }
     720              :   return false;
     721              : }
     722              : 
     723              : /* Given NAME, if NAME is defined by a unary operation OPCODE, return the
     724              :    operand of the negate operation.  Otherwise, return NULL.  */
     725              : 
     726              : static tree
     727      7808789 : get_unary_op (tree name, enum tree_code opcode)
     728              : {
     729      7808789 :   gimple *stmt = SSA_NAME_DEF_STMT (name);
     730              : 
     731              :   /* Look through nop conversions (sign changes).  */
     732      7808789 :   if (gimple_nop_conversion_p (stmt)
     733      7808789 :       && TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME)
     734       927402 :     stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
     735              : 
     736      7808789 :   gassign *assign = dyn_cast<gassign *> (stmt);
     737      4959160 :   if (!assign)
     738              :     return NULL_TREE;
     739              : 
     740      4959160 :   if (gimple_assign_rhs_code (stmt) == opcode)
     741       127550 :     return gimple_assign_rhs1 (assign);
     742              :   return NULL_TREE;
     743              : }
     744              : 
     745              : /* Return true if OP1 and OP2 have the same value if casted to either type.  */
     746              : 
     747              : static bool
     748        47427 : ops_equal_values_p (tree op1, tree op2)
     749              : {
     750        47427 :   if (op1 == op2)
     751              :     return true;
     752              : 
     753        47122 :   tree orig_op1 = op1;
     754        47122 :   if (TREE_CODE (op1) == SSA_NAME)
     755              :     {
     756        47122 :       gimple *stmt = SSA_NAME_DEF_STMT (op1);
     757        47122 :       if (gimple_nop_conversion_p (stmt))
     758              :         {
     759        19370 :           op1 = gimple_assign_rhs1 (stmt);
     760        19370 :           if (op1 == op2)
     761              :             return true;
     762              :         }
     763              :     }
     764              : 
     765        45206 :   if (TREE_CODE (op2) == SSA_NAME)
     766              :     {
     767        45206 :       gimple *stmt = SSA_NAME_DEF_STMT (op2);
     768        45206 :       if (gimple_nop_conversion_p (stmt))
     769              :         {
     770        17383 :           op2 = gimple_assign_rhs1 (stmt);
     771        17383 :           if (op1 == op2
     772        17383 :               || orig_op1 == op2)
     773              :             return true;
     774              :         }
     775              :     }
     776              : 
     777              :   return false;
     778              : }
     779              : 
     780              : 
     781              : /* If CURR and LAST are a pair of ops that OPCODE allows us to
     782              :    eliminate through equivalences, do so, remove them from OPS, and
     783              :    return true.  Otherwise, return false.  */
     784              : 
     785              : static bool
     786      9876414 : eliminate_duplicate_pair (enum tree_code opcode,
     787              :                           vec<operand_entry *> *ops,
     788              :                           bool *all_done,
     789              :                           unsigned int i,
     790              :                           operand_entry *curr,
     791              :                           operand_entry *last)
     792              : {
     793              : 
     794              :   /* If we have two of the same op, and the opcode is & |, min, or max,
     795              :      we can eliminate one of them.
     796              :      If we have two of the same op, and the opcode is ^, we can
     797              :      eliminate both of them.  */
     798              : 
     799      9876414 :   if (last && last->op == curr->op)
     800              :     {
     801         5706 :       switch (opcode)
     802              :         {
     803           29 :         case MAX_EXPR:
     804           29 :         case MIN_EXPR:
     805           29 :         case BIT_IOR_EXPR:
     806           29 :         case BIT_AND_EXPR:
     807           29 :           if (dump_file && (dump_flags & TDF_DETAILS))
     808              :             {
     809            1 :               fprintf (dump_file, "Equivalence: ");
     810            1 :               print_generic_expr (dump_file, curr->op);
     811            1 :               fprintf (dump_file, " [&|minmax] ");
     812            1 :               print_generic_expr (dump_file, last->op);
     813            1 :               fprintf (dump_file, " -> ");
     814            1 :               print_generic_stmt (dump_file, last->op);
     815              :             }
     816              : 
     817           29 :           ops->ordered_remove (i);
     818           29 :           reassociate_stats.ops_eliminated ++;
     819              : 
     820           29 :           return true;
     821              : 
     822          138 :         case BIT_XOR_EXPR:
     823          138 :           if (dump_file && (dump_flags & TDF_DETAILS))
     824              :             {
     825            0 :               fprintf (dump_file, "Equivalence: ");
     826            0 :               print_generic_expr (dump_file, curr->op);
     827            0 :               fprintf (dump_file, " ^ ");
     828            0 :               print_generic_expr (dump_file, last->op);
     829            0 :               fprintf (dump_file, " -> nothing\n");
     830              :             }
     831              : 
     832          138 :           reassociate_stats.ops_eliminated += 2;
     833              : 
     834          138 :           if (ops->length () == 2)
     835              :             {
     836            1 :               ops->truncate (0);
     837            1 :               add_to_ops_vec (ops, build_zero_cst (TREE_TYPE (last->op)));
     838            1 :               *all_done = true;
     839              :             }
     840              :           else
     841              :             {
     842          137 :               ops->ordered_remove (i-1);
     843          137 :               ops->ordered_remove (i-1);
     844              :             }
     845              : 
     846              :           return true;
     847              : 
     848              :         default:
     849              :           break;
     850              :         }
     851              :     }
     852              :   return false;
     853              : }
     854              : 
     855              : static vec<tree> plus_negates;
     856              : 
     857              : /* If OPCODE is PLUS_EXPR, CURR->OP is a negate expression or a bitwise not
     858              :    expression, look in OPS for a corresponding positive operation to cancel
     859              :    it out.  If we find one, remove the other from OPS, replace
     860              :    OPS[CURRINDEX] with 0 or -1, respectively, and return true.  Otherwise,
     861              :    return false. */
     862              : 
     863              : static bool
     864      9876247 : eliminate_plus_minus_pair (enum tree_code opcode,
     865              :                            vec<operand_entry *> *ops,
     866              :                            unsigned int currindex,
     867              :                            operand_entry *curr)
     868              : {
     869      9876247 :   tree negateop;
     870      9876247 :   tree notop;
     871      9876247 :   unsigned int i;
     872      9876247 :   operand_entry *oe;
     873              : 
     874      9876247 :   if (opcode != PLUS_EXPR || TREE_CODE (curr->op) != SSA_NAME)
     875              :     return false;
     876              : 
     877      3128396 :   negateop = get_unary_op (curr->op, NEGATE_EXPR);
     878      3128396 :   notop = get_unary_op (curr->op, BIT_NOT_EXPR);
     879      3128396 :   if (negateop == NULL_TREE && notop == NULL_TREE)
     880              :     return false;
     881              : 
     882              :   /* Any non-negated version will have a rank that is one less than
     883              :      the current rank.  So once we hit those ranks, if we don't find
     884              :      one, we can stop.  */
     885              : 
     886       135292 :   for (i = currindex + 1;
     887       198884 :        ops->iterate (i, &oe)
     888       246311 :        && oe->rank >= curr->rank - 1 ;
     889              :        i++)
     890              :     {
     891        47427 :       if (negateop
     892        47427 :           && ops_equal_values_p (oe->op, negateop))
     893              :         {
     894         1669 :           if (dump_file && (dump_flags & TDF_DETAILS))
     895              :             {
     896            0 :               fprintf (dump_file, "Equivalence: ");
     897            0 :               print_generic_expr (dump_file, negateop);
     898            0 :               fprintf (dump_file, " + -");
     899            0 :               print_generic_expr (dump_file, oe->op);
     900            0 :               fprintf (dump_file, " -> 0\n");
     901              :             }
     902              : 
     903         1669 :           ops->ordered_remove (i);
     904         1669 :           add_to_ops_vec (ops, build_zero_cst (TREE_TYPE (oe->op)));
     905         1669 :           ops->ordered_remove (currindex);
     906         1669 :           reassociate_stats.ops_eliminated ++;
     907              : 
     908         1669 :           return true;
     909              :         }
     910        45758 :       else if (notop
     911        45758 :                && ops_equal_values_p (oe->op, notop))
     912              :         {
     913         1908 :           tree op_type = TREE_TYPE (oe->op);
     914              : 
     915         1908 :           if (dump_file && (dump_flags & TDF_DETAILS))
     916              :             {
     917            0 :               fprintf (dump_file, "Equivalence: ");
     918            0 :               print_generic_expr (dump_file, notop);
     919            0 :               fprintf (dump_file, " + ~");
     920            0 :               print_generic_expr (dump_file, oe->op);
     921            0 :               fprintf (dump_file, " -> -1\n");
     922              :             }
     923              : 
     924         1908 :           ops->ordered_remove (i);
     925         1908 :           add_to_ops_vec (ops, build_all_ones_cst (op_type));
     926         1908 :           ops->ordered_remove (currindex);
     927         1908 :           reassociate_stats.ops_eliminated ++;
     928              : 
     929         1908 :           return true;
     930              :         }
     931              :     }
     932              : 
     933              :   /* If CURR->OP is a negate expr without nop conversion in a plus expr:
     934              :      save it for later inspection in repropagate_negates().  */
     935        87865 :   if (negateop != NULL_TREE
     936        87865 :       && gimple_assign_rhs_code (SSA_NAME_DEF_STMT (curr->op)) == NEGATE_EXPR)
     937        87358 :     plus_negates.safe_push (curr->op);
     938              : 
     939              :   return false;
     940              : }
     941              : 
     942              : /* If OPCODE is BIT_IOR_EXPR, BIT_AND_EXPR, and, CURR->OP is really a
     943              :    bitwise not expression, look in OPS for a corresponding operand to
     944              :    cancel it out.  If we find one, remove the other from OPS, replace
     945              :    OPS[CURRINDEX] with 0, and return true.  Otherwise, return
     946              :    false. */
     947              : 
     948              : static bool
     949      9876415 : eliminate_not_pairs (enum tree_code opcode,
     950              :                      vec<operand_entry *> *ops,
     951              :                      unsigned int currindex,
     952              :                      operand_entry *curr)
     953              : {
     954      9876415 :   tree notop;
     955      9876415 :   unsigned int i;
     956      9876415 :   operand_entry *oe;
     957              : 
     958      9876415 :   if ((opcode != BIT_IOR_EXPR && opcode != BIT_AND_EXPR)
     959      2053572 :       || TREE_CODE (curr->op) != SSA_NAME)
     960              :     return false;
     961              : 
     962      1551997 :   notop = get_unary_op (curr->op, BIT_NOT_EXPR);
     963      1551997 :   if (notop == NULL_TREE)
     964              :     return false;
     965              : 
     966              :   /* Any non-not version will have a rank that is one less than
     967              :      the current rank.  So once we hit those ranks, if we don't find
     968              :      one, we can stop.  */
     969              : 
     970        36108 :   for (i = currindex + 1;
     971      9905027 :        ops->iterate (i, &oe)
     972        72487 :        && oe->rank >= curr->rank - 1;
     973              :        i++)
     974              :     {
     975         7768 :       if (oe->op == notop)
     976              :         {
     977            1 :           if (dump_file && (dump_flags & TDF_DETAILS))
     978              :             {
     979            0 :               fprintf (dump_file, "Equivalence: ");
     980            0 :               print_generic_expr (dump_file, notop);
     981            0 :               if (opcode == BIT_AND_EXPR)
     982            0 :                 fprintf (dump_file, " & ~");
     983            0 :               else if (opcode == BIT_IOR_EXPR)
     984            0 :                 fprintf (dump_file, " | ~");
     985            0 :               print_generic_expr (dump_file, oe->op);
     986            0 :               if (opcode == BIT_AND_EXPR)
     987            0 :                 fprintf (dump_file, " -> 0\n");
     988            0 :               else if (opcode == BIT_IOR_EXPR)
     989            0 :                 fprintf (dump_file, " -> -1\n");
     990              :             }
     991              : 
     992            1 :           if (opcode == BIT_AND_EXPR)
     993            1 :             oe->op = build_zero_cst (TREE_TYPE (oe->op));
     994            0 :           else if (opcode == BIT_IOR_EXPR)
     995            0 :             oe->op = build_all_ones_cst (TREE_TYPE (oe->op));
     996              : 
     997            1 :           reassociate_stats.ops_eliminated += ops->length () - 1;
     998            1 :           ops->truncate (0);
     999            1 :           ops->quick_push (oe);
    1000            1 :           return true;
    1001              :         }
    1002              :     }
    1003              : 
    1004              :   return false;
    1005              : }
    1006              : 
    1007              : /* Use constant value that may be present in OPS to try to eliminate
    1008              :    operands.  Note that this function is only really used when we've
    1009              :    eliminated ops for other reasons, or merged constants.  Across
    1010              :    single statements, fold already does all of this, plus more.  There
    1011              :    is little point in duplicating logic, so I've only included the
    1012              :    identities that I could ever construct testcases to trigger.  */
    1013              : 
    1014              : static void
    1015      4813901 : eliminate_using_constants (enum tree_code opcode,
    1016              :                            vec<operand_entry *> *ops)
    1017              : {
    1018      4813901 :   operand_entry *oelast = ops->last ();
    1019      4813901 :   tree type = TREE_TYPE (oelast->op);
    1020              : 
    1021      4813901 :   if (oelast->rank == 0
    1022      4813901 :       && (ANY_INTEGRAL_TYPE_P (type) || FLOAT_TYPE_P (type)))
    1023              :     {
    1024      3461479 :       switch (opcode)
    1025              :         {
    1026       428196 :         case BIT_AND_EXPR:
    1027       428196 :           if (integer_zerop (oelast->op))
    1028              :             {
    1029            0 :               if (ops->length () != 1)
    1030              :                 {
    1031            0 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    1032            0 :                     fprintf (dump_file, "Found & 0, removing all other ops\n");
    1033              : 
    1034            0 :                   reassociate_stats.ops_eliminated += ops->length () - 1;
    1035              : 
    1036            0 :                   ops->truncate (0);
    1037            0 :                   ops->quick_push (oelast);
    1038         1920 :                   return;
    1039              :                 }
    1040              :             }
    1041       428196 :           else if (integer_all_onesp (oelast->op))
    1042              :             {
    1043            4 :               if (ops->length () != 1)
    1044              :                 {
    1045            4 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    1046            0 :                     fprintf (dump_file, "Found & -1, removing\n");
    1047            4 :                   ops->pop ();
    1048            4 :                   reassociate_stats.ops_eliminated++;
    1049              :                 }
    1050              :             }
    1051              :           break;
    1052        72846 :         case BIT_IOR_EXPR:
    1053        72846 :           if (integer_all_onesp (oelast->op))
    1054              :             {
    1055            0 :               if (ops->length () != 1)
    1056              :                 {
    1057            0 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    1058            0 :                     fprintf (dump_file, "Found | -1, removing all other ops\n");
    1059              : 
    1060            0 :                   reassociate_stats.ops_eliminated += ops->length () - 1;
    1061              : 
    1062            0 :                   ops->truncate (0);
    1063            0 :                   ops->quick_push (oelast);
    1064            0 :                   return;
    1065              :                 }
    1066              :             }
    1067        72846 :           else if (integer_zerop (oelast->op))
    1068              :             {
    1069            4 :               if (ops->length () != 1)
    1070              :                 {
    1071            4 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    1072            0 :                     fprintf (dump_file, "Found | 0, removing\n");
    1073            4 :                   ops->pop ();
    1074            4 :                   reassociate_stats.ops_eliminated++;
    1075              :                 }
    1076              :             }
    1077              :           break;
    1078       969955 :         case MULT_EXPR:
    1079       969955 :           if (integer_zerop (oelast->op)
    1080       969955 :               || (FLOAT_TYPE_P (type)
    1081         1444 :                   && !HONOR_NANS (type)
    1082         1349 :                   && !HONOR_SIGNED_ZEROS (type)
    1083         1349 :                   && real_zerop (oelast->op)))
    1084              :             {
    1085            0 :               if (ops->length () != 1)
    1086              :                 {
    1087            0 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    1088            0 :                     fprintf (dump_file, "Found * 0, removing all other ops\n");
    1089              : 
    1090            0 :                   reassociate_stats.ops_eliminated += ops->length () - 1;
    1091            0 :                   ops->truncate (0);
    1092            0 :                   ops->quick_push (oelast);
    1093            0 :                   return;
    1094              :                 }
    1095              :             }
    1096       969955 :           else if (integer_onep (oelast->op)
    1097       969955 :                    || (FLOAT_TYPE_P (type)
    1098         1444 :                        && !HONOR_SNANS (type)
    1099         1444 :                        && real_onep (oelast->op)))
    1100              :             {
    1101            4 :               if (ops->length () != 1)
    1102              :                 {
    1103            4 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    1104            0 :                     fprintf (dump_file, "Found * 1, removing\n");
    1105            4 :                   ops->pop ();
    1106            4 :                   reassociate_stats.ops_eliminated++;
    1107            4 :                   return;
    1108              :                 }
    1109              :             }
    1110              :           break;
    1111      1811856 :         case BIT_XOR_EXPR:
    1112      1811856 :         case PLUS_EXPR:
    1113      1811856 :         case MINUS_EXPR:
    1114      1811856 :           if (integer_zerop (oelast->op)
    1115      1811856 :               || (FLOAT_TYPE_P (type)
    1116          867 :                   && (opcode == PLUS_EXPR || opcode == MINUS_EXPR)
    1117          867 :                   && fold_real_zero_addition_p (type, 0, oelast->op,
    1118              :                                                 opcode == MINUS_EXPR)))
    1119              :             {
    1120         1916 :               if (ops->length () != 1)
    1121              :                 {
    1122         1916 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    1123            0 :                     fprintf (dump_file, "Found [|^+] 0, removing\n");
    1124         1916 :                   ops->pop ();
    1125         1916 :                   reassociate_stats.ops_eliminated++;
    1126         1916 :                   return;
    1127              :                 }
    1128              :             }
    1129              :           break;
    1130              :         default:
    1131              :           break;
    1132              :         }
    1133              :     }
    1134              : }
    1135              : 
    1136              : 
    1137              : static void linearize_expr_tree (vec<operand_entry *> *, gimple *,
    1138              :                                  bool, bool);
    1139              : 
    1140              : /* Structure for tracking and counting operands.  */
    1141              : struct oecount {
    1142              :   unsigned int cnt;
    1143              :   unsigned int id;
    1144              :   enum tree_code oecode;
    1145              :   tree op;
    1146              : };
    1147              : 
    1148              : 
    1149              : /* The heap for the oecount hashtable and the sorted list of operands.  */
    1150              : static vec<oecount> cvec;
    1151              : 
    1152              : 
    1153              : /* Oecount hashtable helpers.  */
    1154              : 
    1155              : struct oecount_hasher : int_hash <int, 0, 1>
    1156              : {
    1157              :   static inline hashval_t hash (int);
    1158              :   static inline bool equal (int, int);
    1159              : };
    1160              : 
    1161              : /* Hash function for oecount.  */
    1162              : 
    1163              : inline hashval_t
    1164       154214 : oecount_hasher::hash (int p)
    1165              : {
    1166       154214 :   const oecount *c = &cvec[p - 42];
    1167       154214 :   return htab_hash_pointer (c->op) ^ (hashval_t)c->oecode;
    1168              : }
    1169              : 
    1170              : /* Comparison function for oecount.  */
    1171              : 
    1172              : inline bool
    1173        83340 : oecount_hasher::equal (int p1, int p2)
    1174              : {
    1175        83340 :   const oecount *c1 = &cvec[p1 - 42];
    1176        83340 :   const oecount *c2 = &cvec[p2 - 42];
    1177        83340 :   return c1->oecode == c2->oecode && c1->op == c2->op;
    1178              : }
    1179              : 
    1180              : /* Comparison function for qsort sorting oecount elements by count.  */
    1181              : 
    1182              : static int
    1183       602103 : oecount_cmp (const void *p1, const void *p2)
    1184              : {
    1185       602103 :   const oecount *c1 = (const oecount *)p1;
    1186       602103 :   const oecount *c2 = (const oecount *)p2;
    1187       602103 :   if (c1->cnt != c2->cnt)
    1188         9075 :     return c1->cnt > c2->cnt ? 1 : -1;
    1189              :   else
    1190              :     /* If counts are identical, use unique IDs to stabilize qsort.  */
    1191       593028 :     return c1->id > c2->id ? 1 : -1;
    1192              : }
    1193              : 
    1194              : static bool acceptable_pow_call (gcall *, tree *, HOST_WIDE_INT *);
    1195              : 
    1196              : /* Return TRUE iff STMT represents a builtin call that raises OP
    1197              :    to some constant integer exponent, as required by decrement_power.
    1198              :    This has to agree with the calls linearize_expr_tree expands into
    1199              :    repeated operands, otherwise zero_one_operation can strip OP from
    1200              :    a call that was not accounted for, for example by decrementing
    1201              :    a negative exponent over and over.  */
    1202              : 
    1203              : static bool
    1204         1318 : stmt_is_power_of_op (gimple *stmt, tree op)
    1205              : {
    1206         1318 :   tree base;
    1207         1318 :   HOST_WIDE_INT exponent;
    1208              : 
    1209         1318 :   if (!is_gimple_call (stmt))
    1210              :     return false;
    1211              : 
    1212           19 :   return (reassoc_insert_powi_p
    1213           19 :           && flag_unsafe_math_optimizations
    1214           12 :           && acceptable_pow_call (as_a <gcall *> (stmt), &base, &exponent)
    1215           21 :           && operand_equal_p (base, op, 0));
    1216              : }
    1217              : 
    1218              : /* Given STMT which is a __builtin_pow* call, decrement its exponent
    1219              :    in place and return the result.  Assumes that stmt_is_power_of_op
    1220              :    was previously called for STMT and returned TRUE.  */
    1221              : 
    1222              : static HOST_WIDE_INT
    1223            2 : decrement_power (gimple *stmt)
    1224              : {
    1225            2 :   REAL_VALUE_TYPE c, cint;
    1226            2 :   HOST_WIDE_INT power;
    1227            2 :   tree arg1;
    1228              : 
    1229            2 :   switch (gimple_call_combined_fn (stmt))
    1230              :     {
    1231            0 :     CASE_CFN_POW:
    1232            0 :       arg1 = gimple_call_arg (stmt, 1);
    1233            0 :       c = TREE_REAL_CST (arg1);
    1234            0 :       power = real_to_integer (&c) - 1;
    1235            0 :       real_from_integer (&cint, VOIDmode, power, SIGNED);
    1236            0 :       gimple_call_set_arg (stmt, 1, build_real (TREE_TYPE (arg1), cint));
    1237            0 :       return power;
    1238              : 
    1239            2 :     CASE_CFN_POWI:
    1240            2 :       arg1 = gimple_call_arg (stmt, 1);
    1241            2 :       power = TREE_INT_CST_LOW (arg1) - 1;
    1242            2 :       gimple_call_set_arg (stmt, 1, build_int_cst (TREE_TYPE (arg1), power));
    1243            2 :       return power;
    1244              : 
    1245            0 :     default:
    1246            0 :       gcc_unreachable ();
    1247              :     }
    1248              : }
    1249              : 
    1250              : /* Replace SSA defined by STMT and replace all its uses with new
    1251              :    SSA.  Also return the new SSA.  */
    1252              : 
    1253              : static tree
    1254          357 : make_new_ssa_for_def (gimple *stmt, enum tree_code opcode, tree op)
    1255              : {
    1256          357 :   gimple *use_stmt;
    1257          357 :   use_operand_p use;
    1258          357 :   imm_use_iterator iter;
    1259          357 :   tree new_lhs, new_debug_lhs = NULL_TREE;
    1260          357 :   tree lhs = gimple_get_lhs (stmt);
    1261              : 
    1262          357 :   new_lhs = make_ssa_name (TREE_TYPE (lhs));
    1263          357 :   gimple_set_lhs (stmt, new_lhs);
    1264              : 
    1265              :   /* Also need to update GIMPLE_DEBUGs.  */
    1266          771 :   FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
    1267              :     {
    1268          414 :       tree repl = new_lhs;
    1269          414 :       if (is_gimple_debug (use_stmt))
    1270              :         {
    1271           57 :           if (new_debug_lhs == NULL_TREE)
    1272              :             {
    1273           21 :               new_debug_lhs = build_debug_expr_decl (TREE_TYPE (lhs));
    1274           21 :               gdebug *def_temp
    1275           21 :                 = gimple_build_debug_bind (new_debug_lhs,
    1276           21 :                                            build2 (opcode, TREE_TYPE (lhs),
    1277              :                                                    new_lhs, op),
    1278              :                                            stmt);
    1279           21 :               gimple_set_uid (def_temp, gimple_uid (stmt));
    1280           21 :               gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
    1281           21 :               gsi_insert_after (&gsi, def_temp, GSI_SAME_STMT);
    1282              :             }
    1283              :           repl = new_debug_lhs;
    1284              :         }
    1285          828 :       FOR_EACH_IMM_USE_ON_STMT (use, iter)
    1286          414 :         SET_USE (use, repl);
    1287          414 :       update_stmt (use_stmt);
    1288          357 :     }
    1289          357 :   return new_lhs;
    1290              : }
    1291              : 
    1292              : /* Replace all SSAs defined in STMTS_TO_FIX and replace its
    1293              :    uses with new SSAs.  Also do this for the stmt that defines DEF
    1294              :    if *DEF is not OP.  */
    1295              : 
    1296              : static void
    1297          299 : make_new_ssa_for_all_defs (tree *def, enum tree_code opcode, tree op,
    1298              :                            vec<gimple *> &stmts_to_fix)
    1299              : {
    1300          299 :   unsigned i;
    1301          299 :   gimple *stmt;
    1302              : 
    1303          299 :   if (*def != op
    1304          299 :       && TREE_CODE (*def) == SSA_NAME
    1305          299 :       && (stmt = SSA_NAME_DEF_STMT (*def))
    1306          598 :       && gimple_code (stmt) != GIMPLE_NOP)
    1307          299 :     *def = make_new_ssa_for_def (stmt, opcode, op);
    1308              : 
    1309          357 :   FOR_EACH_VEC_ELT (stmts_to_fix, i, stmt)
    1310           58 :     make_new_ssa_for_def (stmt, opcode, op);
    1311          299 : }
    1312              : 
    1313              : /* Find the single immediate use of STMT's LHS, and replace it
    1314              :    with OP.  Remove STMT.  If STMT's LHS is the same as *DEF,
    1315              :    replace *DEF with OP as well.  */
    1316              : 
    1317              : static void
    1318          902 : propagate_op_to_single_use (tree op, gimple *stmt, tree *def)
    1319              : {
    1320          902 :   tree lhs;
    1321          902 :   gimple *use_stmt;
    1322          902 :   use_operand_p use;
    1323          902 :   gimple_stmt_iterator gsi;
    1324              : 
    1325          902 :   if (is_gimple_call (stmt))
    1326            0 :     lhs = gimple_call_lhs (stmt);
    1327              :   else
    1328          902 :     lhs = gimple_assign_lhs (stmt);
    1329              : 
    1330          902 :   gcc_assert (has_single_use (lhs));
    1331          902 :   single_imm_use (lhs, &use, &use_stmt);
    1332          902 :   if (lhs == *def)
    1333          609 :     *def = op;
    1334          902 :   SET_USE (use, op);
    1335          902 :   if (TREE_CODE (op) != SSA_NAME)
    1336           40 :     update_stmt (use_stmt);
    1337          902 :   gsi = gsi_for_stmt (stmt);
    1338          902 :   unlink_stmt_vdef (stmt);
    1339          902 :   reassoc_remove_stmt (&gsi);
    1340          902 :   release_defs (stmt);
    1341          902 : }
    1342              : 
    1343              : /* Walks the linear chain with result *DEF searching for an operation
    1344              :    with operand OP and code OPCODE removing that from the chain.  *DEF
    1345              :    is updated if there is only one operand but no operation left.  */
    1346              : 
    1347              : static void
    1348          908 : zero_one_operation (tree *def, enum tree_code opcode, tree op)
    1349              : {
    1350          908 :   tree orig_def = *def;
    1351          908 :   gimple *stmt = SSA_NAME_DEF_STMT (*def);
    1352              :   /* PR72835 - Record the stmt chain that has to be updated such that
    1353              :      we dont use the same LHS when the values computed are different.  */
    1354          908 :   auto_vec<gimple *, 64> stmts_to_fix;
    1355              : 
    1356         1606 :   do
    1357              :     {
    1358         1257 :       tree name;
    1359              : 
    1360         1257 :       if (opcode == MULT_EXPR)
    1361              :         {
    1362         1255 :           if (stmt_is_power_of_op (stmt, op))
    1363              :             {
    1364            0 :               if (decrement_power (stmt) == 1)
    1365              :                 {
    1366            0 :                   if (stmts_to_fix.length () > 0)
    1367            0 :                     stmts_to_fix.pop ();
    1368            0 :                   propagate_op_to_single_use (op, stmt, def);
    1369              :                 }
    1370              :               break;
    1371              :             }
    1372         1255 :           else if (gimple_assign_rhs_code (stmt) == NEGATE_EXPR)
    1373              :             {
    1374           15 :               if (gimple_assign_rhs1 (stmt) == op)
    1375              :                 {
    1376           11 :                   tree cst = build_minus_one_cst (TREE_TYPE (op));
    1377           11 :                   if (stmts_to_fix.length () > 0)
    1378           11 :                     stmts_to_fix.pop ();
    1379           11 :                   propagate_op_to_single_use (cst, stmt, def);
    1380           11 :                   break;
    1381              :                 }
    1382            4 :               else if (integer_minus_onep (op)
    1383            4 :                        || real_minus_onep (op))
    1384              :                 {
    1385            4 :                   gimple_assign_set_rhs_code
    1386            4 :                     (stmt, TREE_CODE (gimple_assign_rhs1 (stmt)));
    1387            4 :                   break;
    1388              :                 }
    1389              :             }
    1390              :         }
    1391              : 
    1392         1242 :       name = gimple_assign_rhs1 (stmt);
    1393              : 
    1394              :       /* If this is the operation we look for and one of the operands
    1395              :          is ours simply propagate the other operand into the stmts
    1396              :          single use.  */
    1397         1242 :       if (gimple_assign_rhs_code (stmt) == opcode
    1398         1242 :           && (name == op
    1399          963 :               || gimple_assign_rhs2 (stmt) == op))
    1400              :         {
    1401          891 :           if (name == op)
    1402          279 :             name = gimple_assign_rhs2 (stmt);
    1403          891 :           if (stmts_to_fix.length () > 0)
    1404          282 :             stmts_to_fix.pop ();
    1405          891 :           propagate_op_to_single_use (name, stmt, def);
    1406          891 :           break;
    1407              :         }
    1408              : 
    1409              :       /* We might have a multiply of two __builtin_pow* calls, and
    1410              :          the operand might be hiding in the rightmost one.  Likewise
    1411              :          this can happen for a negate.  */
    1412          351 :       if (opcode == MULT_EXPR
    1413          351 :           && gimple_assign_rhs_code (stmt) == opcode
    1414          351 :           && TREE_CODE (gimple_assign_rhs2 (stmt)) == SSA_NAME
    1415          637 :           && has_single_use (gimple_assign_rhs2 (stmt)))
    1416              :         {
    1417           63 :           gimple *stmt2 = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
    1418           63 :           if (stmt_is_power_of_op (stmt2, op))
    1419              :             {
    1420            2 :               if (decrement_power (stmt2) == 1)
    1421            0 :                 propagate_op_to_single_use (op, stmt2, def);
    1422              :               else
    1423            2 :                 stmts_to_fix.safe_push (stmt2);
    1424            2 :               break;
    1425              :             }
    1426           61 :           else if (is_gimple_assign (stmt2)
    1427           61 :                    && gimple_assign_rhs_code (stmt2) == NEGATE_EXPR)
    1428              :             {
    1429            0 :               if (gimple_assign_rhs1 (stmt2) == op)
    1430              :                 {
    1431            0 :                   tree cst = build_minus_one_cst (TREE_TYPE (op));
    1432            0 :                   propagate_op_to_single_use (cst, stmt2, def);
    1433            0 :                   break;
    1434              :                 }
    1435            0 :               else if (integer_minus_onep (op)
    1436            0 :                        || real_minus_onep (op))
    1437              :                 {
    1438            0 :                   stmts_to_fix.safe_push (stmt2);
    1439            0 :                   gimple_assign_set_rhs_code
    1440            0 :                     (stmt2, TREE_CODE (gimple_assign_rhs1 (stmt2)));
    1441            0 :                   break;
    1442              :                 }
    1443              :             }
    1444              :         }
    1445              : 
    1446              :       /* Continue walking the chain.  */
    1447          349 :       gcc_assert (name != op
    1448              :                   && TREE_CODE (name) == SSA_NAME);
    1449          349 :       stmt = SSA_NAME_DEF_STMT (name);
    1450          349 :       stmts_to_fix.safe_push (stmt);
    1451          349 :     }
    1452              :   while (1);
    1453              : 
    1454          908 :   if (stmts_to_fix.length () > 0 || *def == orig_def)
    1455          299 :     make_new_ssa_for_all_defs (def, opcode, op, stmts_to_fix);
    1456          908 : }
    1457              : 
    1458              : /* Returns true if statement S1 dominates statement S2.  Like
    1459              :    stmt_dominates_stmt_p, but uses stmt UIDs to optimize.  */
    1460              : 
    1461              : static bool
    1462      4862160 : reassoc_stmt_dominates_stmt_p (gimple *s1, gimple *s2)
    1463              : {
    1464      4862160 :   basic_block bb1 = gimple_bb (s1), bb2 = gimple_bb (s2);
    1465              : 
    1466              :   /* If bb1 is NULL, it should be a GIMPLE_NOP def stmt of an (D)
    1467              :      SSA_NAME.  Assume it lives at the beginning of function and
    1468              :      thus dominates everything.  */
    1469      4862160 :   if (!bb1 || s1 == s2)
    1470              :     return true;
    1471              : 
    1472              :   /* If bb2 is NULL, it doesn't dominate any stmt with a bb.  */
    1473      4858978 :   if (!bb2)
    1474              :     return false;
    1475              : 
    1476      4851345 :   if (bb1 == bb2)
    1477              :     {
    1478              :       /* PHIs in the same basic block are assumed to be
    1479              :          executed all in parallel, if only one stmt is a PHI,
    1480              :          it dominates the other stmt in the same basic block.  */
    1481      4708524 :       if (gimple_code (s1) == GIMPLE_PHI)
    1482              :         return true;
    1483              : 
    1484      4582990 :       if (gimple_code (s2) == GIMPLE_PHI)
    1485              :         return false;
    1486              : 
    1487      4531059 :       gcc_assert (gimple_uid (s1) && gimple_uid (s2));
    1488              : 
    1489      4531059 :       if (gimple_uid (s1) < gimple_uid (s2))
    1490              :         return true;
    1491              : 
    1492      2487421 :       if (gimple_uid (s1) > gimple_uid (s2))
    1493              :         return false;
    1494              : 
    1495        37195 :       gimple_stmt_iterator gsi = gsi_for_stmt (s1);
    1496        37195 :       unsigned int uid = gimple_uid (s1);
    1497        81467 :       for (gsi_next (&gsi); !gsi_end_p (gsi); gsi_next (&gsi))
    1498              :         {
    1499        79253 :           gimple *s = gsi_stmt (gsi);
    1500        79253 :           if (gimple_uid (s) != uid)
    1501              :             break;
    1502        47570 :           if (s == s2)
    1503              :             return true;
    1504              :         }
    1505              : 
    1506              :       return false;
    1507              :     }
    1508              : 
    1509       142821 :   return dominated_by_p (CDI_DOMINATORS, bb2, bb1);
    1510              : }
    1511              : 
    1512              : /* Insert STMT after INSERT_POINT.  */
    1513              : 
    1514              : static void
    1515        39443 : insert_stmt_after (gimple *stmt, gimple *insert_point)
    1516              : {
    1517        39443 :   gimple_stmt_iterator gsi;
    1518        39443 :   basic_block bb;
    1519              : 
    1520        39443 :   if (gimple_code (insert_point) == GIMPLE_PHI)
    1521           30 :     bb = gimple_bb (insert_point);
    1522        39413 :   else if (!stmt_ends_bb_p (insert_point))
    1523              :     {
    1524        39405 :       gsi = gsi_for_stmt (insert_point);
    1525        39405 :       gimple_set_uid (stmt, gimple_uid (insert_point));
    1526        39405 :       gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
    1527        39405 :       return;
    1528              :     }
    1529            8 :   else if (gimple_code (insert_point) == GIMPLE_ASM
    1530            5 :            && gimple_asm_nlabels (as_a <gasm *> (insert_point)) != 0
    1531           13 :            && !single_succ_p (gimple_bb (insert_point)))
    1532              :     /* We have no idea where to insert - it depends on where the
    1533              :        uses will be placed.  */
    1534            0 :     gcc_unreachable ();
    1535              :   else
    1536              :     /* We assume INSERT_POINT is a SSA_NAME_DEF_STMT of some SSA_NAME,
    1537              :        thus if it must end a basic block, it should be a call that can
    1538              :        throw, or some assignment that can throw.  If it throws, the LHS
    1539              :        of it will not be initialized though, so only valid places using
    1540              :        the SSA_NAME should be dominated by the fallthru edge.  */
    1541            8 :     bb = find_fallthru_edge (gimple_bb (insert_point)->succs)->dest;
    1542           38 :   gsi = gsi_after_labels (bb);
    1543           38 :   if (gsi_end_p (gsi))
    1544              :     {
    1545            0 :       gimple_stmt_iterator gsi2 = gsi_last_bb (bb);
    1546            0 :       gimple_set_uid (stmt,
    1547            0 :                       gsi_end_p (gsi2) ? 1 : gimple_uid (gsi_stmt (gsi2)));
    1548              :     }
    1549              :   else
    1550           38 :     gimple_set_uid (stmt, gimple_uid (gsi_stmt (gsi)));
    1551           38 :   gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
    1552              : }
    1553              : 
    1554              : /* Builds one statement performing OP1 OPCODE OP2 using TMPVAR for
    1555              :    the result.  Places the statement after the definition of either
    1556              :    OP1 or OP2.  Returns the new statement.  */
    1557              : 
    1558              : static gassign *
    1559         8831 : build_and_add_sum (tree type, tree op1, tree op2, enum tree_code opcode)
    1560              : {
    1561         8831 :   gimple *op1def = NULL, *op2def = NULL;
    1562         8831 :   gimple_stmt_iterator gsi;
    1563         8831 :   tree op;
    1564         8831 :   gassign *sum;
    1565              : 
    1566              :   /* Create the addition statement.  */
    1567         8831 :   op = make_ssa_name (type);
    1568         8831 :   sum = gimple_build_assign (op, opcode, op1, op2);
    1569              : 
    1570              :   /* Find an insertion place and insert.  */
    1571         8831 :   if (TREE_CODE (op1) == SSA_NAME)
    1572         8830 :     op1def = SSA_NAME_DEF_STMT (op1);
    1573         8831 :   if (TREE_CODE (op2) == SSA_NAME)
    1574         8538 :     op2def = SSA_NAME_DEF_STMT (op2);
    1575         8830 :   if ((!op1def || gimple_nop_p (op1def))
    1576         8917 :       && (!op2def || gimple_nop_p (op2def)))
    1577              :     {
    1578           86 :       gsi = gsi_start_nondebug_after_labels_bb
    1579           86 :                 (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
    1580           86 :       if (!gsi_end_p (gsi)
    1581           86 :           && is_gimple_call (gsi_stmt (gsi))
    1582           98 :           && (gimple_call_flags (gsi_stmt (gsi)) & ECF_RETURNS_TWICE))
    1583              :         {
    1584              :           /* Don't add statements before a returns_twice call at the start
    1585              :              of a function.  */
    1586            2 :           split_edge (single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
    1587            2 :           gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
    1588              :         }
    1589           86 :       if (gsi_end_p (gsi))
    1590              :         {
    1591            2 :           gimple_stmt_iterator gsi2
    1592            2 :             = gsi_last_bb (single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
    1593            2 :           gimple_set_uid (sum,
    1594            2 :                           gsi_end_p (gsi2) ? 1 : gimple_uid (gsi_stmt (gsi2)));
    1595              :         }
    1596              :       else
    1597           84 :         gimple_set_uid (sum, gimple_uid (gsi_stmt (gsi)));
    1598           86 :       gsi_insert_before (&gsi, sum, GSI_NEW_STMT);
    1599              :     }
    1600              :   else
    1601              :     {
    1602         8745 :       gimple *insert_point;
    1603         8744 :       if ((!op1def || gimple_nop_p (op1def))
    1604        17489 :            || (op2def && !gimple_nop_p (op2def)
    1605         8401 :                && reassoc_stmt_dominates_stmt_p (op1def, op2def)))
    1606              :         insert_point = op2def;
    1607              :       else
    1608              :         insert_point = op1def;
    1609         8745 :       insert_stmt_after (sum, insert_point);
    1610              :     }
    1611         8831 :   update_stmt (sum);
    1612              : 
    1613         8831 :   return sum;
    1614              : }
    1615              : 
    1616              : /* Perform un-distribution of divisions and multiplications.
    1617              :    A * X + B * X is transformed into (A + B) * X and A / X + B / X
    1618              :    to (A + B) / X for real X.
    1619              : 
    1620              :    The algorithm is organized as follows.
    1621              : 
    1622              :     - First we walk the addition chain *OPS looking for summands that
    1623              :       are defined by a multiplication or a real division.  This results
    1624              :       in the candidates bitmap with relevant indices into *OPS.
    1625              : 
    1626              :     - Second we build the chains of multiplications or divisions for
    1627              :       these candidates, counting the number of occurrences of (operand, code)
    1628              :       pairs in all of the candidates chains.
    1629              : 
    1630              :     - Third we sort the (operand, code) pairs by number of occurrence and
    1631              :       process them starting with the pair with the most uses.
    1632              : 
    1633              :       * For each such pair we walk the candidates again to build a
    1634              :         second candidate bitmap noting all multiplication/division chains
    1635              :         that have at least one occurrence of (operand, code).
    1636              : 
    1637              :       * We build an alternate addition chain only covering these
    1638              :         candidates with one (operand, code) operation removed from their
    1639              :         multiplication/division chain.
    1640              : 
    1641              :       * The first candidate gets replaced by the alternate addition chain
    1642              :         multiplied/divided by the operand.
    1643              : 
    1644              :       * All candidate chains get disabled for further processing and
    1645              :         processing of (operand, code) pairs continues.
    1646              : 
    1647              :   The alternate addition chains built are re-processed by the main
    1648              :   reassociation algorithm which allows optimizing a * x * y + b * y * x
    1649              :   to (a + b ) * x * y in one invocation of the reassociation pass.  */
    1650              : 
    1651              : static bool
    1652      4811604 : undistribute_ops_list (enum tree_code opcode,
    1653              :                        vec<operand_entry *> *ops, class loop *loop)
    1654              : {
    1655      4811604 :   unsigned int length = ops->length ();
    1656      4811604 :   operand_entry *oe1;
    1657      4811604 :   unsigned i, j;
    1658      4811604 :   unsigned nr_candidates, nr_candidates2;
    1659      4811604 :   sbitmap_iterator sbi0;
    1660      4811604 :   vec<operand_entry *> *subops;
    1661      4811604 :   bool changed = false;
    1662      4811604 :   unsigned int next_oecount_id = 0;
    1663              : 
    1664      4811604 :   if (length <= 1
    1665      4811604 :       || opcode != PLUS_EXPR)
    1666              :     return false;
    1667              : 
    1668              :   /* Build a list of candidates to process.  */
    1669      2369813 :   auto_sbitmap candidates (length);
    1670      2369813 :   bitmap_clear (candidates);
    1671      2369813 :   nr_candidates = 0;
    1672      7286972 :   FOR_EACH_VEC_ELT (*ops, i, oe1)
    1673              :     {
    1674      4917159 :       enum tree_code dcode;
    1675      4917159 :       gimple *oe1def;
    1676              : 
    1677      4917159 :       if (TREE_CODE (oe1->op) != SSA_NAME)
    1678      1796664 :         continue;
    1679      3120495 :       oe1def = SSA_NAME_DEF_STMT (oe1->op);
    1680      3120495 :       if (!is_gimple_assign (oe1def))
    1681      1133527 :         continue;
    1682      1986968 :       dcode = gimple_assign_rhs_code (oe1def);
    1683      3740108 :       if ((dcode != MULT_EXPR
    1684      1986968 :            && dcode != RDIV_EXPR)
    1685      1986968 :           || !is_reassociable_op (oe1def, dcode, loop))
    1686      1753140 :         continue;
    1687              : 
    1688       233828 :       bitmap_set_bit (candidates, i);
    1689       233828 :       nr_candidates++;
    1690              :     }
    1691              : 
    1692      2369813 :   if (nr_candidates < 2)
    1693              :     return false;
    1694              : 
    1695        16366 :   if (dump_file && (dump_flags & TDF_DETAILS))
    1696              :     {
    1697            1 :       fprintf (dump_file, "searching for un-distribute opportunities ");
    1698            2 :       print_generic_expr (dump_file,
    1699            1 :         (*ops)[bitmap_first_set_bit (candidates)]->op, TDF_NONE);
    1700            1 :       fprintf (dump_file, " %d\n", nr_candidates);
    1701              :     }
    1702              : 
    1703              :   /* Build linearized sub-operand lists and the counting table.  */
    1704        16366 :   cvec.create (0);
    1705              : 
    1706        16366 :   hash_table<oecount_hasher> ctable (15);
    1707              : 
    1708              :   /* ??? Macro arguments cannot have multi-argument template types in
    1709              :      them.  This typedef is needed to workaround that limitation.  */
    1710        16366 :   typedef vec<operand_entry *> vec_operand_entry_t_heap;
    1711        32732 :   subops = XCNEWVEC (vec_operand_entry_t_heap, ops->length ());
    1712        72803 :   EXECUTE_IF_SET_IN_BITMAP (candidates, 0, i, sbi0)
    1713              :     {
    1714        40071 :       gimple *oedef;
    1715        40071 :       enum tree_code oecode;
    1716        40071 :       unsigned j;
    1717              : 
    1718        40071 :       oedef = SSA_NAME_DEF_STMT ((*ops)[i]->op);
    1719        40071 :       oecode = gimple_assign_rhs_code (oedef);
    1720        40071 :       linearize_expr_tree (&subops[i], oedef,
    1721              :                            associative_tree_code (oecode), false);
    1722              : 
    1723       201058 :       FOR_EACH_VEC_ELT (subops[i], j, oe1)
    1724              :         {
    1725        80845 :           oecount c;
    1726        80845 :           int *slot;
    1727        80845 :           int idx;
    1728        80845 :           c.oecode = oecode;
    1729        80845 :           c.cnt = 1;
    1730        80845 :           c.id = next_oecount_id++;
    1731        80845 :           c.op = oe1->op;
    1732        80845 :           cvec.safe_push (c);
    1733        80845 :           idx = cvec.length () + 41;
    1734        80845 :           slot = ctable.find_slot (idx, INSERT);
    1735        80845 :           if (!*slot)
    1736              :             {
    1737        79815 :               *slot = idx;
    1738              :             }
    1739              :           else
    1740              :             {
    1741         1030 :               cvec.pop ();
    1742         1030 :               cvec[*slot - 42].cnt++;
    1743              :             }
    1744              :         }
    1745              :     }
    1746              : 
    1747              :   /* Sort the counting table.  */
    1748        16366 :   cvec.qsort (oecount_cmp);
    1749              : 
    1750        16366 :   if (dump_file && (dump_flags & TDF_DETAILS))
    1751              :     {
    1752            1 :       oecount *c;
    1753            1 :       fprintf (dump_file, "Candidates:\n");
    1754            5 :       FOR_EACH_VEC_ELT (cvec, j, c)
    1755              :         {
    1756            3 :           fprintf (dump_file, "  %u %s: ", c->cnt,
    1757            3 :                    c->oecode == MULT_EXPR
    1758              :                    ? "*" : c->oecode == RDIV_EXPR ? "/" : "?");
    1759            3 :           print_generic_expr (dump_file, c->op);
    1760            3 :           fprintf (dump_file, "\n");
    1761              :         }
    1762              :     }
    1763              : 
    1764              :   /* Process the (operand, code) pairs in order of most occurrence.  */
    1765        16366 :   auto_sbitmap candidates2 (length);
    1766        33453 :   while (!cvec.is_empty ())
    1767              :     {
    1768        17017 :       oecount *c = &cvec.last ();
    1769        17017 :       if (c->cnt < 2)
    1770              :         break;
    1771              : 
    1772              :       /* Now collect the operands in the outer chain that contain
    1773              :          the common operand in their inner chain.  */
    1774          721 :       bitmap_clear (candidates2);
    1775          721 :       nr_candidates2 = 0;
    1776         4762 :       EXECUTE_IF_SET_IN_BITMAP (candidates, 0, i, sbi0)
    1777              :         {
    1778         3320 :           gimple *oedef;
    1779         3320 :           enum tree_code oecode;
    1780         3320 :           unsigned j;
    1781         3320 :           tree op = (*ops)[i]->op;
    1782              : 
    1783              :           /* If we undistributed in this chain already this may be
    1784              :              a constant.  */
    1785         3320 :           if (TREE_CODE (op) != SSA_NAME)
    1786          762 :             continue;
    1787              : 
    1788         2558 :           oedef = SSA_NAME_DEF_STMT (op);
    1789         2558 :           oecode = gimple_assign_rhs_code (oedef);
    1790         2558 :           if (oecode != c->oecode)
    1791            2 :             continue;
    1792              : 
    1793         9000 :           FOR_EACH_VEC_ELT (subops[i], j, oe1)
    1794              :             {
    1795         4629 :               if (oe1->op == c->op)
    1796              :                 {
    1797         1238 :                   bitmap_set_bit (candidates2, i);
    1798         1238 :                   ++nr_candidates2;
    1799         1238 :                   break;
    1800              :                 }
    1801              :             }
    1802              :         }
    1803              : 
    1804          721 :       if (nr_candidates2 >= 2)
    1805              :         {
    1806          345 :           operand_entry *oe1, *oe2;
    1807          345 :           gassign *prod;
    1808          345 :           int first = bitmap_first_set_bit (candidates2);
    1809              : 
    1810              :           /* Build the new addition chain.  */
    1811          345 :           oe1 = (*ops)[first];
    1812          345 :           if (dump_file && (dump_flags & TDF_DETAILS))
    1813              :             {
    1814            0 :               fprintf (dump_file, "Building (");
    1815            0 :               print_generic_expr (dump_file, oe1->op);
    1816              :             }
    1817          345 :           zero_one_operation (&oe1->op, c->oecode, c->op);
    1818         1253 :           EXECUTE_IF_SET_IN_BITMAP (candidates2, first+1, i, sbi0)
    1819              :             {
    1820          563 :               gimple *sum;
    1821          563 :               oe2 = (*ops)[i];
    1822          563 :               if (dump_file && (dump_flags & TDF_DETAILS))
    1823              :                 {
    1824            0 :                   fprintf (dump_file, " + ");
    1825            0 :                   print_generic_expr (dump_file, oe2->op);
    1826              :                 }
    1827          563 :               zero_one_operation (&oe2->op, c->oecode, c->op);
    1828          563 :               sum = build_and_add_sum (TREE_TYPE (oe1->op),
    1829              :                                        oe1->op, oe2->op, opcode);
    1830          563 :               oe2->op = build_zero_cst (TREE_TYPE (oe2->op));
    1831          563 :               oe2->rank = 0;
    1832          563 :               oe1->op = gimple_get_lhs (sum);
    1833              :             }
    1834              : 
    1835              :           /* Apply the multiplication/division.  */
    1836          345 :           prod = build_and_add_sum (TREE_TYPE (oe1->op),
    1837              :                                     oe1->op, c->op, c->oecode);
    1838          345 :           if (dump_file && (dump_flags & TDF_DETAILS))
    1839              :             {
    1840            0 :               fprintf (dump_file, ") %s ", c->oecode == MULT_EXPR ? "*" : "/");
    1841            0 :               print_generic_expr (dump_file, c->op);
    1842            0 :               fprintf (dump_file, "\n");
    1843              :             }
    1844              : 
    1845              :           /* Record it in the addition chain and disable further
    1846              :              undistribution with this op.  */
    1847          345 :           oe1->op = gimple_assign_lhs (prod);
    1848          345 :           oe1->rank = get_rank (oe1->op);
    1849          345 :           subops[first].release ();
    1850              : 
    1851          345 :           changed = true;
    1852              :         }
    1853              : 
    1854          721 :       cvec.pop ();
    1855              :     }
    1856              : 
    1857        71288 :   for (i = 0; i < ops->length (); ++i)
    1858        54922 :     subops[i].release ();
    1859        16366 :   free (subops);
    1860        16366 :   cvec.release ();
    1861              : 
    1862        16366 :   return changed;
    1863      2369813 : }
    1864              : 
    1865              : /* Pair to hold the information of one specific VECTOR_TYPE SSA_NAME:
    1866              :    first: element index for each relevant BIT_FIELD_REF.
    1867              :    second: the index of vec ops* for each relevant BIT_FIELD_REF.  */
    1868              : typedef std::pair<unsigned, unsigned> v_info_elem;
    1869         8014 : struct v_info {
    1870              :   tree vec_type;
    1871              :   auto_vec<v_info_elem, 32> vec;
    1872              : };
    1873              : typedef v_info *v_info_ptr;
    1874              : 
    1875              : /* Comparison function for qsort on VECTOR SSA_NAME trees by machine mode.  */
    1876              : static int
    1877        10567 : sort_by_mach_mode (const void *p_i, const void *p_j)
    1878              : {
    1879        10567 :   const tree tr1 = *((const tree *) p_i);
    1880        10567 :   const tree tr2 = *((const tree *) p_j);
    1881        10567 :   unsigned int mode1 = TYPE_MODE (TREE_TYPE (tr1));
    1882        10567 :   unsigned int mode2 = TYPE_MODE (TREE_TYPE (tr2));
    1883        10567 :   if (mode1 > mode2)
    1884              :     return 1;
    1885        10541 :   else if (mode1 < mode2)
    1886              :     return -1;
    1887        10499 :   if (SSA_NAME_VERSION (tr1) < SSA_NAME_VERSION (tr2))
    1888              :     return -1;
    1889         5059 :   else if (SSA_NAME_VERSION (tr1) > SSA_NAME_VERSION (tr2))
    1890         5059 :     return 1;
    1891              :   return 0;
    1892              : }
    1893              : 
    1894              : /* Cleanup hash map for VECTOR information.  */
    1895              : static void
    1896      4578818 : cleanup_vinfo_map (hash_map<tree, v_info_ptr> &info_map)
    1897              : {
    1898      4586832 :   for (hash_map<tree, v_info_ptr>::iterator it = info_map.begin ();
    1899      4586832 :        it != info_map.end (); ++it)
    1900              :     {
    1901         8014 :       v_info_ptr info = (*it).second;
    1902         8014 :       delete info;
    1903         8014 :       (*it).second = NULL;
    1904              :     }
    1905      4578818 : }
    1906              : 
    1907              : /* Perform un-distribution of BIT_FIELD_REF on VECTOR_TYPE.
    1908              :      V1[0] + V1[1] + ... + V1[k] + V2[0] + V2[1] + ... + V2[k] + ... Vn[k]
    1909              :    is transformed to
    1910              :      Vs = (V1 + V2 + ... + Vn)
    1911              :      Vs[0] + Vs[1] + ... + Vs[k]
    1912              : 
    1913              :    The basic steps are listed below:
    1914              : 
    1915              :     1) Check the addition chain *OPS by looking those summands coming from
    1916              :        VECTOR bit_field_ref on VECTOR type.  Put the information into
    1917              :        v_info_map for each satisfied summand, using VECTOR SSA_NAME as key.
    1918              : 
    1919              :     2) For each key (VECTOR SSA_NAME), validate all its BIT_FIELD_REFs are
    1920              :        continuous, they can cover the whole VECTOR perfectly without any holes.
    1921              :        Obtain one VECTOR list which contain candidates to be transformed.
    1922              : 
    1923              :     3) Sort the VECTOR list by machine mode of VECTOR type, for each group of
    1924              :        candidates with same mode, build the addition statements for them and
    1925              :        generate BIT_FIELD_REFs accordingly.
    1926              : 
    1927              :    TODO:
    1928              :        The current implementation requires the whole VECTORs should be fully
    1929              :        covered, but it can be extended to support partial, checking adjacent
    1930              :        but not fill the whole, it may need some cost model to define the
    1931              :        boundary to do or not.
    1932              : */
    1933              : static bool
    1934      4811604 : undistribute_bitref_for_vector (enum tree_code opcode,
    1935              :                                 vec<operand_entry *> *ops, struct loop *loop)
    1936              : {
    1937      4811604 :   if (ops->length () <= 1)
    1938              :     return false;
    1939              : 
    1940      4808192 :   if (opcode != PLUS_EXPR
    1941      4808192 :       && opcode != MULT_EXPR
    1942              :       && opcode != BIT_XOR_EXPR
    1943      1292099 :       && opcode != BIT_IOR_EXPR
    1944       891410 :       && opcode != BIT_AND_EXPR)
    1945              :     return false;
    1946              : 
    1947      4578818 :   hash_map<tree, v_info_ptr> v_info_map;
    1948      4578818 :   operand_entry *oe1;
    1949      4578818 :   unsigned i;
    1950              : 
    1951              :   /* Find those summands from VECTOR BIT_FIELD_REF in addition chain, put the
    1952              :      information into map.  */
    1953     18559981 :   FOR_EACH_VEC_ELT (*ops, i, oe1)
    1954              :     {
    1955      9402345 :       enum tree_code dcode;
    1956              : 
    1957      9402345 :       if (TREE_CODE (oe1->op) != SSA_NAME)
    1958      3281211 :         continue;
    1959      6121134 :       auto oe1def = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (oe1->op));
    1960      6121134 :       if (!oe1def)
    1961      1549348 :         continue;
    1962      4571786 :       dcode = gimple_assign_rhs_code (oe1def);
    1963      4571786 :       if (dcode != BIT_FIELD_REF || !is_reassociable_op (oe1def, dcode, loop))
    1964      4516834 :         continue;
    1965              : 
    1966        54952 :       tree rhs = gimple_assign_rhs1 (oe1def);
    1967        54952 :       tree vec = TREE_OPERAND (rhs, 0);
    1968        54952 :       tree vec_type = TREE_TYPE (vec);
    1969              : 
    1970        54952 :       if (TREE_CODE (vec) != SSA_NAME || !VECTOR_TYPE_P (vec_type))
    1971        30444 :         continue;
    1972              : 
    1973              :       /* Ignore it if target machine can't support this VECTOR type.  */
    1974        24508 :       if (!VECTOR_MODE_P (TYPE_MODE (vec_type)))
    1975         5617 :         continue;
    1976              : 
    1977              :       /* Check const vector type, constrain BIT_FIELD_REF offset and size.  */
    1978        18891 :       if (!TYPE_VECTOR_SUBPARTS (vec_type).is_constant ())
    1979              :         continue;
    1980              : 
    1981        18891 :       if (VECTOR_TYPE_P (TREE_TYPE (rhs))
    1982        18891 :           || !is_a <scalar_mode> (TYPE_MODE (TREE_TYPE (rhs))))
    1983         7824 :         continue;
    1984              : 
    1985              :       /* The type of BIT_FIELD_REF might not be equal to the element type of
    1986              :          the vector.  We want to use a vector type with element type the
    1987              :          same as the BIT_FIELD_REF and size the same as TREE_TYPE (vec).  */
    1988        11067 :       if (!useless_type_conversion_p (TREE_TYPE (rhs), TREE_TYPE (vec_type)))
    1989              :         {
    1990         1893 :           machine_mode simd_mode;
    1991         1893 :           unsigned HOST_WIDE_INT size, nunits;
    1992         1893 :           unsigned HOST_WIDE_INT elem_size
    1993         1893 :             = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (rhs)));
    1994         3786 :           if (!GET_MODE_BITSIZE (TYPE_MODE (vec_type)).is_constant (&size))
    1995      9391712 :             continue;
    1996         1893 :           if (size <= elem_size || (size % elem_size) != 0)
    1997            0 :             continue;
    1998         1893 :           nunits = size / elem_size;
    1999         1893 :           if (!mode_for_vector (SCALAR_TYPE_MODE (TREE_TYPE (rhs)),
    2000         1893 :                                 nunits).exists (&simd_mode))
    2001            0 :             continue;
    2002         1893 :           vec_type = build_vector_type_for_mode (TREE_TYPE (rhs), simd_mode);
    2003              : 
    2004              :           /* Ignore it if target machine can't support this VECTOR type.  */
    2005         1893 :           if (!VECTOR_MODE_P (TYPE_MODE (vec_type)))
    2006            0 :             continue;
    2007              : 
    2008              :           /* Check const vector type, constrain BIT_FIELD_REF offset and
    2009              :              size.  */
    2010         1893 :           if (!TYPE_VECTOR_SUBPARTS (vec_type).is_constant ())
    2011              :             continue;
    2012              : 
    2013         3786 :           if (maybe_ne (GET_MODE_SIZE (TYPE_MODE (vec_type)),
    2014         3786 :                         GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (vec)))))
    2015            0 :             continue;
    2016              :         }
    2017              : 
    2018        11067 :       tree elem_type = TREE_TYPE (vec_type);
    2019        11067 :       unsigned HOST_WIDE_INT elem_size = tree_to_uhwi (TYPE_SIZE (elem_type));
    2020        11067 :       if (maybe_ne (bit_field_size (rhs), elem_size))
    2021            0 :         continue;
    2022              : 
    2023        11067 :       unsigned idx;
    2024        11067 :       if (!constant_multiple_p (bit_field_offset (rhs), elem_size, &idx))
    2025            0 :         continue;
    2026              : 
    2027              :       /* Ignore it if target machine can't support this type of VECTOR
    2028              :          operation.  */
    2029        11067 :       optab op_tab = optab_for_tree_code (opcode, vec_type, optab_vector);
    2030        11067 :       if (optab_handler (op_tab, TYPE_MODE (vec_type)) == CODE_FOR_nothing)
    2031          434 :         continue;
    2032              : 
    2033        10633 :       bool existed;
    2034        10633 :       v_info_ptr &info = v_info_map.get_or_insert (vec, &existed);
    2035        10633 :       if (!existed)
    2036              :         {
    2037         8014 :           info = new v_info;
    2038         8014 :           info->vec_type = vec_type;
    2039              :         }
    2040         2619 :       else if (!types_compatible_p (vec_type, info->vec_type))
    2041            0 :         continue;
    2042        10633 :       info->vec.safe_push (std::make_pair (idx, i));
    2043              :     }
    2044              : 
    2045              :   /* At least two VECTOR to combine.  */
    2046      4578818 :   if (v_info_map.elements () <= 1)
    2047              :     {
    2048      4578569 :       cleanup_vinfo_map (v_info_map);
    2049      4578569 :       return false;
    2050              :     }
    2051              : 
    2052              :   /* Verify all VECTOR candidates by checking two conditions:
    2053              :        1) sorted offsets are adjacent, no holes.
    2054              :        2) can fill the whole VECTOR perfectly.
    2055              :      And add the valid candidates to a vector for further handling.  */
    2056          249 :   auto_vec<tree> valid_vecs (v_info_map.elements ());
    2057         1211 :   for (hash_map<tree, v_info_ptr>::iterator it = v_info_map.begin ();
    2058         1211 :        it != v_info_map.end (); ++it)
    2059              :     {
    2060          962 :       tree cand_vec = (*it).first;
    2061          962 :       v_info_ptr cand_info = (*it).second;
    2062          962 :       unsigned int num_elems
    2063          962 :         = TYPE_VECTOR_SUBPARTS (cand_info->vec_type).to_constant ();
    2064         1924 :       if (cand_info->vec.length () != num_elems)
    2065          597 :         continue;
    2066          365 :       sbitmap holes = sbitmap_alloc (num_elems);
    2067          365 :       bitmap_ones (holes);
    2068          365 :       bool valid = true;
    2069          365 :       v_info_elem *curr;
    2070         2124 :       FOR_EACH_VEC_ELT (cand_info->vec, i, curr)
    2071              :         {
    2072         1394 :           if (!bitmap_bit_p (holes, curr->first))
    2073              :             {
    2074              :               valid = false;
    2075              :               break;
    2076              :             }
    2077              :           else
    2078         1394 :             bitmap_clear_bit (holes, curr->first);
    2079              :         }
    2080          365 :       if (valid && bitmap_empty_p (holes))
    2081          365 :         valid_vecs.quick_push (cand_vec);
    2082          365 :       sbitmap_free (holes);
    2083              :     }
    2084              : 
    2085              :   /* At least two VECTOR to combine.  */
    2086          249 :   if (valid_vecs.length () <= 1)
    2087              :     {
    2088          213 :       cleanup_vinfo_map (v_info_map);
    2089          213 :       return false;
    2090              :     }
    2091              : 
    2092           36 :   valid_vecs.qsort (sort_by_mach_mode);
    2093              :   /* Go through all candidates by machine mode order, query the mode_to_total
    2094              :      to get the total number for each mode and skip the single one.  */
    2095          112 :   for (unsigned i = 0; i < valid_vecs.length () - 1; ++i)
    2096              :     {
    2097           40 :       tree tvec = valid_vecs[i];
    2098           40 :       enum machine_mode mode = TYPE_MODE (TREE_TYPE (tvec));
    2099              : 
    2100              :       /* Skip modes with only a single candidate.  */
    2101           40 :       if (TYPE_MODE (TREE_TYPE (valid_vecs[i + 1])) != mode)
    2102            0 :         continue;
    2103              : 
    2104           40 :       unsigned int idx, j;
    2105           40 :       gimple *sum = NULL;
    2106           40 :       tree sum_vec = tvec;
    2107           40 :       v_info_ptr info_ptr = *(v_info_map.get (tvec));
    2108           40 :       v_info_elem *elem;
    2109           40 :       tree vec_type = info_ptr->vec_type;
    2110              : 
    2111              :       /* Build the sum for all candidates with same mode.  */
    2112          323 :       do
    2113              :         {
    2114          969 :           sum = build_and_add_sum (vec_type, sum_vec,
    2115          323 :                                    valid_vecs[i + 1], opcode);
    2116              :           /* Update the operands only after build_and_add_sum,
    2117              :              so that we don't have to repeat the placement algorithm
    2118              :              of build_and_add_sum.  */
    2119          323 :           if (sum_vec == tvec
    2120          323 :               && !useless_type_conversion_p (vec_type, TREE_TYPE (sum_vec)))
    2121              :             {
    2122           18 :               gimple_stmt_iterator gsi = gsi_for_stmt (sum);
    2123           18 :               tree vce = build1 (VIEW_CONVERT_EXPR, vec_type, sum_vec);
    2124           18 :               tree lhs = make_ssa_name (vec_type);
    2125           18 :               gimple *g = gimple_build_assign (lhs, VIEW_CONVERT_EXPR, vce);
    2126           18 :               gimple_set_uid (g, gimple_uid (sum));
    2127           18 :               gsi_insert_before (&gsi, g, GSI_NEW_STMT);
    2128           18 :               gimple_assign_set_rhs1 (sum, lhs);
    2129           18 :               update_stmt (sum);
    2130              :             }
    2131          323 :           if (!useless_type_conversion_p (vec_type,
    2132          323 :                                           TREE_TYPE (valid_vecs[i + 1])))
    2133              :             {
    2134          270 :               gimple_stmt_iterator gsi = gsi_for_stmt (sum);
    2135          810 :               tree vce = build1 (VIEW_CONVERT_EXPR, vec_type,
    2136          270 :                                  valid_vecs[i + 1]);
    2137          270 :               tree lhs = make_ssa_name (vec_type);
    2138          270 :               gimple *g = gimple_build_assign (lhs, VIEW_CONVERT_EXPR, vce);
    2139          270 :               gimple_set_uid (g, gimple_uid (sum));
    2140          270 :               gsi_insert_before (&gsi, g, GSI_NEW_STMT);
    2141          270 :               gimple_assign_set_rhs2 (sum, lhs);
    2142          270 :               update_stmt (sum);
    2143              :             }
    2144          323 :           sum_vec = gimple_get_lhs (sum);
    2145          323 :           info_ptr = *(v_info_map.get (valid_vecs[i + 1]));
    2146          323 :           gcc_assert (types_compatible_p (vec_type, info_ptr->vec_type));
    2147              :           /* Update those related ops of current candidate VECTOR.  */
    2148         1569 :           FOR_EACH_VEC_ELT (info_ptr->vec, j, elem)
    2149              :             {
    2150         1246 :               idx = elem->second;
    2151         1246 :               gimple *def = SSA_NAME_DEF_STMT ((*ops)[idx]->op);
    2152              :               /* Set this then op definition will get DCEd later.  */
    2153         1246 :               gimple_set_visited (def, true);
    2154         1246 :               if (opcode == PLUS_EXPR
    2155         1246 :                   || opcode == BIT_XOR_EXPR
    2156           96 :                   || opcode == BIT_IOR_EXPR)
    2157         1186 :                 (*ops)[idx]->op = build_zero_cst (TREE_TYPE ((*ops)[idx]->op));
    2158           60 :               else if (opcode == MULT_EXPR)
    2159           24 :                 (*ops)[idx]->op = build_one_cst (TREE_TYPE ((*ops)[idx]->op));
    2160              :               else
    2161              :                 {
    2162           36 :                   gcc_assert (opcode == BIT_AND_EXPR);
    2163           36 :                   (*ops)[idx]->op
    2164           36 :                     = build_all_ones_cst (TREE_TYPE ((*ops)[idx]->op));
    2165              :                 }
    2166         1246 :               (*ops)[idx]->rank = 0;
    2167              :             }
    2168          323 :           if (dump_file && (dump_flags & TDF_DETAILS))
    2169              :             {
    2170            0 :               fprintf (dump_file, "Generating addition -> ");
    2171            0 :               print_gimple_stmt (dump_file, sum, 0);
    2172              :             }
    2173          323 :           i++;
    2174              :         }
    2175          323 :       while ((i < valid_vecs.length () - 1)
    2176          363 :              && TYPE_MODE (TREE_TYPE (valid_vecs[i + 1])) == mode);
    2177              : 
    2178              :       /* Referring to first valid VECTOR with this mode, generate the
    2179              :          BIT_FIELD_REF statements accordingly.  */
    2180           40 :       info_ptr = *(v_info_map.get (tvec));
    2181           40 :       gcc_assert (sum);
    2182           40 :       tree elem_type = TREE_TYPE (vec_type);
    2183          224 :       FOR_EACH_VEC_ELT (info_ptr->vec, j, elem)
    2184              :         {
    2185          144 :           idx = elem->second;
    2186          144 :           tree dst = make_ssa_name (elem_type);
    2187          144 :           tree pos = bitsize_int (elem->first
    2188              :                                   * tree_to_uhwi (TYPE_SIZE (elem_type)));
    2189          144 :           tree bfr = build3 (BIT_FIELD_REF, elem_type, sum_vec,
    2190          144 :                              TYPE_SIZE (elem_type), pos);
    2191          144 :           gassign *gs = gimple_build_assign (dst, BIT_FIELD_REF, bfr);
    2192          144 :           insert_stmt_after (gs, sum);
    2193          144 :           gimple *def = SSA_NAME_DEF_STMT ((*ops)[idx]->op);
    2194              :           /* Set this then op definition will get DCEd later.  */
    2195          144 :           gimple_set_visited (def, true);
    2196          144 :           (*ops)[idx]->op = gimple_assign_lhs (gs);
    2197          144 :           (*ops)[idx]->rank = get_rank ((*ops)[idx]->op);
    2198          144 :           if (dump_file && (dump_flags & TDF_DETAILS))
    2199              :             {
    2200            0 :               fprintf (dump_file, "Generating bit_field_ref -> ");
    2201            0 :               print_gimple_stmt (dump_file, gs, 0);
    2202              :             }
    2203              :         }
    2204              :     }
    2205              : 
    2206           36 :   if (dump_file && (dump_flags & TDF_DETAILS))
    2207            0 :     fprintf (dump_file, "undistributiong bit_field_ref for vector done.\n");
    2208              : 
    2209           36 :   cleanup_vinfo_map (v_info_map);
    2210              : 
    2211           36 :   return true;
    2212      4579067 : }
    2213              : 
    2214              : /* If OPCODE is BIT_IOR_EXPR or BIT_AND_EXPR and CURR is a comparison
    2215              :    expression, examine the other OPS to see if any of them are comparisons
    2216              :    of the same values, which we may be able to combine or eliminate.
    2217              :    For example, we can rewrite (a < b) | (a == b) as (a <= b).  */
    2218              : 
    2219              : static bool
    2220      9872670 : eliminate_redundant_comparison (enum tree_code opcode,
    2221              :                                 vec<operand_entry *> *ops,
    2222              :                                 unsigned int currindex,
    2223              :                                 operand_entry *curr)
    2224              : {
    2225      9872670 :   tree op1, op2;
    2226      9872670 :   enum tree_code lcode, rcode;
    2227      9872670 :   gimple *def1;
    2228      9872670 :   int i;
    2229      9872670 :   operand_entry *oe;
    2230              : 
    2231      9872670 :   if (opcode != BIT_IOR_EXPR && opcode != BIT_AND_EXPR)
    2232              :     return false;
    2233              : 
    2234              :   /* Check that CURR is a comparison.  */
    2235      2053547 :   if (TREE_CODE (curr->op) != SSA_NAME)
    2236              :     return false;
    2237      1551972 :   def1 = SSA_NAME_DEF_STMT (curr->op);
    2238      1551972 :   if (!is_gimple_assign (def1))
    2239              :     return false;
    2240      1337455 :   lcode = gimple_assign_rhs_code (def1);
    2241      1337455 :   if (TREE_CODE_CLASS (lcode) != tcc_comparison)
    2242              :     return false;
    2243       543903 :   op1 = gimple_assign_rhs1 (def1);
    2244       543903 :   op2 = gimple_assign_rhs2 (def1);
    2245              : 
    2246              :   /* Now look for a similar comparison in the remaining OPS.  */
    2247       908186 :   for (i = currindex + 1; ops->iterate (i, &oe); i++)
    2248              :     {
    2249       364521 :       tree t;
    2250              : 
    2251       364521 :       if (TREE_CODE (oe->op) != SSA_NAME)
    2252           41 :         continue;
    2253       364480 :       auto def2 = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (oe->op));
    2254       364480 :       if (!def2)
    2255         7895 :         continue;
    2256       356585 :       rcode = gimple_assign_rhs_code (def2);
    2257       356585 :       if (TREE_CODE_CLASS (rcode) != tcc_comparison)
    2258         6677 :         continue;
    2259              : 
    2260              :       /* If we got here, we have a match.  See if we can combine the
    2261              :          two comparisons.  */
    2262       349908 :       tree type = TREE_TYPE (gimple_assign_lhs (def1));
    2263       349908 :       if (opcode == BIT_IOR_EXPR)
    2264       397786 :         t = maybe_fold_or_comparisons (type, TRUTH_OR_EXPR,
    2265              :                                        lcode, op1, op2,
    2266              :                                        rcode, gimple_assign_rhs1 (def2),
    2267              :                                        gimple_assign_rhs2 (def2));
    2268              :       else
    2269       302030 :         t = maybe_fold_and_comparisons (type, TRUTH_AND_EXPR,
    2270              :                                         lcode, op1, op2,
    2271              :                                         rcode, gimple_assign_rhs1 (def2),
    2272              :                                         gimple_assign_rhs2 (def2));
    2273       349908 :       if (!t)
    2274       349622 :         continue;
    2275              : 
    2276              :       /* maybe_fold_and_comparisons and maybe_fold_or_comparisons
    2277              :          always give us a boolean_type_node value back.  If the original
    2278              :          BIT_AND_EXPR or BIT_IOR_EXPR was of a wider integer type,
    2279              :          we need to convert.  */
    2280          286 :       if (!useless_type_conversion_p (TREE_TYPE (curr->op), TREE_TYPE (t)))
    2281              :         {
    2282            2 :           if (!fold_convertible_p (TREE_TYPE (curr->op), t))
    2283            0 :             continue;
    2284            2 :           t = fold_convert (TREE_TYPE (curr->op), t);
    2285              :         }
    2286              : 
    2287          286 :       if (TREE_CODE (t) != INTEGER_CST
    2288          286 :           && !operand_equal_p (t, curr->op, 0))
    2289              :         {
    2290          282 :           enum tree_code subcode;
    2291          282 :           tree newop1, newop2;
    2292          282 :           if (!COMPARISON_CLASS_P (t))
    2293           48 :             continue;
    2294          254 :           extract_ops_from_tree (t, &subcode, &newop1, &newop2);
    2295          254 :           STRIP_USELESS_TYPE_CONVERSION (newop1);
    2296          254 :           STRIP_USELESS_TYPE_CONVERSION (newop2);
    2297          254 :           if (!is_gimple_val (newop1) || !is_gimple_val (newop2))
    2298            0 :             continue;
    2299          254 :           if (lcode == TREE_CODE (t)
    2300          186 :               && operand_equal_p (op1, newop1, 0)
    2301          440 :               && operand_equal_p (op2, newop2, 0))
    2302          141 :             t = curr->op;
    2303          133 :           else if ((TREE_CODE (newop1) == SSA_NAME
    2304          113 :                     && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (newop1))
    2305          206 :                    || (TREE_CODE (newop2) == SSA_NAME
    2306           53 :                        && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (newop2)))
    2307           20 :             continue;
    2308              :         }
    2309              : 
    2310          238 :       if (dump_file && (dump_flags & TDF_DETAILS))
    2311              :         {
    2312            6 :           fprintf (dump_file, "Equivalence: ");
    2313            6 :           print_generic_expr (dump_file, curr->op);
    2314            6 :           fprintf (dump_file, " %s ", op_symbol_code (opcode));
    2315            6 :           print_generic_expr (dump_file, oe->op);
    2316            6 :           fprintf (dump_file, " -> ");
    2317            6 :           print_generic_expr (dump_file, t);
    2318            6 :           fprintf (dump_file, "\n");
    2319              :         }
    2320              : 
    2321              :       /* Now we can delete oe, as it has been subsumed by the new combined
    2322              :          expression t.  */
    2323          238 :       ops->ordered_remove (i);
    2324          238 :       reassociate_stats.ops_eliminated ++;
    2325              : 
    2326              :       /* If t is the same as curr->op, we're done.  Otherwise we must
    2327              :          replace curr->op with t.  Special case is if we got a constant
    2328              :          back, in which case we add it to the end instead of in place of
    2329              :          the current entry.  */
    2330          238 :       if (TREE_CODE (t) == INTEGER_CST)
    2331              :         {
    2332            4 :           ops->ordered_remove (currindex);
    2333            4 :           add_to_ops_vec (ops, t);
    2334              :         }
    2335          234 :       else if (!operand_equal_p (t, curr->op, 0))
    2336              :         {
    2337           93 :           gimple *sum;
    2338           93 :           enum tree_code subcode;
    2339           93 :           tree newop1;
    2340           93 :           tree newop2;
    2341           93 :           gcc_assert (COMPARISON_CLASS_P (t));
    2342           93 :           extract_ops_from_tree (t, &subcode, &newop1, &newop2);
    2343           93 :           STRIP_USELESS_TYPE_CONVERSION (newop1);
    2344           93 :           STRIP_USELESS_TYPE_CONVERSION (newop2);
    2345           93 :           gcc_checking_assert (is_gimple_val (newop1)
    2346              :                                && is_gimple_val (newop2));
    2347           93 :           sum = build_and_add_sum (TREE_TYPE (t), newop1, newop2, subcode);
    2348           93 :           curr->op = gimple_get_lhs (sum);
    2349              :         }
    2350              :       return true;
    2351              :     }
    2352              : 
    2353              :   return false;
    2354              : }
    2355              : 
    2356              : 
    2357              : /* Transform repeated addition of same values into multiply with
    2358              :    constant.  */
    2359              : static bool
    2360      2373016 : transform_add_to_multiply (vec<operand_entry *> *ops)
    2361              : {
    2362      2373016 :   operand_entry *oe;
    2363      2373016 :   tree op = NULL_TREE;
    2364      2373016 :   int j;
    2365      2373016 :   int i, start = -1, end = 0, count = 0;
    2366      2373016 :   auto_vec<std::pair <int, int> > indxs;
    2367      2373016 :   bool changed = false;
    2368              : 
    2369      2373016 :   if (!INTEGRAL_TYPE_P (TREE_TYPE ((*ops)[0]->op))
    2370        70151 :       && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE ((*ops)[0]->op))
    2371        32100 :           || !flag_unsafe_math_optimizations))
    2372              :     return false;
    2373              : 
    2374              :   /* Look for repeated operands.  */
    2375      7167500 :   FOR_EACH_VEC_ELT (*ops, i, oe)
    2376              :     {
    2377      4832619 :       if (start == -1)
    2378              :         {
    2379      2334881 :           count = 1;
    2380      2334881 :           op = oe->op;
    2381      2334881 :           start = i;
    2382              :         }
    2383      2497738 :       else if (operand_equal_p (oe->op, op, 0))
    2384              :         {
    2385          155 :           count++;
    2386          155 :           end = i;
    2387              :         }
    2388              :       else
    2389              :         {
    2390      2497583 :           if (count > 1)
    2391           47 :             indxs.safe_push (std::make_pair (start, end));
    2392      2497583 :           count = 1;
    2393      2497583 :           op = oe->op;
    2394      2497583 :           start = i;
    2395              :         }
    2396              :     }
    2397              : 
    2398      2334881 :   if (count > 1)
    2399           38 :     indxs.safe_push (std::make_pair (start, end));
    2400              : 
    2401      2335039 :   for (j = indxs.length () - 1; j >= 0; --j)
    2402              :     {
    2403              :       /* Convert repeated operand addition to multiplication.  */
    2404           85 :       start = indxs[j].first;
    2405           85 :       end = indxs[j].second;
    2406           85 :       op = (*ops)[start]->op;
    2407           85 :       count = end - start + 1;
    2408          325 :       for (i = end; i >= start; --i)
    2409          240 :         ops->unordered_remove (i);
    2410           85 :       tree tmp = make_ssa_name (TREE_TYPE (op));
    2411           85 :       tree cst = build_int_cst (integer_type_node, count);
    2412           85 :       gassign *mul_stmt
    2413           85 :         = gimple_build_assign (tmp, MULT_EXPR,
    2414           85 :                                op, fold_convert (TREE_TYPE (op), cst));
    2415           85 :       gimple_set_visited (mul_stmt, true);
    2416           85 :       add_to_ops_vec (ops, tmp, mul_stmt);
    2417           85 :       changed = true;
    2418              :     }
    2419              : 
    2420              :   return changed;
    2421      2373016 : }
    2422              : 
    2423              : 
    2424              : /* Perform various identities and other optimizations on the list of
    2425              :    operand entries, stored in OPS.  The tree code for the binary
    2426              :    operation between all the operands is OPCODE.  */
    2427              : 
    2428              : static void
    2429      4811964 : optimize_ops_list (enum tree_code opcode,
    2430              :                    vec<operand_entry *> *ops)
    2431              : {
    2432      4829967 :   unsigned int length = ops->length ();
    2433      4829967 :   unsigned int i;
    2434      4829967 :   operand_entry *oe;
    2435      9658028 :   operand_entry *oelast = NULL;
    2436      9658028 :   bool iterate = false;
    2437              : 
    2438      4829967 :   if (length == 1)
    2439              :     return;
    2440              : 
    2441      4828061 :   oelast = ops->last ();
    2442              : 
    2443              :   /* If the last two are constants, pop the constants off, merge them
    2444              :      and try the next two.  */
    2445      4828061 :   if (oelast->rank == 0 && is_gimple_min_invariant (oelast->op))
    2446              :     {
    2447      3476401 :       operand_entry *oelm1 = (*ops)[length - 2];
    2448              : 
    2449      3476401 :       if (oelm1->rank == 0
    2450        14210 :           && is_gimple_min_invariant (oelm1->op)
    2451      3490611 :           && useless_type_conversion_p (TREE_TYPE (oelm1->op),
    2452        14210 :                                        TREE_TYPE (oelast->op)))
    2453              :         {
    2454        14210 :           tree folded = fold_binary (opcode, TREE_TYPE (oelm1->op),
    2455              :                                      oelm1->op, oelast->op);
    2456              : 
    2457        14210 :           if (folded && is_gimple_min_invariant (folded))
    2458              :             {
    2459        14160 :               if (dump_file && (dump_flags & TDF_DETAILS))
    2460            0 :                 fprintf (dump_file, "Merging constants\n");
    2461              : 
    2462        14160 :               ops->pop ();
    2463        14160 :               ops->pop ();
    2464              : 
    2465        14160 :               add_to_ops_vec (ops, folded);
    2466        14160 :               reassociate_stats.constants_eliminated++;
    2467              : 
    2468        14160 :               optimize_ops_list (opcode, ops);
    2469        14160 :               return;
    2470              :             }
    2471              :         }
    2472              :     }
    2473              : 
    2474      4813901 :   eliminate_using_constants (opcode, ops);
    2475      4813901 :   oelast = NULL;
    2476              : 
    2477     19504215 :   for (i = 0; ops->iterate (i, &oe);)
    2478              :     {
    2479      9876415 :       bool done = false;
    2480              : 
    2481      9876415 :       if (eliminate_not_pairs (opcode, ops, i, oe))
    2482            2 :         return;
    2483      9876414 :       if (eliminate_duplicate_pair (opcode, ops, &done, i, oe, oelast)
    2484      9876247 :           || (!done && eliminate_plus_minus_pair (opcode, ops, i, oe))
    2485     19749084 :           || (!done && eliminate_redundant_comparison (opcode, ops, i, oe)))
    2486              :         {
    2487         3982 :           if (done)
    2488              :             return;
    2489         3981 :           iterate = true;
    2490         3981 :           oelast = NULL;
    2491         3981 :           continue;
    2492              :         }
    2493      9872432 :       oelast = oe;
    2494      9872432 :       i++;
    2495              :     }
    2496              : 
    2497      4813899 :   if (iterate)
    2498              :     optimize_ops_list (opcode, ops);
    2499              : }
    2500              : 
    2501              : /* The following functions are subroutines to optimize_range_tests and allow
    2502              :    it to try to change a logical combination of comparisons into a range
    2503              :    test.
    2504              : 
    2505              :    For example, both
    2506              :         X == 2 || X == 5 || X == 3 || X == 4
    2507              :    and
    2508              :         X >= 2 && X <= 5
    2509              :    are converted to
    2510              :         (unsigned) (X - 2) <= 3
    2511              : 
    2512              :    For more information see comments above fold_test_range in fold-const.cc,
    2513              :    this implementation is for GIMPLE.  */
    2514              : 
    2515              : 
    2516              : 
    2517              : /* Dump the range entry R to FILE, skipping its expression if SKIP_EXP.  */
    2518              : 
    2519              : void
    2520          141 : dump_range_entry (FILE *file, struct range_entry *r, bool skip_exp)
    2521              : {
    2522          141 :   if (!skip_exp)
    2523           59 :     print_generic_expr (file, r->exp);
    2524          251 :   fprintf (file, " %c[", r->in_p ? '+' : '-');
    2525          141 :   print_generic_expr (file, r->low);
    2526          141 :   fputs (", ", file);
    2527          141 :   print_generic_expr (file, r->high);
    2528          141 :   fputc (']', file);
    2529          141 : }
    2530              : 
    2531              : /* Dump the range entry R to STDERR.  */
    2532              : 
    2533              : DEBUG_FUNCTION void
    2534            0 : debug_range_entry (struct range_entry *r)
    2535              : {
    2536            0 :   dump_range_entry (stderr, r, false);
    2537            0 :   fputc ('\n', stderr);
    2538            0 : }
    2539              : 
    2540              : /* This is similar to make_range in fold-const.cc, but on top of
    2541              :    GIMPLE instead of trees.  If EXP is non-NULL, it should be
    2542              :    an SSA_NAME and STMT argument is ignored, otherwise STMT
    2543              :    argument should be a GIMPLE_COND.  */
    2544              : 
    2545              : void
    2546      5741109 : init_range_entry (struct range_entry *r, tree exp, gimple *stmt)
    2547              : {
    2548      5741109 :   int in_p;
    2549      5741109 :   tree low, high;
    2550      5741109 :   bool is_bool;
    2551              : 
    2552      5741109 :   r->exp = NULL_TREE;
    2553      5741109 :   r->in_p = false;
    2554      5741109 :   r->low = NULL_TREE;
    2555      5741109 :   r->high = NULL_TREE;
    2556      5741109 :   if (exp != NULL_TREE
    2557      5741109 :       && (TREE_CODE (exp) != SSA_NAME || !INTEGRAL_TYPE_P (TREE_TYPE (exp))))
    2558       800860 :     return;
    2559              : 
    2560              :   /* Start with simply saying "EXP != 0" and then look at the code of EXP
    2561              :      and see if we can refine the range.  Some of the cases below may not
    2562              :      happen, but it doesn't seem worth worrying about this.  We "continue"
    2563              :      the outer loop when we've changed something; otherwise we "break"
    2564              :      the switch, which will "break" the while.  */
    2565      5246443 :   low = exp ? build_int_cst (TREE_TYPE (exp), 0) : boolean_false_node;
    2566      5246443 :   high = low;
    2567      5246443 :   in_p = 0;
    2568      5246443 :   is_bool = false;
    2569      5246443 :   if (exp == NULL_TREE)
    2570      5246219 :     is_bool = true;
    2571      1600755 :   else if (TYPE_PRECISION (TREE_TYPE (exp)) == 1)
    2572              :     {
    2573       678466 :       if (TYPE_UNSIGNED (TREE_TYPE (exp)))
    2574              :         is_bool = true;
    2575              :       else
    2576              :         return;
    2577              :     }
    2578       922289 :   else if (TREE_CODE (TREE_TYPE (exp)) == BOOLEAN_TYPE)
    2579      4323930 :     is_bool = true;
    2580              : 
    2581      8339243 :   while (1)
    2582              :     {
    2583      8339243 :       enum tree_code code;
    2584      8339243 :       tree arg0, arg1, exp_type;
    2585      8339243 :       tree nexp;
    2586      8339243 :       location_t loc;
    2587              : 
    2588      8339243 :       if (exp != NULL_TREE)
    2589              :         {
    2590      4693555 :           if (TREE_CODE (exp) != SSA_NAME
    2591      4693555 :               || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (exp))
    2592              :             break;
    2593              : 
    2594      4693555 :           stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (exp));
    2595      2866514 :           if (!stmt)
    2596              :             break;
    2597              : 
    2598      2866514 :           code = gimple_assign_rhs_code (stmt);
    2599      2866514 :           arg0 = gimple_assign_rhs1 (stmt);
    2600      2866514 :           arg1 = gimple_assign_rhs2 (stmt);
    2601      2866514 :           exp_type = TREE_TYPE (exp);
    2602              :         }
    2603              :       else
    2604              :         {
    2605      3645688 :           code = gimple_cond_code (stmt);
    2606      3645688 :           arg0 = gimple_cond_lhs (stmt);
    2607      3645688 :           arg1 = gimple_cond_rhs (stmt);
    2608      3645688 :           exp_type = boolean_type_node;
    2609              :         }
    2610              : 
    2611      6512202 :       if (TREE_CODE (arg0) != SSA_NAME
    2612      5177200 :           || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (arg0)
    2613     11688975 :           || ssa_name_maybe_undef_p (arg0))
    2614              :         break;
    2615      5169909 :       loc = gimple_location (stmt);
    2616      5169909 :       switch (code)
    2617              :         {
    2618        34404 :         case BIT_NOT_EXPR:
    2619        34404 :           if (TREE_CODE (TREE_TYPE (exp)) == BOOLEAN_TYPE
    2620              :               /* Ensure the range is either +[-,0], +[0,0],
    2621              :                  -[-,0], -[0,0] or +[1,-], +[1,1], -[1,-] or
    2622              :                  -[1,1].  If it is e.g. +[-,-] or -[-,-]
    2623              :                  or similar expression of unconditional true or
    2624              :                  false, it should not be negated.  */
    2625        34404 :               && ((high && integer_zerop (high))
    2626            0 :                   || (low && integer_onep (low))))
    2627              :             {
    2628         6412 :               in_p = !in_p;
    2629         6412 :               exp = arg0;
    2630         6412 :               continue;
    2631              :             }
    2632              :           break;
    2633         1894 :         case SSA_NAME:
    2634         1894 :           exp = arg0;
    2635         1894 :           continue;
    2636       246369 :         CASE_CONVERT:
    2637       246369 :           if (is_bool)
    2638              :             {
    2639       127327 :               if ((TYPE_PRECISION (exp_type) == 1
    2640       120418 :                    || TREE_CODE (exp_type) == BOOLEAN_TYPE)
    2641       127327 :                   && TYPE_PRECISION (TREE_TYPE (arg0)) > 1)
    2642              :                 return;
    2643              :             }
    2644       119042 :           else if (TYPE_PRECISION (TREE_TYPE (arg0)) == 1)
    2645              :             {
    2646         4553 :               if (TYPE_UNSIGNED (TREE_TYPE (arg0)))
    2647              :                 is_bool = true;
    2648              :               else
    2649              :                 return;
    2650              :             }
    2651       114489 :           else if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE)
    2652       128920 :             is_bool = true;
    2653       243409 :           goto do_default;
    2654              :         case EQ_EXPR:
    2655              :         case NE_EXPR:
    2656              :         case LT_EXPR:
    2657              :         case LE_EXPR:
    2658              :         case GE_EXPR:
    2659              :         case GT_EXPR:
    2660              :           is_bool = true;
    2661              :           /* FALLTHRU */
    2662       665091 :         default:
    2663       665091 :           if (!is_bool)
    2664              :             return;
    2665       362081 :         do_default:
    2666      4827641 :           nexp = make_range_step (loc, code, arg0, arg1, exp_type,
    2667              :                                   &low, &high, &in_p);
    2668      4827641 :           if (nexp != NULL_TREE)
    2669              :             {
    2670      3084718 :               exp = nexp;
    2671      3084718 :               gcc_assert (TREE_CODE (exp) == SSA_NAME);
    2672      3084718 :               continue;
    2673              :             }
    2674              :           break;
    2675              :         }
    2676              :       break;
    2677              :     }
    2678      4940249 :   if (is_bool)
    2679              :     {
    2680      4325523 :       r->exp = exp;
    2681      4325523 :       r->in_p = in_p;
    2682      4325523 :       r->low = low;
    2683      4325523 :       r->high = high;
    2684              :     }
    2685              : }
    2686              : 
    2687              : /* Comparison function for qsort.  Sort entries
    2688              :    without SSA_NAME exp first, then with SSA_NAMEs sorted
    2689              :    by increasing SSA_NAME_VERSION, and for the same SSA_NAMEs
    2690              :    by increasing ->low and if ->low is the same, by increasing
    2691              :    ->high.  ->low == NULL_TREE means minimum, ->high == NULL_TREE
    2692              :    maximum.  */
    2693              : 
    2694              : static int
    2695      6214897 : range_entry_cmp (const void *a, const void *b)
    2696              : {
    2697      6214897 :   const struct range_entry *p = (const struct range_entry *) a;
    2698      6214897 :   const struct range_entry *q = (const struct range_entry *) b;
    2699              : 
    2700      6214897 :   if (p->exp != NULL_TREE && TREE_CODE (p->exp) == SSA_NAME)
    2701              :     {
    2702      2509155 :       if (q->exp != NULL_TREE && TREE_CODE (q->exp) == SSA_NAME)
    2703              :         {
    2704              :           /* Group range_entries for the same SSA_NAME together.  */
    2705      2455909 :           if (SSA_NAME_VERSION (p->exp) < SSA_NAME_VERSION (q->exp))
    2706              :             return -1;
    2707      1057342 :           else if (SSA_NAME_VERSION (p->exp) > SSA_NAME_VERSION (q->exp))
    2708              :             return 1;
    2709              :           /* If ->low is different, NULL low goes first, then by
    2710              :              ascending low.  */
    2711       157329 :           if (p->low != NULL_TREE)
    2712              :             {
    2713       142162 :               if (q->low != NULL_TREE)
    2714              :                 {
    2715       135692 :                   tree tem = fold_binary (LT_EXPR, boolean_type_node,
    2716              :                                           p->low, q->low);
    2717       135692 :                   if (tem && integer_onep (tem))
    2718              :                     return -1;
    2719        66506 :                   tem = fold_binary (GT_EXPR, boolean_type_node,
    2720              :                                      p->low, q->low);
    2721        66506 :                   if (tem && integer_onep (tem))
    2722              :                     return 1;
    2723              :                 }
    2724              :               else
    2725              :                 return 1;
    2726              :             }
    2727        15167 :           else if (q->low != NULL_TREE)
    2728              :             return -1;
    2729              :           /* If ->high is different, NULL high goes last, before that by
    2730              :              ascending high.  */
    2731        29028 :           if (p->high != NULL_TREE)
    2732              :             {
    2733        28944 :               if (q->high != NULL_TREE)
    2734              :                 {
    2735        28783 :                   tree tem = fold_binary (LT_EXPR, boolean_type_node,
    2736              :                                           p->high, q->high);
    2737        28783 :                   if (tem && integer_onep (tem))
    2738              :                     return -1;
    2739         8302 :                   tem = fold_binary (GT_EXPR, boolean_type_node,
    2740              :                                      p->high, q->high);
    2741         8302 :                   if (tem && integer_onep (tem))
    2742              :                     return 1;
    2743              :                 }
    2744              :               else
    2745              :                 return -1;
    2746              :             }
    2747           84 :           else if (q->high != NULL_TREE)
    2748              :             return 1;
    2749              :           /* If both ranges are the same, sort below by ascending idx.  */
    2750              :         }
    2751              :       else
    2752              :         return 1;
    2753              :     }
    2754      3705742 :   else if (q->exp != NULL_TREE && TREE_CODE (q->exp) == SSA_NAME)
    2755              :     return -1;
    2756              : 
    2757      3632302 :   if (p->idx < q->idx)
    2758              :     return -1;
    2759              :   else
    2760              :     {
    2761      1834042 :       gcc_checking_assert (p->idx > q->idx);
    2762              :       return 1;
    2763              :     }
    2764              : }
    2765              : 
    2766              : /* Helper function for update_range_test.  Force EXPR into an SSA_NAME,
    2767              :    insert needed statements BEFORE or after GSI.  */
    2768              : 
    2769              : static tree
    2770        23689 : force_into_ssa_name (gimple_stmt_iterator *gsi, tree expr, bool before)
    2771              : {
    2772        23689 :   enum gsi_iterator_update m = before ? GSI_SAME_STMT : GSI_CONTINUE_LINKING;
    2773        23689 :   tree ret = force_gimple_operand_gsi (gsi, expr, true, NULL_TREE, before, m);
    2774        23689 :   if (TREE_CODE (ret) != SSA_NAME)
    2775              :     {
    2776           42 :       gassign *g = gimple_build_assign (make_ssa_name (TREE_TYPE (ret)), ret);
    2777           42 :       if (before)
    2778           42 :         gsi_insert_before (gsi, g, GSI_SAME_STMT);
    2779              :       else
    2780            0 :         gsi_insert_after (gsi, g, GSI_CONTINUE_LINKING);
    2781           42 :       ret = gimple_assign_lhs (g);
    2782              :     }
    2783        23689 :   return ret;
    2784              : }
    2785              : 
    2786              : /* Helper routine of optimize_range_test.
    2787              :    [EXP, IN_P, LOW, HIGH] is a merged range for
    2788              :    RANGE and OTHERRANGE through OTHERRANGE + COUNT - 1 ranges,
    2789              :    OPCODE and OPS are arguments of optimize_range_tests.  If OTHERRANGE
    2790              :    is NULL, OTHERRANGEP should not be and then OTHERRANGEP points to
    2791              :    an array of COUNT pointers to other ranges.  Return
    2792              :    true if the range merge has been successful.
    2793              :    If OPCODE is ERROR_MARK, this is called from within
    2794              :    maybe_optimize_range_tests and is performing inter-bb range optimization.
    2795              :    In that case, whether an op is BIT_AND_EXPR or BIT_IOR_EXPR is found in
    2796              :    oe->rank.  */
    2797              : 
    2798              : static bool
    2799        23707 : update_range_test (struct range_entry *range, struct range_entry *otherrange,
    2800              :                    struct range_entry **otherrangep,
    2801              :                    unsigned int count, enum tree_code opcode,
    2802              :                    vec<operand_entry *> *ops, tree exp, gimple_seq seq,
    2803              :                    bool in_p, tree low, tree high)
    2804              : {
    2805        23707 :   unsigned int idx = range->idx;
    2806        23707 :   struct range_entry *swap_with = NULL;
    2807        23707 :   basic_block rewrite_bb_first = NULL, rewrite_bb_last = NULL;
    2808        23707 :   if (opcode == ERROR_MARK)
    2809              :     {
    2810              :       /* For inter-bb range test optimization, pick from the range tests
    2811              :          the one which is tested in the earliest condition (one dominating
    2812              :          the others), because otherwise there could be some UB (e.g. signed
    2813              :          overflow) in following bbs that we'd expose which wasn't there in
    2814              :          the original program.  See PR104196.  */
    2815        12831 :       basic_block orig_range_bb = BASIC_BLOCK_FOR_FN (cfun, (*ops)[idx]->id);
    2816        12831 :       basic_block range_bb = orig_range_bb;
    2817        29017 :       for (unsigned int i = 0; i < count; i++)
    2818              :         {
    2819        16186 :           struct range_entry *this_range;
    2820        16186 :           if (otherrange)
    2821         8503 :             this_range = otherrange + i;
    2822              :           else
    2823         7683 :             this_range = otherrangep[i];
    2824        16186 :           operand_entry *oe = (*ops)[this_range->idx];
    2825        16186 :           basic_block this_bb = BASIC_BLOCK_FOR_FN (cfun, oe->id);
    2826        16186 :           if (range_bb != this_bb
    2827        16186 :               && dominated_by_p (CDI_DOMINATORS, range_bb, this_bb))
    2828              :             {
    2829         6693 :               swap_with = this_range;
    2830         6693 :               range_bb = this_bb;
    2831         6693 :               idx = this_range->idx;
    2832              :             }
    2833              :         }
    2834              :       /* If seq is non-NULL, it can contain statements that use SSA_NAMEs
    2835              :          only defined in later blocks.  In this case we can't move the
    2836              :          merged comparison earlier, so instead check if there are any stmts
    2837              :          that might trigger signed integer overflow in between and rewrite
    2838              :          them.  But only after we check if the optimization is possible.  */
    2839        12831 :       if (seq && swap_with)
    2840              :         {
    2841         3852 :           rewrite_bb_first = range_bb;
    2842         3852 :           rewrite_bb_last = orig_range_bb;
    2843         3852 :           idx = range->idx;
    2844         3852 :           swap_with = NULL;
    2845              :         }
    2846              :     }
    2847        23707 :   operand_entry *oe = (*ops)[idx];
    2848        23707 :   tree op = oe->op;
    2849        23707 :   gimple *stmt = op ? SSA_NAME_DEF_STMT (op)
    2850        10678 :                     : last_nondebug_stmt (BASIC_BLOCK_FOR_FN (cfun, oe->id));
    2851        23707 :   location_t loc = gimple_location (stmt);
    2852        23707 :   tree optype = op ? TREE_TYPE (op) : boolean_type_node;
    2853        23707 :   tree tem = build_range_check (loc, optype, unshare_expr (exp),
    2854              :                                 in_p, low, high);
    2855        23707 :   gimple_stmt_iterator gsi;
    2856        23707 :   unsigned int i, uid;
    2857              : 
    2858        23707 :   if (tem == NULL_TREE)
    2859              :     return false;
    2860              : 
    2861              :   /* If op is default def SSA_NAME, or the range test on OP itself would
    2862              :      have to follow a definition of OP that ends its basic block, there
    2863              :      is no place to insert the new comparison.  Give up, unless we can
    2864              :      use OP itself as the range test.  */
    2865        23707 :   if (op
    2866        36736 :       && (SSA_NAME_IS_DEFAULT_DEF (op)
    2867        13029 :           || (op == range->exp && stmt_ends_bb_p (stmt))))
    2868              :     {
    2869           18 :       if (op == range->exp
    2870           18 :           && ((TYPE_PRECISION (optype) == 1 && TYPE_UNSIGNED (optype))
    2871            0 :               || TREE_CODE (optype) == BOOLEAN_TYPE)
    2872           18 :           && (op == tem
    2873           18 :               || (TREE_CODE (tem) == EQ_EXPR
    2874            0 :                   && TREE_OPERAND (tem, 0) == op
    2875            0 :                   && integer_onep (TREE_OPERAND (tem, 1))))
    2876            0 :           && opcode != BIT_IOR_EXPR
    2877           18 :           && (opcode != ERROR_MARK || oe->rank != BIT_IOR_EXPR))
    2878              :         {
    2879              :           stmt = NULL;
    2880              :           tem = op;
    2881              :         }
    2882              :       else
    2883              :         return false;
    2884              :     }
    2885              : 
    2886        23689 :   if (swap_with)
    2887         1051 :     std::swap (range->idx, swap_with->idx);
    2888              : 
    2889        23689 :   if (dump_file && (dump_flags & TDF_DETAILS))
    2890              :     {
    2891           39 :       struct range_entry *r;
    2892           39 :       fprintf (dump_file, "Optimizing range tests ");
    2893           39 :       dump_range_entry (dump_file, range, false);
    2894          180 :       for (i = 0; i < count; i++)
    2895              :         {
    2896          102 :           if (otherrange)
    2897           82 :             r = otherrange + i;
    2898              :           else
    2899           20 :             r = otherrangep[i];
    2900          102 :           if (r->exp
    2901          102 :               && r->exp != range->exp
    2902           20 :               && TREE_CODE (r->exp) == SSA_NAME)
    2903              :             {
    2904           20 :               fprintf (dump_file, " and ");
    2905           20 :               dump_range_entry (dump_file, r, false);
    2906              :             }
    2907              :           else
    2908              :             {
    2909           82 :               fprintf (dump_file, " and");
    2910           82 :               dump_range_entry (dump_file, r, true);
    2911              :             }
    2912              :         }
    2913           39 :       fprintf (dump_file, "\n into ");
    2914           39 :       print_generic_expr (dump_file, tem);
    2915           39 :       fprintf (dump_file, "\n");
    2916              :     }
    2917              : 
    2918              :   /* In inter-bb range optimization mode, if we have a seq, we can't
    2919              :      move the merged comparison to the earliest bb from the comparisons
    2920              :      being replaced, so instead rewrite stmts that could trigger signed
    2921              :      integer overflow.  */
    2922        31258 :   for (basic_block bb = rewrite_bb_last;
    2923        31258 :        bb != rewrite_bb_first; bb = single_pred (bb))
    2924        15138 :     for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
    2925        29711 :          !gsi_end_p (gsi); gsi_next (&gsi))
    2926              :       {
    2927        22142 :         gimple *stmt = gsi_stmt (gsi);
    2928        22142 :         if (gimple_needing_rewrite_undefined (stmt))
    2929              :           {
    2930           63 :             gimple_stmt_iterator gsip = gsi;
    2931           63 :             gimple_stmt_iterator gsin = gsi;
    2932           63 :             gsi_prev (&gsip);
    2933           63 :             gsi_next (&gsin);
    2934           63 :             rewrite_to_defined_unconditional (&gsi);
    2935           63 :             unsigned uid = gimple_uid (stmt);
    2936           63 :             if (gsi_end_p (gsip))
    2937           27 :               gsip = gsi_after_labels (bb);
    2938              :             else
    2939           36 :               gsi_next (&gsip);
    2940          253 :             for (; gsi_stmt (gsip) != gsi_stmt (gsin);
    2941          190 :                  gsi_next (&gsip))
    2942          190 :               gimple_set_uid (gsi_stmt (gsip), uid);
    2943              :           }
    2944              :       }
    2945              : 
    2946        23689 :   if (opcode == BIT_IOR_EXPR
    2947        17393 :       || (opcode == ERROR_MARK && oe->rank == BIT_IOR_EXPR))
    2948        16261 :     tem = invert_truthvalue_loc (loc, tem);
    2949              : 
    2950        23689 :   tem = fold_convert_loc (loc, optype, tem);
    2951        23689 :   if (stmt)
    2952              :     {
    2953        23689 :       gsi = gsi_for_stmt (stmt);
    2954        23689 :       uid = gimple_uid (stmt);
    2955              :     }
    2956              :   else
    2957              :     {
    2958            0 :       gsi = gsi_none ();
    2959            0 :       uid = 0;
    2960              :     }
    2961        23689 :   if (stmt == NULL)
    2962            0 :     gcc_checking_assert (tem == op);
    2963              :   /* In rare cases range->exp can be equal to lhs of stmt.
    2964              :      In that case we have to insert after the stmt rather then before
    2965              :      it.  If stmt is a PHI, insert it at the start of the basic block.  */
    2966        23689 :   else if (op != range->exp)
    2967              :     {
    2968        23689 :       gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
    2969        23689 :       tem = force_into_ssa_name (&gsi, tem, true);
    2970        23689 :       gsi_prev (&gsi);
    2971              :     }
    2972            0 :   else if (gimple_code (stmt) != GIMPLE_PHI)
    2973              :     {
    2974            0 :       gsi_insert_seq_after (&gsi, seq, GSI_CONTINUE_LINKING);
    2975            0 :       tem = force_into_ssa_name (&gsi, tem, false);
    2976              :     }
    2977              :   else
    2978              :     {
    2979            0 :       gsi = gsi_after_labels (gimple_bb (stmt));
    2980            0 :       if (!gsi_end_p (gsi))
    2981            0 :         uid = gimple_uid (gsi_stmt (gsi));
    2982              :       else
    2983              :         {
    2984            0 :           gsi = gsi_start_bb (gimple_bb (stmt));
    2985            0 :           uid = 1;
    2986            0 :           while (!gsi_end_p (gsi))
    2987              :             {
    2988            0 :               uid = gimple_uid (gsi_stmt (gsi));
    2989            0 :               gsi_next (&gsi);
    2990              :             }
    2991              :         }
    2992            0 :       gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
    2993            0 :       tem = force_into_ssa_name (&gsi, tem, true);
    2994            0 :       if (gsi_end_p (gsi))
    2995            0 :         gsi = gsi_last_bb (gimple_bb (stmt));
    2996              :       else
    2997            0 :         gsi_prev (&gsi);
    2998              :     }
    2999        88517 :   for (; !gsi_end_p (gsi); gsi_prev (&gsi))
    3000        84303 :     if (gimple_uid (gsi_stmt (gsi)))
    3001              :       break;
    3002              :     else
    3003        62721 :       gimple_set_uid (gsi_stmt (gsi), uid);
    3004              : 
    3005        23689 :   oe->op = tem;
    3006        23689 :   range->exp = exp;
    3007        23689 :   range->low = low;
    3008        23689 :   range->high = high;
    3009        23689 :   range->in_p = in_p;
    3010              : 
    3011        51910 :   for (i = 0; i < count; i++)
    3012              :     {
    3013        28221 :       if (otherrange)
    3014        16499 :         range = otherrange + i;
    3015              :       else
    3016        11722 :         range = otherrangep[i];
    3017        28221 :       oe = (*ops)[range->idx];
    3018              :       /* Now change all the other range test immediate uses, so that
    3019              :          those tests will be optimized away.  */
    3020        28221 :       if (opcode == ERROR_MARK)
    3021              :         {
    3022        16186 :           if (oe->op)
    3023         2349 :             oe->op = build_int_cst (TREE_TYPE (oe->op),
    3024         2349 :                                     oe->rank == BIT_IOR_EXPR ? 0 : 1);
    3025              :           else
    3026        13837 :             oe->op = (oe->rank == BIT_IOR_EXPR
    3027        13837 :                       ? boolean_false_node : boolean_true_node);
    3028              :         }
    3029              :       else
    3030        12035 :         oe->op = error_mark_node;
    3031        28221 :       range->exp = NULL_TREE;
    3032        28221 :       range->low = NULL_TREE;
    3033        28221 :       range->high = NULL_TREE;
    3034              :     }
    3035              :   return true;
    3036              : }
    3037              : 
    3038              : /* Optimize X == CST1 || X == CST2
    3039              :    if popcount (CST1 ^ CST2) == 1 into
    3040              :    (X & ~(CST1 ^ CST2)) == (CST1 & ~(CST1 ^ CST2)).
    3041              :    Similarly for ranges.  E.g.
    3042              :    X != 2 && X != 3 && X != 10 && X != 11
    3043              :    will be transformed by the previous optimization into
    3044              :    !((X - 2U) <= 1U || (X - 10U) <= 1U)
    3045              :    and this loop can transform that into
    3046              :    !(((X & ~8) - 2U) <= 1U).  */
    3047              : 
    3048              : static bool
    3049        21918 : optimize_range_tests_xor (enum tree_code opcode, tree type,
    3050              :                           tree lowi, tree lowj, tree highi, tree highj,
    3051              :                           vec<operand_entry *> *ops,
    3052              :                           struct range_entry *rangei,
    3053              :                           struct range_entry *rangej)
    3054              : {
    3055        21918 :   tree lowxor, highxor, tem, exp;
    3056              :   /* Check lowi ^ lowj == highi ^ highj and
    3057              :      popcount (lowi ^ lowj) == 1.  */
    3058        21918 :   lowxor = fold_binary (BIT_XOR_EXPR, type, lowi, lowj);
    3059        21918 :   if (lowxor == NULL_TREE || TREE_CODE (lowxor) != INTEGER_CST)
    3060              :     return false;
    3061        21918 :   if (!integer_pow2p (lowxor))
    3062              :     return false;
    3063         2833 :   highxor = fold_binary (BIT_XOR_EXPR, type, highi, highj);
    3064         2833 :   if (!tree_int_cst_equal (lowxor, highxor))
    3065              :     return false;
    3066              : 
    3067         2431 :   exp = rangei->exp;
    3068         2431 :   scalar_int_mode mode = as_a <scalar_int_mode> (TYPE_MODE (type));
    3069         2431 :   int prec = GET_MODE_PRECISION (mode);
    3070         2431 :   if (TYPE_PRECISION (type) < prec
    3071         2430 :       || (wi::to_wide (TYPE_MIN_VALUE (type))
    3072         7291 :           != wi::min_value (prec, TYPE_SIGN (type)))
    3073         4861 :       || (wi::to_wide (TYPE_MAX_VALUE (type))
    3074         7291 :           != wi::max_value (prec, TYPE_SIGN (type))))
    3075              :     {
    3076            1 :       type = build_nonstandard_integer_type (prec, TYPE_UNSIGNED (type));
    3077            1 :       exp = fold_convert (type, exp);
    3078            1 :       lowxor = fold_convert (type, lowxor);
    3079            1 :       lowi = fold_convert (type, lowi);
    3080            1 :       highi = fold_convert (type, highi);
    3081              :     }
    3082         2431 :   tem = fold_build1 (BIT_NOT_EXPR, type, lowxor);
    3083         2431 :   exp = fold_build2 (BIT_AND_EXPR, type, exp, tem);
    3084         2431 :   lowj = fold_build2 (BIT_AND_EXPR, type, lowi, tem);
    3085         2431 :   highj = fold_build2 (BIT_AND_EXPR, type, highi, tem);
    3086         2431 :   if (update_range_test (rangei, rangej, NULL, 1, opcode, ops, exp,
    3087              :                          NULL, rangei->in_p, lowj, highj))
    3088              :     return true;
    3089              :   return false;
    3090              : }
    3091              : 
    3092              : /* Optimize X == CST1 || X == CST2
    3093              :    if popcount (CST2 - CST1) == 1 into
    3094              :    ((X - CST1) & ~(CST2 - CST1)) == 0.
    3095              :    Similarly for ranges.  E.g.
    3096              :    X == 43 || X == 76 || X == 44 || X == 78 || X == 77 || X == 46
    3097              :    || X == 75 || X == 45
    3098              :    will be transformed by the previous optimization into
    3099              :    (X - 43U) <= 3U || (X - 75U) <= 3U
    3100              :    and this loop can transform that into
    3101              :    ((X - 43U) & ~(75U - 43U)) <= 3U.  */
    3102              : static bool
    3103        17165 : optimize_range_tests_diff (enum tree_code opcode, tree type,
    3104              :                            tree lowi, tree lowj, tree highi, tree highj,
    3105              :                            vec<operand_entry *> *ops,
    3106              :                            struct range_entry *rangei,
    3107              :                            struct range_entry *rangej)
    3108              : {
    3109        17165 :   tree tem1, tem2, mask;
    3110              :   /* Check highi - lowi == highj - lowj.  */
    3111        17165 :   tem1 = fold_binary (MINUS_EXPR, type, highi, lowi);
    3112        17165 :   if (tem1 == NULL_TREE || TREE_CODE (tem1) != INTEGER_CST)
    3113              :     return false;
    3114        17165 :   tem2 = fold_binary (MINUS_EXPR, type, highj, lowj);
    3115        17165 :   if (!tree_int_cst_equal (tem1, tem2))
    3116              :     return false;
    3117              :   /* Check popcount (lowj - lowi) == 1.  */
    3118        11208 :   tem1 = fold_binary (MINUS_EXPR, type, lowj, lowi);
    3119        11208 :   if (tem1 == NULL_TREE || TREE_CODE (tem1) != INTEGER_CST)
    3120              :     return false;
    3121        11208 :   if (!integer_pow2p (tem1))
    3122              :     return false;
    3123              : 
    3124         1731 :   scalar_int_mode mode = as_a <scalar_int_mode> (TYPE_MODE (type));
    3125         1731 :   int prec = GET_MODE_PRECISION (mode);
    3126         1731 :   if (TYPE_PRECISION (type) < prec
    3127         1731 :       || (wi::to_wide (TYPE_MIN_VALUE (type))
    3128         5193 :           != wi::min_value (prec, TYPE_SIGN (type)))
    3129         3462 :       || (wi::to_wide (TYPE_MAX_VALUE (type))
    3130         5193 :           != wi::max_value (prec, TYPE_SIGN (type))))
    3131            0 :     type = build_nonstandard_integer_type (prec, 1);
    3132              :   else
    3133         1731 :     type = unsigned_type_for (type);
    3134         1731 :   tem1 = fold_convert (type, tem1);
    3135         1731 :   tem2 = fold_convert (type, tem2);
    3136         1731 :   lowi = fold_convert (type, lowi);
    3137         1731 :   mask = fold_build1 (BIT_NOT_EXPR, type, tem1);
    3138         1731 :   tem1 = fold_build2 (MINUS_EXPR, type,
    3139              :                       fold_convert (type, rangei->exp), lowi);
    3140         1731 :   tem1 = fold_build2 (BIT_AND_EXPR, type, tem1, mask);
    3141         1731 :   lowj = build_int_cst (type, 0);
    3142         1731 :   if (update_range_test (rangei, rangej, NULL, 1, opcode, ops, tem1,
    3143              :                          NULL, rangei->in_p, lowj, tem2))
    3144              :     return true;
    3145              :   return false;
    3146              : }
    3147              : 
    3148              : /* It does some common checks for function optimize_range_tests_xor and
    3149              :    optimize_range_tests_diff.
    3150              :    If OPTIMIZE_XOR is TRUE, it calls optimize_range_tests_xor.
    3151              :    Else it calls optimize_range_tests_diff.  */
    3152              : 
    3153              : static bool
    3154      2185992 : optimize_range_tests_1 (enum tree_code opcode, int first, int length,
    3155              :                         bool optimize_xor, vec<operand_entry *> *ops,
    3156              :                         struct range_entry *ranges)
    3157              : {
    3158      2185992 :   int i, j;
    3159      2185992 :   bool any_changes = false;
    3160      3818886 :   for (i = first; i < length; i++)
    3161              :     {
    3162      1632894 :       tree lowi, highi, lowj, highj, type, tem;
    3163              : 
    3164      1632894 :       if (ranges[i].exp == NULL_TREE || ranges[i].in_p)
    3165      1021361 :         continue;
    3166       611533 :       type = TREE_TYPE (ranges[i].exp);
    3167       611533 :       if (!INTEGRAL_TYPE_P (type))
    3168        50004 :         continue;
    3169       561529 :       lowi = ranges[i].low;
    3170       561529 :       if (lowi == NULL_TREE)
    3171        36286 :         lowi = TYPE_MIN_VALUE (type);
    3172       561529 :       highi = ranges[i].high;
    3173       561529 :       if (highi == NULL_TREE)
    3174         6728 :         continue;
    3175       944679 :       for (j = i + 1; j < length && j < i + 64; j++)
    3176              :         {
    3177       394040 :           bool changes;
    3178       394040 :           if (ranges[i].exp != ranges[j].exp || ranges[j].in_p)
    3179       354957 :             continue;
    3180        39083 :           lowj = ranges[j].low;
    3181        39083 :           if (lowj == NULL_TREE)
    3182            0 :             continue;
    3183        39083 :           highj = ranges[j].high;
    3184        39083 :           if (highj == NULL_TREE)
    3185           68 :             highj = TYPE_MAX_VALUE (type);
    3186              :           /* Check lowj > highi.  */
    3187        39083 :           tem = fold_binary (GT_EXPR, boolean_type_node,
    3188              :                              lowj, highi);
    3189        39083 :           if (tem == NULL_TREE || !integer_onep (tem))
    3190            0 :             continue;
    3191        39083 :           if (optimize_xor)
    3192        21918 :             changes = optimize_range_tests_xor (opcode, type, lowi, lowj,
    3193              :                                                 highi, highj, ops,
    3194              :                                                 ranges + i, ranges + j);
    3195              :           else
    3196        17165 :             changes = optimize_range_tests_diff (opcode, type, lowi, lowj,
    3197              :                                                  highi, highj, ops,
    3198              :                                                  ranges + i, ranges + j);
    3199        39083 :           if (changes)
    3200              :             {
    3201              :               any_changes = true;
    3202              :               break;
    3203              :             }
    3204              :         }
    3205              :     }
    3206      2185992 :   return any_changes;
    3207              : }
    3208              : 
    3209              : /* Helper function of optimize_range_tests_to_bit_test.  Handle a single
    3210              :    range, EXP, LOW, HIGH, compute bit mask of bits to test and return
    3211              :    EXP on success, NULL otherwise.  */
    3212              : 
    3213              : static tree
    3214       169566 : extract_bit_test_mask (tree exp, int prec, tree totallow, tree low, tree high,
    3215              :                        wide_int *mask, tree *totallowp)
    3216              : {
    3217       169566 :   tree tem = int_const_binop (MINUS_EXPR, high, low);
    3218       169566 :   if (tem == NULL_TREE
    3219       169566 :       || TREE_CODE (tem) != INTEGER_CST
    3220       169566 :       || TREE_OVERFLOW (tem)
    3221       158376 :       || tree_int_cst_sgn (tem) == -1
    3222       327942 :       || compare_tree_int (tem, prec) != -1)
    3223              :     return NULL_TREE;
    3224              : 
    3225       154460 :   unsigned HOST_WIDE_INT max = tree_to_uhwi (tem) + 1;
    3226       154460 :   *mask = wi::shifted_mask (0, max, false, prec);
    3227       154460 :   if (TREE_CODE (exp) == BIT_AND_EXPR
    3228       154460 :       && TREE_CODE (TREE_OPERAND (exp, 1)) == INTEGER_CST)
    3229              :     {
    3230         4443 :       widest_int msk = wi::to_widest (TREE_OPERAND (exp, 1));
    3231         4443 :       msk = wi::zext (~msk, TYPE_PRECISION (TREE_TYPE (exp)));
    3232         4443 :       if (wi::popcount (msk) == 1
    3233         4443 :           && wi::ltu_p (msk, prec - max))
    3234              :         {
    3235         3827 :           *mask |= wi::shifted_mask (msk.to_uhwi (), max, false, prec);
    3236         3827 :           max += msk.to_uhwi ();
    3237         3827 :           exp = TREE_OPERAND (exp, 0);
    3238         3827 :           if (integer_zerop (low)
    3239         1982 :               && TREE_CODE (exp) == PLUS_EXPR
    3240         5513 :               && TREE_CODE (TREE_OPERAND (exp, 1)) == INTEGER_CST)
    3241              :             {
    3242         1686 :               tree ret = TREE_OPERAND (exp, 0);
    3243         1686 :               STRIP_NOPS (ret);
    3244         1686 :               widest_int bias
    3245         1686 :                 = wi::neg (wi::sext (wi::to_widest (TREE_OPERAND (exp, 1)),
    3246         3372 :                                      TYPE_PRECISION (TREE_TYPE (low))));
    3247         1686 :               tree tbias = wide_int_to_tree (TREE_TYPE (ret), bias);
    3248         1686 :               if (totallowp)
    3249              :                 {
    3250         1654 :                   *totallowp = tbias;
    3251         1654 :                   return ret;
    3252              :                 }
    3253           32 :               else if (!tree_int_cst_lt (totallow, tbias))
    3254              :                 return NULL_TREE;
    3255           32 :               bias = wi::to_widest (tbias);
    3256           32 :               bias -= wi::to_widest (totallow);
    3257           32 :               if (bias >= 0 && bias < prec - max)
    3258              :                 {
    3259           26 :                   *mask = wi::lshift (*mask, bias);
    3260           26 :                   return ret;
    3261              :                 }
    3262         1686 :             }
    3263              :         }
    3264         4443 :     }
    3265       152780 :   if (totallowp)
    3266              :     return exp;
    3267        13313 :   if (!tree_int_cst_lt (totallow, low))
    3268              :     return exp;
    3269        13295 :   tem = int_const_binop (MINUS_EXPR, low, totallow);
    3270        13295 :   if (tem == NULL_TREE
    3271        13295 :       || TREE_CODE (tem) != INTEGER_CST
    3272        13295 :       || TREE_OVERFLOW (tem)
    3273        26434 :       || compare_tree_int (tem, prec - max) == 1)
    3274              :     return NULL_TREE;
    3275              : 
    3276         9513 :   *mask = wi::lshift (*mask, wi::to_widest (tem));
    3277         9513 :   return exp;
    3278              : }
    3279              : 
    3280              : /* Attempt to optimize small range tests using bit test.
    3281              :    E.g.
    3282              :    X != 43 && X != 76 && X != 44 && X != 78 && X != 49
    3283              :    && X != 77 && X != 46 && X != 75 && X != 45 && X != 82
    3284              :    has been by earlier optimizations optimized into:
    3285              :    ((X - 43U) & ~32U) > 3U && X != 49 && X != 82
    3286              :    As all the 43 through 82 range is less than 64 numbers,
    3287              :    for 64-bit word targets optimize that into:
    3288              :    (X - 43U) > 40U && ((1 << (X - 43U)) & 0x8F0000004FULL) == 0  */
    3289              : 
    3290              : static bool
    3291      1093004 : optimize_range_tests_to_bit_test (enum tree_code opcode, int first, int length,
    3292              :                                   vec<operand_entry *> *ops,
    3293              :                                   struct range_entry *ranges)
    3294              : {
    3295      1093004 :   int i, j;
    3296      1093004 :   bool any_changes = false;
    3297      1093004 :   int prec = GET_MODE_BITSIZE (word_mode);
    3298      1093004 :   auto_vec<struct range_entry *, 64> candidates;
    3299              : 
    3300      1527548 :   for (i = first; i < length - 1; i++)
    3301              :     {
    3302       434544 :       tree lowi, highi, lowj, highj, type;
    3303              : 
    3304       434544 :       if (ranges[i].exp == NULL_TREE || ranges[i].in_p)
    3305       293423 :         continue;
    3306       175626 :       type = TREE_TYPE (ranges[i].exp);
    3307       175626 :       if (!INTEGRAL_TYPE_P (type))
    3308        17049 :         continue;
    3309       158577 :       lowi = ranges[i].low;
    3310       158577 :       if (lowi == NULL_TREE)
    3311        11320 :         lowi = TYPE_MIN_VALUE (type);
    3312       158577 :       highi = ranges[i].high;
    3313       158577 :       if (highi == NULL_TREE)
    3314         2424 :         continue;
    3315       156153 :       wide_int mask;
    3316       156153 :       tree exp = extract_bit_test_mask (ranges[i].exp, prec, lowi, lowi,
    3317              :                                         highi, &mask, &lowi);
    3318       156153 :       if (exp == NULL_TREE)
    3319        15032 :         continue;
    3320       141121 :       candidates.truncate (0);
    3321       141121 :       int end = MIN (i + 64, length);
    3322       309407 :       for (j = i + 1; j < end; j++)
    3323              :         {
    3324       168286 :           tree exp2;
    3325       168286 :           if (ranges[j].exp == NULL_TREE || ranges[j].in_p)
    3326       158755 :             continue;
    3327       100538 :           if (ranges[j].exp == exp)
    3328              :             ;
    3329        87598 :           else if (TREE_CODE (ranges[j].exp) == BIT_AND_EXPR)
    3330              :             {
    3331         1440 :               exp2 = TREE_OPERAND (ranges[j].exp, 0);
    3332         1440 :               if (exp2 == exp)
    3333              :                 ;
    3334         1011 :               else if (TREE_CODE (exp2) == PLUS_EXPR)
    3335              :                 {
    3336          810 :                   exp2 = TREE_OPERAND (exp2, 0);
    3337          810 :                   STRIP_NOPS (exp2);
    3338          810 :                   if (exp2 != exp)
    3339          766 :                     continue;
    3340              :                 }
    3341              :               else
    3342          201 :                 continue;
    3343              :             }
    3344              :           else
    3345        86158 :             continue;
    3346        13413 :           lowj = ranges[j].low;
    3347        13413 :           if (lowj == NULL_TREE)
    3348            0 :             continue;
    3349        13413 :           highj = ranges[j].high;
    3350        13413 :           if (highj == NULL_TREE)
    3351           34 :             highj = TYPE_MAX_VALUE (TREE_TYPE (lowj));
    3352        13413 :           wide_int mask2;
    3353        13413 :           exp2 = extract_bit_test_mask (ranges[j].exp, prec, lowi, lowj,
    3354              :                                         highj, &mask2, NULL);
    3355        13413 :           if (exp2 != exp)
    3356         3882 :             continue;
    3357         9531 :           mask |= mask2;
    3358         9531 :           candidates.safe_push (&ranges[j]);
    3359        13413 :         }
    3360              : 
    3361              :       /* If every possible relative value of the expression is a valid shift
    3362              :          amount, then we can merge the entry test in the bit test.  In this
    3363              :          case, if we would need otherwise 2 or more comparisons, then use
    3364              :          the bit test; in the other cases, the threshold is 3 comparisons.  */
    3365       141121 :       bool entry_test_needed;
    3366       141121 :       int_range_max r;
    3367       282242 :       if (TREE_CODE (exp) == SSA_NAME
    3368       281118 :           && get_range_query (cfun)->range_of_expr (r, exp)
    3369       140559 :           && !r.undefined_p ()
    3370       140559 :           && !r.varying_p ()
    3371       321601 :           && wi::leu_p (r.upper_bound () - r.lower_bound (), prec - 1))
    3372              :         {
    3373         4885 :           wide_int min = r.lower_bound ();
    3374         4885 :           wide_int ilowi = wi::to_wide (lowi);
    3375         4885 :           if (wi::lt_p (min, ilowi, TYPE_SIGN (TREE_TYPE (lowi))))
    3376              :             {
    3377          557 :               lowi = wide_int_to_tree (TREE_TYPE (lowi), min);
    3378          557 :               mask = wi::lshift (mask, ilowi - min);
    3379              :             }
    3380         4328 :           else if (wi::gt_p (min, ilowi, TYPE_SIGN (TREE_TYPE (lowi))))
    3381              :             {
    3382            1 :               lowi = wide_int_to_tree (TREE_TYPE (lowi), min);
    3383            1 :               mask = wi::lrshift (mask, min - ilowi);
    3384              :             }
    3385         4885 :           entry_test_needed = false;
    3386         4885 :         }
    3387              :       else
    3388              :         entry_test_needed = true;
    3389       287127 :       if (candidates.length () >= (entry_test_needed ? 2 : 1))
    3390              :         {
    3391          880 :           tree high = wide_int_to_tree (TREE_TYPE (lowi),
    3392          440 :                                         wi::to_widest (lowi)
    3393         1320 :                                         + prec - 1 - wi::clz (mask));
    3394          440 :           operand_entry *oe = (*ops)[ranges[i].idx];
    3395          440 :           tree op = oe->op;
    3396          440 :           gimple *stmt = op ? SSA_NAME_DEF_STMT (op)
    3397           42 :                             : last_nondebug_stmt (BASIC_BLOCK_FOR_FN
    3398          398 :                                                           (cfun, oe->id));
    3399          440 :           location_t loc = gimple_location (stmt);
    3400          440 :           tree optype = op ? TREE_TYPE (op) : boolean_type_node;
    3401              : 
    3402              :           /* See if it isn't cheaper to pretend the minimum value of the
    3403              :              range is 0, if maximum value is small enough.
    3404              :              We can avoid then subtraction of the minimum value, but the
    3405              :              mask constant could be perhaps more expensive.  */
    3406          440 :           if (compare_tree_int (lowi, 0) > 0
    3407          371 :               && compare_tree_int (high, prec) < 0
    3408          825 :               && (entry_test_needed || wi::ltu_p (r.upper_bound (), prec)))
    3409              :             {
    3410          153 :               int cost_diff;
    3411          153 :               HOST_WIDE_INT m = tree_to_uhwi (lowi);
    3412          153 :               rtx reg = gen_raw_REG (word_mode, 10000);
    3413          153 :               bool speed_p = optimize_bb_for_speed_p (gimple_bb (stmt));
    3414          153 :               cost_diff = set_src_cost (gen_rtx_PLUS (word_mode, reg,
    3415              :                                                       GEN_INT (-m)),
    3416              :                                         word_mode, speed_p);
    3417          153 :               rtx r = immed_wide_int_const (mask, word_mode);
    3418          153 :               cost_diff += set_src_cost (gen_rtx_AND (word_mode, reg, r),
    3419              :                                          word_mode, speed_p);
    3420          153 :               r = immed_wide_int_const (wi::lshift (mask, m), word_mode);
    3421          153 :               cost_diff -= set_src_cost (gen_rtx_AND (word_mode, reg, r),
    3422              :                                          word_mode, speed_p);
    3423          153 :               if (cost_diff > 0)
    3424              :                 {
    3425           62 :                   mask = wi::lshift (mask, m);
    3426           62 :                   lowi = build_zero_cst (TREE_TYPE (lowi));
    3427              :                 }
    3428              :             }
    3429              : 
    3430          440 :           tree tem;
    3431          440 :           if (entry_test_needed)
    3432              :             {
    3433          387 :               tem = build_range_check (loc, optype, unshare_expr (exp),
    3434              :                                        false, lowi, high);
    3435          387 :               if (tem == NULL_TREE || is_gimple_val (tem))
    3436            0 :                 continue;
    3437              :             }
    3438              :           else
    3439           53 :             tem = NULL_TREE;
    3440          440 :           tree etype = unsigned_type_for (TREE_TYPE (exp));
    3441          440 :           exp = fold_build2_loc (loc, MINUS_EXPR, etype,
    3442              :                                  fold_convert_loc (loc, etype, exp),
    3443              :                                  fold_convert_loc (loc, etype, lowi));
    3444          440 :           exp = fold_convert_loc (loc, integer_type_node, exp);
    3445          440 :           tree word_type = lang_hooks.types.type_for_mode (word_mode, 1);
    3446          440 :           exp = fold_build2_loc (loc, LSHIFT_EXPR, word_type,
    3447              :                                  build_int_cst (word_type, 1), exp);
    3448          880 :           exp = fold_build2_loc (loc, BIT_AND_EXPR, word_type, exp,
    3449          440 :                                  wide_int_to_tree (word_type, mask));
    3450          440 :           exp = fold_build2_loc (loc, EQ_EXPR, optype, exp,
    3451              :                                  build_zero_cst (word_type));
    3452          440 :           if (is_gimple_val (exp))
    3453            0 :             continue;
    3454              : 
    3455              :           /* The shift might have undefined behavior if TEM is true,
    3456              :              but reassociate_bb isn't prepared to have basic blocks
    3457              :              split when it is running.  So, temporarily emit a code
    3458              :              with BIT_IOR_EXPR instead of &&, and fix it up in
    3459              :              branch_fixup.  */
    3460          440 :           gimple_seq seq = NULL;
    3461          440 :           if (tem)
    3462              :             {
    3463          387 :               tem = force_gimple_operand (tem, &seq, true, NULL_TREE);
    3464          387 :               gcc_assert (TREE_CODE (tem) == SSA_NAME);
    3465          387 :               gimple_set_visited (SSA_NAME_DEF_STMT (tem), true);
    3466              :             }
    3467          440 :           gimple_seq seq2;
    3468          440 :           exp = force_gimple_operand (exp, &seq2, true, NULL_TREE);
    3469          440 :           gimple_seq_add_seq_without_update (&seq, seq2);
    3470          440 :           gcc_assert (TREE_CODE (exp) == SSA_NAME);
    3471          440 :           gimple_set_visited (SSA_NAME_DEF_STMT (exp), true);
    3472          440 :           if (tem)
    3473              :             {
    3474          387 :               gassign *g = gimple_build_assign (make_ssa_name (optype),
    3475              :                                                 BIT_IOR_EXPR, tem, exp);
    3476          387 :               gimple_set_location (g, loc);
    3477          387 :               gimple_seq_add_stmt_without_update (&seq, g);
    3478          387 :               exp = gimple_assign_lhs (g);
    3479              :             }
    3480          440 :           tree val = build_zero_cst (optype);
    3481         1320 :           if (update_range_test (&ranges[i], NULL, candidates.address (),
    3482              :                                  candidates.length (), opcode, ops, exp,
    3483              :                                  seq, false, val, val))
    3484              :             {
    3485          440 :               any_changes = true;
    3486          440 :               if (tem)
    3487          387 :                 reassoc_branch_fixups.safe_push (tem);
    3488              :             }
    3489              :           else
    3490            0 :             gimple_seq_discard (seq);
    3491              :         }
    3492       156153 :     }
    3493      1093004 :   return any_changes;
    3494      1093004 : }
    3495              : 
    3496              : /* Optimize x != 0 && y != 0 && z != 0 into (x | y | z) != 0
    3497              :    and similarly x != -1 && y != -1 && y != -1 into (x & y & z) != -1.
    3498              :    Also, handle x < C && y < C && z < C where C is power of two as
    3499              :    (x | y | z) < C.  And also handle signed x < 0 && y < 0 && z < 0
    3500              :    as (x | y | z) < 0.  */
    3501              : 
    3502              : static bool
    3503      1093004 : optimize_range_tests_cmp_bitwise (enum tree_code opcode, int first, int length,
    3504              :                                   vec<operand_entry *> *ops,
    3505              :                                   struct range_entry *ranges)
    3506              : {
    3507      1093004 :   int i;
    3508      1093004 :   unsigned int b;
    3509      1093004 :   bool any_changes = false;
    3510      1093004 :   auto_vec<int, 128> buckets;
    3511      1093004 :   auto_vec<int, 32> chains;
    3512      1093004 :   auto_vec<struct range_entry *, 32> candidates;
    3513              : 
    3514      1909458 :   for (i = first; i < length; i++)
    3515              :     {
    3516       816454 :       int idx;
    3517              : 
    3518      1166205 :       if (ranges[i].exp == NULL_TREE
    3519       798318 :           || TREE_CODE (ranges[i].exp) != SSA_NAME
    3520       794389 :           || TYPE_PRECISION (TREE_TYPE (ranges[i].exp)) <= 1
    3521      1283157 :           || TREE_CODE (TREE_TYPE (ranges[i].exp)) == BOOLEAN_TYPE)
    3522       349751 :         continue;
    3523              : 
    3524       466703 :       if (ranges[i].low != NULL_TREE
    3525       439245 :           && ranges[i].high != NULL_TREE
    3526       384969 :           && ranges[i].in_p
    3527       700884 :           && tree_int_cst_equal (ranges[i].low, ranges[i].high))
    3528              :         {
    3529       207232 :           idx = !integer_zerop (ranges[i].low);
    3530       207232 :           if (idx && !integer_all_onesp (ranges[i].low))
    3531       115495 :             continue;
    3532              :         }
    3533       259471 :       else if (ranges[i].high != NULL_TREE
    3534       205153 :                && TREE_CODE (ranges[i].high) == INTEGER_CST
    3535       205153 :                && ranges[i].in_p)
    3536              :         {
    3537        36263 :           wide_int w = wi::to_wide (ranges[i].high);
    3538        36263 :           int prec = TYPE_PRECISION (TREE_TYPE (ranges[i].exp));
    3539        36263 :           int l = wi::clz (w);
    3540        36263 :           idx = 2;
    3541        98692 :           if (l <= 0
    3542        36263 :               || l >= prec
    3543        66495 :               || w != wi::mask (prec - l, false, prec))
    3544        26166 :             continue;
    3545        10097 :           if (!((TYPE_UNSIGNED (TREE_TYPE (ranges[i].exp))
    3546         6315 :                  && ranges[i].low == NULL_TREE)
    3547        10097 :                 || (ranges[i].low
    3548         8052 :                     && integer_zerop (ranges[i].low))))
    3549         3348 :             continue;
    3550        36263 :         }
    3551       422587 :       else if (ranges[i].high == NULL_TREE
    3552        54318 :                && ranges[i].low != NULL_TREE
    3553              :                /* Perform this optimization only in the last
    3554              :                   reassoc pass, as it interferes with the reassociation
    3555              :                   itself or could also with VRP etc. which might not
    3556              :                   be able to virtually undo the optimization.  */
    3557        54276 :                && !reassoc_insert_powi_p
    3558        27262 :                && !TYPE_UNSIGNED (TREE_TYPE (ranges[i].exp))
    3559       250153 :                && integer_zerop (ranges[i].low))
    3560              :         idx = 3;
    3561              :       else
    3562       199379 :         continue;
    3563              : 
    3564       122315 :       b = TYPE_PRECISION (TREE_TYPE (ranges[i].exp)) * 4 + idx;
    3565       122315 :       if (buckets.length () <= b)
    3566       107508 :         buckets.safe_grow_cleared (b + 1, true);
    3567       122315 :       if (chains.length () <= (unsigned) i)
    3568       122315 :         chains.safe_grow (i + 1, true);
    3569       122315 :       chains[i] = buckets[b];
    3570       122315 :       buckets[b] = i + 1;
    3571              :     }
    3572              : 
    3573     20800943 :   FOR_EACH_VEC_ELT (buckets, b, i)
    3574     19707939 :     if (i && chains[i - 1])
    3575              :       {
    3576         7176 :         int j, k = i;
    3577         7176 :         if ((b % 4) == 2)
    3578              :           {
    3579              :             /* When ranges[X - 1].high + 1 is a power of two,
    3580              :                we need to process the same bucket up to
    3581              :                precision - 1 times, each time split the entries
    3582              :                with the same high bound into one chain and the
    3583              :                rest into another one to be processed later.  */
    3584              :             int this_prev = i;
    3585              :             int other_prev = 0;
    3586          170 :             for (j = chains[i - 1]; j; j = chains[j - 1])
    3587              :               {
    3588           91 :                 if (tree_int_cst_equal (ranges[i - 1].high,
    3589           91 :                                         ranges[j - 1].high))
    3590              :                   {
    3591           74 :                     chains[this_prev - 1] = j;
    3592           74 :                     this_prev = j;
    3593              :                   }
    3594           17 :                 else if (other_prev == 0)
    3595              :                   {
    3596           15 :                     buckets[b] = j;
    3597           15 :                     other_prev = j;
    3598              :                   }
    3599              :                 else
    3600              :                   {
    3601            2 :                     chains[other_prev - 1] = j;
    3602            2 :                     other_prev = j;
    3603              :                   }
    3604              :               }
    3605           79 :             chains[this_prev - 1] = 0;
    3606           79 :             if (other_prev)
    3607           15 :               chains[other_prev - 1] = 0;
    3608           79 :             if (chains[i - 1] == 0)
    3609              :               {
    3610           13 :                 if (other_prev)
    3611           13 :                   b--;
    3612           13 :                 continue;
    3613              :               }
    3614              :           }
    3615        17805 :         for (j = chains[i - 1]; j; j = chains[j - 1])
    3616              :           {
    3617        10642 :             gimple *gk = SSA_NAME_DEF_STMT (ranges[k - 1].exp);
    3618        10642 :             gimple *gj = SSA_NAME_DEF_STMT (ranges[j - 1].exp);
    3619        10642 :             if (reassoc_stmt_dominates_stmt_p (gk, gj))
    3620         3062 :               k = j;
    3621              :           }
    3622         7163 :         tree type1 = TREE_TYPE (ranges[k - 1].exp);
    3623         7163 :         tree type2 = NULL_TREE;
    3624         7163 :         candidates.truncate (0);
    3625         7163 :         if (POINTER_TYPE_P (type1) || TREE_CODE (type1) == OFFSET_TYPE)
    3626          703 :           type1 = pointer_sized_int_node;
    3627        24968 :         for (j = i; j; j = chains[j - 1])
    3628              :           {
    3629        17805 :             tree type = TREE_TYPE (ranges[j - 1].exp);
    3630        17805 :             if (POINTER_TYPE_P (type) || TREE_CODE (type) == OFFSET_TYPE)
    3631         1451 :               type = pointer_sized_int_node;
    3632        17805 :             if ((b % 4) == 3)
    3633              :               {
    3634              :                 /* For the signed < 0 cases, the types should be
    3635              :                    really compatible (all signed with the same precision,
    3636              :                    instead put ranges that have different in_p from
    3637              :                    k first.  */
    3638         3667 :                 if (!useless_type_conversion_p (type1, type))
    3639            0 :                   continue;
    3640         3667 :                 if (ranges[j - 1].in_p != ranges[k - 1].in_p)
    3641         1009 :                   candidates.safe_push (&ranges[j - 1]);
    3642         3667 :                 type2 = type1;
    3643         3667 :                 continue;
    3644              :               }
    3645        14138 :             if (j == k
    3646        14138 :                 || useless_type_conversion_p (type1, type))
    3647              :               ;
    3648          426 :             else if (type2 == NULL_TREE
    3649          426 :                      || useless_type_conversion_p (type2, type))
    3650              :               {
    3651          426 :                 if (type2 == NULL_TREE)
    3652          412 :                   type2 = type;
    3653          426 :                 candidates.safe_push (&ranges[j - 1]);
    3654              :               }
    3655              :           }
    3656         7163 :         unsigned l = candidates.length ();
    3657        24968 :         for (j = i; j; j = chains[j - 1])
    3658              :           {
    3659        17805 :             tree type = TREE_TYPE (ranges[j - 1].exp);
    3660        17805 :             if (j == k)
    3661         7163 :               continue;
    3662        10642 :             if (POINTER_TYPE_P (type) || TREE_CODE (type) == OFFSET_TYPE)
    3663          748 :               type = pointer_sized_int_node;
    3664        10642 :             if ((b % 4) == 3)
    3665              :               {
    3666         2032 :                 if (!useless_type_conversion_p (type1, type))
    3667            0 :                   continue;
    3668         2032 :                 if (ranges[j - 1].in_p == ranges[k - 1].in_p)
    3669         1023 :                   candidates.safe_push (&ranges[j - 1]);
    3670         2032 :                 continue;
    3671              :               }
    3672         8610 :             if (useless_type_conversion_p (type1, type))
    3673              :               ;
    3674          852 :             else if (type2 == NULL_TREE
    3675          426 :                      || useless_type_conversion_p (type2, type))
    3676          426 :               continue;
    3677         8184 :             candidates.safe_push (&ranges[j - 1]);
    3678              :           }
    3679         7163 :         gimple_seq seq = NULL;
    3680         7163 :         tree op = NULL_TREE;
    3681         7163 :         unsigned int id;
    3682         7163 :         struct range_entry *r;
    3683         7163 :         candidates.safe_push (&ranges[k - 1]);
    3684        24968 :         FOR_EACH_VEC_ELT (candidates, id, r)
    3685              :           {
    3686        17805 :             gassign *g;
    3687        17805 :             enum tree_code code;
    3688        17805 :             if (id == 0)
    3689              :               {
    3690         7163 :                 op = r->exp;
    3691         7163 :                 continue;
    3692              :               }
    3693        10642 :             if (id == l
    3694         9221 :                 || POINTER_TYPE_P (TREE_TYPE (op))
    3695        19247 :                 || TREE_CODE (TREE_TYPE (op)) == OFFSET_TYPE)
    3696              :               {
    3697         2042 :                 code = (b % 4) == 3 ? BIT_NOT_EXPR : NOP_EXPR;
    3698         2042 :                 tree type3 = id >= l ? type1 : pointer_sized_int_node;
    3699         2042 :                 if (code == BIT_NOT_EXPR
    3700         2042 :                     && TREE_CODE (TREE_TYPE (op)) == OFFSET_TYPE)
    3701              :                   {
    3702            0 :                     g = gimple_build_assign (make_ssa_name (type3),
    3703              :                                              NOP_EXPR, op);
    3704            0 :                     gimple_seq_add_stmt_without_update (&seq, g);
    3705            0 :                     op = gimple_assign_lhs (g);
    3706              :                   }
    3707         2042 :                 g = gimple_build_assign (make_ssa_name (type3), code, op);
    3708         2042 :                 gimple_seq_add_stmt_without_update (&seq, g);
    3709         2042 :                 op = gimple_assign_lhs (g);
    3710              :               }
    3711        10642 :             tree type = TREE_TYPE (r->exp);
    3712        10642 :             tree exp = r->exp;
    3713        10642 :             if (POINTER_TYPE_P (type)
    3714         9886 :                 || TREE_CODE (type) == OFFSET_TYPE
    3715        20523 :                 || (id >= l && !useless_type_conversion_p (type1, type)))
    3716              :               {
    3717          761 :                 tree type3 = id >= l ? type1 : pointer_sized_int_node;
    3718          761 :                 g = gimple_build_assign (make_ssa_name (type3), NOP_EXPR, exp);
    3719          761 :                 gimple_seq_add_stmt_without_update (&seq, g);
    3720          761 :                 exp = gimple_assign_lhs (g);
    3721              :               }
    3722        10642 :             if ((b % 4) == 3)
    3723         3386 :               code = r->in_p ? BIT_IOR_EXPR : BIT_AND_EXPR;
    3724              :             else
    3725         8610 :               code = (b % 4) == 1 ? BIT_AND_EXPR : BIT_IOR_EXPR;
    3726        21284 :             g = gimple_build_assign (make_ssa_name (id >= l ? type1 : type2),
    3727              :                                      code, op, exp);
    3728        10642 :             gimple_seq_add_stmt_without_update (&seq, g);
    3729        10642 :             op = gimple_assign_lhs (g);
    3730              :           }
    3731         7163 :         type1 = TREE_TYPE (ranges[k - 1].exp);
    3732         7163 :         if (POINTER_TYPE_P (type1) || TREE_CODE (type1) == OFFSET_TYPE)
    3733              :           {
    3734          703 :             gassign *g
    3735          703 :               = gimple_build_assign (make_ssa_name (type1), NOP_EXPR, op);
    3736          703 :             gimple_seq_add_stmt_without_update (&seq, g);
    3737          703 :             op = gimple_assign_lhs (g);
    3738              :           }
    3739         7163 :         candidates.pop ();
    3740         7163 :         if (update_range_test (&ranges[k - 1], NULL, candidates.address (),
    3741              :                                candidates.length (), opcode, ops, op,
    3742              :                                seq, ranges[k - 1].in_p, ranges[k - 1].low,
    3743              :                                ranges[k - 1].high))
    3744              :           any_changes = true;
    3745              :         else
    3746            0 :           gimple_seq_discard (seq);
    3747         7229 :         if ((b % 4) == 2 && buckets[b] != i)
    3748              :           /* There is more work to do for this bucket.  */
    3749            2 :           b--;
    3750              :       }
    3751              : 
    3752      1093004 :   return any_changes;
    3753      1093004 : }
    3754              : 
    3755              : /* Attempt to optimize for signed a and b where b is known to be >= 0:
    3756              :    a >= 0 && a < b into (unsigned) a < (unsigned) b
    3757              :    a >= 0 && a <= b into (unsigned) a <= (unsigned) b  */
    3758              : 
    3759              : static bool
    3760      1093004 : optimize_range_tests_var_bound (enum tree_code opcode, int first, int length,
    3761              :                                 vec<operand_entry *> *ops,
    3762              :                                 struct range_entry *ranges,
    3763              :                                 basic_block first_bb)
    3764              : {
    3765      1093004 :   int i;
    3766      1093004 :   bool any_changes = false;
    3767      1093004 :   hash_map<tree, int> *map = NULL;
    3768              : 
    3769      1909458 :   for (i = first; i < length; i++)
    3770              :     {
    3771       816454 :       if (ranges[i].exp == NULL_TREE
    3772       798875 :           || TREE_CODE (ranges[i].exp) != SSA_NAME
    3773       794946 :           || !ranges[i].in_p)
    3774       321404 :         continue;
    3775              : 
    3776       495050 :       tree type = TREE_TYPE (ranges[i].exp);
    3777       944728 :       if (!INTEGRAL_TYPE_P (type)
    3778       485245 :           || TYPE_UNSIGNED (type)
    3779       205825 :           || ranges[i].low == NULL_TREE
    3780       196511 :           || !integer_zerop (ranges[i].low)
    3781       569272 :           || ranges[i].high != NULL_TREE)
    3782       449678 :         continue;
    3783              :       /* EXP >= 0 here.  */
    3784        45372 :       if (map == NULL)
    3785        43701 :         map = new hash_map <tree, int>;
    3786        45372 :       map->put (ranges[i].exp, i);
    3787              :     }
    3788              : 
    3789      1093004 :   if (map == NULL)
    3790              :     return false;
    3791              : 
    3792       134817 :   for (i = 0; i < length; i++)
    3793              :     {
    3794        91116 :       bool in_p = ranges[i].in_p;
    3795        91116 :       if (ranges[i].low == NULL_TREE
    3796        90405 :           || ranges[i].high == NULL_TREE)
    3797        90559 :         continue;
    3798        43257 :       if (!integer_zerop (ranges[i].low)
    3799        43257 :           || !integer_zerop (ranges[i].high))
    3800              :         {
    3801         8982 :           if (ranges[i].exp
    3802         4491 :               && TYPE_PRECISION (TREE_TYPE (ranges[i].exp)) == 1
    3803            0 :               && TYPE_UNSIGNED (TREE_TYPE (ranges[i].exp))
    3804            0 :               && integer_onep (ranges[i].low)
    3805         4491 :               && integer_onep (ranges[i].high))
    3806            0 :             in_p = !in_p;
    3807              :           else
    3808         4491 :             continue;
    3809              :         }
    3810              : 
    3811        38766 :       gimple *stmt;
    3812        38766 :       tree_code ccode;
    3813        38766 :       tree rhs1, rhs2;
    3814        38766 :       if (ranges[i].exp)
    3815              :         {
    3816        37674 :           if (TREE_CODE (ranges[i].exp) != SSA_NAME)
    3817            5 :             continue;
    3818        37669 :           stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (ranges[i].exp));
    3819        37669 :           if (!stmt)
    3820          941 :             continue;
    3821        36728 :           ccode = gimple_assign_rhs_code (stmt);
    3822        36728 :           rhs1 = gimple_assign_rhs1 (stmt);
    3823        36728 :           rhs2 = gimple_assign_rhs2 (stmt);
    3824              :         }
    3825              :       else
    3826              :         {
    3827         1092 :           operand_entry *oe = (*ops)[ranges[i].idx];
    3828         1092 :           stmt = last_nondebug_stmt (BASIC_BLOCK_FOR_FN (cfun, oe->id));
    3829         1092 :           if (gimple_code (stmt) != GIMPLE_COND)
    3830            0 :             continue;
    3831         1092 :           ccode = gimple_cond_code (stmt);
    3832         1092 :           rhs1 = gimple_cond_lhs (stmt);
    3833         1092 :           rhs2 = gimple_cond_rhs (stmt);
    3834              :         }
    3835              : 
    3836        37820 :       if (TREE_CODE (rhs1) != SSA_NAME
    3837        37311 :           || rhs2 == NULL_TREE
    3838        37208 :           || TREE_CODE (rhs2) != SSA_NAME)
    3839          630 :         continue;
    3840              : 
    3841        37190 :       switch (ccode)
    3842              :         {
    3843        35986 :         case GT_EXPR:
    3844        35986 :         case GE_EXPR:
    3845        35986 :         case LT_EXPR:
    3846        35986 :         case LE_EXPR:
    3847        35986 :           break;
    3848         1204 :         default:
    3849         1204 :           continue;
    3850              :         }
    3851        35986 :       if (in_p)
    3852          805 :         ccode = invert_tree_comparison (ccode, false);
    3853        35986 :       switch (ccode)
    3854              :         {
    3855        14926 :         case GT_EXPR:
    3856        14926 :         case GE_EXPR:
    3857        14926 :           std::swap (rhs1, rhs2);
    3858        14926 :           ccode = swap_tree_comparison (ccode);
    3859        14926 :           break;
    3860              :         case LT_EXPR:
    3861              :         case LE_EXPR:
    3862              :           break;
    3863            0 :         default:
    3864            0 :           gcc_unreachable ();
    3865              :         }
    3866              : 
    3867        35986 :       int *idx = map->get (rhs1);
    3868        35986 :       if (idx == NULL)
    3869         1067 :         continue;
    3870              : 
    3871              :       /* maybe_optimize_range_tests allows statements without side-effects
    3872              :          in the basic blocks as long as they are consumed in the same bb.
    3873              :          Make sure rhs2's def stmt is not among them, otherwise we can't
    3874              :          use safely get_nonzero_bits on it.  E.g. in:
    3875              :           # RANGE [-83, 1] NONZERO 173
    3876              :           # k_32 = PHI <k_47(13), k_12(9)>
    3877              :          ...
    3878              :           if (k_32 >= 0)
    3879              :             goto <bb 5>; [26.46%]
    3880              :           else
    3881              :             goto <bb 9>; [73.54%]
    3882              : 
    3883              :           <bb 5> [local count: 140323371]:
    3884              :           # RANGE [0, 1] NONZERO 1
    3885              :           _5 = (int) k_32;
    3886              :           # RANGE [0, 4] NONZERO 4
    3887              :           _21 = _5 << 2;
    3888              :           # RANGE [0, 4] NONZERO 4
    3889              :           iftmp.0_44 = (char) _21;
    3890              :           if (k_32 < iftmp.0_44)
    3891              :             goto <bb 6>; [84.48%]
    3892              :           else
    3893              :             goto <bb 9>; [15.52%]
    3894              :          the ranges on _5/_21/iftmp.0_44 are flow sensitive, assume that
    3895              :          k_32 >= 0.  If we'd optimize k_32 >= 0 to true and k_32 < iftmp.0_44
    3896              :          to (unsigned) k_32 < (unsigned) iftmp.0_44, then we would execute
    3897              :          those stmts even for negative k_32 and the value ranges would be no
    3898              :          longer guaranteed and so the optimization would be invalid.  */
    3899        34921 :       while (opcode == ERROR_MARK)
    3900              :         {
    3901          644 :           gimple *g = SSA_NAME_DEF_STMT (rhs2);
    3902          644 :           basic_block bb2 = gimple_bb (g);
    3903          644 :           if (bb2
    3904          644 :               && bb2 != first_bb
    3905          644 :               && dominated_by_p (CDI_DOMINATORS, bb2, first_bb))
    3906              :             {
    3907              :               /* As an exception, handle a few common cases.  */
    3908          562 :               if (gimple_assign_cast_p (g)
    3909          562 :                   && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (g))))
    3910              :                 {
    3911           42 :                   tree op0 = gimple_assign_rhs1 (g);
    3912           42 :                   if (TYPE_UNSIGNED (TREE_TYPE (op0))
    3913           42 :                       && (TYPE_PRECISION (TREE_TYPE (rhs2))
    3914           12 :                           > TYPE_PRECISION (TREE_TYPE (op0))))
    3915              :                     /* Zero-extension is always ok.  */
    3916              :                     break;
    3917           32 :                   else if (TYPE_PRECISION (TREE_TYPE (rhs2))
    3918           32 :                            == TYPE_PRECISION (TREE_TYPE (op0))
    3919           32 :                            && TREE_CODE (op0) == SSA_NAME)
    3920              :                     {
    3921              :                       /* Cast from signed to unsigned or vice versa.  Retry
    3922              :                          with the op0 as new rhs2.  */
    3923            2 :                       rhs2 = op0;
    3924            2 :                       continue;
    3925              :                     }
    3926              :                 }
    3927          520 :               else if (is_gimple_assign (g)
    3928          520 :                        && gimple_assign_rhs_code (g) == BIT_AND_EXPR
    3929            0 :                        && TREE_CODE (gimple_assign_rhs2 (g)) == INTEGER_CST
    3930         1040 :                        && !wi::neg_p (wi::to_wide (gimple_assign_rhs2 (g))))
    3931              :                 /* Masking with INTEGER_CST with MSB clear is always ok
    3932              :                    too.  */
    3933              :                 break;
    3934              :               rhs2 = NULL_TREE;
    3935              :             }
    3936              :           break;
    3937              :         }
    3938        34369 :       if (rhs2 == NULL_TREE)
    3939          550 :         continue;
    3940              : 
    3941        34926 :       wide_int nz = get_nonzero_bits (rhs2);
    3942        34369 :       if (wi::neg_p (nz))
    3943        33812 :         continue;
    3944              : 
    3945              :       /* We have EXP < RHS2 or EXP <= RHS2 where EXP >= 0
    3946              :          and RHS2 is known to be RHS2 >= 0.  */
    3947          557 :       tree utype = unsigned_type_for (TREE_TYPE (rhs1));
    3948              : 
    3949          557 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3950              :         {
    3951            7 :           struct range_entry *r = &ranges[*idx];
    3952            7 :           fprintf (dump_file, "Optimizing range test ");
    3953            7 :           print_generic_expr (dump_file, r->exp);
    3954            7 :           fprintf (dump_file, " +[");
    3955            7 :           print_generic_expr (dump_file, r->low);
    3956            7 :           fprintf (dump_file, ", ");
    3957            7 :           print_generic_expr (dump_file, r->high);
    3958            7 :           fprintf (dump_file, "] and comparison ");
    3959            7 :           print_generic_expr (dump_file, rhs1);
    3960            7 :           fprintf (dump_file, " %s ", op_symbol_code (ccode));
    3961            7 :           print_generic_expr (dump_file, rhs2);
    3962            7 :           fprintf (dump_file, "\n into (");
    3963            7 :           print_generic_expr (dump_file, utype);
    3964            7 :           fprintf (dump_file, ") ");
    3965            7 :           print_generic_expr (dump_file, rhs1);
    3966            7 :           fprintf (dump_file, " %s (", op_symbol_code (ccode));
    3967            7 :           print_generic_expr (dump_file, utype);
    3968            7 :           fprintf (dump_file, ") ");
    3969            7 :           print_generic_expr (dump_file, rhs2);
    3970            7 :           fprintf (dump_file, "\n");
    3971              :         }
    3972              : 
    3973          557 :       operand_entry *oe = (*ops)[ranges[i].idx];
    3974          557 :       ranges[i].in_p = 0;
    3975          557 :       if (opcode == BIT_IOR_EXPR
    3976          518 :           || (opcode == ERROR_MARK && oe->rank == BIT_IOR_EXPR))
    3977              :         {
    3978           40 :           ranges[i].in_p = 1;
    3979           40 :           ccode = invert_tree_comparison (ccode, false);
    3980              :         }
    3981              : 
    3982          557 :       unsigned int uid = gimple_uid (stmt);
    3983          557 :       gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
    3984          557 :       gassign *g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, rhs1);
    3985          557 :       gimple_set_uid (g, uid);
    3986          557 :       rhs1 = gimple_assign_lhs (g);
    3987          557 :       gsi_insert_before (&gsi, g, GSI_SAME_STMT);
    3988          557 :       if (!useless_type_conversion_p (utype, TREE_TYPE (rhs2)))
    3989              :         {
    3990          557 :           g = gimple_build_assign (make_ssa_name (utype), NOP_EXPR, rhs2);
    3991          557 :           gimple_set_uid (g, uid);
    3992          557 :           rhs2 = gimple_assign_lhs (g);
    3993          557 :           gsi_insert_before (&gsi, g, GSI_SAME_STMT);
    3994              :         }
    3995          557 :       if (tree_swap_operands_p (rhs1, rhs2))
    3996              :         {
    3997          504 :           std::swap (rhs1, rhs2);
    3998          504 :           ccode = swap_tree_comparison (ccode);
    3999              :         }
    4000          557 :       if (gimple_code (stmt) == GIMPLE_COND)
    4001              :         {
    4002            8 :           gcond *c = as_a <gcond *> (stmt);
    4003            8 :           gimple_cond_set_code (c, ccode);
    4004            8 :           gimple_cond_set_lhs (c, rhs1);
    4005            8 :           gimple_cond_set_rhs (c, rhs2);
    4006            8 :           update_stmt (stmt);
    4007              :         }
    4008              :       else
    4009              :         {
    4010          549 :           tree ctype = oe->op ? TREE_TYPE (oe->op) : boolean_type_node;
    4011          549 :           if (!INTEGRAL_TYPE_P (ctype)
    4012          549 :               || (TREE_CODE (ctype) != BOOLEAN_TYPE
    4013            3 :                   && TYPE_PRECISION (ctype) != 1))
    4014            3 :             ctype = boolean_type_node;
    4015          549 :           g = gimple_build_assign (make_ssa_name (ctype), ccode, rhs1, rhs2);
    4016          549 :           gimple_set_uid (g, uid);
    4017          549 :           gsi_insert_before (&gsi, g, GSI_SAME_STMT);
    4018          549 :           if (oe->op && ctype != TREE_TYPE (oe->op))
    4019              :             {
    4020            3 :               g = gimple_build_assign (make_ssa_name (TREE_TYPE (oe->op)),
    4021              :                                        NOP_EXPR, gimple_assign_lhs (g));
    4022            3 :               gimple_set_uid (g, uid);
    4023            3 :               gsi_insert_before (&gsi, g, GSI_SAME_STMT);
    4024              :             }
    4025          549 :           ranges[i].exp = gimple_assign_lhs (g);
    4026          549 :           oe->op = ranges[i].exp;
    4027          549 :           ranges[i].low = build_zero_cst (TREE_TYPE (ranges[i].exp));
    4028          549 :           ranges[i].high = ranges[i].low;
    4029              :         }
    4030          557 :       oe = (*ops)[ranges[*idx].idx];
    4031              :       /* Now change all the other range test immediate uses, so that
    4032              :          those tests will be optimized away.  */
    4033          557 :       if (opcode == ERROR_MARK)
    4034              :         {
    4035           11 :           if (oe->op)
    4036            3 :             oe->op = build_int_cst (TREE_TYPE (oe->op),
    4037            3 :                                     oe->rank == BIT_IOR_EXPR ? 0 : 1);
    4038              :           else
    4039            8 :             oe->op = (oe->rank == BIT_IOR_EXPR
    4040            8 :                       ? boolean_false_node : boolean_true_node);
    4041              :         }
    4042              :       else
    4043          546 :         oe->op = error_mark_node;
    4044          557 :       ranges[*idx].exp = NULL_TREE;
    4045          557 :       ranges[*idx].low = NULL_TREE;
    4046          557 :       ranges[*idx].high = NULL_TREE;
    4047          557 :       any_changes = true;
    4048              :     }
    4049              : 
    4050        43701 :   delete map;
    4051              :   return any_changes;
    4052              : }
    4053              : 
    4054              : /* Optimize range tests, similarly how fold_range_test optimizes
    4055              :    it on trees.  The tree code for the binary
    4056              :    operation between all the operands is OPCODE.
    4057              :    If OPCODE is ERROR_MARK, optimize_range_tests is called from within
    4058              :    maybe_optimize_range_tests for inter-bb range optimization.
    4059              :    In that case if oe->op is NULL, oe->id is bb->index whose
    4060              :    GIMPLE_COND is && or ||ed into the test, and oe->rank says
    4061              :    the actual opcode.
    4062              :    FIRST_BB is the first basic block if OPCODE is ERROR_MARK.  */
    4063              : 
    4064              : static bool
    4065      1093125 : optimize_range_tests (enum tree_code opcode,
    4066              :                       vec<operand_entry *> *ops, basic_block first_bb)
    4067              : {
    4068      1093125 :   unsigned int length = ops->length (), i, j, first;
    4069      1093125 :   operand_entry *oe;
    4070      1093125 :   struct range_entry *ranges;
    4071      2186129 :   bool any_changes = false;
    4072              : 
    4073      1093125 :   if (length == 1)
    4074              :     return false;
    4075              : 
    4076      1093004 :   ranges = XNEWVEC (struct range_entry, length);
    4077      4492842 :   for (i = 0; i < length; i++)
    4078              :     {
    4079      2306834 :       oe = (*ops)[i];
    4080      2306834 :       ranges[i].idx = i;
    4081      2306834 :       init_range_entry (ranges + i, oe->op,
    4082      2306834 :                         oe->op
    4083              :                         ? NULL
    4084       269551 :                         : last_nondebug_stmt (BASIC_BLOCK_FOR_FN (cfun, oe->id)));
    4085              :       /* For | invert it now, we will invert it again before emitting
    4086              :          the optimized expression.  */
    4087      2306834 :       if (opcode == BIT_IOR_EXPR
    4088      1616138 :           || (opcode == ERROR_MARK && oe->rank == BIT_IOR_EXPR))
    4089       887595 :         ranges[i].in_p = !ranges[i].in_p;
    4090              :     }
    4091              : 
    4092      1093004 :   qsort (ranges, length, sizeof (*ranges), range_entry_cmp);
    4093      3676388 :   for (i = 0; i < length; i++)
    4094      1872290 :     if (ranges[i].exp != NULL_TREE && TREE_CODE (ranges[i].exp) == SSA_NAME)
    4095              :       break;
    4096              : 
    4097              :   /* Try to merge ranges.  */
    4098      1897121 :   for (first = i; i < length; i++)
    4099              :     {
    4100       804117 :       tree low = ranges[i].low;
    4101       804117 :       tree high = ranges[i].high;
    4102       804117 :       int in_p = ranges[i].in_p;
    4103       804117 :       int update_fail_count = 0;
    4104              : 
    4105       816472 :       for (j = i + 1; j < length; j++)
    4106              :         {
    4107       434544 :           if (ranges[i].exp != ranges[j].exp)
    4108              :             break;
    4109        32515 :           if (!merge_ranges (&in_p, &low, &high, in_p, low, high,
    4110        32515 :                              ranges[j].in_p, ranges[j].low, ranges[j].high))
    4111              :             break;
    4112              :         }
    4113              : 
    4114       804117 :       if (j == i + 1)
    4115       792175 :         continue;
    4116              : 
    4117        11942 :       if (update_range_test (ranges + i, ranges + i + 1, NULL, j - i - 1,
    4118              :                              opcode, ops, ranges[i].exp, NULL, in_p,
    4119              :                              low, high))
    4120              :         {
    4121        11924 :           i = j - 1;
    4122        11924 :           any_changes = true;
    4123              :         }
    4124              :       /* Avoid quadratic complexity if all merge_ranges calls would succeed,
    4125              :          while update_range_test would fail.  */
    4126              :       else if (update_fail_count == 64)
    4127              :         i = j - 1;
    4128              :       else
    4129        11942 :         ++update_fail_count;
    4130              :     }
    4131              : 
    4132      1093004 :   any_changes |= optimize_range_tests_1 (opcode, first, length, true,
    4133              :                                          ops, ranges);
    4134              : 
    4135      1093004 :   if (BRANCH_COST (optimize_function_for_speed_p (cfun), false) >= 2)
    4136      1092988 :     any_changes |= optimize_range_tests_1 (opcode, first, length, false,
    4137              :                                            ops, ranges);
    4138      1093004 :   if (lshift_cheap_p (optimize_function_for_speed_p (cfun)))
    4139      1093004 :     any_changes |= optimize_range_tests_to_bit_test (opcode, first, length,
    4140              :                                                      ops, ranges);
    4141      1093004 :   any_changes |= optimize_range_tests_var_bound (opcode, first, length, ops,
    4142              :                                                  ranges, first_bb);
    4143      1093004 :   any_changes |= optimize_range_tests_cmp_bitwise (opcode, first, length,
    4144              :                                                    ops, ranges);
    4145              : 
    4146      1093004 :   if (any_changes && opcode != ERROR_MARK)
    4147              :     {
    4148              :       j = 0;
    4149        36507 :       FOR_EACH_VEC_ELT (*ops, i, oe)
    4150              :         {
    4151        25524 :           if (oe->op == error_mark_node)
    4152        12581 :             continue;
    4153        12943 :           else if (i != j)
    4154         5345 :             (*ops)[j] = oe;
    4155        12943 :           j++;
    4156              :         }
    4157        10983 :       ops->truncate (j);
    4158              :     }
    4159              : 
    4160      1093004 :   XDELETEVEC (ranges);
    4161      1093004 :   return any_changes;
    4162              : }
    4163              : 
    4164              : /* A subroutine of optimize_vec_cond_expr to extract and canonicalize
    4165              :    the operands of the VEC_COND_EXPR.  Returns ERROR_MARK on failure,
    4166              :    otherwise the comparison code.  TYPE is a return value that is set
    4167              :    to type of comparison.  */
    4168              : 
    4169              : static tree_code
    4170        58134 : ovce_extract_ops (tree var, gassign **rets, bool *reti, tree *type,
    4171              :                   tree *lhs, tree *rhs, gassign **vcond)
    4172              : {
    4173        58134 :   if (TREE_CODE (var) != SSA_NAME)
    4174              :     return ERROR_MARK;
    4175              : 
    4176        50695 :   gassign *stmt = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (var));
    4177        37125 :   if (stmt == NULL)
    4178              :     return ERROR_MARK;
    4179        37125 :   if (vcond)
    4180        37125 :     *vcond = stmt;
    4181              : 
    4182              :   /* ??? If we start creating more COND_EXPR, we could perform
    4183              :      this same optimization with them.  For now, simplify.  */
    4184        49726 :   if (gimple_assign_rhs_code (stmt) != VEC_COND_EXPR)
    4185              :     return ERROR_MARK;
    4186              : 
    4187         1412 :   tree cond = gimple_assign_rhs1 (stmt);
    4188         1412 :   tree_code cmp = TREE_CODE (cond);
    4189         1412 :   if (cmp != SSA_NAME)
    4190              :     return ERROR_MARK;
    4191              : 
    4192         1390 :   gassign *assign = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (cond));
    4193         1386 :   if (assign == NULL
    4194         1386 :       || TREE_CODE_CLASS (gimple_assign_rhs_code (assign)) != tcc_comparison)
    4195              :     return ERROR_MARK;
    4196              : 
    4197         1273 :   cmp = gimple_assign_rhs_code (assign);
    4198         1273 :   if (lhs)
    4199         1273 :     *lhs = gimple_assign_rhs1 (assign);
    4200         1273 :   if (rhs)
    4201         2546 :     *rhs = gimple_assign_rhs2 (assign);
    4202              : 
    4203              :   /* ??? For now, allow only canonical true and false result vectors.
    4204              :      We could expand this to other constants should the need arise,
    4205              :      but at the moment we don't create them.  */
    4206         1273 :   tree t = gimple_assign_rhs2 (stmt);
    4207         1273 :   tree f = gimple_assign_rhs3 (stmt);
    4208         1273 :   bool inv;
    4209         1273 :   if (integer_all_onesp (t))
    4210              :     inv = false;
    4211         1141 :   else if (integer_all_onesp (f))
    4212              :     {
    4213            1 :       cmp = invert_tree_comparison (cmp, false);
    4214            1 :       inv = true;
    4215              :     }
    4216              :   else
    4217              :     return ERROR_MARK;
    4218          133 :   if (!integer_zerop (inv ? t : f))
    4219              :     return ERROR_MARK;
    4220              : 
    4221              :   /* Success!  */
    4222          114 :   if (rets)
    4223          114 :     *rets = assign;
    4224          114 :   if (reti)
    4225           80 :     *reti = inv;
    4226          114 :   if (type)
    4227           80 :     *type = TREE_TYPE (cond);
    4228              :   return cmp;
    4229              : }
    4230              : 
    4231              : /* Optimize the condition of VEC_COND_EXPRs which have been combined
    4232              :    with OPCODE (either BIT_AND_EXPR or BIT_IOR_EXPR).  */
    4233              : 
    4234              : static bool
    4235        27281 : optimize_vec_cond_expr (tree_code opcode, vec<operand_entry *> *ops)
    4236              : {
    4237        27281 :   unsigned int length = ops->length (), i, j;
    4238        27281 :   bool any_changes = false;
    4239              : 
    4240        27281 :   if (length == 1)
    4241              :     return false;
    4242              : 
    4243        85363 :   for (i = 0; i < length; ++i)
    4244              :     {
    4245        58082 :       tree &elt0 = (*ops)[i]->op;
    4246              : 
    4247        58082 :       gassign *stmt0, *vcond0;
    4248        58082 :       bool invert;
    4249        58082 :       tree type, lhs0, rhs0;
    4250        58082 :       tree_code cmp0 = ovce_extract_ops (elt0, &stmt0, &invert, &type, &lhs0,
    4251              :                                          &rhs0, &vcond0);
    4252        58082 :       if (cmp0 == ERROR_MARK)
    4253        58002 :         continue;
    4254              : 
    4255          132 :       for (j = i + 1; j < length; ++j)
    4256              :         {
    4257           52 :           tree &elt1 = (*ops)[j]->op;
    4258              : 
    4259           52 :           gassign *stmt1, *vcond1;
    4260           52 :           tree lhs1, rhs1;
    4261           52 :           tree_code cmp1 = ovce_extract_ops (elt1, &stmt1, NULL, NULL, &lhs1,
    4262              :                                              &rhs1, &vcond1);
    4263           52 :           if (cmp1 == ERROR_MARK)
    4264           46 :             continue;
    4265              : 
    4266           34 :           tree comb;
    4267           34 :           if (opcode == BIT_AND_EXPR)
    4268            0 :             comb = maybe_fold_and_comparisons (type, TRUTH_AND_EXPR,
    4269              :                                                cmp0, lhs0, rhs0,
    4270              :                                                cmp1, lhs1, rhs1);
    4271           34 :           else if (opcode == BIT_IOR_EXPR)
    4272           34 :             comb = maybe_fold_or_comparisons (type, TRUTH_OR_EXPR,
    4273              :                                               cmp0, lhs0, rhs0,
    4274              :                                               cmp1, lhs1, rhs1);
    4275              :           else
    4276            0 :             gcc_unreachable ();
    4277           34 :           if (comb == NULL)
    4278           28 :             continue;
    4279              : 
    4280              :           /* Success! */
    4281            6 :           if (dump_file && (dump_flags & TDF_DETAILS))
    4282              :             {
    4283            0 :               fprintf (dump_file, "Transforming ");
    4284            0 :               print_generic_expr (dump_file, gimple_assign_lhs (stmt0));
    4285            0 :               fprintf (dump_file, " %c ", opcode == BIT_AND_EXPR ? '&' : '|');
    4286            0 :               print_generic_expr (dump_file, gimple_assign_lhs (stmt1));
    4287            0 :               fprintf (dump_file, " into ");
    4288            0 :               print_generic_expr (dump_file, comb);
    4289            0 :               fputc ('\n', dump_file);
    4290              :             }
    4291              : 
    4292            6 :           gimple_stmt_iterator gsi = gsi_for_stmt (vcond0);
    4293            6 :           tree exp = force_gimple_operand_gsi (&gsi, comb, true, NULL_TREE,
    4294              :                                                true, GSI_SAME_STMT);
    4295           18 :           tree res = gimple_build (&gsi, true, GSI_SAME_STMT, UNKNOWN_LOCATION,
    4296            6 :                                    VEC_COND_EXPR, TREE_TYPE (elt0), exp,
    4297              :                                    constant_boolean_node (true,
    4298            6 :                                                           TREE_TYPE (elt0)),
    4299              :                                    constant_boolean_node (false,
    4300            6 :                                                           TREE_TYPE (elt0)));
    4301            6 :           elt0 = res;
    4302              : 
    4303            6 :           elt1 = error_mark_node;
    4304            6 :           any_changes = true;
    4305              :         }
    4306              :     }
    4307              : 
    4308        27281 :   if (any_changes)
    4309              :     {
    4310              :       operand_entry *oe;
    4311              :       j = 0;
    4312           18 :       FOR_EACH_VEC_ELT (*ops, i, oe)
    4313              :         {
    4314           12 :           if (oe->op == error_mark_node)
    4315            6 :             continue;
    4316            6 :           else if (i != j)
    4317            0 :             (*ops)[j] = oe;
    4318            6 :           j++;
    4319              :         }
    4320            6 :       ops->truncate (j);
    4321              :     }
    4322              : 
    4323              :   return any_changes;
    4324              : }
    4325              : 
    4326              : /* Return true if STMT is a cast like:
    4327              :    <bb N>:
    4328              :    ...
    4329              :    _123 = (int) _234;
    4330              : 
    4331              :    <bb M>:
    4332              :    # _345 = PHI <_123(N), 1(...), 1(...)>
    4333              :    where _234 has bool type, _123 has single use and
    4334              :    bb N has a single successor M.  This is commonly used in
    4335              :    the last block of a range test.
    4336              : 
    4337              :    Also Return true if STMT is tcc_compare like:
    4338              :    <bb N>:
    4339              :    ...
    4340              :    _234 = a_2(D) == 2;
    4341              : 
    4342              :    <bb M>:
    4343              :    # _345 = PHI <_234(N), 1(...), 1(...)>
    4344              :    _346 = (int) _345;
    4345              :    where _234 has booltype, single use and
    4346              :    bb N has a single successor M.  This is commonly used in
    4347              :    the last block of a range test.  */
    4348              : 
    4349              : static bool
    4350     15975306 : final_range_test_p (gimple *stmt)
    4351              : {
    4352     15975306 :   basic_block bb, rhs_bb, lhs_bb;
    4353     15975306 :   edge e;
    4354     15975306 :   tree lhs, rhs;
    4355     15975306 :   use_operand_p use_p;
    4356     15975306 :   gimple *use_stmt;
    4357              : 
    4358     15975306 :   if (!gimple_assign_cast_p (stmt)
    4359     15975306 :       && (!is_gimple_assign (stmt)
    4360      5050155 :           || (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
    4361              :               != tcc_comparison)))
    4362              :     return false;
    4363       570414 :   bb = gimple_bb (stmt);
    4364       570414 :   if (!single_succ_p (bb))
    4365              :     return false;
    4366       570119 :   e = single_succ_edge (bb);
    4367       570119 :   if (e->flags & EDGE_COMPLEX)
    4368              :     return false;
    4369              : 
    4370       570119 :   lhs = gimple_assign_lhs (stmt);
    4371       570119 :   rhs = gimple_assign_rhs1 (stmt);
    4372       570119 :   if (gimple_assign_cast_p (stmt)
    4373       570119 :       && (!INTEGRAL_TYPE_P (TREE_TYPE (lhs))
    4374       404691 :           || TREE_CODE (rhs) != SSA_NAME
    4375       384082 :           || TREE_CODE (TREE_TYPE (rhs)) != BOOLEAN_TYPE))
    4376              :     return false;
    4377              : 
    4378       188395 :   if (!gimple_assign_cast_p (stmt)
    4379       188395 :       && (TREE_CODE (TREE_TYPE (lhs)) != BOOLEAN_TYPE))
    4380              :       return false;
    4381              : 
    4382              :   /* Test whether lhs is consumed only by a PHI in the only successor bb.  */
    4383       187917 :   if (!single_imm_use (lhs, &use_p, &use_stmt))
    4384              :     return false;
    4385              : 
    4386       184554 :   if (gimple_code (use_stmt) != GIMPLE_PHI
    4387       184554 :       || gimple_bb (use_stmt) != e->dest)
    4388              :     return false;
    4389              : 
    4390              :   /* And that the rhs is defined in the same loop.  */
    4391       182707 :   if (gimple_assign_cast_p (stmt))
    4392              :     {
    4393        66125 :       if (TREE_CODE (rhs) != SSA_NAME
    4394        66125 :           || !(rhs_bb = gimple_bb (SSA_NAME_DEF_STMT (rhs)))
    4395       132244 :           || !flow_bb_inside_loop_p (loop_containing_stmt (stmt), rhs_bb))
    4396           53 :         return false;
    4397              :     }
    4398              :   else
    4399              :     {
    4400       116582 :       if (TREE_CODE (lhs) != SSA_NAME
    4401       116582 :           || !(lhs_bb = gimple_bb (SSA_NAME_DEF_STMT (lhs)))
    4402       233164 :           || !flow_bb_inside_loop_p (loop_containing_stmt (stmt), lhs_bb))
    4403            0 :         return false;
    4404              :     }
    4405              : 
    4406              :   return true;
    4407              : }
    4408              : 
    4409              : /* Return true if BB is suitable basic block for inter-bb range test
    4410              :    optimization.  If BACKWARD is true, BB should be the only predecessor
    4411              :    of TEST_BB, and *OTHER_BB is either NULL and filled by the routine,
    4412              :    or compared with to find a common basic block to which all conditions
    4413              :    branch to if true resp. false.  If BACKWARD is false, TEST_BB should
    4414              :    be the only predecessor of BB.  *TEST_SWAPPED_P is set to true if
    4415              :    TEST_BB is a bb ending in condition where the edge to non-*OTHER_BB
    4416              :    block points to an empty block that falls through into *OTHER_BB and
    4417              :    the phi args match that path.  */
    4418              : 
    4419              : static bool
    4420     11430209 : suitable_cond_bb (basic_block bb, basic_block test_bb, basic_block *other_bb,
    4421              :                   bool *test_swapped_p, bool backward)
    4422              : {
    4423     11430209 :   edge_iterator ei, ei2;
    4424     11430209 :   edge e, e2;
    4425     11430209 :   gimple *stmt;
    4426     11430209 :   gphi_iterator gsi;
    4427     11430209 :   bool other_edge_seen = false;
    4428     11430209 :   bool is_cond;
    4429              : 
    4430     11430209 :   if (test_bb == bb)
    4431              :     return false;
    4432              :   /* Check last stmt first.  */
    4433     11430209 :   stmt = last_nondebug_stmt (bb);
    4434     11430209 :   if (stmt == NULL
    4435     10553493 :       || (gimple_code (stmt) != GIMPLE_COND
    4436       544445 :           && (backward || !final_range_test_p (stmt)))
    4437     10049033 :       || gimple_visited_p (stmt)
    4438      9988037 :       || stmt_could_throw_p (cfun, stmt)
    4439     21418132 :       || *other_bb == bb)
    4440              :     return false;
    4441      9987920 :   is_cond = gimple_code (stmt) == GIMPLE_COND;
    4442      9987920 :   if (is_cond)
    4443              :     {
    4444              :       /* If last stmt is GIMPLE_COND, verify that one of the succ edges
    4445              :          goes to the next bb (if BACKWARD, it is TEST_BB), and the other
    4446              :          to *OTHER_BB (if not set yet, try to find it out).  */
    4447      9948049 :       if (EDGE_COUNT (bb->succs) != 2)
    4448              :         return false;
    4449     19619718 :       FOR_EACH_EDGE (e, ei, bb->succs)
    4450              :         {
    4451     16177994 :           if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
    4452              :             return false;
    4453     16177994 :           if (e->dest == test_bb)
    4454              :             {
    4455      5365905 :               if (backward)
    4456      5362858 :                 continue;
    4457              :               else
    4458              :                 return false;
    4459              :             }
    4460     10812089 :           if (e->dest == bb)
    4461              :             return false;
    4462     10650599 :           if (*other_bb == NULL)
    4463              :             {
    4464     26113080 :               FOR_EACH_EDGE (e2, ei2, test_bb->succs)
    4465     17408720 :                 if (!(e2->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
    4466              :                   return false;
    4467     17408720 :                 else if (e->dest == e2->dest)
    4468      2393043 :                   *other_bb = e->dest;
    4469      8704360 :               if (*other_bb == NULL)
    4470              :                 return false;
    4471              :             }
    4472      4339282 :           if (e->dest == *other_bb)
    4473              :             other_edge_seen = true;
    4474       937458 :           else if (backward)
    4475              :             return false;
    4476              :         }
    4477      3441724 :       if (*other_bb == NULL || !other_edge_seen)
    4478              :         return false;
    4479              :     }
    4480        39871 :   else if (single_succ (bb) != *other_bb)
    4481              :     return false;
    4482              : 
    4483              :   /* Now check all PHIs of *OTHER_BB.  */
    4484      3440911 :   e = find_edge (bb, *other_bb);
    4485      3440911 :   e2 = find_edge (test_bb, *other_bb);
    4486      3444376 :  retry:;
    4487      5026940 :   for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
    4488              :     {
    4489      2656690 :       gphi *phi = gsi.phi ();
    4490              :       /* If both BB and TEST_BB end with GIMPLE_COND, all PHI arguments
    4491              :          corresponding to BB and TEST_BB predecessor must be the same.  */
    4492      2656690 :       if (!operand_equal_p (gimple_phi_arg_def (phi, e->dest_idx),
    4493      2656690 :                             gimple_phi_arg_def (phi, e2->dest_idx), 0))
    4494              :         {
    4495              :           /* Otherwise, if one of the blocks doesn't end with GIMPLE_COND,
    4496              :              one of the PHIs should have the lhs of the last stmt in
    4497              :              that block as PHI arg and that PHI should have 0 or 1
    4498              :              corresponding to it in all other range test basic blocks
    4499              :              considered.  */
    4500      1143081 :           if (!is_cond)
    4501              :             {
    4502        41880 :               if (gimple_phi_arg_def (phi, e->dest_idx)
    4503        41880 :                   == gimple_assign_lhs (stmt)
    4504        41880 :                   && (integer_zerop (gimple_phi_arg_def (phi, e2->dest_idx))
    4505        17825 :                       || integer_onep (gimple_phi_arg_def (phi,
    4506        17825 :                                                            e2->dest_idx))))
    4507        37374 :                 continue;
    4508              :             }
    4509              :           else
    4510              :             {
    4511      1101201 :               gimple *test_last = last_nondebug_stmt (test_bb);
    4512      1101201 :               if (gimple_code (test_last) == GIMPLE_COND)
    4513              :                 {
    4514      1065176 :                   if (backward ? e2->src != test_bb : e->src != bb)
    4515              :                     return false;
    4516              : 
    4517              :                   /* For last_bb, handle also:
    4518              :                      if (x_3(D) == 3)
    4519              :                        goto <bb 6>; [34.00%]
    4520              :                      else
    4521              :                        goto <bb 7>; [66.00%]
    4522              : 
    4523              :                      <bb 6> [local count: 79512730]:
    4524              : 
    4525              :                      <bb 7> [local count: 1073741824]:
    4526              :                      # prephitmp_7 = PHI <1(3), 1(4), 0(5), 1(2), 1(6)>
    4527              :                      where bb 7 is *OTHER_BB, but the PHI values from the
    4528              :                      earlier bbs match the path through the empty bb
    4529              :                      in between.  */
    4530      1063198 :                   edge e3;
    4531      1063198 :                   if (backward)
    4532      1453462 :                     e3 = EDGE_SUCC (test_bb,
    4533              :                                     e2 == EDGE_SUCC (test_bb, 0) ? 1 : 0);
    4534              :                   else
    4535        25587 :                     e3 = EDGE_SUCC (bb,
    4536              :                                     e == EDGE_SUCC (bb, 0) ? 1 : 0);
    4537      1063198 :                   if (empty_block_p (e3->dest)
    4538        31951 :                       && single_succ_p (e3->dest)
    4539        31951 :                       && single_succ (e3->dest) == *other_bb
    4540        31681 :                       && single_pred_p (e3->dest)
    4541      1094143 :                       && single_succ_edge (e3->dest)->flags == EDGE_FALLTHRU)
    4542              :                     {
    4543         3465 :                       if (backward)
    4544         2960 :                         e2 = single_succ_edge (e3->dest);
    4545              :                       else
    4546          505 :                         e = single_succ_edge (e3->dest);
    4547         3465 :                       if (test_swapped_p)
    4548          147 :                         *test_swapped_p = true;
    4549         3465 :                       goto retry;
    4550              :                     }
    4551              :                 }
    4552        36025 :               else if (gimple_phi_arg_def (phi, e2->dest_idx)
    4553        36025 :                        == gimple_assign_lhs (test_last)
    4554        68611 :                        && (integer_zerop (gimple_phi_arg_def (phi,
    4555        32586 :                                                               e->dest_idx))
    4556        14759 :                            || integer_onep (gimple_phi_arg_def (phi,
    4557        14759 :                                                                 e->dest_idx))))
    4558        31581 :                 continue;
    4559              :             }
    4560              : 
    4561              :           return false;
    4562              :         }
    4563              :     }
    4564              :   return true;
    4565              : }
    4566              : 
    4567              : /* Return true if BB doesn't have side-effects that would disallow
    4568              :    range test optimization, all SSA_NAMEs set in the bb are consumed
    4569              :    in the bb and there are no PHIs.  */
    4570              : 
    4571              : bool
    4572      5499960 : no_side_effect_bb (basic_block bb)
    4573              : {
    4574      5499960 :   gimple_stmt_iterator gsi;
    4575      5499960 :   gimple *last;
    4576              : 
    4577      5499960 :   if (!gimple_seq_empty_p (phi_nodes (bb)))
    4578              :     return false;
    4579      4358216 :   last = last_nondebug_stmt (bb);
    4580     15460370 :   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
    4581              :     {
    4582     11102154 :       gimple *stmt = gsi_stmt (gsi);
    4583     11102154 :       tree lhs;
    4584     11102154 :       imm_use_iterator imm_iter;
    4585     11102154 :       use_operand_p use_p;
    4586              : 
    4587     11102154 :       if (is_gimple_debug (stmt))
    4588      4843688 :         continue;
    4589      6258466 :       if (gimple_has_side_effects (stmt))
    4590      4358216 :         return false;
    4591      5333052 :       if (stmt == last)
    4592              :         return true;
    4593      4236015 :       if (!is_gimple_assign (stmt))
    4594              :         return false;
    4595      3550937 :       lhs = gimple_assign_lhs (stmt);
    4596      3550937 :       if (TREE_CODE (lhs) != SSA_NAME)
    4597              :         return false;
    4598      3304990 :       if (gimple_assign_rhs_could_trap_p (stmt))
    4599              :         return false;
    4600      4689848 :       FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
    4601              :         {
    4602      2789598 :           gimple *use_stmt = USE_STMT (use_p);
    4603      2789598 :           if (is_gimple_debug (use_stmt))
    4604       215713 :             continue;
    4605      2573885 :           if (gimple_bb (use_stmt) != bb)
    4606       544488 :             return false;
    4607      2444738 :         }
    4608              :     }
    4609              :   return false;
    4610              : }
    4611              : 
    4612              : /* If VAR is set by CODE (BIT_{AND,IOR}_EXPR) which is reassociable,
    4613              :    return true and fill in *OPS recursively.  */
    4614              : 
    4615              : static bool
    4616        91166 : get_ops (tree var, enum tree_code code, vec<operand_entry *> *ops,
    4617              :          class loop *loop)
    4618              : {
    4619        91166 :   gimple *stmt = SSA_NAME_DEF_STMT (var);
    4620        91166 :   tree rhs[2];
    4621        91166 :   int i;
    4622              : 
    4623        91166 :   if (!is_reassociable_op (stmt, code, loop))
    4624              :     return false;
    4625              : 
    4626        22717 :   rhs[0] = gimple_assign_rhs1 (stmt);
    4627        22717 :   rhs[1] = gimple_assign_rhs2 (stmt);
    4628        22717 :   gimple_set_visited (stmt, true);
    4629        68151 :   for (i = 0; i < 2; i++)
    4630        45434 :     if (TREE_CODE (rhs[i]) == SSA_NAME
    4631        45434 :         && !get_ops (rhs[i], code, ops, loop)
    4632        84204 :         && has_single_use (rhs[i]))
    4633              :       {
    4634        37989 :         operand_entry *oe = operand_entry_pool.allocate ();
    4635              : 
    4636        37989 :         oe->op = rhs[i];
    4637        37989 :         oe->rank = code;
    4638        37989 :         oe->id = 0;
    4639        37989 :         oe->count = 1;
    4640        37989 :         oe->stmt_to_insert = NULL;
    4641        37989 :         ops->safe_push (oe);
    4642              :       }
    4643              :   return true;
    4644              : }
    4645              : 
    4646              : /* Find the ops that were added by get_ops starting from VAR, see if
    4647              :    they were changed during update_range_test and if yes, create new
    4648              :    stmts.  */
    4649              : 
    4650              : static tree
    4651        10798 : update_ops (tree var, enum tree_code code, const vec<operand_entry *> &ops,
    4652              :             unsigned int *pidx, class loop *loop)
    4653              : {
    4654        10798 :   gimple *stmt = SSA_NAME_DEF_STMT (var);
    4655        10798 :   tree rhs[4];
    4656        10798 :   int i;
    4657              : 
    4658        10798 :   if (!is_reassociable_op (stmt, code, loop))
    4659              :     return NULL;
    4660              : 
    4661         3603 :   rhs[0] = gimple_assign_rhs1 (stmt);
    4662         3603 :   rhs[1] = gimple_assign_rhs2 (stmt);
    4663         3603 :   rhs[2] = rhs[0];
    4664         3603 :   rhs[3] = rhs[1];
    4665        10809 :   for (i = 0; i < 2; i++)
    4666         7206 :     if (TREE_CODE (rhs[i]) == SSA_NAME)
    4667              :       {
    4668         7206 :         rhs[2 + i] = update_ops (rhs[i], code, ops, pidx, loop);
    4669         7206 :         if (rhs[2 + i] == NULL_TREE)
    4670              :           {
    4671         6797 :             if (has_single_use (rhs[i]))
    4672         6779 :               rhs[2 + i] = ops[(*pidx)++]->op;
    4673              :             else
    4674           18 :               rhs[2 + i] = rhs[i];
    4675              :           }
    4676              :       }
    4677         3603 :   if ((rhs[2] != rhs[0] || rhs[3] != rhs[1])
    4678         3354 :       && (rhs[2] != rhs[1] || rhs[3] != rhs[0]))
    4679              :     {
    4680         3354 :       gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
    4681         3354 :       var = make_ssa_name (TREE_TYPE (var));
    4682         3354 :       gassign *g = gimple_build_assign (var, gimple_assign_rhs_code (stmt),
    4683              :                                         rhs[2], rhs[3]);
    4684         3354 :       gimple_set_uid (g, gimple_uid (stmt));
    4685         3354 :       gimple_set_visited (g, true);
    4686         3354 :       gsi_insert_before (&gsi, g, GSI_SAME_STMT);
    4687         3354 :       gimple_stmt_iterator gsi2 = gsi_for_stmt (g);
    4688         3354 :       if (fold_stmt_inplace (&gsi2))
    4689         2188 :         update_stmt (g);
    4690              :     }
    4691              :   return var;
    4692              : }
    4693              : 
    4694              : /* Structure to track the initial value passed to get_ops and
    4695              :    the range in the ops vector for each basic block.  */
    4696              : 
    4697              : struct inter_bb_range_test_entry
    4698              : {
    4699              :   tree op;
    4700              :   unsigned int first_idx, last_idx;
    4701              : };
    4702              : 
    4703              : /* Inter-bb range test optimization.
    4704              : 
    4705              :    Returns TRUE if a gimple conditional is optimized to a true/false,
    4706              :    otherwise return FALSE.
    4707              : 
    4708              :    This indicates to the caller that it should run a CFG cleanup pass
    4709              :    once reassociation is completed.  */
    4710              : 
    4711              : static bool
    4712     19351457 : maybe_optimize_range_tests (gimple *stmt)
    4713              : {
    4714     19351457 :   basic_block first_bb = gimple_bb (stmt);
    4715     19351457 :   basic_block last_bb = first_bb;
    4716     19351457 :   basic_block other_bb = NULL;
    4717     19351457 :   basic_block bb;
    4718     19351457 :   edge_iterator ei;
    4719     19351457 :   edge e;
    4720     19351457 :   auto_vec<operand_entry *> ops;
    4721     19351457 :   auto_vec<inter_bb_range_test_entry> bbinfo;
    4722     19351457 :   bool any_changes = false;
    4723     19351457 :   bool cfg_cleanup_needed = false;
    4724              : 
    4725              :   /* Consider only basic blocks that end with GIMPLE_COND or
    4726              :      a cast statement satisfying final_range_test_p.  All
    4727              :      but the last bb in the first_bb .. last_bb range
    4728              :      should end with GIMPLE_COND.  */
    4729     19351457 :   if (gimple_code (stmt) == GIMPLE_COND)
    4730              :     {
    4731      8861181 :       if (EDGE_COUNT (first_bb->succs) != 2)
    4732              :         return cfg_cleanup_needed;
    4733              :     }
    4734     10490276 :   else if (final_range_test_p (stmt))
    4735        73787 :     other_bb = single_succ (first_bb);
    4736              :   else
    4737              :     return cfg_cleanup_needed;
    4738              : 
    4739      8934968 :   if (stmt_could_throw_p (cfun, stmt))
    4740              :     return cfg_cleanup_needed;
    4741              : 
    4742              :   /* As relative ordering of post-dominator sons isn't fixed,
    4743              :      maybe_optimize_range_tests can be called first on any
    4744              :      bb in the range we want to optimize.  So, start searching
    4745              :      backwards, if first_bb can be set to a predecessor.  */
    4746      8936981 :   while (single_pred_p (first_bb))
    4747              :     {
    4748      5859898 :       basic_block pred_bb = single_pred (first_bb);
    4749      5859898 :       if (!suitable_cond_bb (pred_bb, first_bb, &other_bb, NULL, true))
    4750              :         break;
    4751       630383 :       if (!no_side_effect_bb (first_bb))
    4752              :         break;
    4753              :       first_bb = pred_bb;
    4754              :     }
    4755              :   /* If first_bb is last_bb, other_bb hasn't been computed yet.
    4756              :      Before starting forward search in last_bb successors, find
    4757              :      out the other_bb.  */
    4758      8934800 :   if (first_bb == last_bb)
    4759              :     {
    4760      8932681 :       other_bb = NULL;
    4761              :       /* As non-GIMPLE_COND last stmt always terminates the range,
    4762              :          if forward search didn't discover anything, just give up.  */
    4763      8932681 :       if (gimple_code (stmt) != GIMPLE_COND)
    4764              :         return cfg_cleanup_needed;
    4765              :       /* Look at both successors.  Either it ends with a GIMPLE_COND
    4766              :          and satisfies suitable_cond_bb, or ends with a cast and
    4767              :          other_bb is that cast's successor.  */
    4768     24570262 :       FOR_EACH_EDGE (e, ei, first_bb->succs)
    4769     16999629 :         if (!(e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE))
    4770     16999629 :             || e->dest == first_bb)
    4771              :           return cfg_cleanup_needed;
    4772     25754748 :         else if (single_pred_p (e->dest))
    4773              :           {
    4774     10043636 :             stmt = last_nondebug_stmt (e->dest);
    4775     10043636 :             if (stmt
    4776      9862391 :                 && gimple_code (stmt) == GIMPLE_COND
    4777     14506495 :                 && EDGE_COUNT (e->dest->succs) == 2)
    4778              :               {
    4779      4462859 :                 if (suitable_cond_bb (first_bb, e->dest, &other_bb,
    4780              :                                       NULL, true))
    4781              :                   break;
    4782              :                 else
    4783      3716903 :                   other_bb = NULL;
    4784              :               }
    4785      5580777 :             else if (stmt
    4786      5399532 :                      && final_range_test_p (stmt)
    4787      5649659 :                      && find_edge (first_bb, single_succ (e->dest)))
    4788              :               {
    4789        38674 :                 other_bb = single_succ (e->dest);
    4790        38674 :                 if (other_bb == first_bb)
    4791            0 :                   other_bb = NULL;
    4792              :               }
    4793              :           }
    4794      8316589 :       if (other_bb == NULL)
    4795              :         return cfg_cleanup_needed;
    4796              :     }
    4797              :   /* Now do the forward search, moving last_bb to successor bbs
    4798              :      that aren't other_bb.  */
    4799      1001427 :   while (EDGE_COUNT (last_bb->succs) == 2)
    4800              :     {
    4801      1615250 :       FOR_EACH_EDGE (e, ei, last_bb->succs)
    4802      1615250 :         if (e->dest != other_bb)
    4803              :           break;
    4804       995869 :       if (e == NULL)
    4805              :         break;
    4806       995869 :       if (!single_pred_p (e->dest))
    4807              :         break;
    4808       959271 :       if (!suitable_cond_bb (e->dest, last_bb, &other_bb, NULL, false))
    4809              :         break;
    4810       845730 :       if (!no_side_effect_bb (e->dest))
    4811              :         break;
    4812       214678 :       last_bb = e->dest;
    4813              :     }
    4814       786749 :   if (first_bb == last_bb)
    4815              :     return cfg_cleanup_needed;
    4816              :   /* Here basic blocks first_bb through last_bb's predecessor
    4817              :      end with GIMPLE_COND, all of them have one of the edges to
    4818              :      other_bb and another to another block in the range,
    4819              :      all blocks except first_bb don't have side-effects and
    4820              :      last_bb ends with either GIMPLE_COND, or cast satisfying
    4821              :      final_range_test_p.  */
    4822       216859 :   for (bb = last_bb; ; bb = single_pred (bb))
    4823              :     {
    4824       370598 :       enum tree_code code;
    4825       370598 :       tree lhs, rhs;
    4826       370598 :       inter_bb_range_test_entry bb_ent;
    4827              : 
    4828       370598 :       bb_ent.op = NULL_TREE;
    4829       370598 :       bb_ent.first_idx = ops.length ();
    4830       370598 :       bb_ent.last_idx = bb_ent.first_idx;
    4831       370598 :       e = find_edge (bb, other_bb);
    4832       370598 :       stmt = last_nondebug_stmt (bb);
    4833       370598 :       gimple_set_visited (stmt, true);
    4834       370598 :       if (gimple_code (stmt) != GIMPLE_COND)
    4835              :         {
    4836         5558 :           use_operand_p use_p;
    4837         5558 :           gimple *phi;
    4838         5558 :           edge e2;
    4839         5558 :           unsigned int d;
    4840              : 
    4841         5558 :           lhs = gimple_assign_lhs (stmt);
    4842         5558 :           rhs = gimple_assign_rhs1 (stmt);
    4843         5558 :           gcc_assert (bb == last_bb);
    4844              : 
    4845              :           /* stmt is
    4846              :              _123 = (int) _234;
    4847              :              OR
    4848              :              _234 = a_2(D) == 2;
    4849              : 
    4850              :              followed by:
    4851              :              <bb M>:
    4852              :              # _345 = PHI <_123(N), 1(...), 1(...)>
    4853              : 
    4854              :              or 0 instead of 1.  If it is 0, the _234
    4855              :              range test is anded together with all the
    4856              :              other range tests, if it is 1, it is ored with
    4857              :              them.  */
    4858         5558 :           single_imm_use (lhs, &use_p, &phi);
    4859         5558 :           gcc_assert (gimple_code (phi) == GIMPLE_PHI);
    4860         5558 :           e2 = find_edge (first_bb, other_bb);
    4861         5558 :           d = e2->dest_idx;
    4862         5558 :           gcc_assert (gimple_phi_arg_def (phi, e->dest_idx) == lhs);
    4863         5558 :           if (integer_zerop (gimple_phi_arg_def (phi, d)))
    4864              :             code = BIT_AND_EXPR;
    4865              :           else
    4866              :             {
    4867         2893 :               gcc_checking_assert (integer_onep (gimple_phi_arg_def (phi, d)));
    4868              :               code = BIT_IOR_EXPR;
    4869              :             }
    4870              : 
    4871              :           /* If _234 SSA_NAME_DEF_STMT is
    4872              :              _234 = _567 | _789;
    4873              :              (or &, corresponding to 1/0 in the phi arguments,
    4874              :              push into ops the individual range test arguments
    4875              :              of the bitwise or resp. and, recursively.  */
    4876         5558 :           if (TREE_CODE (rhs) == SSA_NAME
    4877         5558 :               && (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
    4878              :                   != tcc_comparison)
    4879         3027 :               && !get_ops (rhs, code, &ops,
    4880              :                            loop_containing_stmt (stmt))
    4881         8406 :               && has_single_use (rhs))
    4882              :             {
    4883              :               /* Otherwise, push the _234 range test itself.  */
    4884         2828 :               operand_entry *oe = operand_entry_pool.allocate ();
    4885              : 
    4886         2828 :               oe->op = rhs;
    4887         2828 :               oe->rank = code;
    4888         2828 :               oe->id = 0;
    4889         2828 :               oe->count = 1;
    4890         2828 :               oe->stmt_to_insert = NULL;
    4891         2828 :               ops.safe_push (oe);
    4892         2828 :               bb_ent.last_idx++;
    4893         2828 :               bb_ent.op = rhs;
    4894              :             }
    4895         2730 :           else if (is_gimple_assign (stmt)
    4896         2730 :                    && (TREE_CODE_CLASS (gimple_assign_rhs_code (stmt))
    4897              :                        == tcc_comparison)
    4898         2531 :                    && !get_ops (lhs, code, &ops,
    4899              :                                 loop_containing_stmt (stmt))
    4900         5261 :                    && has_single_use (lhs))
    4901              :             {
    4902         2531 :               operand_entry *oe = operand_entry_pool.allocate ();
    4903         2531 :               oe->op = lhs;
    4904         2531 :               oe->rank = code;
    4905         2531 :               oe->id = 0;
    4906         2531 :               oe->count = 1;
    4907         2531 :               ops.safe_push (oe);
    4908         2531 :               bb_ent.last_idx++;
    4909         2531 :               bb_ent.op = lhs;
    4910              :             }
    4911              :           else
    4912              :             {
    4913          199 :               bb_ent.last_idx = ops.length ();
    4914          199 :               bb_ent.op = rhs;
    4915              :             }
    4916         5558 :           bbinfo.safe_push (bb_ent);
    4917        16873 :           for (unsigned int i = bb_ent.first_idx; i < bb_ent.last_idx; ++i)
    4918         5757 :             ops[i]->id = bb->index;
    4919         5558 :           continue;
    4920         5558 :         }
    4921       365040 :       else if (bb == last_bb)
    4922              :         {
    4923              :           /* For last_bb, handle also:
    4924              :              if (x_3(D) == 3)
    4925              :                goto <bb 6>; [34.00%]
    4926              :              else
    4927              :                goto <bb 7>; [66.00%]
    4928              : 
    4929              :              <bb 6> [local count: 79512730]:
    4930              : 
    4931              :              <bb 7> [local count: 1073741824]:
    4932              :              # prephitmp_7 = PHI <1(3), 1(4), 0(5), 1(2), 1(6)>
    4933              :              where bb 7 is OTHER_BB, but the PHI values from the
    4934              :              earlier bbs match the path through the empty bb
    4935              :              in between.  */
    4936       148181 :           bool test_swapped_p = false;
    4937       148181 :           bool ok = suitable_cond_bb (single_pred (last_bb), last_bb,
    4938              :                                       &other_bb, &test_swapped_p, true);
    4939       148181 :           gcc_assert (ok);
    4940       148181 :           if (test_swapped_p)
    4941          202 :             e = EDGE_SUCC (bb, e == EDGE_SUCC (bb, 0) ? 1 : 0);
    4942              :         }
    4943              :       /* Otherwise stmt is GIMPLE_COND.  */
    4944       365040 :       code = gimple_cond_code (stmt);
    4945       365040 :       lhs = gimple_cond_lhs (stmt);
    4946       365040 :       rhs = gimple_cond_rhs (stmt);
    4947       365040 :       if (TREE_CODE (lhs) == SSA_NAME
    4948       364974 :           && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
    4949       669274 :           && ((code != EQ_EXPR && code != NE_EXPR)
    4950       231310 :               || rhs != boolean_false_node
    4951              :                  /* Either push into ops the individual bitwise
    4952              :                     or resp. and operands, depending on which
    4953              :                     edge is other_bb.  */
    4954        40174 :               || !get_ops (lhs, (((e->flags & EDGE_TRUE_VALUE) == 0)
    4955        40174 :                                  ^ (code == EQ_EXPR))
    4956              :                                 ? BIT_AND_EXPR : BIT_IOR_EXPR, &ops,
    4957              :                            loop_containing_stmt (stmt))))
    4958              :         {
    4959              :           /* Or push the GIMPLE_COND stmt itself.  */
    4960       288360 :           operand_entry *oe = operand_entry_pool.allocate ();
    4961              : 
    4962       288360 :           oe->op = NULL;
    4963       576720 :           oe->rank = (e->flags & EDGE_TRUE_VALUE)
    4964       288360 :                      ? BIT_IOR_EXPR : BIT_AND_EXPR;
    4965              :           /* oe->op = NULL signs that there is no SSA_NAME
    4966              :              for the range test, and oe->id instead is the
    4967              :              basic block number, at which's end the GIMPLE_COND
    4968              :              is.  */
    4969       288360 :           oe->id = bb->index;
    4970       288360 :           oe->count = 1;
    4971       288360 :           oe->stmt_to_insert = NULL;
    4972       288360 :           ops.safe_push (oe);
    4973       288360 :           bb_ent.op = NULL;
    4974       288360 :           bb_ent.last_idx++;
    4975              :         }
    4976        76680 :       else if (ops.length () > bb_ent.first_idx)
    4977              :         {
    4978        15802 :           bb_ent.op = lhs;
    4979        15802 :           bb_ent.last_idx = ops.length ();
    4980              :         }
    4981       365040 :       bbinfo.safe_push (bb_ent);
    4982      1056031 :       for (unsigned int i = bb_ent.first_idx; i < bb_ent.last_idx; ++i)
    4983       325951 :         ops[i]->id = bb->index;
    4984       365040 :       if (bb == first_bb)
    4985              :         break;
    4986       216859 :     }
    4987     19470964 :   if (ops.length () > 1)
    4988       119507 :     any_changes = optimize_range_tests (ERROR_MARK, &ops, first_bb);
    4989       119507 :   if (any_changes)
    4990              :     {
    4991              :       unsigned int idx, max_idx = 0;
    4992              :       /* update_ops relies on has_single_use predicates returning the
    4993              :          same values as it did during get_ops earlier.  Additionally it
    4994              :          never removes statements, only adds new ones and it should walk
    4995              :          from the single imm use and check the predicate already before
    4996              :          making those changes.
    4997              :          On the other side, the handling of GIMPLE_COND directly can turn
    4998              :          previously multiply used SSA_NAMEs into single use SSA_NAMEs, so
    4999              :          it needs to be done in a separate loop afterwards.  */
    5000        20179 :       for (bb = last_bb, idx = 0; ; bb = single_pred (bb), idx++)
    5001              :         {
    5002        32628 :           if (bbinfo[idx].first_idx < bbinfo[idx].last_idx
    5003        32628 :               && bbinfo[idx].op != NULL_TREE)
    5004              :             {
    5005         3592 :               tree new_op;
    5006              : 
    5007         3592 :               max_idx = idx;
    5008         3592 :               stmt = last_nondebug_stmt (bb);
    5009         7184 :               new_op = update_ops (bbinfo[idx].op,
    5010              :                                    (enum tree_code)
    5011         3592 :                                    ops[bbinfo[idx].first_idx]->rank,
    5012         3592 :                                    ops, &bbinfo[idx].first_idx,
    5013              :                                    loop_containing_stmt (stmt));
    5014         3592 :               if (new_op == NULL_TREE)
    5015              :                 {
    5016          398 :                   gcc_assert (bb == last_bb);
    5017          398 :                   new_op = ops[bbinfo[idx].first_idx++]->op;
    5018              :                 }
    5019         3592 :               if (bbinfo[idx].op != new_op)
    5020              :                 {
    5021         3336 :                   imm_use_iterator iter;
    5022         3336 :                   use_operand_p use_p;
    5023         3336 :                   gimple *use_stmt, *cast_or_tcc_cmp_stmt = NULL;
    5024              : 
    5025         6682 :                   FOR_EACH_IMM_USE_STMT (use_stmt, iter, bbinfo[idx].op)
    5026         3346 :                     if (is_gimple_debug (use_stmt))
    5027           10 :                       continue;
    5028         3336 :                     else if (gimple_code (use_stmt) == GIMPLE_COND
    5029         3336 :                              || gimple_code (use_stmt) == GIMPLE_PHI)
    5030         6068 :                       FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
    5031         3034 :                         SET_USE (use_p, new_op);
    5032          302 :                     else if ((is_gimple_assign (use_stmt)
    5033          302 :                               && (TREE_CODE_CLASS
    5034              :                                   (gimple_assign_rhs_code (use_stmt))
    5035              :                                   == tcc_comparison)))
    5036              :                       cast_or_tcc_cmp_stmt = use_stmt;
    5037          302 :                     else if (gimple_assign_cast_p (use_stmt))
    5038              :                       cast_or_tcc_cmp_stmt = use_stmt;
    5039              :                     else
    5040            0 :                       gcc_unreachable ();
    5041              : 
    5042         3336 :                   if (cast_or_tcc_cmp_stmt)
    5043              :                     {
    5044          302 :                       gcc_assert (bb == last_bb);
    5045          302 :                       tree lhs = gimple_assign_lhs (cast_or_tcc_cmp_stmt);
    5046          302 :                       tree new_lhs = make_ssa_name (TREE_TYPE (lhs));
    5047          302 :                       enum tree_code rhs_code
    5048          302 :                         = gimple_assign_cast_p (cast_or_tcc_cmp_stmt)
    5049          302 :                         ? gimple_assign_rhs_code (cast_or_tcc_cmp_stmt)
    5050              :                         : CONVERT_EXPR;
    5051          302 :                       gassign *g;
    5052          302 :                       if (is_gimple_min_invariant (new_op))
    5053              :                         {
    5054           79 :                           new_op = fold_convert (TREE_TYPE (lhs), new_op);
    5055           79 :                           g = gimple_build_assign (new_lhs, new_op);
    5056              :                         }
    5057              :                       else
    5058          223 :                         g = gimple_build_assign (new_lhs, rhs_code, new_op);
    5059          302 :                       gimple_stmt_iterator gsi
    5060          302 :                         = gsi_for_stmt (cast_or_tcc_cmp_stmt);
    5061          302 :                       gimple_set_uid (g, gimple_uid (cast_or_tcc_cmp_stmt));
    5062          302 :                       gimple_set_visited (g, true);
    5063          302 :                       gsi_insert_before (&gsi, g, GSI_SAME_STMT);
    5064          604 :                       FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
    5065          302 :                         if (is_gimple_debug (use_stmt))
    5066            0 :                           continue;
    5067          302 :                         else if (gimple_code (use_stmt) == GIMPLE_COND
    5068          302 :                                  || gimple_code (use_stmt) == GIMPLE_PHI)
    5069          604 :                           FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
    5070          302 :                             SET_USE (use_p, new_lhs);
    5071              :                         else
    5072          302 :                           gcc_unreachable ();
    5073              :                     }
    5074              :                 }
    5075              :             }
    5076        32628 :           if (bb == first_bb)
    5077              :             break;
    5078        20179 :         }
    5079        20179 :       for (bb = last_bb, idx = 0; ; bb = single_pred (bb), idx++)
    5080              :         {
    5081        32628 :           if (bbinfo[idx].first_idx < bbinfo[idx].last_idx
    5082        28576 :               && bbinfo[idx].op == NULL_TREE
    5083        61204 :               && ops[bbinfo[idx].first_idx]->op != NULL_TREE)
    5084              :             {
    5085        49046 :               gcond *cond_stmt = as_a <gcond *> (*gsi_last_bb (bb));
    5086              : 
    5087        24523 :               if (idx > max_idx)
    5088              :                 max_idx = idx;
    5089              : 
    5090              :               /* If we collapse the conditional to a true/false
    5091              :                  condition, then bubble that knowledge up to our caller.  */
    5092        24523 :               if (integer_zerop (ops[bbinfo[idx].first_idx]->op))
    5093              :                 {
    5094        10806 :                   gimple_cond_make_false (cond_stmt);
    5095        10806 :                   cfg_cleanup_needed = true;
    5096              :                 }
    5097        13717 :               else if (integer_onep (ops[bbinfo[idx].first_idx]->op))
    5098              :                 {
    5099         3043 :                   gimple_cond_make_true (cond_stmt);
    5100         3043 :                   cfg_cleanup_needed = true;
    5101              :                 }
    5102              :               else
    5103              :                 {
    5104        10674 :                   gimple_cond_set_code (cond_stmt, NE_EXPR);
    5105        10674 :                   gimple_cond_set_lhs (cond_stmt,
    5106        10674 :                                        ops[bbinfo[idx].first_idx]->op);
    5107        10674 :                   gimple_cond_set_rhs (cond_stmt, boolean_false_node);
    5108              :                 }
    5109        24523 :               update_stmt (cond_stmt);
    5110              :             }
    5111        32628 :           if (bb == first_bb)
    5112              :             break;
    5113        20179 :         }
    5114              : 
    5115              :       /* The above changes could result in basic blocks after the first
    5116              :          modified one, up to and including last_bb, to be executed even if
    5117              :          they would not be in the original program.  If the value ranges of
    5118              :          assignment lhs' in those bbs were dependent on the conditions
    5119              :          guarding those basic blocks which now can change, the VRs might
    5120              :          be incorrect.  As no_side_effect_bb should ensure those SSA_NAMEs
    5121              :          are only used within the same bb, it should be not a big deal if
    5122              :          we just reset all the VRs in those bbs.  See PR68671.  */
    5123        31172 :       for (bb = last_bb, idx = 0; idx < max_idx; bb = single_pred (bb), idx++)
    5124        18723 :         reset_flow_sensitive_info_in_bb (bb);
    5125              :     }
    5126              :   return cfg_cleanup_needed;
    5127     19351457 : }
    5128              : 
    5129              : /* Remove def stmt of VAR if VAR has zero uses and recurse
    5130              :    on rhs1 operand if so.  */
    5131              : 
    5132              : static void
    5133        72681 : remove_visited_stmt_chain (tree var)
    5134              : {
    5135        97796 :   gimple_stmt_iterator gsi;
    5136              : 
    5137       122911 :   while (1)
    5138              :     {
    5139        97796 :       if (TREE_CODE (var) != SSA_NAME || !has_zero_uses (var))
    5140              :         return;
    5141        36715 :       auto stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (var));
    5142        36696 :       if (stmt && gimple_visited_p (stmt))
    5143              :         {
    5144        25115 :           var = gimple_assign_rhs1 (stmt);
    5145        25115 :           gsi = gsi_for_stmt (stmt);
    5146        25115 :           reassoc_remove_stmt (&gsi);
    5147        25115 :           release_defs (stmt);
    5148              :         }
    5149              :       else
    5150              :         return;
    5151        25115 :     }
    5152              : }
    5153              : 
    5154              : /* This function checks three consecutive operands in
    5155              :    passed operands vector OPS starting from OPINDEX and
    5156              :    swaps two operands if it is profitable for binary operation
    5157              :    consuming OPINDEX + 1 and OPINDEX + 2 operands.
    5158              : 
    5159              :    We pair ops with the same rank if possible.  */
    5160              : 
    5161              : static void
    5162       131941 : swap_ops_for_binary_stmt (const vec<operand_entry *> &ops,
    5163              :                           unsigned int opindex)
    5164              : {
    5165       131941 :   operand_entry *oe1, *oe2, *oe3;
    5166              : 
    5167       131941 :   oe1 = ops[opindex];
    5168       131941 :   oe2 = ops[opindex + 1];
    5169       131941 :   oe3 = ops[opindex + 2];
    5170              : 
    5171       131941 :   if (oe1->rank == oe2->rank && oe2->rank != oe3->rank)
    5172        17324 :     std::swap (*oe1, *oe3);
    5173       114617 :   else if (oe1->rank == oe3->rank && oe2->rank != oe3->rank)
    5174          363 :     std::swap (*oe1, *oe2);
    5175       131941 : }
    5176              : 
    5177              : /* Return true if OP is set by a comparison in BB, which a conditional
    5178              :    compare can compute into the condition flags.  */
    5179              : 
    5180              : static bool
    5181            2 : ccmp_comparison_p (tree op, basic_block bb)
    5182              : {
    5183            2 :   if (TREE_CODE (op) != SSA_NAME)
    5184              :     return false;
    5185              : 
    5186            2 :   gimple *def = SSA_NAME_DEF_STMT (op);
    5187            2 :   if (!is_gimple_assign (def)
    5188            2 :       || gimple_bb (def) != bb
    5189            4 :       || TREE_CODE_CLASS (gimple_assign_rhs_code (def)) != tcc_comparison)
    5190              :     return false;
    5191              : 
    5192              :   /* A conditional compare sets the flags from one scalar comparison.  */
    5193            2 :   machine_mode mode = TYPE_MODE (TREE_TYPE (gimple_assign_rhs1 (def)));
    5194            2 :   return SCALAR_INT_MODE_P (mode) || SCALAR_FLOAT_MODE_P (mode);
    5195              : }
    5196              : 
    5197              : /* Return how strongly OP should start a conditional compare sequence.
    5198              :    FOLDABLE is true if OP can be folded into the flags.  */
    5199              : 
    5200              : static ccmp_first_kind
    5201            2 : ccmp_first_preference (tree op, bool foldable)
    5202              : {
    5203            2 :   if (!foldable)
    5204              :     return CCMP_FIRST_NONE;
    5205              : 
    5206            2 :   gimple *def = SSA_NAME_DEF_STMT (op);
    5207            2 :   gcc_checking_assert (is_gimple_assign (def));
    5208              : 
    5209            2 :   tree op0 = gimple_assign_rhs1 (def);
    5210            2 :   tree op1 = gimple_assign_rhs2 (def);
    5211            2 :   ccmp_first_kind kind = targetm.ccmp_first_preference
    5212            2 :     (TYPE_MODE (TREE_TYPE (op0)), gimple_assign_rhs_code (def), op0, op1);
    5213            2 :   if (kind == CCMP_FIRST_UNSUPPORTED || !gimple_could_trap_p (def))
    5214            2 :     return kind;
    5215              :   return CCMP_FIRST_REQUIRED;
    5216              : }
    5217              : 
    5218              : /* Return true if all operands in OPS form one conditional compare sequence
    5219              :    for CODE in BB.  Put the operand that must start the sequence last in OPS,
    5220              :    where rewrite_expr_tree builds the innermost pair.  Every operand must be a
    5221              :    comparison, and at least one must be foldable into the flags.  */
    5222              : 
    5223              : static bool
    5224       184254 : prepare_ccmp_chain (vec<operand_entry *> &ops, tree_code code, basic_block bb)
    5225              : {
    5226       184254 :   if (!targetm.have_ccmp ()
    5227       184254 :       || (code != BIT_AND_EXPR && code != BIT_IOR_EXPR))
    5228              :     return false;
    5229              : 
    5230              :   bool seen_foldable = false;
    5231              :   int head = -1;
    5232              :   ccmp_first_kind head_kind = CCMP_FIRST_NONE;
    5233              : 
    5234            2 :   for (unsigned int i = 0; i < ops.length (); ++i)
    5235              :     {
    5236            2 :       const operand_entry *oe = ops[i];
    5237            2 :       if (!ccmp_comparison_p (oe->op, bb))
    5238              :         return false;
    5239              : 
    5240            2 :       bool foldable = has_single_use (oe->op);
    5241              : 
    5242            2 :       ccmp_first_kind kind
    5243            2 :         = ccmp_first_preference (oe->op, foldable);
    5244            2 :       if (kind == CCMP_FIRST_UNSUPPORTED)
    5245              :         return false;
    5246            0 :       if (kind == CCMP_FIRST_REQUIRED && head_kind == CCMP_FIRST_REQUIRED)
    5247              :         return false;
    5248            0 :       if (kind > head_kind)
    5249              :         {
    5250            0 :           head = i;
    5251            0 :           head_kind = kind;
    5252              :         }
    5253              : 
    5254              :       /* Comparison leaves can have uses outside this chain.  */
    5255            0 :       seen_foldable |= foldable;
    5256              :     }
    5257              : 
    5258            0 :   if (head >= 0)
    5259            0 :     std::swap (*ops[head], *ops.last ());
    5260              :   return seen_foldable;
    5261              : }
    5262              : 
    5263              : /* If definition of RHS1 or RHS2 dominates STMT, return the later of those
    5264              :    two definitions, otherwise return STMT.  Sets INSERT_BEFORE to indicate
    5265              :    whether RHS1 op RHS2 can be inserted before or needs to be inserted
    5266              :    after the returned stmt.  */
    5267              : 
    5268              : static inline gimple *
    5269       381474 : find_insert_point (gimple *stmt, tree rhs1, tree rhs2, bool &insert_before)
    5270              : {
    5271       381474 :   insert_before = true;
    5272       381474 :   if (TREE_CODE (rhs1) == SSA_NAME
    5273       381474 :       && reassoc_stmt_dominates_stmt_p (stmt, SSA_NAME_DEF_STMT (rhs1)))
    5274              :     {
    5275        11386 :       stmt = SSA_NAME_DEF_STMT (rhs1);
    5276        11386 :       insert_before = false;
    5277              :     }
    5278       381474 :   if (TREE_CODE (rhs2) == SSA_NAME
    5279       381474 :       && reassoc_stmt_dominates_stmt_p (stmt, SSA_NAME_DEF_STMT (rhs2)))
    5280              :     {
    5281        20271 :       stmt = SSA_NAME_DEF_STMT (rhs2);
    5282        20271 :       insert_before = false;
    5283              :     }
    5284       381474 :   return stmt;
    5285              : }
    5286              : 
    5287              : /* If the stmt that defines operand has to be inserted, insert it
    5288              :    before the use.  */
    5289              : static void
    5290           85 : insert_stmt_before_use (gimple *stmt, gimple *stmt_to_insert)
    5291              : {
    5292           85 :   gcc_assert (is_gimple_assign (stmt_to_insert));
    5293           85 :   tree rhs1 = gimple_assign_rhs1 (stmt_to_insert);
    5294           85 :   tree rhs2 = gimple_assign_rhs2 (stmt_to_insert);
    5295           85 :   bool insert_before;
    5296           85 :   gimple *insert_point = find_insert_point (stmt, rhs1, rhs2, insert_before);
    5297           85 :   gimple_stmt_iterator gsi = gsi_for_stmt (insert_point);
    5298           85 :   gimple_set_uid (stmt_to_insert, gimple_uid (insert_point));
    5299              : 
    5300              :   /* If the insert point is not stmt, then insert_point would be
    5301              :      the point where operand rhs1 or rhs2 is defined. In this case,
    5302              :      stmt_to_insert has to be inserted afterwards. This would
    5303              :      only happen when the stmt insertion point is flexible. */
    5304           85 :   if (insert_before)
    5305           85 :     gsi_insert_before (&gsi, stmt_to_insert, GSI_NEW_STMT);
    5306              :   else
    5307            0 :     insert_stmt_after (stmt_to_insert, insert_point);
    5308           85 : }
    5309              : 
    5310              : 
    5311              : /* Recursively rewrite our linearized statements so that the operators
    5312              :    match those in OPS[OPINDEX], putting the computation in rank
    5313              :    order.  Return new lhs.
    5314              :    CHANGED is true if we shouldn't reuse the lhs SSA_NAME both in
    5315              :    the current stmt and during recursive invocations.
    5316              :    NEXT_CHANGED is true if we shouldn't reuse the lhs SSA_NAME in
    5317              :    recursive invocations.  */
    5318              : 
    5319              : static tree
    5320      5027335 : rewrite_expr_tree (gimple *stmt, enum tree_code rhs_code, unsigned int opindex,
    5321              :                    const vec<operand_entry *> &ops, bool changed,
    5322              :                    bool next_changed)
    5323              : {
    5324      5027335 :   tree rhs1 = gimple_assign_rhs1 (stmt);
    5325      5027335 :   tree rhs2 = gimple_assign_rhs2 (stmt);
    5326      5027335 :   tree lhs = gimple_assign_lhs (stmt);
    5327      5027335 :   operand_entry *oe;
    5328              : 
    5329              :   /* The final recursion case for this function is that you have
    5330              :      exactly two operations left.
    5331              :      If we had exactly one op in the entire list to start with, we
    5332              :      would have never called this function, and the tail recursion
    5333              :      rewrites them one at a time.  */
    5334     10054670 :   if (opindex + 2 == ops.length ())
    5335              :     {
    5336      4794863 :       operand_entry *oe1, *oe2;
    5337              : 
    5338      4794863 :       oe1 = ops[opindex];
    5339      4794863 :       oe2 = ops[opindex + 1];
    5340      4794863 :       if (commutative_tree_code (rhs_code)
    5341      4794863 :           && tree_swap_operands_p (oe1->op, oe2->op))
    5342              :         std::swap (oe1, oe2);
    5343              : 
    5344      4794863 :       if (rhs1 != oe1->op || rhs2 != oe2->op)
    5345              :         {
    5346       249947 :           gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
    5347       249947 :           unsigned int uid = gimple_uid (stmt);
    5348              : 
    5349       249947 :           if (dump_file && (dump_flags & TDF_DETAILS))
    5350              :             {
    5351           31 :               fprintf (dump_file, "Transforming ");
    5352           31 :               print_gimple_stmt (dump_file, stmt, 0);
    5353              :             }
    5354              : 
    5355              :           /* If the stmt that defines operand has to be inserted, insert it
    5356              :              before the use.  */
    5357       249947 :           if (oe1->stmt_to_insert)
    5358           34 :             insert_stmt_before_use (stmt, oe1->stmt_to_insert);
    5359       249947 :           if (oe2->stmt_to_insert)
    5360           51 :             insert_stmt_before_use (stmt, oe2->stmt_to_insert);
    5361              :           /* Even when changed is false, reassociation could have e.g. removed
    5362              :              some redundant operations, so unless we are just swapping the
    5363              :              arguments or unless there is no change at all (then we just
    5364              :              return lhs), force creation of a new SSA_NAME.  */
    5365       249947 :           if (changed || ((rhs1 != oe2->op || rhs2 != oe1->op) && opindex))
    5366              :             {
    5367       111383 :               bool insert_before;
    5368       111383 :               gimple *insert_point
    5369       111383 :                 = find_insert_point (stmt, oe1->op, oe2->op, insert_before);
    5370       111383 :               lhs = make_ssa_name (TREE_TYPE (lhs));
    5371       111383 :               stmt
    5372       111383 :                 = gimple_build_assign (lhs, rhs_code,
    5373              :                                        oe1->op, oe2->op);
    5374       111383 :               gimple_set_uid (stmt, uid);
    5375       111383 :               gimple_set_visited (stmt, true);
    5376       111383 :               if (insert_before)
    5377        88620 :                 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
    5378              :               else
    5379        22763 :                 insert_stmt_after (stmt, insert_point);
    5380       111383 :             }
    5381              :           else
    5382              :             {
    5383       138564 :               bool insert_before;
    5384       138564 :               gcc_checking_assert (find_insert_point (stmt, oe1->op, oe2->op,
    5385              :                                                       insert_before)
    5386              :                                    == stmt);
    5387       138564 :               gimple_assign_set_rhs1 (stmt, oe1->op);
    5388       138564 :               gimple_assign_set_rhs2 (stmt, oe2->op);
    5389       138564 :               update_stmt (stmt);
    5390              :             }
    5391              : 
    5392       249947 :           if (rhs1 != oe1->op && rhs1 != oe2->op)
    5393        55940 :             remove_visited_stmt_chain (rhs1);
    5394              : 
    5395       249947 :           if (dump_file && (dump_flags & TDF_DETAILS))
    5396              :             {
    5397           31 :               fprintf (dump_file, " into ");
    5398           31 :               print_gimple_stmt (dump_file, stmt, 0);
    5399              :             }
    5400              :         }
    5401              :       return lhs;
    5402              :     }
    5403              : 
    5404              :   /* If we hit here, we should have 3 or more ops left.  */
    5405       232472 :   gcc_assert (opindex + 2 < ops.length ());
    5406              : 
    5407              :   /* Rewrite the next operator.  */
    5408       232472 :   oe = ops[opindex];
    5409              : 
    5410              :   /* If the stmt that defines operand has to be inserted, insert it
    5411              :      before the use.  */
    5412       232472 :   if (oe->stmt_to_insert)
    5413            0 :     insert_stmt_before_use (stmt, oe->stmt_to_insert);
    5414              : 
    5415              :   /* Recurse on the LHS of the binary operator, which is guaranteed to
    5416              :      be the non-leaf side.  */
    5417       232472 :   tree new_rhs1
    5418       445433 :     = rewrite_expr_tree (SSA_NAME_DEF_STMT (rhs1), rhs_code, opindex + 1, ops,
    5419       212961 :                          changed || oe->op != rhs2 || next_changed,
    5420              :                          false);
    5421              : 
    5422       232472 :   if (oe->op != rhs2 || new_rhs1 != rhs1)
    5423              :     {
    5424       131442 :       if (dump_file && (dump_flags & TDF_DETAILS))
    5425              :         {
    5426            6 :           fprintf (dump_file, "Transforming ");
    5427            6 :           print_gimple_stmt (dump_file, stmt, 0);
    5428              :         }
    5429              : 
    5430              :       /* If changed is false, this is either opindex == 0
    5431              :          or all outer rhs2's were equal to corresponding oe->op,
    5432              :          and powi_result is NULL.
    5433              :          That means lhs is equivalent before and after reassociation.
    5434              :          Otherwise ensure the old lhs SSA_NAME is not reused and
    5435              :          create a new stmt as well, so that any debug stmts will be
    5436              :          properly adjusted.  */
    5437       131442 :       if (changed)
    5438              :         {
    5439        19276 :           gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
    5440        19276 :           unsigned int uid = gimple_uid (stmt);
    5441        19276 :           bool insert_before;
    5442        19276 :           gimple *insert_point = find_insert_point (stmt, new_rhs1, oe->op,
    5443              :                                                     insert_before);
    5444              : 
    5445        19276 :           lhs = make_ssa_name (TREE_TYPE (lhs));
    5446        19276 :           stmt = gimple_build_assign (lhs, rhs_code,
    5447              :                                       new_rhs1, oe->op);
    5448        19276 :           gimple_set_uid (stmt, uid);
    5449        19276 :           gimple_set_visited (stmt, true);
    5450        19276 :           if (insert_before)
    5451        11508 :             gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
    5452              :           else
    5453         7768 :             insert_stmt_after (stmt, insert_point);
    5454              :         }
    5455              :       else
    5456              :         {
    5457       112166 :           bool insert_before;
    5458       112166 :           gcc_checking_assert (find_insert_point (stmt, new_rhs1, oe->op,
    5459              :                                                   insert_before)
    5460              :                                == stmt);
    5461       112166 :           gimple_assign_set_rhs1 (stmt, new_rhs1);
    5462       112166 :           gimple_assign_set_rhs2 (stmt, oe->op);
    5463       112166 :           update_stmt (stmt);
    5464              :         }
    5465              : 
    5466       131442 :       if (dump_file && (dump_flags & TDF_DETAILS))
    5467              :         {
    5468            6 :           fprintf (dump_file, " into ");
    5469            6 :           print_gimple_stmt (dump_file, stmt, 0);
    5470              :         }
    5471              :     }
    5472              :   return lhs;
    5473              : }
    5474              : 
    5475              : /* Find out how many cycles we need to compute statements chain.
    5476              :    OPS_NUM holds number os statements in a chain.  CPU_WIDTH is a
    5477              :    maximum number of independent statements we may execute per cycle.  */
    5478              : 
    5479              : static int
    5480        19061 : get_required_cycles (int ops_num, int cpu_width)
    5481              : {
    5482        19061 :   int res;
    5483        19061 :   int elog;
    5484        19061 :   unsigned int rest;
    5485              : 
    5486              :   /* While we have more than 2 * cpu_width operands
    5487              :      we may reduce number of operands by cpu_width
    5488              :      per cycle.  */
    5489        19061 :   res = ops_num / (2 * cpu_width);
    5490              : 
    5491              :   /* Remained operands count may be reduced twice per cycle
    5492              :      until we have only one operand.  */
    5493        19061 :   rest = (unsigned)(ops_num - res * cpu_width);
    5494        19061 :   elog = exact_log2 (rest);
    5495         9038 :   if (elog >= 0)
    5496         9038 :     res += elog;
    5497              :   else
    5498        20046 :     res += floor_log2 (rest) + 1;
    5499              : 
    5500        19061 :   return res;
    5501              : }
    5502              : 
    5503              : /* Given that the target fully pipelines FMA instructions, return the latency
    5504              :    of MULT_EXPRs that can't be hidden by the FMAs.  WIDTH is the number of
    5505              :    pipes.  */
    5506              : 
    5507              : static inline int
    5508            0 : get_mult_latency_consider_fma (int ops_num, int mult_num, int width)
    5509              : {
    5510            0 :   gcc_checking_assert (mult_num && mult_num <= ops_num);
    5511              : 
    5512              :   /* For each partition, if mult_num == ops_num, there's latency(MULT)*2.
    5513              :      e.g:
    5514              : 
    5515              :         A * B + C * D
    5516              :         =>
    5517              :         _1 = A * B;
    5518              :         _2 = .FMA (C, D, _1);
    5519              : 
    5520              :       Otherwise there's latency(MULT)*1 in the first FMA.  */
    5521            0 :   return CEIL (ops_num, width) == CEIL (mult_num, width) ? 2 : 1;
    5522              : }
    5523              : 
    5524              : /* Returns an optimal number of registers to use for computation of
    5525              :    given statements.
    5526              : 
    5527              :    LHS is the result ssa name of OPS.  MULT_NUM is number of sub-expressions
    5528              :    that are MULT_EXPRs, when OPS are PLUS_EXPRs or MINUS_EXPRs.  */
    5529              : 
    5530              : static int
    5531        19554 : get_reassociation_width (vec<operand_entry *> *ops, int mult_num, tree lhs,
    5532              :                          enum tree_code opc, machine_mode mode)
    5533              : {
    5534        19554 :   int param_width = param_tree_reassoc_width;
    5535        19554 :   int width;
    5536        19554 :   int width_min;
    5537        19554 :   int cycles_best;
    5538        19554 :   int ops_num = ops->length ();
    5539              : 
    5540        19554 :   if (param_width > 0)
    5541              :     width = param_width;
    5542              :   else
    5543        19510 :     width = targetm.sched.reassociation_width (opc, mode);
    5544              : 
    5545        19554 :   if (width == 1)
    5546              :     return width;
    5547              : 
    5548              :   /* Get the minimal time required for sequence computation.  */
    5549         7260 :   cycles_best = get_required_cycles (ops_num, width);
    5550              : 
    5551              :   /* Check if we may use less width and still compute sequence for
    5552              :      the same time.  It will allow us to reduce registers usage.
    5553              :      get_required_cycles is monotonically increasing with lower width
    5554              :      so we can perform a binary search for the minimal width that still
    5555              :      results in the optimal cycle count.  */
    5556         7260 :   width_min = 1;
    5557              : 
    5558              :   /* If the target fully pipelines FMA instruction, the multiply part can start
    5559              :      already if its operands are ready.  Assuming symmetric pipes are used for
    5560              :      FMUL/FADD/FMA, then for a sequence of FMA like:
    5561              : 
    5562              :         _8 = .FMA (_2, _3, _1);
    5563              :         _9 = .FMA (_5, _4, _8);
    5564              :         _10 = .FMA (_7, _6, _9);
    5565              : 
    5566              :      , if width=1, the latency is latency(MULT) + latency(ADD)*3.
    5567              :      While with width=2:
    5568              : 
    5569              :         _8 = _4 * _5;
    5570              :         _9 = .FMA (_2, _3, _1);
    5571              :         _10 = .FMA (_6, _7, _8);
    5572              :         _11 = _9 + _10;
    5573              : 
    5574              :      , it is latency(MULT)*2 + latency(ADD)*2.  Assuming latency(MULT) >=
    5575              :      latency(ADD), the first variant is preferred.
    5576              : 
    5577              :      Find out if we can get a smaller width considering FMA.
    5578              :      Assume FMUL and FMA use the same units that can also do FADD.
    5579              :      For other scenarios, such as when FMUL and FADD are using separated units,
    5580              :      the following code may not apply.  */
    5581              : 
    5582         7260 :   int width_mult = targetm.sched.reassociation_width (MULT_EXPR, mode);
    5583         7260 :   if (width > 1 && mult_num && param_fully_pipelined_fma
    5584            0 :       && width_mult <= width)
    5585              :     {
    5586              :       /* Latency of MULT_EXPRs.  */
    5587            0 :       int lat_mul
    5588            0 :         = get_mult_latency_consider_fma (ops_num, mult_num, width_mult);
    5589              : 
    5590              :       /* Quick search might not apply.  So start from 1.  */
    5591            0 :       for (int i = 1; i < width_mult; i++)
    5592              :         {
    5593            0 :           int lat_mul_new
    5594            0 :             = get_mult_latency_consider_fma (ops_num, mult_num, i);
    5595            0 :           int lat_add_new = get_required_cycles (ops_num, i);
    5596              : 
    5597              :           /* Assume latency(MULT) >= latency(ADD).  */
    5598            0 :           if (lat_mul - lat_mul_new >= lat_add_new - cycles_best)
    5599              :             {
    5600              :               width = i;
    5601              :               break;
    5602              :             }
    5603              :         }
    5604              :     }
    5605              :   else
    5606              :     {
    5607        17096 :       while (width > width_min)
    5608              :         {
    5609        11801 :           int width_mid = (width + width_min) / 2;
    5610              : 
    5611        11801 :           if (get_required_cycles (ops_num, width_mid) == cycles_best)
    5612              :             width = width_mid;
    5613         2163 :           else if (width_min < width_mid)
    5614              :             width_min = width_mid;
    5615              :           else
    5616              :             break;
    5617              :         }
    5618              :     }
    5619              : 
    5620              :   /* If there's loop dependent FMA result, return width=2 to avoid it.  This is
    5621              :      better than skipping these FMA candidates in widening_mul.  */
    5622         7260 :   if (width == 1
    5623         7260 :       && maybe_le (tree_to_poly_int64 (TYPE_SIZE (TREE_TYPE (lhs))),
    5624              :                    param_avoid_fma_max_bits))
    5625              :     {
    5626              :       /* Look for cross backedge dependency:
    5627              :         1. LHS is a phi argument in the same basic block it is defined.
    5628              :         2. And the result of the phi node is used in OPS.  */
    5629         4875 :       basic_block bb = gimple_bb (SSA_NAME_DEF_STMT (lhs));
    5630              : 
    5631         4875 :       use_operand_p use_p;
    5632         4875 :       imm_use_iterator iter;
    5633        10963 :       FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
    5634        10330 :         if (gphi *phi = dyn_cast<gphi *> (USE_STMT (use_p)))
    5635              :           {
    5636         4242 :             if (gimple_phi_arg_edge (phi, phi_arg_index_from_use (use_p))->src
    5637              :                 != bb)
    5638            0 :               continue;
    5639         4242 :             tree phi_result = gimple_phi_result (phi);
    5640         4242 :             operand_entry *oe;
    5641         4242 :             unsigned int j;
    5642        21017 :             FOR_EACH_VEC_ELT (*ops, j, oe)
    5643              :               {
    5644        12726 :                 if (TREE_CODE (oe->op) != SSA_NAME)
    5645            0 :                   continue;
    5646              : 
    5647              :                 /* Result of phi is operand of PLUS_EXPR.  */
    5648        12726 :                 if (oe->op == phi_result)
    5649         2039 :                   return 2;
    5650              : 
    5651              :                 /* Check is result of phi is operand of MULT_EXPR.  */
    5652        10687 :                 auto *def_stmt
    5653        10687 :                   = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (oe->op));
    5654         9580 :                 if (def_stmt
    5655         9580 :                     && gimple_assign_rhs_code (def_stmt) == NEGATE_EXPR)
    5656              :                   {
    5657         2246 :                     tree rhs = gimple_assign_rhs1 (def_stmt);
    5658         2246 :                     if (TREE_CODE (rhs) == SSA_NAME)
    5659              :                       {
    5660         2246 :                         if (rhs == phi_result)
    5661              :                           return 2;
    5662         2246 :                         def_stmt
    5663        20267 :                           = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (rhs));
    5664              :                       }
    5665              :                   }
    5666        18021 :                 if (def_stmt && gimple_assign_rhs_code (def_stmt) == MULT_EXPR)
    5667              :                   {
    5668         8484 :                     if (gimple_assign_rhs1 (def_stmt) == phi_result
    5669        16968 :                         || gimple_assign_rhs2 (def_stmt) == phi_result)
    5670              :                       return 2;
    5671              :                   }
    5672              :               }
    5673         4875 :           }
    5674              :     }
    5675              : 
    5676              :   return width;
    5677              : }
    5678              : 
    5679              : #define SPECIAL_BIASED_END_STMT 0 /* It is the end stmt of all ops.  */
    5680              : #define BIASED_END_STMT 1 /* It is the end stmt of normal or biased ops.  */
    5681              : #define NORMAL_END_STMT 2 /* It is the end stmt of normal ops.  */
    5682              : 
    5683              : /* Rewrite statements with dependency chain with regard the chance to generate
    5684              :    FMA.
    5685              :    For the chain with FMA: Try to keep fma opportunity as much as possible.
    5686              :    For the chain without FMA: Putting the computation in rank order and trying
    5687              :    to allow operations to be executed in parallel.
    5688              :    E.g.
    5689              :    e + f + a * b + c * d;
    5690              : 
    5691              :    ssa1 = e + a * b;
    5692              :    ssa2 = f + c * d;
    5693              :    ssa3 = ssa1 + ssa2;
    5694              : 
    5695              :    This reassociation approach preserves the chance of fma generation as much
    5696              :    as possible.
    5697              : 
    5698              :    Another thing is to avoid adding loop-carried ops to long chains, otherwise
    5699              :    the whole chain will have dependencies across the loop iteration.  Just keep
    5700              :    loop-carried ops in a separate chain.
    5701              :    E.g.
    5702              :    x_1 = phi (x_0, x_2)
    5703              :    y_1 = phi (y_0, y_2)
    5704              : 
    5705              :    a + b + c + d + e + x1 + y1
    5706              : 
    5707              :    SSA1 = a + b;
    5708              :    SSA2 = c + d;
    5709              :    SSA3 = SSA1 + e;
    5710              :    SSA4 = SSA3 + SSA2;
    5711              :    SSA5 = x1 + y1;
    5712              :    SSA6 = SSA4 + SSA5;
    5713              :  */
    5714              : static void
    5715         1965 : rewrite_expr_tree_parallel (gassign *stmt, int width, bool has_fma,
    5716              :                             const vec<operand_entry *> &ops)
    5717              : {
    5718         1965 :   enum tree_code opcode = gimple_assign_rhs_code (stmt);
    5719         1965 :   int op_num = ops.length ();
    5720         1965 :   int op_normal_num = op_num;
    5721         1965 :   gcc_assert (op_num > 0);
    5722         1965 :   int stmt_num = op_num - 1;
    5723         1965 :   gimple **stmts = XALLOCAVEC (gimple *, stmt_num);
    5724         1965 :   int i = 0, j = 0;
    5725         1965 :   tree tmp_op[2], op1;
    5726         1965 :   operand_entry *oe;
    5727         1965 :   gimple *stmt1 = NULL;
    5728         1965 :   tree last_rhs1 = gimple_assign_rhs1 (stmt);
    5729         1965 :   int last_rhs1_stmt_index = 0, last_rhs2_stmt_index = 0;
    5730         1965 :   int width_active = 0, width_count = 0;
    5731         1965 :   bool has_biased = false, ops_changed = false;
    5732         1965 :   auto_vec<operand_entry *> ops_normal;
    5733         1965 :   auto_vec<operand_entry *> ops_biased;
    5734         1965 :   vec<operand_entry *> *ops1;
    5735              : 
    5736              :   /* We start expression rewriting from the top statements.
    5737              :      So, in this loop we create a full list of statements
    5738              :      we will work with.  */
    5739         1965 :   stmts[stmt_num - 1] = stmt;
    5740         9472 :   for (i = stmt_num - 2; i >= 0; i--)
    5741         7507 :     stmts[i] = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmts[i+1]));
    5742              : 
    5743              :   /* Avoid adding loop-carried ops to long chains, first filter out the
    5744              :      loop-carried.  But we need to make sure that the length of the remainder
    5745              :      is not less than 4, which is the smallest ops length we can break the
    5746              :      dependency.  */
    5747        15367 :   FOR_EACH_VEC_ELT (ops, i, oe)
    5748              :     {
    5749        11437 :       if (TREE_CODE (oe->op) == SSA_NAME
    5750        11269 :           && bitmap_bit_p (biased_names, SSA_NAME_VERSION (oe->op))
    5751        11693 :           && op_normal_num > 4)
    5752              :         {
    5753          222 :           ops_biased.safe_push (oe);
    5754          222 :           has_biased = true;
    5755          222 :           op_normal_num --;
    5756              :         }
    5757              :       else
    5758        11215 :         ops_normal.safe_push (oe);
    5759              :     }
    5760              : 
    5761              :   /* Width should not be larger than ops length / 2, since we can not create
    5762              :      more parallel dependency chains that exceeds such value.  */
    5763         1965 :   int width_normal = op_normal_num / 2;
    5764         1965 :   int width_biased = (op_num - op_normal_num) / 2;
    5765         1965 :   width_normal = width <= width_normal ? width : width_normal;
    5766         1965 :   width_biased = width <= width_biased ? width : width_biased;
    5767              : 
    5768         1965 :   ops1 = &ops_normal;
    5769         1965 :   width_count = width_active = width_normal;
    5770              : 
    5771              :   /* Build parallel dependency chain according to width.  */
    5772        11437 :   for (i = 0; i < stmt_num; i++)
    5773              :     {
    5774         9472 :       if (dump_file && (dump_flags & TDF_DETAILS))
    5775              :         {
    5776            6 :           fprintf (dump_file, "Transforming ");
    5777            6 :           print_gimple_stmt (dump_file, stmts[i], 0);
    5778              :         }
    5779              : 
    5780              :       /* When the work of normal ops is over, but the loop is not over,
    5781              :          continue to do biased ops.  */
    5782         9472 :       if (width_count == 0 && ops1 == &ops_normal)
    5783              :         {
    5784          218 :           ops1 = &ops_biased;
    5785          218 :           width_count = width_active = width_biased;
    5786          218 :           ops_changed = true;
    5787              :         }
    5788              : 
    5789              :       /* Swap the operands if no FMA in the chain.  */
    5790         9472 :       if (ops1->length () > 2 && !has_fma)
    5791         4604 :         swap_ops_for_binary_stmt (*ops1, ops1->length () - 3);
    5792              : 
    5793         9472 :       if (i < width_active
    5794         5345 :           || (ops_changed && i <= (last_rhs1_stmt_index + width_active)))
    5795              :         {
    5796        12390 :           for (j = 0; j < 2; j++)
    5797              :             {
    5798         8260 :               oe = ops1->pop ();
    5799         8260 :               tmp_op[j] = oe->op;
    5800              :               /* If the stmt that defines operand has to be inserted, insert it
    5801              :                  before the use.  */
    5802         8260 :               stmt1 = oe->stmt_to_insert;
    5803         8260 :               if (stmt1)
    5804            0 :                 insert_stmt_before_use (stmts[i], stmt1);
    5805         8260 :               stmt1 = NULL;
    5806              :             }
    5807         4130 :           stmts[i] = build_and_add_sum (TREE_TYPE (last_rhs1),
    5808              :                                         tmp_op[1],
    5809              :                                         tmp_op[0],
    5810              :                                         opcode);
    5811         4130 :           gimple_set_visited (stmts[i], true);
    5812              : 
    5813              :         }
    5814              :       else
    5815              :         {
    5816              :           /* We keep original statement only for the last one.  All others are
    5817              :              recreated.  */
    5818         5342 :           if (!ops1->length ())
    5819              :             {
    5820              :               /* For biased length equal to 2.  */
    5821         2165 :               if (width_count == BIASED_END_STMT && !last_rhs2_stmt_index)
    5822            1 :                 last_rhs2_stmt_index = i - 1;
    5823              : 
    5824              :               /* When width_count == 2 and there is no biased, just finish.  */
    5825         2165 :               if (width_count == NORMAL_END_STMT && !has_biased)
    5826              :                 {
    5827         1747 :                   last_rhs1_stmt_index = i - 1;
    5828         1747 :                   last_rhs2_stmt_index = i - 2;
    5829              :                 }
    5830         2165 :               if (last_rhs1_stmt_index && (last_rhs2_stmt_index || !has_biased))
    5831              :                 {
    5832              :                   /* We keep original statement only for the last one.  All
    5833              :                      others are recreated.  */
    5834         1749 :                   gimple_assign_set_rhs1 (stmts[i], gimple_assign_lhs
    5835         1749 :                                           (stmts[last_rhs1_stmt_index]));
    5836         1749 :                   gimple_assign_set_rhs2 (stmts[i], gimple_assign_lhs
    5837         1749 :                                           (stmts[last_rhs2_stmt_index]));
    5838         1749 :                   update_stmt (stmts[i]);
    5839              :                 }
    5840              :               else
    5841              :                 {
    5842         1248 :                   stmts[i] =
    5843          416 :                     build_and_add_sum (TREE_TYPE (last_rhs1),
    5844          416 :                                        gimple_assign_lhs (stmts[i-width_count]),
    5845              :                                        gimple_assign_lhs
    5846          416 :                                        (stmts[i-width_count+1]),
    5847              :                                        opcode);
    5848          416 :                   gimple_set_visited (stmts[i], true);
    5849          416 :                   width_count--;
    5850              : 
    5851              :                   /* It is the end of normal or biased ops.
    5852              :                      last_rhs1_stmt_index used to record the last stmt index
    5853              :                      for normal ops.  last_rhs2_stmt_index used to record the
    5854              :                      last stmt index for biased ops.  */
    5855          416 :                   if (width_count == BIASED_END_STMT)
    5856              :                     {
    5857          219 :                       gcc_assert (has_biased);
    5858          219 :                       if (ops_biased.length ())
    5859              :                         last_rhs1_stmt_index = i;
    5860              :                       else
    5861            1 :                         last_rhs2_stmt_index = i;
    5862              :                       width_count--;
    5863              :                     }
    5864              :                 }
    5865              :             }
    5866              :           else
    5867              :             {
    5868              :               /* Attach the rest ops to the parallel dependency chain.  */
    5869         3177 :               oe = ops1->pop ();
    5870         3177 :               op1 = oe->op;
    5871         3177 :               stmt1 = oe->stmt_to_insert;
    5872         3177 :               if (stmt1)
    5873            0 :                 insert_stmt_before_use (stmts[i], stmt1);
    5874         3177 :               stmt1 = NULL;
    5875              : 
    5876              :               /* For only one biased ops.  */
    5877         3177 :               if (width_count == SPECIAL_BIASED_END_STMT)
    5878              :                 {
    5879              :                   /* We keep original statement only for the last one.  All
    5880              :                      others are recreated.  */
    5881          216 :                   gcc_assert (has_biased);
    5882          216 :                   gimple_assign_set_rhs1 (stmts[i], gimple_assign_lhs
    5883          216 :                                           (stmts[last_rhs1_stmt_index]));
    5884          216 :                   gimple_assign_set_rhs2 (stmts[i], op1);
    5885          216 :                   update_stmt (stmts[i]);
    5886              :                 }
    5887              :               else
    5888              :                 {
    5889         2961 :                   stmts[i] = build_and_add_sum (TREE_TYPE (last_rhs1),
    5890              :                                                 gimple_assign_lhs
    5891         2961 :                                                 (stmts[i-width_active]),
    5892              :                                                 op1,
    5893              :                                                 opcode);
    5894         2961 :                   gimple_set_visited (stmts[i], true);
    5895              :                 }
    5896              :             }
    5897              :         }
    5898              : 
    5899         9472 :       if (dump_file && (dump_flags & TDF_DETAILS))
    5900              :         {
    5901            6 :           fprintf (dump_file, " into ");
    5902            6 :           print_gimple_stmt (dump_file, stmts[i], 0);
    5903              :         }
    5904              :     }
    5905              : 
    5906         1965 :   remove_visited_stmt_chain (last_rhs1);
    5907         1965 : }
    5908              : 
    5909              : /* Transform STMT, which is really (A +B) + (C + D) into the left
    5910              :    linear form, ((A+B)+C)+D.
    5911              :    Recurse on D if necessary.  */
    5912              : 
    5913              : static void
    5914         2759 : linearize_expr (gimple *stmt)
    5915              : {
    5916         2759 :   gimple_stmt_iterator gsi;
    5917         2759 :   gimple *binlhs = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
    5918         2759 :   gimple *binrhs = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
    5919         2759 :   gimple *oldbinrhs = binrhs;
    5920         2759 :   enum tree_code rhscode = gimple_assign_rhs_code (stmt);
    5921         2759 :   gimple *newbinrhs = NULL;
    5922         2759 :   class loop *loop = loop_containing_stmt (stmt);
    5923         2759 :   tree lhs = gimple_assign_lhs (stmt);
    5924              : 
    5925         2759 :   gcc_assert (is_reassociable_op (binlhs, rhscode, loop)
    5926              :               && is_reassociable_op (binrhs, rhscode, loop));
    5927              : 
    5928         2759 :   gsi = gsi_for_stmt (stmt);
    5929              : 
    5930         2759 :   gimple_assign_set_rhs2 (stmt, gimple_assign_rhs1 (binrhs));
    5931         2759 :   binrhs = gimple_build_assign (make_ssa_name (TREE_TYPE (lhs)),
    5932              :                                 gimple_assign_rhs_code (binrhs),
    5933              :                                 gimple_assign_lhs (binlhs),
    5934              :                                 gimple_assign_rhs2 (binrhs));
    5935         2759 :   gimple_assign_set_rhs1 (stmt, gimple_assign_lhs (binrhs));
    5936         2759 :   gsi_insert_before (&gsi, binrhs, GSI_SAME_STMT);
    5937         2759 :   gimple_set_uid (binrhs, gimple_uid (stmt));
    5938              : 
    5939         2759 :   if (TREE_CODE (gimple_assign_rhs2 (stmt)) == SSA_NAME)
    5940         2756 :     newbinrhs = SSA_NAME_DEF_STMT (gimple_assign_rhs2 (stmt));
    5941              : 
    5942         2759 :   if (dump_file && (dump_flags & TDF_DETAILS))
    5943              :     {
    5944            0 :       fprintf (dump_file, "Linearized: ");
    5945            0 :       print_gimple_stmt (dump_file, stmt, 0);
    5946              :     }
    5947              : 
    5948         2759 :   reassociate_stats.linearized++;
    5949         2759 :   update_stmt (stmt);
    5950              : 
    5951         2759 :   gsi = gsi_for_stmt (oldbinrhs);
    5952         2759 :   reassoc_remove_stmt (&gsi);
    5953         2759 :   release_defs (oldbinrhs);
    5954              : 
    5955         2759 :   gimple_set_visited (stmt, true);
    5956         2759 :   gimple_set_visited (binlhs, true);
    5957         2759 :   gimple_set_visited (binrhs, true);
    5958              : 
    5959              :   /* Tail recurse on the new rhs if it still needs reassociation.  */
    5960         2759 :   if (newbinrhs && is_reassociable_op (newbinrhs, rhscode, loop))
    5961              :     /* ??? This should probably be linearize_expr (newbinrhs) but I don't
    5962              :            want to change the algorithm while converting to tuples.  */
    5963          652 :     linearize_expr (stmt);
    5964         2759 : }
    5965              : 
    5966              : /* If LHS has a single immediate use that is a GIMPLE_ASSIGN statement, return
    5967              :    it.  Otherwise, return NULL.  */
    5968              : 
    5969              : static gimple *
    5970       418175 : get_single_immediate_use (tree lhs)
    5971              : {
    5972       418175 :   use_operand_p immuse;
    5973       418175 :   gimple *immusestmt;
    5974              : 
    5975       418175 :   if (TREE_CODE (lhs) == SSA_NAME
    5976       418175 :       && single_imm_use (lhs, &immuse, &immusestmt)
    5977       740676 :       && is_gimple_assign (immusestmt))
    5978       245090 :     return immusestmt;
    5979              : 
    5980              :   return NULL;
    5981              : }
    5982              : 
    5983              : /* Recursively negate the value of TONEGATE, and return the SSA_NAME
    5984              :    representing the negated value.  Insertions of any necessary
    5985              :    instructions go before GSI.
    5986              :    This function is recursive in that, if you hand it "a_5" as the
    5987              :    value to negate, and a_5 is defined by "a_5 = b_3 + b_4", it will
    5988              :    transform b_3 + b_4 into a_5 = -b_3 + -b_4.  */
    5989              : 
    5990              : static tree
    5991        79162 : negate_value (tree tonegate, gimple_stmt_iterator *gsip)
    5992              : {
    5993        79162 :   tree resultofnegate;
    5994        79162 :   gimple_stmt_iterator gsi;
    5995        79162 :   unsigned int uid;
    5996              : 
    5997              :   /* If we are trying to negate a name, defined by an add, negate the
    5998              :      add operands instead.  */
    5999        79162 :   gassign *negatedefstmt = NULL;
    6000        79162 :   if (TREE_CODE (tonegate) == SSA_NAME)
    6001        77303 :     negatedefstmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (tonegate));
    6002        79162 :   if (TREE_CODE (tonegate) == SSA_NAME
    6003        77303 :       && negatedefstmt
    6004        67198 :       && TREE_CODE (gimple_assign_lhs (negatedefstmt)) == SSA_NAME
    6005        67198 :       && has_single_use (gimple_assign_lhs (negatedefstmt))
    6006       129069 :       && gimple_assign_rhs_code (negatedefstmt) == PLUS_EXPR)
    6007              :     {
    6008          937 :       tree rhs1 = gimple_assign_rhs1 (negatedefstmt);
    6009          937 :       tree rhs2 = gimple_assign_rhs2 (negatedefstmt);
    6010          937 :       tree lhs = gimple_assign_lhs (negatedefstmt);
    6011          937 :       gimple *g;
    6012              : 
    6013          937 :       gsi = gsi_for_stmt (negatedefstmt);
    6014          937 :       rhs1 = negate_value (rhs1, &gsi);
    6015              : 
    6016          937 :       gsi = gsi_for_stmt (negatedefstmt);
    6017          937 :       rhs2 = negate_value (rhs2, &gsi);
    6018              : 
    6019          937 :       gsi = gsi_for_stmt (negatedefstmt);
    6020          937 :       lhs = make_ssa_name (TREE_TYPE (lhs));
    6021          937 :       gimple_set_visited (negatedefstmt, true);
    6022          937 :       g = gimple_build_assign (lhs, PLUS_EXPR, rhs1, rhs2);
    6023          937 :       gimple_set_uid (g, gimple_uid (negatedefstmt));
    6024          937 :       gsi_insert_before (&gsi, g, GSI_SAME_STMT);
    6025          937 :       return lhs;
    6026              :     }
    6027              : 
    6028        78225 :   tonegate = fold_build1 (NEGATE_EXPR, TREE_TYPE (tonegate), tonegate);
    6029        78225 :   resultofnegate = force_gimple_operand_gsi (gsip, tonegate, true,
    6030              :                                              NULL_TREE, true, GSI_SAME_STMT);
    6031        78225 :   gsi = *gsip;
    6032        78225 :   uid = gimple_uid (gsi_stmt (gsi));
    6033       159283 :   for (gsi_prev (&gsi); !gsi_end_p (gsi); gsi_prev (&gsi))
    6034              :     {
    6035       149899 :       gimple *stmt = gsi_stmt (gsi);
    6036       149899 :       if (gimple_uid (stmt) != 0)
    6037              :         break;
    6038        76366 :       gimple_set_uid (stmt, uid);
    6039              :     }
    6040              :   return resultofnegate;
    6041              : }
    6042              : 
    6043              : /* Return true if we should break up the subtract in STMT into an add
    6044              :    with negate.  This is true when we the subtract operands are really
    6045              :    adds, or the subtract itself is used in an add expression.  In
    6046              :    either case, breaking up the subtract into an add with negate
    6047              :    exposes the adds to reassociation.  */
    6048              : 
    6049              : static bool
    6050       303136 : should_break_up_subtract (gassign *stmt)
    6051              : {
    6052       303136 :   tree lhs = gimple_assign_lhs (stmt);
    6053       303136 :   tree binlhs = gimple_assign_rhs1 (stmt);
    6054       303136 :   tree binrhs = gimple_assign_rhs2 (stmt);
    6055       303136 :   gimple *immusestmt;
    6056       303136 :   class loop *loop = loop_containing_stmt (stmt);
    6057              : 
    6058       303136 :   if (TREE_CODE (binlhs) == SSA_NAME
    6059       303136 :       && is_reassociable_op (SSA_NAME_DEF_STMT (binlhs), PLUS_EXPR, loop))
    6060              :     return true;
    6061              : 
    6062       285130 :   if (TREE_CODE (binrhs) == SSA_NAME
    6063       285130 :       && is_reassociable_op (SSA_NAME_DEF_STMT (binrhs), PLUS_EXPR, loop))
    6064              :     return true;
    6065              : 
    6066       284286 :   if (TREE_CODE (lhs) == SSA_NAME
    6067       284286 :       && (immusestmt = get_single_immediate_use (lhs))
    6068       132534 :       && is_gimple_assign (immusestmt)
    6069       416820 :       && (gimple_assign_rhs_code (immusestmt) == PLUS_EXPR
    6070        87680 :           || (gimple_assign_rhs_code (immusestmt) == MINUS_EXPR
    6071         2257 :               && gimple_assign_rhs1 (immusestmt) == lhs)
    6072        85439 :           || gimple_assign_rhs_code (immusestmt) == MULT_EXPR))
    6073        58438 :     return true;
    6074              :   return false;
    6075              : }
    6076              : 
    6077              : /* Transform STMT from A - B into A + -B.  */
    6078              : 
    6079              : static void
    6080        77288 : break_up_subtract (gassign *stmt, gimple_stmt_iterator *gsip)
    6081              : {
    6082        77288 :   tree rhs1 = gimple_assign_rhs1 (stmt);
    6083        77288 :   tree rhs2 = gimple_assign_rhs2 (stmt);
    6084              : 
    6085        77288 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6086              :     {
    6087            0 :       fprintf (dump_file, "Breaking up subtract ");
    6088            0 :       print_gimple_stmt (dump_file, stmt, 0);
    6089              :     }
    6090              : 
    6091        77288 :   rhs2 = negate_value (rhs2, gsip);
    6092        77288 :   gimple_assign_set_rhs_with_ops (gsip, PLUS_EXPR, rhs1, rhs2);
    6093        77288 :   update_stmt (stmt);
    6094        77288 : }
    6095              : 
    6096              : /* Determine whether STMT is a builtin call that raises an SSA name
    6097              :    to an integer power and has only one use.  If so, and this is early
    6098              :    reassociation and unsafe math optimizations are permitted, place
    6099              :    the SSA name in *BASE and the exponent in *EXPONENT, and return TRUE.
    6100              :    If any of these conditions does not hold, return FALSE.  */
    6101              : 
    6102              : static bool
    6103          153 : acceptable_pow_call (gcall *stmt, tree *base, HOST_WIDE_INT *exponent)
    6104              : {
    6105          153 :   tree arg1;
    6106          153 :   REAL_VALUE_TYPE c, cint;
    6107              : 
    6108          153 :   switch (gimple_call_combined_fn (stmt))
    6109              :     {
    6110           34 :     CASE_CFN_POW:
    6111           34 :       if (flag_errno_math)
    6112              :         return false;
    6113              : 
    6114           34 :       *base = gimple_call_arg (stmt, 0);
    6115           34 :       arg1 = gimple_call_arg (stmt, 1);
    6116              : 
    6117           34 :       if (TREE_CODE (arg1) != REAL_CST)
    6118              :         return false;
    6119              : 
    6120           28 :       c = TREE_REAL_CST (arg1);
    6121              : 
    6122           28 :       if (REAL_EXP (&c) > HOST_BITS_PER_WIDE_INT)
    6123              :         return false;
    6124              : 
    6125           28 :       *exponent = real_to_integer (&c);
    6126           28 :       real_from_integer (&cint, VOIDmode, *exponent, SIGNED);
    6127           28 :       if (!real_identical (&c, &cint))
    6128              :         return false;
    6129              : 
    6130              :       break;
    6131              : 
    6132           16 :     CASE_CFN_POWI:
    6133           16 :       *base = gimple_call_arg (stmt, 0);
    6134           16 :       arg1 = gimple_call_arg (stmt, 1);
    6135              : 
    6136           16 :       if (!tree_fits_shwi_p (arg1))
    6137              :         return false;
    6138              : 
    6139           13 :       *exponent = tree_to_shwi (arg1);
    6140           13 :       break;
    6141              : 
    6142              :     default:
    6143              :       return false;
    6144              :     }
    6145              : 
    6146              :   /* Expanding negative exponents is generally unproductive, so we don't
    6147              :      complicate matters with those.  Exponents of zero and one should
    6148              :      have been handled by expression folding.  Exponents not fitting
    6149              :      the exponent argument of __builtin_powi are not handled either.  */
    6150           30 :   if (*exponent < 2
    6151           24 :       || !wi::fits_to_tree_p (*exponent, integer_type_node)
    6152           23 :       || TREE_CODE (*base) != SSA_NAME
    6153           53 :       || !can_reassociate_op_p (*base))
    6154           11 :     return false;
    6155              : 
    6156              :   return true;
    6157              : }
    6158              : 
    6159              : /* Try to derive and add operand entry for OP to *OPS.  Return false if
    6160              :    unsuccessful.  */
    6161              : 
    6162              : static bool
    6163      9965379 : try_special_add_to_ops (vec<operand_entry *> *ops,
    6164              :                         enum tree_code code,
    6165              :                         tree op, gimple* def_stmt)
    6166              : {
    6167      9965379 :   tree base = NULL_TREE;
    6168      9965379 :   HOST_WIDE_INT exponent = 0;
    6169              : 
    6170      9965379 :   if (TREE_CODE (op) != SSA_NAME
    6171      9965379 :       || ! has_single_use (op))
    6172              :     return false;
    6173              : 
    6174      3740524 :   gassign *def_assign = dyn_cast<gassign *> (def_stmt);
    6175      3740524 :   if (code == MULT_EXPR
    6176       807444 :       && reassoc_insert_powi_p
    6177       377535 :       && flag_unsafe_math_optimizations
    6178        30411 :       && is_gimple_call (def_stmt)
    6179      3740665 :       && acceptable_pow_call (as_a <gcall *> (def_stmt), &base, &exponent))
    6180              :     {
    6181           17 :       add_repeat_to_ops_vec (ops, base, exponent);
    6182           17 :       gimple_set_visited (def_stmt, true);
    6183           17 :       return true;
    6184              :     }
    6185      3740507 :   else if (code == MULT_EXPR
    6186      3740507 :            && def_assign
    6187       765759 :            && gimple_assign_rhs_code (def_assign) == NEGATE_EXPR
    6188          584 :            && !HONOR_SNANS (TREE_TYPE (op))
    6189          584 :            && (!HONOR_SIGNED_ZEROS (TREE_TYPE (op))
    6190            0 :                || !COMPLEX_FLOAT_TYPE_P (TREE_TYPE (op)))
    6191      3741091 :            && (!FLOAT_TYPE_P (TREE_TYPE (op))
    6192           50 :                || !DECIMAL_FLOAT_MODE_P (element_mode (op))))
    6193              :     {
    6194          577 :       tree rhs1 = gimple_assign_rhs1 (def_assign);
    6195          577 :       if (!can_reassociate_op_p (rhs1))
    6196              :         return false;
    6197          567 :       tree cst = build_minus_one_cst (TREE_TYPE (op));
    6198          567 :       add_to_ops_vec (ops, rhs1);
    6199          567 :       add_to_ops_vec (ops, cst);
    6200          567 :       gimple_set_visited (def_assign, true);
    6201          567 :       return true;
    6202              :     }
    6203              : 
    6204              :   return false;
    6205              : }
    6206              : 
    6207              : /* Recursively linearize a binary expression that is the RHS of STMT.
    6208              :    Place the operands of the expression tree in the vector named OPS.  */
    6209              : 
    6210              : static void
    6211      5113738 : linearize_expr_tree (vec<operand_entry *> *ops, gimple *stmt,
    6212              :                      bool is_associative, bool set_visited)
    6213              : {
    6214      5113738 :   tree binlhs = gimple_assign_rhs1 (stmt);
    6215      5113738 :   tree binrhs = gimple_assign_rhs2 (stmt);
    6216      5113738 :   gimple *binlhsdef = NULL, *binrhsdef = NULL;
    6217      5113738 :   bool binlhsisreassoc = false;
    6218      5113738 :   bool binrhsisreassoc = false;
    6219      5113738 :   enum tree_code rhscode = gimple_assign_rhs_code (stmt);
    6220      5113738 :   class loop *loop = loop_containing_stmt (stmt);
    6221              : 
    6222      5113738 :   if (set_visited)
    6223      5072962 :     gimple_set_visited (stmt, true);
    6224              : 
    6225      5113738 :   if (TREE_CODE (binlhs) == SSA_NAME)
    6226              :     {
    6227      5111054 :       binlhsdef = SSA_NAME_DEF_STMT (binlhs);
    6228      5111054 :       binlhsisreassoc = (is_reassociable_op (binlhsdef, rhscode, loop)
    6229      5111054 :                          && !stmt_could_throw_p (cfun, binlhsdef));
    6230              :     }
    6231              : 
    6232      5113738 :   if (TREE_CODE (binrhs) == SSA_NAME)
    6233              :     {
    6234      1632063 :       binrhsdef = SSA_NAME_DEF_STMT (binrhs);
    6235      1632063 :       binrhsisreassoc = (is_associative
    6236      1632046 :                          && is_reassociable_op (binrhsdef, rhscode, loop)
    6237      1699532 :                          && !stmt_could_throw_p (cfun, binrhsdef));
    6238              :     }
    6239              : 
    6240              :   /* If the LHS is not reassociable, but the RHS is, we need to swap
    6241              :      them.  If neither is reassociable, there is nothing we can do, so
    6242              :      just put them in the ops vector.  If the LHS is reassociable,
    6243              :      linearize it.  If both are reassociable, then linearize the RHS
    6244              :      and the LHS.  */
    6245              : 
    6246      5113738 :   if (!binlhsisreassoc)
    6247              :     {
    6248              :       /* If this is not a associative operation like division, give up.  */
    6249      4917037 :       if (!is_associative)
    6250              :         {
    6251           17 :           add_to_ops_vec (ops, binrhs);
    6252           17 :           return;
    6253              :         }
    6254              : 
    6255      4917020 :       if (!binrhsisreassoc)
    6256              :         {
    6257      4851658 :           bool swap = false;
    6258      4851658 :           if (try_special_add_to_ops (ops, rhscode, binrhs, binrhsdef))
    6259              :             /* If we add ops for the rhs we expect to be able to recurse
    6260              :                to it via the lhs during expression rewrite so swap
    6261              :                operands.  */
    6262              :             swap = true;
    6263              :           else
    6264      4851281 :             add_to_ops_vec (ops, binrhs);
    6265              : 
    6266      4851658 :           if (!try_special_add_to_ops (ops, rhscode, binlhs, binlhsdef))
    6267      4851461 :             add_to_ops_vec (ops, binlhs);
    6268              : 
    6269      4851658 :           if (!swap)
    6270              :             return;
    6271              :         }
    6272              : 
    6273        65739 :       if (dump_file && (dump_flags & TDF_DETAILS))
    6274              :         {
    6275            9 :           fprintf (dump_file, "swapping operands of ");
    6276            9 :           print_gimple_stmt (dump_file, stmt, 0);
    6277              :         }
    6278              : 
    6279        65739 :       swap_ssa_operands (stmt,
    6280              :                          gimple_assign_rhs1_ptr (stmt),
    6281              :                          gimple_assign_rhs2_ptr (stmt));
    6282        65739 :       update_stmt (stmt);
    6283              : 
    6284        65739 :       if (dump_file && (dump_flags & TDF_DETAILS))
    6285              :         {
    6286            9 :           fprintf (dump_file, " is now ");
    6287            9 :           print_gimple_stmt (dump_file, stmt, 0);
    6288              :         }
    6289        65739 :       if (!binrhsisreassoc)
    6290              :         return;
    6291              : 
    6292              :       /* We want to make it so the lhs is always the reassociative op,
    6293              :          so swap.  */
    6294              :       std::swap (binlhs, binrhs);
    6295              :     }
    6296       196701 :   else if (binrhsisreassoc)
    6297              :     {
    6298         2107 :       linearize_expr (stmt);
    6299         2107 :       binlhs = gimple_assign_rhs1 (stmt);
    6300         2107 :       binrhs = gimple_assign_rhs2 (stmt);
    6301              :     }
    6302              : 
    6303       262063 :   gcc_checking_assert (TREE_CODE (binrhs) != SSA_NAME
    6304              :                        || !is_associative
    6305              :                        || !is_reassociable_op (SSA_NAME_DEF_STMT (binrhs),
    6306              :                                                rhscode, loop));
    6307       262063 :   linearize_expr_tree (ops, SSA_NAME_DEF_STMT (binlhs),
    6308              :                        is_associative, set_visited);
    6309              : 
    6310       262063 :   if (!try_special_add_to_ops (ops, rhscode, binrhs, binrhsdef))
    6311       262053 :     add_to_ops_vec (ops, binrhs);
    6312              : }
    6313              : 
    6314              : /* Repropagate the negates back into subtracts, since no other pass
    6315              :    currently does it.  */
    6316              : 
    6317              : static void
    6318      2136209 : repropagate_negates (void)
    6319              : {
    6320      2136209 :   unsigned int i = 0;
    6321      2136209 :   tree negate;
    6322              : 
    6323      2270098 :   FOR_EACH_VEC_ELT (plus_negates, i, negate)
    6324              :     {
    6325       133889 :       auto *user = safe_dyn_cast<gassign *> (get_single_immediate_use (negate));
    6326       133889 :       if (!user)
    6327        21333 :         continue;
    6328              : 
    6329       112556 :       tree negateop = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (negate));
    6330       112566 :       if (TREE_CODE (negateop) == SSA_NAME
    6331       112556 :           && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (negateop))
    6332           10 :         continue;
    6333              : 
    6334              :       /* The negate operand can be either operand of a PLUS_EXPR
    6335              :          (it can be the LHS if the RHS is a constant for example).
    6336              : 
    6337              :          Force the negate operand to the RHS of the PLUS_EXPR, then
    6338              :          transform the PLUS_EXPR into a MINUS_EXPR.  */
    6339       114827 :       if (gimple_assign_rhs_code (user) == PLUS_EXPR)
    6340              :         {
    6341              :           /* If the negated operand appears on the LHS of the
    6342              :              PLUS_EXPR, exchange the operands of the PLUS_EXPR
    6343              :              to force the negated operand to the RHS of the PLUS_EXPR.  */
    6344        85467 :           if (gimple_assign_rhs1 (user) == negate)
    6345              :             {
    6346        26248 :               swap_ssa_operands (user,
    6347              :                                  gimple_assign_rhs1_ptr (user),
    6348              :                                  gimple_assign_rhs2_ptr (user));
    6349              :             }
    6350              : 
    6351              :           /* Now transform the PLUS_EXPR into a MINUS_EXPR and replace
    6352              :              the RHS of the PLUS_EXPR with the operand of the NEGATE_EXPR.  */
    6353       170934 :           if (gimple_assign_rhs2 (user) == negate)
    6354              :             {
    6355        85467 :               tree rhs1 = gimple_assign_rhs1 (user);
    6356        85467 :               gimple_stmt_iterator gsi = gsi_for_stmt (user);
    6357        85467 :               gimple_assign_set_rhs_with_ops (&gsi, MINUS_EXPR, rhs1,
    6358              :                                               negateop);
    6359        85467 :               update_stmt (user);
    6360              :             }
    6361              :         }
    6362        27079 :       else if (gimple_assign_rhs_code (user) == MINUS_EXPR)
    6363              :         {
    6364         2059 :           if (gimple_assign_rhs1 (user) == negate)
    6365              :             {
    6366              :               /* We have
    6367              :                    x = -negateop
    6368              :                    y = x - b
    6369              :                  which we transform into
    6370              :                    x = negateop + b
    6371              :                    y = -x .
    6372              :                  This pushes down the negate which we possibly can merge
    6373              :                  into some other operation, hence insert it into the
    6374              :                  plus_negates vector.  */
    6375         2059 :               gimple *feed = SSA_NAME_DEF_STMT (negate);
    6376         2059 :               tree b = gimple_assign_rhs2 (user);
    6377         2059 :               gimple_stmt_iterator gsi = gsi_for_stmt (feed);
    6378         2059 :               gimple_stmt_iterator gsi2 = gsi_for_stmt (user);
    6379         2059 :               tree x = make_ssa_name (TREE_TYPE (gimple_assign_lhs (feed)));
    6380         2059 :               gimple *g = gimple_build_assign (x, PLUS_EXPR, negateop, b);
    6381         2059 :               gsi_insert_before (&gsi2, g, GSI_SAME_STMT);
    6382         2059 :               gimple_assign_set_rhs_with_ops (&gsi2, NEGATE_EXPR, x);
    6383         2059 :               user = as_a<gassign *> (gsi_stmt (gsi2));
    6384         2059 :               update_stmt (user);
    6385         2059 :               reassoc_remove_stmt (&gsi);
    6386         2059 :               release_defs (feed);
    6387         2059 :               plus_negates.safe_push (gimple_assign_lhs (user));
    6388              :             }
    6389              :           else
    6390              :             {
    6391              :               /* Transform "x = -negateop; y = b - x" into "y = b + negateop",
    6392              :                  getting rid of one operation.  */
    6393            0 :               tree rhs1 = gimple_assign_rhs1 (user);
    6394            0 :               gimple_stmt_iterator gsi = gsi_for_stmt (user);
    6395            0 :               gimple_assign_set_rhs_with_ops (&gsi, PLUS_EXPR, rhs1, negateop);
    6396            0 :               update_stmt (gsi_stmt (gsi));
    6397              :             }
    6398              :         }
    6399              :     }
    6400      2136209 : }
    6401              : 
    6402              : /* Break up subtract operations in block BB.
    6403              : 
    6404              :    We do this top down because we don't know whether the subtract is
    6405              :    part of a possible chain of reassociation except at the top.
    6406              : 
    6407              :    IE given
    6408              :    d = f + g
    6409              :    c = a + e
    6410              :    b = c - d
    6411              :    q = b - r
    6412              :    k = t - q
    6413              : 
    6414              :    we want to break up k = t - q, but we won't until we've transformed q
    6415              :    = b - r, which won't be broken up until we transform b = c - d.
    6416              : 
    6417              :    En passant, clear the GIMPLE visited flag on every statement
    6418              :    and set UIDs within each basic block.  */
    6419              : 
    6420              : static void
    6421     19990146 : break_up_subtract_bb (basic_block bb)
    6422              : {
    6423     19990146 :   gimple_stmt_iterator gsi;
    6424     19990146 :   unsigned int uid = 1;
    6425              : 
    6426    220266523 :   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
    6427              :     {
    6428    180286231 :       gimple *stmt = gsi_stmt (gsi);
    6429    180286231 :       gimple_set_visited (stmt, false);
    6430    180286231 :       gimple_set_uid (stmt, uid++);
    6431              : 
    6432    180286231 :       gassign *assign = dyn_cast<gassign *> (stmt);
    6433     48945715 :       if (!assign
    6434     48945715 :           || !can_reassociate_type_p (TREE_TYPE (gimple_assign_lhs (assign)))
    6435     17953775 :           || !can_reassociate_op_p (gimple_assign_lhs (assign)))
    6436    162332825 :         continue;
    6437              : 
    6438              :       /* Look for simple gimple subtract operations.  */
    6439     26075118 :       if (gimple_assign_rhs_code (assign) == MINUS_EXPR)
    6440              :         {
    6441       303401 :           if (!can_reassociate_op_p (gimple_assign_rhs1 (assign))
    6442       606613 :               || !can_reassociate_op_p (gimple_assign_rhs2 (assign)))
    6443          265 :             continue;
    6444              : 
    6445              :           /* Check for a subtract used only in an addition.  If this
    6446              :              is the case, transform it into add of a negate for better
    6447              :              reassociation.  IE transform C = A-B into C = A + -B if C
    6448              :              is only used in an addition.  */
    6449       303136 :           if (should_break_up_subtract (assign))
    6450        77288 :             break_up_subtract (assign, &gsi);
    6451              :         }
    6452     17650005 :       else if (gimple_assign_rhs_code (assign) == NEGATE_EXPR
    6453     17650005 :                && can_reassociate_op_p (gimple_assign_rhs1 (assign)))
    6454        44472 :         plus_negates.safe_push (gimple_assign_lhs (assign));
    6455              :     }
    6456     19990146 : }
    6457              : 
    6458              : /* Used for repeated factor analysis.  */
    6459              : struct repeat_factor
    6460              : {
    6461              :   /* An SSA name that occurs in a multiply chain.  */
    6462              :   tree factor;
    6463              : 
    6464              :   /* Cached rank of the factor.  */
    6465              :   unsigned rank;
    6466              : 
    6467              :   /* Number of occurrences of the factor in the chain.  */
    6468              :   HOST_WIDE_INT count;
    6469              : 
    6470              :   /* An SSA name representing the product of this factor and
    6471              :      all factors appearing later in the repeated factor vector.  */
    6472              :   tree repr;
    6473              : };
    6474              : 
    6475              : 
    6476              : static vec<repeat_factor> repeat_factor_vec;
    6477              : 
    6478              : /* Used for sorting the repeat factor vector.  Sort primarily by
    6479              :    ascending occurrence count, secondarily by descending rank.  */
    6480              : 
    6481              : static int
    6482       270877 : compare_repeat_factors (const void *x1, const void *x2)
    6483              : {
    6484       270877 :   const repeat_factor *rf1 = (const repeat_factor *) x1;
    6485       270877 :   const repeat_factor *rf2 = (const repeat_factor *) x2;
    6486              : 
    6487       270877 :   if (rf1->count < rf2->count)
    6488              :     return -1;
    6489       270239 :   else if (rf1->count > rf2->count)
    6490              :     return 1;
    6491              : 
    6492       269743 :   if (rf1->rank < rf2->rank)
    6493              :     return 1;
    6494       146440 :   else if (rf1->rank > rf2->rank)
    6495       122154 :     return -1;
    6496              : 
    6497              :   return 0;
    6498              : }
    6499              : 
    6500              : /* Look for repeated operands in OPS in the multiply tree rooted at
    6501              :    STMT.  Replace them with an optimal sequence of multiplies and powi
    6502              :    builtin calls, and remove the used operands from OPS.  Return an
    6503              :    SSA name representing the value of the replacement sequence.  */
    6504              : 
    6505              : static tree
    6506       506668 : attempt_builtin_powi (gimple *stmt, vec<operand_entry *> *ops)
    6507              : {
    6508       506668 :   unsigned i, j, vec_len;
    6509       506668 :   int ii;
    6510       506668 :   operand_entry *oe;
    6511       506668 :   repeat_factor *rf1, *rf2;
    6512       506668 :   repeat_factor rfnew;
    6513       506668 :   tree result = NULL_TREE;
    6514       506668 :   tree target_ssa, iter_result;
    6515       506668 :   tree type = TREE_TYPE (gimple_get_lhs (stmt));
    6516       506668 :   tree powi_fndecl = mathfn_built_in (type, BUILT_IN_POWI);
    6517       506668 :   gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
    6518       506668 :   gimple *mul_stmt, *pow_stmt;
    6519              : 
    6520              :   /* Expand powers as a series of multiplications if type is integral
    6521              :      or BUILT_IN_POWI doesn't exist for this type and target.  We cannot
    6522              :      simply give up in the latter case as OPS can contain entries with
    6523              :      an occurrence count larger than one for __builtin_pow calls.  */
    6524       506668 :   bool use_mults = INTEGRAL_TYPE_P (type) || !powi_fndecl;
    6525              : 
    6526              :   /* Allocate the repeated factor vector.  */
    6527       506668 :   repeat_factor_vec.create (10);
    6528              : 
    6529              :   /* Scan the OPS vector for all SSA names in the product and build
    6530              :      up a vector of occurrence counts for each factor.  */
    6531      2031046 :   FOR_EACH_VEC_ELT (*ops, i, oe)
    6532              :     {
    6533      1017710 :       if (TREE_CODE (oe->op) == SSA_NAME)
    6534              :         {
    6535       648151 :           FOR_EACH_VEC_ELT (repeat_factor_vec, j, rf1)
    6536              :             {
    6537              :               /* If the occurrence count would overflow, record the
    6538              :                  factor in a separate element instead.  */
    6539        73219 :               if (rf1->factor == oe->op
    6540         2835 :                   && oe->count <= HOST_WIDE_INT_MAX - rf1->count)
    6541              :                 {
    6542         2835 :                   rf1->count += oe->count;
    6543         2835 :                   break;
    6544              :                 }
    6545              :             }
    6546              : 
    6547       577767 :           if (j >= repeat_factor_vec.length ())
    6548              :             {
    6549       574932 :               rfnew.factor = oe->op;
    6550       574932 :               rfnew.rank = oe->rank;
    6551       574932 :               rfnew.count = oe->count;
    6552       574932 :               rfnew.repr = NULL_TREE;
    6553       574932 :               repeat_factor_vec.safe_push (rfnew);
    6554              :             }
    6555              :         }
    6556              :     }
    6557              : 
    6558              :   /* Sort the repeated factor vector by (a) increasing occurrence count,
    6559              :      and (b) decreasing rank.  */
    6560       506668 :   repeat_factor_vec.qsort (compare_repeat_factors);
    6561              : 
    6562              :   /* It is generally best to combine as many base factors as possible
    6563              :      into a product before applying __builtin_powi to the result.
    6564              :      However, the sort order chosen for the repeated factor vector
    6565              :      allows us to cache partial results for the product of the base
    6566              :      factors for subsequent use.  When we already have a cached partial
    6567              :      result from a previous iteration, it is best to make use of it
    6568              :      before looking for another __builtin_pow opportunity.
    6569              : 
    6570              :      As an example, consider x * x * y * y * y * z * z * z * z.
    6571              :      We want to first compose the product x * y * z, raise it to the
    6572              :      second power, then multiply this by y * z, and finally multiply
    6573              :      by z.  This can be done in 5 multiplies provided we cache y * z
    6574              :      for use in both expressions:
    6575              : 
    6576              :         t1 = y * z
    6577              :         t2 = t1 * x
    6578              :         t3 = t2 * t2
    6579              :         t4 = t1 * t3
    6580              :         result = t4 * z
    6581              : 
    6582              :      If we instead ignored the cached y * z and first multiplied by
    6583              :      the __builtin_pow opportunity z * z, we would get the inferior:
    6584              : 
    6585              :         t1 = y * z
    6586              :         t2 = t1 * x
    6587              :         t3 = t2 * t2
    6588              :         t4 = z * z
    6589              :         t5 = t3 * t4
    6590              :         result = t5 * y  */
    6591              : 
    6592       506668 :   vec_len = repeat_factor_vec.length ();
    6593              : 
    6594              :   /* The occurrence counts can exceed the range of the exponent argument
    6595              :      of __builtin_powi, in which case multiple calls are emitted.  */
    6596       506668 :   HOST_WIDE_INT max_power = HOST_WIDE_INT_MAX;
    6597       506668 :   if (!use_mults)
    6598        13939 :     max_power = tree_to_shwi (TYPE_MAX_VALUE (integer_type_node));
    6599              : 
    6600              :   /* Repeatedly look for opportunities to create a builtin_powi call.  */
    6601       508469 :   while (true)
    6602              :     {
    6603       508469 :       HOST_WIDE_INT power;
    6604              : 
    6605              :       /* First look for the largest cached product of factors from
    6606              :          preceding iterations.  If found, create a builtin_powi for
    6607              :          it if the minimum occurrence count for its factors is at
    6608              :          least 2, or just use this cached product as our next
    6609              :          multiplicand if the minimum occurrence count is 1.  */
    6610      1085504 :       FOR_EACH_VEC_ELT (repeat_factor_vec, j, rf1)
    6611              :         {
    6612       577045 :           if (rf1->repr && rf1->count > 0)
    6613              :             break;
    6614              :         }
    6615              : 
    6616       508469 :       if (j < vec_len)
    6617              :         {
    6618           10 :           power = MIN (rf1->count, max_power);
    6619              : 
    6620           10 :           if (power == 1)
    6621              :             {
    6622            7 :               iter_result = rf1->repr;
    6623              : 
    6624            7 :               if (dump_file && (dump_flags & TDF_DETAILS))
    6625              :                 {
    6626            0 :                   unsigned elt;
    6627            0 :                   repeat_factor *rf;
    6628            0 :                   fputs ("Multiplying by cached product ", dump_file);
    6629            0 :                   for (elt = j; elt < vec_len; elt++)
    6630              :                     {
    6631            0 :                       rf = &repeat_factor_vec[elt];
    6632            0 :                       print_generic_expr (dump_file, rf->factor);
    6633            0 :                       if (elt < vec_len - 1)
    6634            0 :                         fputs (" * ", dump_file);
    6635              :                     }
    6636            0 :                   fputs ("\n", dump_file);
    6637              :                 }
    6638              :             }
    6639              :           else
    6640              :             {
    6641            3 :               if (use_mults)
    6642              :                 {
    6643            0 :                   gcc_assert (power > 1);
    6644            0 :                   gimple_stmt_iterator gsip = gsi;
    6645            0 :                   gsi_prev (&gsip);
    6646            0 :                   iter_result = powi_as_mults (&gsi, gimple_location (stmt),
    6647              :                                                rf1->repr, power);
    6648            0 :                   gimple_stmt_iterator gsic = gsi;
    6649            0 :                   while (gsi_stmt (gsic) != gsi_stmt (gsip))
    6650              :                     {
    6651            0 :                       gimple_set_uid (gsi_stmt (gsic), gimple_uid (stmt));
    6652            0 :                       gimple_set_visited (gsi_stmt (gsic), true);
    6653            0 :                       gsi_prev (&gsic);
    6654              :                     }
    6655              :                 }
    6656              :               else
    6657              :                 {
    6658            3 :                   iter_result = make_temp_ssa_name (type, NULL, "reassocpow");
    6659            3 :                   pow_stmt
    6660            3 :                     = gimple_build_call (powi_fndecl, 2, rf1->repr,
    6661              :                                          build_int_cst (integer_type_node,
    6662            3 :                                                         power));
    6663            3 :                   gimple_call_set_lhs (pow_stmt, iter_result);
    6664            3 :                   gimple_set_location (pow_stmt, gimple_location (stmt));
    6665            3 :                   gimple_set_uid (pow_stmt, gimple_uid (stmt));
    6666            3 :                   gsi_insert_before (&gsi, pow_stmt, GSI_SAME_STMT);
    6667              :                 }
    6668              : 
    6669            3 :               if (dump_file && (dump_flags & TDF_DETAILS))
    6670              :                 {
    6671            0 :                   unsigned elt;
    6672            0 :                   repeat_factor *rf;
    6673            0 :                   fputs ("Building __builtin_pow call for cached product (",
    6674              :                          dump_file);
    6675            0 :                   for (elt = j; elt < vec_len; elt++)
    6676              :                     {
    6677            0 :                       rf = &repeat_factor_vec[elt];
    6678            0 :                       print_generic_expr (dump_file, rf->factor);
    6679            0 :                       if (elt < vec_len - 1)
    6680            0 :                         fputs (" * ", dump_file);
    6681              :                     }
    6682            0 :                   fprintf (dump_file, ")^" HOST_WIDE_INT_PRINT_DEC"\n",
    6683              :                            power);
    6684              :                 }
    6685              :             }
    6686              :         }
    6687              :       else
    6688              :         {
    6689              :           /* Otherwise, find the first factor in the repeated factor
    6690              :              vector whose occurrence count is at least 2.  If no such
    6691              :              factor exists, there are no builtin_powi opportunities
    6692              :              remaining.  */
    6693      1083659 :           FOR_EACH_VEC_ELT (repeat_factor_vec, j, rf1)
    6694              :             {
    6695       576991 :               if (rf1->count >= 2)
    6696              :                 break;
    6697              :             }
    6698              : 
    6699       508459 :           if (j >= vec_len)
    6700              :             break;
    6701              : 
    6702         1791 :           power = MIN (rf1->count, max_power);
    6703              : 
    6704         1791 :           if (dump_file && (dump_flags & TDF_DETAILS))
    6705              :             {
    6706            0 :               unsigned elt;
    6707            0 :               repeat_factor *rf;
    6708            0 :               fputs ("Building __builtin_pow call for (", dump_file);
    6709            0 :               for (elt = j; elt < vec_len; elt++)
    6710              :                 {
    6711            0 :                   rf = &repeat_factor_vec[elt];
    6712            0 :                   print_generic_expr (dump_file, rf->factor);
    6713            0 :                   if (elt < vec_len - 1)
    6714            0 :                     fputs (" * ", dump_file);
    6715              :                 }
    6716            0 :               fprintf (dump_file, ")^" HOST_WIDE_INT_PRINT_DEC"\n", power);
    6717              :             }
    6718              : 
    6719         1791 :           reassociate_stats.pows_created++;
    6720              : 
    6721              :           /* Visit each element of the vector in reverse order (so that
    6722              :              high-occurrence elements are visited first, and within the
    6723              :              same occurrence count, lower-ranked elements are visited
    6724              :              first).  Form a linear product of all elements in this order
    6725              :              whose occurrencce count is at least that of element J.
    6726              :              Record the SSA name representing the product of each element
    6727              :              with all subsequent elements in the vector.  */
    6728         1791 :           if (j == vec_len - 1)
    6729         1770 :             rf1->repr = rf1->factor;
    6730              :           else
    6731              :             {
    6732           50 :               for (ii = vec_len - 2; ii >= (int)j; ii--)
    6733              :                 {
    6734           29 :                   tree op1, op2;
    6735              : 
    6736           29 :                   rf1 = &repeat_factor_vec[ii];
    6737           29 :                   rf2 = &repeat_factor_vec[ii + 1];
    6738              : 
    6739              :                   /* Init the last factor's representative to be itself.  */
    6740           29 :                   if (!rf2->repr)
    6741           21 :                     rf2->repr = rf2->factor;
    6742              : 
    6743           29 :                   op1 = rf1->factor;
    6744           29 :                   op2 = rf2->repr;
    6745              : 
    6746           29 :                   target_ssa = make_temp_ssa_name (type, NULL, "reassocpow");
    6747           29 :                   mul_stmt = gimple_build_assign (target_ssa, MULT_EXPR,
    6748              :                                                   op1, op2);
    6749           29 :                   gimple_set_location (mul_stmt, gimple_location (stmt));
    6750           29 :                   gimple_set_uid (mul_stmt, gimple_uid (stmt));
    6751           29 :                   gsi_insert_before (&gsi, mul_stmt, GSI_SAME_STMT);
    6752           29 :                   rf1->repr = target_ssa;
    6753              : 
    6754              :                   /* Don't reprocess the multiply we just introduced.  */
    6755           29 :                   gimple_set_visited (mul_stmt, true);
    6756              :                 }
    6757              :             }
    6758              : 
    6759              :           /* Form a call to __builtin_powi for the maximum product
    6760              :              just formed, raised to the power obtained earlier.  */
    6761         1791 :           rf1 = &repeat_factor_vec[j];
    6762         1791 :           if (use_mults)
    6763              :             {
    6764         1226 :               gcc_assert (power > 1);
    6765         1226 :               gimple_stmt_iterator gsip = gsi;
    6766         1226 :               gsi_prev (&gsip);
    6767         1226 :               iter_result = powi_as_mults (&gsi, gimple_location (stmt),
    6768              :                                            rf1->repr, power);
    6769         1226 :               gimple_stmt_iterator gsic = gsi;
    6770         3715 :               while (gsi_stmt (gsic) != gsi_stmt (gsip))
    6771              :                 {
    6772         2489 :                   gimple_set_uid (gsi_stmt (gsic), gimple_uid (stmt));
    6773         2489 :                   gimple_set_visited (gsi_stmt (gsic), true);
    6774         2545 :                   gsi_prev (&gsic);
    6775              :                 }
    6776              :             }
    6777              :           else
    6778              :             {
    6779          565 :               iter_result = make_temp_ssa_name (type, NULL, "reassocpow");
    6780          565 :               pow_stmt = gimple_build_call (powi_fndecl, 2, rf1->repr,
    6781              :                                             build_int_cst (integer_type_node,
    6782          565 :                                                            power));
    6783          565 :               gimple_call_set_lhs (pow_stmt, iter_result);
    6784          565 :               gimple_set_location (pow_stmt, gimple_location (stmt));
    6785          565 :               gimple_set_uid (pow_stmt, gimple_uid (stmt));
    6786          565 :               gsi_insert_before (&gsi, pow_stmt, GSI_SAME_STMT);
    6787              :             }
    6788              :         }
    6789              : 
    6790              :       /* If we previously formed at least one other builtin_powi call,
    6791              :          form the product of this one and those others.  */
    6792         1801 :       if (result)
    6793              :         {
    6794           10 :           tree new_result = make_temp_ssa_name (type, NULL, "reassocpow");
    6795           10 :           mul_stmt = gimple_build_assign (new_result, MULT_EXPR,
    6796              :                                           result, iter_result);
    6797           10 :           gimple_set_location (mul_stmt, gimple_location (stmt));
    6798           10 :           gimple_set_uid (mul_stmt, gimple_uid (stmt));
    6799           10 :           gsi_insert_before (&gsi, mul_stmt, GSI_SAME_STMT);
    6800           10 :           gimple_set_visited (mul_stmt, true);
    6801           10 :           result = new_result;
    6802              :         }
    6803              :       else
    6804              :         result = iter_result;
    6805              : 
    6806              :       /* Decrement the occurrence count of each element in the product
    6807              :          by the count found above, and remove this many copies of each
    6808              :          factor from OPS.  */
    6809         3636 :       for (i = j; i < vec_len; i++)
    6810              :         {
    6811         1835 :           HOST_WIDE_INT k = power;
    6812         1835 :           unsigned n;
    6813              : 
    6814         1835 :           rf1 = &repeat_factor_vec[i];
    6815         1835 :           rf1->count -= power;
    6816              : 
    6817         8748 :           FOR_EACH_VEC_ELT_REVERSE (*ops, n, oe)
    6818              :             {
    6819         5078 :               if (oe->op == rf1->factor)
    6820              :                 {
    6821         4662 :                   if (oe->count <= k)
    6822              :                     {
    6823         4655 :                       ops->ordered_remove (n);
    6824         4655 :                       k -= oe->count;
    6825              : 
    6826         4655 :                       if (k == 0)
    6827              :                         break;
    6828              :                     }
    6829              :                   else
    6830              :                     {
    6831            7 :                       oe->count -= k;
    6832            7 :                       break;
    6833              :                     }
    6834              :                 }
    6835              :             }
    6836              :         }
    6837              :     }
    6838              : 
    6839              :   /* At this point all elements in the repeated factor vector have a
    6840              :      remaining occurrence count of 0 or 1, and those with a count of 1
    6841              :      don't have cached representatives.  Re-sort the ops vector and
    6842              :      clean up.  */
    6843       506668 :   ops->qsort (sort_by_operand_rank);
    6844       506668 :   repeat_factor_vec.release ();
    6845              : 
    6846              :   /* Return the final product computed herein.  Note that there may
    6847              :      still be some elements with single occurrence count left in OPS;
    6848              :      those will be handled by the normal reassociation logic.  */
    6849       506668 :   return result;
    6850              : }
    6851              : 
    6852              : /* Attempt to optimize
    6853              :    CST1 * copysign (CST2, y) -> copysign (CST1 * CST2, y) if CST1 > 0, or
    6854              :    CST1 * copysign (CST2, y) -> -copysign (CST1 * CST2, y) if CST1 < 0.  */
    6855              : 
    6856              : static void
    6857      1120775 : attempt_builtin_copysign (vec<operand_entry *> *ops)
    6858              : {
    6859      1120775 :   operand_entry *oe;
    6860      1120775 :   unsigned int i;
    6861      1120775 :   unsigned int length = ops->length ();
    6862      1120775 :   tree cst = ops->last ()->op;
    6863              : 
    6864      1120775 :   if (length == 1 || TREE_CODE (cst) != REAL_CST)
    6865              :     return;
    6866              : 
    6867         4170 :   FOR_EACH_VEC_ELT (*ops, i, oe)
    6868              :     {
    6869         2973 :       if (TREE_CODE (oe->op) == SSA_NAME
    6870         2973 :           && has_single_use (oe->op))
    6871              :         {
    6872          871 :           gimple *def_stmt = SSA_NAME_DEF_STMT (oe->op);
    6873         3011 :           if (gcall *old_call = dyn_cast <gcall *> (def_stmt))
    6874              :             {
    6875           54 :               tree arg0, arg1;
    6876           54 :               switch (gimple_call_combined_fn (old_call))
    6877              :                 {
    6878           20 :                 CASE_CFN_COPYSIGN:
    6879           20 :                 CASE_CFN_COPYSIGN_FN:
    6880           20 :                   arg0 = gimple_call_arg (old_call, 0);
    6881           20 :                   arg1 = gimple_call_arg (old_call, 1);
    6882              :                   /* The first argument of copysign must be a constant,
    6883              :                      otherwise there's nothing to do.  */
    6884           20 :                   if (TREE_CODE (arg0) == REAL_CST)
    6885              :                     {
    6886           20 :                       tree type = TREE_TYPE (arg0);
    6887           20 :                       tree mul = const_binop (MULT_EXPR, type, cst, arg0);
    6888              :                       /* If we couldn't fold to a single constant, skip it.
    6889              :                          That happens e.g. for inexact multiplication when
    6890              :                          -frounding-math.  */
    6891           20 :                       if (mul == NULL_TREE)
    6892              :                         break;
    6893              :                       /* Instead of adjusting OLD_CALL, let's build a new
    6894              :                          call to not leak the LHS and prevent keeping bogus
    6895              :                          debug statements.  DCE will clean up the old call.  */
    6896           16 :                       gcall *new_call;
    6897           16 :                       if (gimple_call_internal_p (old_call))
    6898            0 :                         new_call = gimple_build_call_internal
    6899            0 :                           (IFN_COPYSIGN, 2, mul, arg1);
    6900              :                       else
    6901           16 :                         new_call = gimple_build_call
    6902           16 :                           (gimple_call_fndecl (old_call), 2, mul, arg1);
    6903           16 :                       tree lhs = make_ssa_name (type);
    6904           16 :                       gimple_call_set_lhs (new_call, lhs);
    6905           16 :                       gimple_set_location (new_call,
    6906              :                                            gimple_location (old_call));
    6907           16 :                       insert_stmt_after (new_call, old_call);
    6908              :                       /* We've used the constant, get rid of it.  */
    6909           16 :                       ops->pop ();
    6910           16 :                       bool cst1_neg = real_isneg (TREE_REAL_CST_PTR (cst));
    6911              :                       /* Handle the CST1 < 0 case by negating the result.  */
    6912           16 :                       if (cst1_neg)
    6913              :                         {
    6914            7 :                           tree negrhs = make_ssa_name (TREE_TYPE (lhs));
    6915            7 :                           gimple *negate_stmt
    6916            7 :                             = gimple_build_assign (negrhs, NEGATE_EXPR, lhs);
    6917            7 :                           insert_stmt_after (negate_stmt, new_call);
    6918            7 :                           oe->op = negrhs;
    6919              :                         }
    6920              :                       else
    6921              :                         oe->op = lhs;
    6922           16 :                       if (dump_file && (dump_flags & TDF_DETAILS))
    6923              :                         {
    6924           14 :                           fprintf (dump_file, "Optimizing copysign: ");
    6925           14 :                           print_generic_expr (dump_file, cst);
    6926           14 :                           fprintf (dump_file, " * COPYSIGN (");
    6927           14 :                           print_generic_expr (dump_file, arg0);
    6928           14 :                           fprintf (dump_file, ", ");
    6929           14 :                           print_generic_expr (dump_file, arg1);
    6930           23 :                           fprintf (dump_file, ") into %sCOPYSIGN (",
    6931              :                                    cst1_neg ? "-" : "");
    6932           14 :                           print_generic_expr (dump_file, mul);
    6933           14 :                           fprintf (dump_file, ", ");
    6934           14 :                           print_generic_expr (dump_file, arg1);
    6935           14 :                           fprintf (dump_file, "\n");
    6936              :                         }
    6937              :                       return;
    6938              :                     }
    6939              :                   break;
    6940              :                 default:
    6941              :                   break;
    6942              :                 }
    6943              :             }
    6944              :         }
    6945              :     }
    6946              : }
    6947              : 
    6948              : /* Transform STMT at *GSI into a copy by replacing its rhs with NEW_RHS.  */
    6949              : 
    6950              : static void
    6951        14582 : transform_stmt_to_copy (gimple_stmt_iterator *gsi, gimple *stmt, tree new_rhs)
    6952              : {
    6953        14582 :   tree rhs1;
    6954              : 
    6955        14582 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6956              :     {
    6957           28 :       fprintf (dump_file, "Transforming ");
    6958           28 :       print_gimple_stmt (dump_file, stmt, 0);
    6959              :     }
    6960              : 
    6961        14582 :   rhs1 = gimple_assign_rhs1 (stmt);
    6962        14582 :   gimple_assign_set_rhs_from_tree (gsi, new_rhs);
    6963        14582 :   update_stmt (stmt);
    6964        14582 :   remove_visited_stmt_chain (rhs1);
    6965              : 
    6966        14582 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6967              :     {
    6968           28 :       fprintf (dump_file, " into ");
    6969           28 :       print_gimple_stmt (dump_file, stmt, 0);
    6970              :     }
    6971        14582 : }
    6972              : 
    6973              : /* Transform STMT at *GSI into a multiply of RHS1 and RHS2.  */
    6974              : 
    6975              : static void
    6976          194 : transform_stmt_to_multiply (gimple_stmt_iterator *gsi, gimple *stmt,
    6977              :                             tree rhs1, tree rhs2)
    6978              : {
    6979          194 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6980              :     {
    6981            0 :       fprintf (dump_file, "Transforming ");
    6982            0 :       print_gimple_stmt (dump_file, stmt, 0);
    6983              :     }
    6984              : 
    6985          194 :   gimple_assign_set_rhs_with_ops (gsi, MULT_EXPR, rhs1, rhs2);
    6986          194 :   update_stmt (gsi_stmt (*gsi));
    6987          194 :   remove_visited_stmt_chain (rhs1);
    6988              : 
    6989          194 :   if (dump_file && (dump_flags & TDF_DETAILS))
    6990              :     {
    6991            0 :       fprintf (dump_file, " into ");
    6992            0 :       print_gimple_stmt (dump_file, stmt, 0);
    6993              :     }
    6994          194 : }
    6995              : 
    6996              : /* Rearrange ops may have more FMA when the chain may has more than 2 FMAs.
    6997              :    Put no-mult ops and mult ops alternately at the end of the queue, which is
    6998              :    conducive to generating more FMA and reducing the loss of FMA when breaking
    6999              :    the chain.
    7000              :    E.g.
    7001              :    a * b + c * d + e generates:
    7002              : 
    7003              :    _4  = c_9(D) * d_10(D);
    7004              :    _12 = .FMA (a_7(D), b_8(D), _4);
    7005              :    _11 = e_6(D) + _12;
    7006              : 
    7007              :    Rearrange ops to -> e + a * b + c * d generates:
    7008              : 
    7009              :    _4  = .FMA (c_7(D), d_8(D), _3);
    7010              :    _11 = .FMA (a_5(D), b_6(D), _4);
    7011              : 
    7012              :    Return the number of MULT_EXPRs in the chain.  */
    7013              : static int
    7014        16950 : rank_ops_for_fma (vec<operand_entry *> *ops)
    7015              : {
    7016        16950 :   operand_entry *oe;
    7017        16950 :   unsigned int i;
    7018        16950 :   unsigned int ops_length = ops->length ();
    7019        16950 :   auto_vec<operand_entry *> ops_mult;
    7020        16950 :   auto_vec<operand_entry *> ops_others;
    7021              : 
    7022        73527 :   FOR_EACH_VEC_ELT (*ops, i, oe)
    7023              :     {
    7024        39627 :       if (TREE_CODE (oe->op) == SSA_NAME)
    7025              :         {
    7026        39611 :           gimple *def_stmt = SSA_NAME_DEF_STMT (oe->op);
    7027        39611 :           if (auto def_assign = dyn_cast<gassign *> (def_stmt))
    7028              :             {
    7029        36184 :               if (gimple_assign_rhs_code (def_assign) == MULT_EXPR)
    7030        13163 :                 ops_mult.safe_push (oe);
    7031              :               /* A negate on the multiplication leads to FNMA.  */
    7032        15183 :               else if (gimple_assign_rhs_code (def_assign) == NEGATE_EXPR
    7033        15183 :                        && (TREE_CODE (gimple_assign_rhs1 (def_assign))
    7034              :                            == SSA_NAME))
    7035              :                 {
    7036         2839 :                   gimple *neg_def_stmt
    7037         2839 :                     = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (def_assign));
    7038         2839 :                   if (is_gimple_assign (neg_def_stmt)
    7039         2836 :                       && gimple_bb (neg_def_stmt) == gimple_bb (def_assign)
    7040         5670 :                       && gimple_assign_rhs_code (neg_def_stmt) == MULT_EXPR)
    7041         2792 :                     ops_mult.safe_push (oe);
    7042              :                   else
    7043           47 :                     ops_others.safe_push (oe);
    7044              :                 }
    7045              :               else
    7046        12344 :                 ops_others.safe_push (oe);
    7047              :             }
    7048              :           else
    7049        11265 :             ops_others.safe_push (oe);
    7050              :         }
    7051              :       else
    7052           16 :         ops_others.safe_push (oe);
    7053              :     }
    7054              :   /* 1. When ops_mult.length == 2, like the following case,
    7055              : 
    7056              :      a * b + c * d + e.
    7057              : 
    7058              :      we need to rearrange the ops.
    7059              : 
    7060              :      Putting ops that not def from mult in front can generate more FMAs.
    7061              : 
    7062              :      2. If all ops are defined with mult, we don't need to rearrange them.  */
    7063        16950 :   unsigned mult_num = ops_mult.length ();
    7064        16950 :   if (mult_num >= 2 && mult_num != ops_length)
    7065              :     {
    7066              :       /* Put no-mult ops and mult ops alternately at the end of the
    7067              :          queue, which is conducive to generating more FMA and reducing the
    7068              :          loss of FMA when breaking the chain.  */
    7069         5299 :       ops->truncate (0);
    7070         5299 :       ops->splice (ops_mult);
    7071         5299 :       int j, opindex = ops->length ();
    7072         5299 :       int others_length = ops_others.length ();
    7073        10603 :       for (j = 0; j < others_length; j++)
    7074              :         {
    7075         5304 :           oe = ops_others.pop ();
    7076         5304 :           ops->quick_insert (opindex, oe);
    7077         5304 :           if (opindex > 0)
    7078         5303 :             opindex--;
    7079              :         }
    7080              :     }
    7081        16950 :   return mult_num;
    7082        16950 : }
    7083              : /* Reassociate expressions in basic block BB and its post-dominator as
    7084              :    children.
    7085              : 
    7086              :    Bubble up return status from maybe_optimize_range_tests.  */
    7087              : 
    7088              : static bool
    7089     19990095 : reassociate_bb (basic_block bb)
    7090              : {
    7091     19990095 :   gimple_stmt_iterator gsi;
    7092     19990095 :   gimple *stmt = last_nondebug_stmt (bb);
    7093     19990095 :   bool cfg_cleanup_needed = false;
    7094              : 
    7095     19990095 :   if (stmt && !gimple_visited_p (stmt))
    7096     19351457 :     cfg_cleanup_needed |= maybe_optimize_range_tests (stmt);
    7097              : 
    7098     19990095 :   bool do_prev = false;
    7099     39980190 :   for (gsi = gsi_last_bb (bb);
    7100    381096019 :        !gsi_end_p (gsi); do_prev ? gsi_prev (&gsi) : (void) 0)
    7101              :     {
    7102    180553194 :       do_prev = true;
    7103    180553194 :       stmt = gsi_stmt (gsi);
    7104              : 
    7105    229760260 :       if (dyn_cast<gassign *> (stmt)
    7106     49207530 :           && !stmt_could_throw_p (cfun, stmt))
    7107              :         {
    7108     47179025 :           tree lhs, rhs1, rhs2;
    7109     47179025 :           enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
    7110              : 
    7111              :           /* If this was part of an already processed statement,
    7112              :              we don't need to touch it again. */
    7113     47179025 :           if (gimple_visited_p (stmt))
    7114              :             {
    7115              :               /* This statement might have become dead because of previous
    7116              :                  reassociations.  */
    7117       408614 :               if (has_zero_uses (gimple_get_lhs (stmt)))
    7118              :                 {
    7119       139807 :                   reassoc_remove_stmt (&gsi);
    7120       139807 :                   release_defs (stmt);
    7121              :                   /* We might end up removing the last stmt above which
    7122              :                      places the iterator to the end of the sequence.
    7123              :                      Reset it to the last stmt in this case and make sure
    7124              :                      we don't do gsi_prev in that case.  */
    7125       139807 :                   if (gsi_end_p (gsi))
    7126              :                     {
    7127          464 :                       gsi = gsi_last_bb (bb);
    7128          464 :                       do_prev = false;
    7129              :                     }
    7130              :                 }
    7131       408614 :               continue;
    7132              :             }
    7133              : 
    7134              :           /* If this is not a gimple binary expression, there is
    7135              :              nothing for us to do with it.  */
    7136     46770411 :           if (get_gimple_rhs_class (rhs_code) != GIMPLE_BINARY_RHS)
    7137     34615946 :             continue;
    7138              : 
    7139     12154465 :           lhs = gimple_assign_lhs (stmt);
    7140     12154465 :           rhs1 = gimple_assign_rhs1 (stmt);
    7141     12154465 :           rhs2 = gimple_assign_rhs2 (stmt);
    7142              : 
    7143              :           /* For non-bit or min/max operations we can't associate
    7144              :              all types.  Verify that here.  */
    7145     17873872 :           if ((rhs_code != BIT_IOR_EXPR
    7146     12154465 :                && rhs_code != BIT_AND_EXPR
    7147     11138235 :                && rhs_code != BIT_XOR_EXPR
    7148     11138235 :                && rhs_code != MIN_EXPR
    7149     10990369 :                && rhs_code != MAX_EXPR
    7150     10845565 :                && !can_reassociate_type_p (TREE_TYPE (lhs)))
    7151      6439730 :               || !can_reassociate_op_p (rhs1)
    7152     18591109 :               || !can_reassociate_op_p (rhs2))
    7153      5719407 :             continue;
    7154              : 
    7155      6435058 :           if (associative_tree_code (rhs_code))
    7156              :             {
    7157      4859381 :               auto_vec<operand_entry *> ops;
    7158      4859381 :               tree powi_result = NULL_TREE;
    7159      4859381 :               bool is_vector = VECTOR_TYPE_P (TREE_TYPE (lhs));
    7160              : 
    7161              :               /* There may be no immediate uses left by the time we
    7162              :                  get here because we may have eliminated them all.  */
    7163      4859381 :               if (TREE_CODE (lhs) == SSA_NAME && has_zero_uses (lhs))
    7164        47777 :                 continue;
    7165              : 
    7166      4811604 :               gimple_set_visited (stmt, true);
    7167      4811604 :               linearize_expr_tree (&ops, stmt, true, true);
    7168      4811604 :               ops.qsort (sort_by_operand_rank);
    7169      4811604 :               int orig_len = ops.length ();
    7170      4811604 :               optimize_ops_list (rhs_code, &ops);
    7171      9623208 :               if (undistribute_ops_list (rhs_code, &ops,
    7172              :                                          loop_containing_stmt (stmt)))
    7173              :                 {
    7174          324 :                   ops.qsort (sort_by_operand_rank);
    7175          324 :                   optimize_ops_list (rhs_code, &ops);
    7176              :                 }
    7177      9623208 :               if (undistribute_bitref_for_vector (rhs_code, &ops,
    7178              :                                                   loop_containing_stmt (stmt)))
    7179              :                 {
    7180           36 :                   ops.qsort (sort_by_operand_rank);
    7181           36 :                   optimize_ops_list (rhs_code, &ops);
    7182              :                 }
    7183      4811604 :               if (rhs_code == PLUS_EXPR
    7184      4811604 :                   && transform_add_to_multiply (&ops))
    7185           73 :                 ops.qsort (sort_by_operand_rank);
    7186              : 
    7187      4811604 :               if (rhs_code == BIT_IOR_EXPR || rhs_code == BIT_AND_EXPR)
    7188              :                 {
    7189      1000899 :                   if (is_vector)
    7190        27281 :                     optimize_vec_cond_expr (rhs_code, &ops);
    7191              :                   else
    7192       973618 :                     optimize_range_tests (rhs_code, &ops, NULL);
    7193              :                 }
    7194              : 
    7195      4811604 :               if (rhs_code == MULT_EXPR && !is_vector)
    7196              :                 {
    7197      1120775 :                   attempt_builtin_copysign (&ops);
    7198              : 
    7199      1120775 :                   if (reassoc_insert_powi_p
    7200      1120775 :                       && (flag_unsafe_math_optimizations
    7201       463192 :                           || (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))))
    7202       506668 :                     powi_result = attempt_builtin_powi (stmt, &ops);
    7203              :                 }
    7204              : 
    7205      4811604 :               operand_entry *last;
    7206      4811604 :               bool negate_result = false;
    7207      4811604 :               if (ops.length () > 1
    7208      4811604 :                   && rhs_code == MULT_EXPR)
    7209              :                 {
    7210      1144688 :                   last = ops.last ();
    7211      1144688 :                   if ((integer_minus_onep (last->op)
    7212      1144168 :                        || real_minus_onep (last->op))
    7213          547 :                       && !HONOR_SNANS (TREE_TYPE (lhs))
    7214      1145235 :                       && (!HONOR_SIGNED_ZEROS (TREE_TYPE (lhs))
    7215            0 :                           || !COMPLEX_FLOAT_TYPE_P (TREE_TYPE (lhs))))
    7216              :                     {
    7217          547 :                       ops.pop ();
    7218          547 :                       negate_result = true;
    7219              :                     }
    7220              :                 }
    7221              : 
    7222      4811604 :               tree new_lhs = lhs;
    7223              :               /* If the operand vector is now empty, all operands were
    7224              :                  consumed by the __builtin_powi optimization.  */
    7225      4811604 :               if (ops.length () == 0)
    7226         1467 :                 transform_stmt_to_copy (&gsi, stmt, powi_result);
    7227      4810137 :               else if (ops.length () == 1)
    7228              :                 {
    7229        13309 :                   tree last_op = ops.last ()->op;
    7230              : 
    7231              :                   /* If the stmt that defines operand has to be inserted, insert it
    7232              :                      before the use.  */
    7233        13309 :                   if (ops.last ()->stmt_to_insert)
    7234            0 :                     insert_stmt_before_use (stmt, ops.last ()->stmt_to_insert);
    7235        13309 :                   if (powi_result)
    7236          194 :                     transform_stmt_to_multiply (&gsi, stmt, last_op,
    7237              :                                                 powi_result);
    7238              :                   else
    7239        13115 :                     transform_stmt_to_copy (&gsi, stmt, last_op);
    7240              :                 }
    7241              :               else
    7242              :                 {
    7243      4796828 :                   machine_mode mode = TYPE_MODE (TREE_TYPE (lhs));
    7244      4796828 :                   int ops_num = ops.length ();
    7245      4796828 :                   int width = 0;
    7246      4796828 :                   int mult_num = 0;
    7247              : 
    7248              :                   /* For binary bit operations, if there are at least 3
    7249              :                      operands and the last operand in OPS is a constant,
    7250              :                      move it to the front.  This helps ensure that we generate
    7251              :                      (X & Y) & C rather than (X & C) & Y.  The former will
    7252              :                      often match a canonical bit test when we get to RTL.  */
    7253      4796828 :                   if (ops.length () > 2
    7254       184254 :                       && (rhs_code == BIT_AND_EXPR
    7255              :                           || rhs_code == BIT_IOR_EXPR
    7256       160870 :                           || rhs_code == BIT_XOR_EXPR)
    7257      4824851 :                       && TREE_CODE (ops.last ()->op) == INTEGER_CST)
    7258         1787 :                     std::swap (*ops[0], *ops[ops_num - 1]);
    7259              : 
    7260      4796828 :                   optimization_type opt_type = bb_optimization_type (bb);
    7261              : 
    7262              :                   /* If the target support FMA, rank_ops_for_fma will detect if
    7263              :                      the chain has fmas and rearrange the ops if so.  */
    7264      4796828 :                   if (!reassoc_insert_powi_p
    7265      2960684 :                       && direct_internal_fn_supported_p (IFN_FMA,
    7266      2960684 :                                                          TREE_TYPE (lhs),
    7267              :                                                          opt_type)
    7268      4831699 :                       && (rhs_code == PLUS_EXPR || rhs_code == MINUS_EXPR))
    7269              :                     {
    7270        16950 :                       mult_num = rank_ops_for_fma (&ops);
    7271              :                     }
    7272              : 
    7273              :                   /* A chain that expands to a conditional compare sequence
    7274              :                      has to stay linear.  Every conditional compare tests the
    7275              :                      flags that the previous comparison set, so the sequence
    7276              :                      cannot be split into independent parts.  */
    7277      4796828 :                   bool ccmp_chain = (ops_num > 2
    7278      4796828 :                                      && prepare_ccmp_chain (ops, rhs_code, bb));
    7279              : 
    7280              :                   /* Only rewrite the expression tree to parallel in the
    7281              :                      last reassoc pass to avoid useless work back-and-forth
    7282              :                      with initial linearization.  */
    7283      4796828 :                   bool has_fma = mult_num >= 2 && mult_num != ops_num;
    7284      4796828 :                   if (!reassoc_insert_powi_p
    7285      2960684 :                       && !ccmp_chain
    7286      2960684 :                       && ops.length () > 3
    7287      4811087 :                       && (width = get_reassociation_width (&ops, mult_num, lhs,
    7288              :                                                            rhs_code, mode))
    7289              :                            > 1)
    7290              :                     {
    7291         1965 :                       if (dump_file && (dump_flags & TDF_DETAILS))
    7292            2 :                         fprintf (dump_file,
    7293              :                                  "Width = %d was chosen for reassociation\n",
    7294              :                                  width);
    7295         1965 :                       rewrite_expr_tree_parallel (as_a<gassign *> (stmt),
    7296              :                                                   width,
    7297              :                                                   has_fma,
    7298              :                                                   ops);
    7299              :                     }
    7300              :                   else
    7301              :                     {
    7302              :                       /* When there are three operands left, we want
    7303              :                          to make sure the ones that get the double
    7304              :                          binary op are chosen wisely.  */
    7305      4794863 :                       int len = ops.length ();
    7306      7753582 :                       if (!reassoc_insert_powi_p && !ccmp_chain
    7307      2958719 :                           && len >= 3
    7308      4925456 :                           && (!has_fma
    7309              :                               /* width > 1 means ranking ops results in better
    7310              :                                  parallelism.  Check current value to avoid
    7311              :                                  calling get_reassociation_width again.  */
    7312         5295 :                               || (width != 1
    7313         5295 :                                   && get_reassociation_width (
    7314              :                                        &ops, mult_num, lhs, rhs_code, mode)
    7315              :                                        > 1)))
    7316       127337 :                         swap_ops_for_binary_stmt (ops, len - 3);
    7317              : 
    7318      4794863 :                       new_lhs = rewrite_expr_tree (stmt, rhs_code, 0, ops,
    7319      4794863 :                                                    powi_result != NULL
    7320              :                                                    || negate_result,
    7321              :                                                    len != orig_len);
    7322              :                     }
    7323              : 
    7324              :                   /* If we combined some repeated factors into a
    7325              :                      __builtin_powi call, multiply that result by the
    7326              :                      reassociated operands.  */
    7327      4796828 :                   if (powi_result)
    7328              :                     {
    7329          130 :                       gimple *mul_stmt, *lhs_stmt = SSA_NAME_DEF_STMT (lhs);
    7330          130 :                       tree type = TREE_TYPE (lhs);
    7331          130 :                       tree target_ssa = make_temp_ssa_name (type, NULL,
    7332              :                                                             "reassocpow");
    7333          130 :                       gimple_set_lhs (lhs_stmt, target_ssa);
    7334          130 :                       update_stmt (lhs_stmt);
    7335          130 :                       if (lhs != new_lhs)
    7336              :                         {
    7337          130 :                           target_ssa = new_lhs;
    7338          130 :                           new_lhs = lhs;
    7339              :                         }
    7340          130 :                       mul_stmt = gimple_build_assign (lhs, MULT_EXPR,
    7341              :                                                       powi_result, target_ssa);
    7342          130 :                       gimple_set_location (mul_stmt, gimple_location (stmt));
    7343          130 :                       gimple_set_uid (mul_stmt, gimple_uid (stmt));
    7344          130 :                       gsi_insert_after (&gsi, mul_stmt, GSI_NEW_STMT);
    7345              :                     }
    7346              :                 }
    7347              : 
    7348      4811604 :               if (negate_result)
    7349              :                 {
    7350          547 :                   stmt = SSA_NAME_DEF_STMT (lhs);
    7351          547 :                   tree tmp = make_ssa_name (TREE_TYPE (lhs));
    7352          547 :                   gimple_set_lhs (stmt, tmp);
    7353          547 :                   if (lhs != new_lhs)
    7354          537 :                     tmp = new_lhs;
    7355          547 :                   gassign *neg_stmt = gimple_build_assign (lhs, NEGATE_EXPR,
    7356              :                                                            tmp);
    7357          547 :                   gimple_set_uid (neg_stmt, gimple_uid (stmt));
    7358          547 :                   gsi_insert_after (&gsi, neg_stmt, GSI_NEW_STMT);
    7359          547 :                   update_stmt (stmt);
    7360              :                 }
    7361      4859381 :             }
    7362              :         }
    7363              :     }
    7364              : 
    7365     19990095 :   return cfg_cleanup_needed;
    7366              : }
    7367              : 
    7368              : /* Add jumps around shifts for range tests turned into bit tests.
    7369              :    For each SSA_NAME VAR we have code like:
    7370              :    VAR = ...; // final stmt of range comparison
    7371              :    // bit test here...;
    7372              :    OTHERVAR = ...; // final stmt of the bit test sequence
    7373              :    RES = VAR | OTHERVAR;
    7374              :    Turn the above into:
    7375              :    VAR = ...;
    7376              :    if (VAR != 0)
    7377              :      goto <l3>;
    7378              :    else
    7379              :      goto <l2>;
    7380              :    <l2>:
    7381              :    // bit test here...;
    7382              :    OTHERVAR = ...;
    7383              :    <l3>:
    7384              :    # RES = PHI<1(l1), OTHERVAR(l2)>;  */
    7385              : 
    7386              : static void
    7387      2136209 : branch_fixup (void)
    7388              : {
    7389      2136209 :   tree var;
    7390      2136209 :   unsigned int i;
    7391              : 
    7392      2136596 :   FOR_EACH_VEC_ELT (reassoc_branch_fixups, i, var)
    7393              :     {
    7394          387 :       gimple *def_stmt = SSA_NAME_DEF_STMT (var);
    7395          387 :       gimple *use_stmt;
    7396          387 :       use_operand_p use;
    7397          387 :       bool ok = single_imm_use (var, &use, &use_stmt);
    7398          387 :       gcc_assert (ok
    7399              :                   && is_gimple_assign (use_stmt)
    7400              :                   && gimple_assign_rhs_code (use_stmt) == BIT_IOR_EXPR
    7401              :                   && gimple_bb (def_stmt) == gimple_bb (use_stmt));
    7402              : 
    7403          387 :       basic_block cond_bb = gimple_bb (def_stmt);
    7404          387 :       basic_block then_bb = split_block (cond_bb, def_stmt)->dest;
    7405          387 :       basic_block merge_bb = split_block (then_bb, use_stmt)->dest;
    7406              : 
    7407          387 :       gimple_stmt_iterator gsi = gsi_for_stmt (def_stmt);
    7408          387 :       gimple *g = gimple_build_cond (NE_EXPR, var,
    7409          387 :                                      build_zero_cst (TREE_TYPE (var)),
    7410              :                                      NULL_TREE, NULL_TREE);
    7411          387 :       location_t loc = gimple_location (use_stmt);
    7412          387 :       gimple_set_location (g, loc);
    7413          387 :       gsi_insert_after (&gsi, g, GSI_NEW_STMT);
    7414              : 
    7415          387 :       edge etrue = make_edge (cond_bb, merge_bb, EDGE_TRUE_VALUE);
    7416          387 :       etrue->probability = profile_probability::even ();
    7417          387 :       edge efalse = find_edge (cond_bb, then_bb);
    7418          387 :       efalse->flags = EDGE_FALSE_VALUE;
    7419          387 :       efalse->probability -= etrue->probability;
    7420          387 :       then_bb->count -= etrue->count ();
    7421              : 
    7422          387 :       tree othervar = NULL_TREE;
    7423          387 :       if (gimple_assign_rhs1 (use_stmt) == var)
    7424          280 :         othervar = gimple_assign_rhs2 (use_stmt);
    7425          107 :       else if (gimple_assign_rhs2 (use_stmt) == var)
    7426              :         othervar = gimple_assign_rhs1 (use_stmt);
    7427              :       else
    7428            0 :         gcc_unreachable ();
    7429          387 :       tree lhs = gimple_assign_lhs (use_stmt);
    7430          387 :       gphi *phi = create_phi_node (lhs, merge_bb);
    7431          387 :       add_phi_arg (phi, build_one_cst (TREE_TYPE (lhs)), etrue, loc);
    7432          387 :       add_phi_arg (phi, othervar, single_succ_edge (then_bb), loc);
    7433          387 :       gsi = gsi_for_stmt (use_stmt);
    7434          387 :       gsi_remove (&gsi, true);
    7435              : 
    7436          387 :       set_immediate_dominator (CDI_DOMINATORS, merge_bb, cond_bb);
    7437          387 :       set_immediate_dominator (CDI_POST_DOMINATORS, cond_bb, merge_bb);
    7438              :     }
    7439      2136209 :   reassoc_branch_fixups.release ();
    7440      2136209 : }
    7441              : 
    7442              : void dump_ops_vector (FILE *file, vec<operand_entry *> ops);
    7443              : void debug_ops_vector (vec<operand_entry *> ops);
    7444              : 
    7445              : /* Dump the operand entry vector OPS to FILE.  */
    7446              : 
    7447              : void
    7448            0 : dump_ops_vector (FILE *file, vec<operand_entry *> ops)
    7449              : {
    7450            0 :   operand_entry *oe;
    7451            0 :   unsigned int i;
    7452              : 
    7453            0 :   FOR_EACH_VEC_ELT (ops, i, oe)
    7454              :     {
    7455            0 :       fprintf (file, "Op %d -> rank: %d, tree: ", i, oe->rank);
    7456            0 :       print_generic_expr (file, oe->op);
    7457            0 :       fprintf (file, "\n");
    7458              :     }
    7459            0 : }
    7460              : 
    7461              : /* Dump the operand entry vector OPS to STDERR.  */
    7462              : 
    7463              : DEBUG_FUNCTION void
    7464            0 : debug_ops_vector (vec<operand_entry *> ops)
    7465              : {
    7466            0 :   dump_ops_vector (stderr, ops);
    7467            0 : }
    7468              : 
    7469              : /* Bubble up return status from reassociate_bb.  */
    7470              : 
    7471              : static bool
    7472      2136209 : do_reassoc ()
    7473              : {
    7474      2136209 :   bool cfg_cleanup_needed = false;
    7475      2136209 :   basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
    7476              : 
    7477      2136209 :   unsigned sp = 0;
    7478      2136209 :   for (auto son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
    7479      4272418 :        son; son = next_dom_son (CDI_DOMINATORS, son))
    7480      2136209 :     worklist[sp++] = son;
    7481     22126355 :   while (sp)
    7482              :     {
    7483     19990146 :       basic_block bb = worklist[--sp];
    7484     19990146 :       break_up_subtract_bb (bb);
    7485     19990146 :       for (auto son = first_dom_son (CDI_DOMINATORS, bb);
    7486     37844083 :            son; son = next_dom_son (CDI_DOMINATORS, son))
    7487     17853937 :         worklist[sp++] = son;
    7488              :     }
    7489              : 
    7490     10999183 :   for (auto son = first_dom_son (CDI_POST_DOMINATORS,
    7491      2136209 :                                  EXIT_BLOCK_PTR_FOR_FN (cfun));
    7492     10999183 :        son; son = next_dom_son (CDI_POST_DOMINATORS, son))
    7493      8862974 :     worklist[sp++] = son;
    7494     22126304 :   while (sp)
    7495              :     {
    7496     19990095 :       basic_block bb = worklist[--sp];
    7497     19990095 :       cfg_cleanup_needed |= reassociate_bb (bb);
    7498     19990095 :       for (auto son = first_dom_son (CDI_POST_DOMINATORS, bb);
    7499     31117216 :            son; son = next_dom_son (CDI_POST_DOMINATORS, son))
    7500     11127121 :         worklist[sp++] = son;
    7501              :     }
    7502              : 
    7503      2136209 :   free (worklist);
    7504      2136209 :   return cfg_cleanup_needed;
    7505              : }
    7506              : 
    7507              : /* Initialize the reassociation pass.  */
    7508              : 
    7509              : static void
    7510      2136209 : init_reassoc (void)
    7511              : {
    7512      2136209 :   int i;
    7513      2136209 :   int64_t rank = 2;
    7514      2136209 :   int *bbs = XNEWVEC (int, n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS);
    7515              : 
    7516              :   /* Find the loops, so that we can prevent moving calculations in
    7517              :      them.  */
    7518      2136209 :   loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
    7519              : 
    7520      2136209 :   memset (&reassociate_stats, 0, sizeof (reassociate_stats));
    7521              : 
    7522      2136209 :   next_operand_entry_id = 0;
    7523              : 
    7524              :   /* Reverse RPO (Reverse Post Order) will give us something where
    7525              :      deeper loops come later.  */
    7526      2136209 :   pre_and_rev_post_order_compute (NULL, bbs, false);
    7527      2136209 :   bb_rank = XCNEWVEC (int64_t, last_basic_block_for_fn (cfun));
    7528      2136209 :   operand_rank = new hash_map<tree, int64_t>;
    7529              : 
    7530              :   /* Give each default definition a distinct rank.  This includes
    7531              :      parameters and the static chain.  Walk backwards over all
    7532              :      SSA names so that we get proper rank ordering according
    7533              :      to tree_swap_operands_p.  */
    7534    113505589 :   for (i = num_ssa_names - 1; i > 0; --i)
    7535              :     {
    7536    109233171 :       tree name = ssa_name (i);
    7537    186599641 :       if (name && SSA_NAME_IS_DEFAULT_DEF (name))
    7538      6344571 :         insert_operand_rank (name, ++rank);
    7539              :     }
    7540              : 
    7541              :   /* Set up rank for each BB  */
    7542     22126304 :   for (i = 0; i < n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS; i++)
    7543     19990095 :     bb_rank[bbs[i]] = ++rank << 16;
    7544              : 
    7545      2136209 :   free (bbs);
    7546      2136209 :   calculate_dominance_info (CDI_POST_DOMINATORS);
    7547      2136209 :   plus_negates = vNULL;
    7548      2136209 :   mark_ssa_maybe_undefs ();
    7549      2136209 : }
    7550              : 
    7551              : /* Cleanup after the reassociation pass, and print stats if
    7552              :    requested.  */
    7553              : 
    7554              : static void
    7555      2136209 : fini_reassoc (void)
    7556              : {
    7557      2136209 :   statistics_counter_event (cfun, "Linearized",
    7558              :                             reassociate_stats.linearized);
    7559      2136209 :   statistics_counter_event (cfun, "Constants eliminated",
    7560              :                             reassociate_stats.constants_eliminated);
    7561      2136209 :   statistics_counter_event (cfun, "Ops eliminated",
    7562              :                             reassociate_stats.ops_eliminated);
    7563      2136209 :   statistics_counter_event (cfun, "Statements rewritten",
    7564              :                             reassociate_stats.rewritten);
    7565      2136209 :   statistics_counter_event (cfun, "Built-in pow[i] calls encountered",
    7566              :                             reassociate_stats.pows_encountered);
    7567      2136209 :   statistics_counter_event (cfun, "Built-in powi calls created",
    7568              :                             reassociate_stats.pows_created);
    7569              : 
    7570      4272418 :   delete operand_rank;
    7571      2136209 :   bitmap_clear (biased_names);
    7572      2136209 :   operand_entry_pool.release ();
    7573      2136209 :   free (bb_rank);
    7574      2136209 :   plus_negates.release ();
    7575      2136209 :   free_dominance_info (CDI_POST_DOMINATORS);
    7576      2136209 :   loop_optimizer_finalize ();
    7577      2136209 : }
    7578              : 
    7579              : /* Gate and execute functions for Reassociation.  If INSERT_POWI_P, enable
    7580              :    insertion of __builtin_powi calls.
    7581              : 
    7582              :    Returns TODO_cfg_cleanup if a CFG cleanup pass is desired due to
    7583              :    optimization of a gimple conditional.  Otherwise returns zero.  */
    7584              : 
    7585              : static unsigned int
    7586      2136209 : execute_reassoc (bool insert_powi_p, bool bias_loop_carried_phi_ranks_p)
    7587              : {
    7588      2136209 :   reassoc_insert_powi_p = insert_powi_p;
    7589      2136209 :   reassoc_bias_loop_carried_phi_ranks_p = bias_loop_carried_phi_ranks_p;
    7590              : 
    7591      2136209 :   init_reassoc ();
    7592              : 
    7593      2136209 :   bool cfg_cleanup_needed;
    7594      2136209 :   cfg_cleanup_needed = do_reassoc ();
    7595      2136209 :   repropagate_negates ();
    7596      2136209 :   branch_fixup ();
    7597              : 
    7598      2136209 :   fini_reassoc ();
    7599      2136209 :   return cfg_cleanup_needed ? TODO_cleanup_cfg : 0;
    7600              : }
    7601              : 
    7602              : namespace {
    7603              : 
    7604              : const pass_data pass_data_reassoc =
    7605              : {
    7606              :   GIMPLE_PASS, /* type */
    7607              :   "reassoc", /* name */
    7608              :   OPTGROUP_NONE, /* optinfo_flags */
    7609              :   TV_TREE_REASSOC, /* tv_id */
    7610              :   ( PROP_cfg | PROP_ssa ), /* properties_required */
    7611              :   0, /* properties_provided */
    7612              :   0, /* properties_destroyed */
    7613              :   0, /* todo_flags_start */
    7614              :   TODO_update_ssa_only_virtuals, /* todo_flags_finish */
    7615              : };
    7616              : 
    7617              : class pass_reassoc : public gimple_opt_pass
    7618              : {
    7619              : public:
    7620       605970 :   pass_reassoc (gcc::context *ctxt)
    7621      1211940 :     : gimple_opt_pass (pass_data_reassoc, ctxt), insert_powi_p (false)
    7622              :   {}
    7623              : 
    7624              :   /* opt_pass methods: */
    7625       302985 :   opt_pass * clone () final override { return new pass_reassoc (m_ctxt); }
    7626       605970 :   void set_pass_param (unsigned int n, bool param) final override
    7627              :     {
    7628       605970 :       gcc_assert (n == 0);
    7629       605970 :       insert_powi_p = param;
    7630       605970 :       bias_loop_carried_phi_ranks_p = !param;
    7631       605970 :     }
    7632      2136602 :   bool gate (function *) final override { return flag_tree_reassoc != 0; }
    7633      2136209 :   unsigned int execute (function *) final override
    7634              :   {
    7635      2136209 :     return execute_reassoc (insert_powi_p, bias_loop_carried_phi_ranks_p);
    7636              :   }
    7637              : 
    7638              :  private:
    7639              :   /* Enable insertion of __builtin_powi calls during execute_reassoc.  See
    7640              :      point 3a in the pass header comment.  */
    7641              :   bool insert_powi_p;
    7642              :   bool bias_loop_carried_phi_ranks_p;
    7643              : }; // class pass_reassoc
    7644              : 
    7645              : } // anon namespace
    7646              : 
    7647              : gimple_opt_pass *
    7648       302985 : make_pass_reassoc (gcc::context *ctxt)
    7649              : {
    7650       302985 :   return new pass_reassoc (ctxt);
    7651              : }
        

Generated by: LCOV version 2.6-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.