LCOV - code coverage report
Current view: top level - gcc - tree-vect-loop.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 88.8 % 5260 4671
Test Date: 2026-12-05 16:10:02 Functions: 95.2 % 104 99
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Loop Vectorization
       2              :    Copyright (C) 2003-2026 Free Software Foundation, Inc.
       3              :    Contributed by Dorit Naishlos <dorit@il.ibm.com> and
       4              :    Ira Rosen <irar@il.ibm.com>
       5              : 
       6              : This file is part of GCC.
       7              : 
       8              : GCC is free software; you can redistribute it and/or modify it under
       9              : the terms of the GNU General Public License as published by the Free
      10              : Software Foundation; either version 3, or (at your option) any later
      11              : version.
      12              : 
      13              : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
      14              : WARRANTY; without even the implied warranty of MERCHANTABILITY or
      15              : FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      16              : for more details.
      17              : 
      18              : You should have received a copy of the GNU General Public License
      19              : along with GCC; see the file COPYING3.  If not see
      20              : <http://www.gnu.org/licenses/>.  */
      21              : 
      22              : #define INCLUDE_ALGORITHM
      23              : #include "config.h"
      24              : #include "system.h"
      25              : #include "coretypes.h"
      26              : #include "backend.h"
      27              : #include "target.h"
      28              : #include "rtl.h"
      29              : #include "tree.h"
      30              : #include "gimple.h"
      31              : #include "cfghooks.h"
      32              : #include "tree-pass.h"
      33              : #include "ssa.h"
      34              : #include "optabs-tree.h"
      35              : #include "memmodel.h"
      36              : #include "optabs.h"
      37              : #include "diagnostic-core.h"
      38              : #include "fold-const.h"
      39              : #include "stor-layout.h"
      40              : #include "cfganal.h"
      41              : #include "gimplify.h"
      42              : #include "gimple-iterator.h"
      43              : #include "gimplify-me.h"
      44              : #include "tree-ssa-loop-ivopts.h"
      45              : #include "tree-ssa-loop-manip.h"
      46              : #include "tree-ssa-loop-niter.h"
      47              : #include "tree-ssa-loop.h"
      48              : #include "cfgloop.h"
      49              : #include "tree-scalar-evolution.h"
      50              : #include "tree-vectorizer.h"
      51              : #include "gimple-fold.h"
      52              : #include "cgraph.h"
      53              : #include "tree-cfg.h"
      54              : #include "tree-if-conv.h"
      55              : #include "internal-fn.h"
      56              : #include "tree-vector-builder.h"
      57              : #include "vec-perm-indices.h"
      58              : #include "tree-eh.h"
      59              : #include "case-cfn-macros.h"
      60              : #include "langhooks.h"
      61              : #include "opts.h"
      62              : #include "hierarchical_discriminator.h"
      63              : 
      64              : /* Loop Vectorization Pass.
      65              : 
      66              :    This pass tries to vectorize loops.
      67              : 
      68              :    For example, the vectorizer transforms the following simple loop:
      69              : 
      70              :         short a[N]; short b[N]; short c[N]; int i;
      71              : 
      72              :         for (i=0; i<N; i++){
      73              :           a[i] = b[i] + c[i];
      74              :         }
      75              : 
      76              :    as if it was manually vectorized by rewriting the source code into:
      77              : 
      78              :         typedef int __attribute__((mode(V8HI))) v8hi;
      79              :         short a[N];  short b[N]; short c[N];   int i;
      80              :         v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
      81              :         v8hi va, vb, vc;
      82              : 
      83              :         for (i=0; i<N/8; i++){
      84              :           vb = pb[i];
      85              :           vc = pc[i];
      86              :           va = vb + vc;
      87              :           pa[i] = va;
      88              :         }
      89              : 
      90              :         The main entry to this pass is vectorize_loops(), in which
      91              :    the vectorizer applies a set of analyses on a given set of loops,
      92              :    followed by the actual vectorization transformation for the loops that
      93              :    had successfully passed the analysis phase.
      94              :         Throughout this pass we make a distinction between two types of
      95              :    data: scalars (which are represented by SSA_NAMES), and memory references
      96              :    ("data-refs").  These two types of data require different handling both
      97              :    during analysis and transformation. The types of data-refs that the
      98              :    vectorizer currently supports are ARRAY_REFS which base is an array DECL
      99              :    (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
     100              :    accesses are required to have a simple (consecutive) access pattern.
     101              : 
     102              :    Analysis phase:
     103              :    ===============
     104              :         The driver for the analysis phase is vect_analyze_loop().
     105              :    It applies a set of analyses, some of which rely on the scalar evolution
     106              :    analyzer (scev) developed by Sebastian Pop.
     107              : 
     108              :         During the analysis phase the vectorizer records some information
     109              :    per stmt in a "stmt_vec_info" struct which is attached to each stmt in the
     110              :    loop, as well as general information about the loop as a whole, which is
     111              :    recorded in a "loop_vec_info" struct attached to each loop.
     112              : 
     113              :    Transformation phase:
     114              :    =====================
     115              :         The loop transformation phase scans all the stmts in the loop, and
     116              :    creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
     117              :    the loop that needs to be vectorized.  It inserts the vector code sequence
     118              :    just before the scalar stmt S, and records a pointer to the vector code
     119              :    in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct
     120              :    attached to S).  This pointer will be used for the vectorization of following
     121              :    stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
     122              :    otherwise, we rely on dead code elimination for removing it.
     123              : 
     124              :         For example, say stmt S1 was vectorized into stmt VS1:
     125              : 
     126              :    VS1: vb = px[i];
     127              :    S1:  b = x[i];    STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
     128              :    S2:  a = b;
     129              : 
     130              :    To vectorize stmt S2, the vectorizer first finds the stmt that defines
     131              :    the operand 'b' (S1), and gets the relevant vector def 'vb' from the
     132              :    vector stmt VS1 pointed to by STMT_VINFO_VEC_STMT (stmt_info (S1)).  The
     133              :    resulting sequence would be:
     134              : 
     135              :    VS1: vb = px[i];
     136              :    S1:  b = x[i];       STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
     137              :    VS2: va = vb;
     138              :    S2:  a = b;          STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
     139              : 
     140              :         Operands that are not SSA_NAMEs, are data-refs that appear in
     141              :    load/store operations (like 'x[i]' in S1), and are handled differently.
     142              : 
     143              :    Target modeling:
     144              :    =================
     145              :         Currently the only target specific information that is used is the
     146              :    size of the vector (in bytes) - "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".
     147              :    Targets that can support different sizes of vectors, for now will need
     148              :    to specify one value for "TARGET_VECTORIZE_UNITS_PER_SIMD_WORD".  More
     149              :    flexibility will be added in the future.
     150              : 
     151              :         Since we only vectorize operations which vector form can be
     152              :    expressed using existing tree codes, to verify that an operation is
     153              :    supported, the vectorizer checks the relevant optab at the relevant
     154              :    machine_mode (e.g, optab_handler (add_optab, V8HImode)).  If
     155              :    the value found is CODE_FOR_nothing, then there's no target support, and
     156              :    we can't vectorize the stmt.
     157              : 
     158              :    For additional information on this project see:
     159              :    http://gcc.gnu.org/projects/tree-ssa/vectorization.html
     160              : */
     161              : 
     162              : static void vect_estimate_min_profitable_iters (loop_vec_info, int *, int *,
     163              :                                                 unsigned *);
     164              : static stmt_vec_info vect_is_simple_reduction (loop_vec_info, stmt_vec_info,
     165              :                                                gphi **);
     166              : 
     167              : 
     168              : /* Function vect_is_simple_iv_evolution.
     169              : 
     170              :    FORNOW: A simple evolution of an induction variables in the loop is
     171              :    considered a polynomial evolution.  */
     172              : 
     173              : static bool
     174       971769 : vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn,
     175              :                              stmt_vec_info stmt_info)
     176              : {
     177       971769 :   tree init_expr;
     178       971769 :   tree step_expr;
     179       971769 :   tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
     180       971769 :   basic_block bb;
     181              : 
     182              :   /* When there is no evolution in this loop, the evolution function
     183              :      is not "simple".  */
     184       971769 :   if (evolution_part == NULL_TREE)
     185              :     return false;
     186              : 
     187              :   /* When the evolution is a polynomial of degree >= 2
     188              :      the evolution function is not "simple".  */
     189       855681 :   if (tree_is_chrec (evolution_part))
     190              :     return false;
     191              : 
     192       855681 :   step_expr = evolution_part;
     193       855681 :   init_expr = unshare_expr (initial_condition_in_loop_num (access_fn, loop_nb));
     194              : 
     195       855681 :   if (dump_enabled_p ())
     196        42687 :     dump_printf_loc (MSG_NOTE, vect_location, "step: %T,  init: %T\n",
     197              :                      step_expr, init_expr);
     198              : 
     199       855681 :   STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_info) = init_expr;
     200       855681 :   STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info) = step_expr;
     201       855681 :   STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_add;
     202              : 
     203       855681 :   if (TREE_CODE (step_expr) != INTEGER_CST
     204        73718 :       && (TREE_CODE (step_expr) != SSA_NAME
     205        58549 :           || ((bb = gimple_bb (SSA_NAME_DEF_STMT (step_expr)))
     206        58296 :               && flow_bb_inside_loop_p (get_loop (cfun, loop_nb), bb))
     207         7858 :           || (!INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
     208          133 :               && (!SCALAR_FLOAT_TYPE_P (TREE_TYPE (step_expr))
     209          133 :                   || !flag_associative_math)))
     210       921638 :       && (TREE_CODE (step_expr) != REAL_CST
     211          416 :           || !flag_associative_math))
     212              :     {
     213        65867 :       if (dump_enabled_p ())
     214         3299 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     215              :                          "step unknown.\n");
     216              :       return false;
     217              :     }
     218              : 
     219              :   return true;
     220              : }
     221              : 
     222              : /* Function vect_is_nonlinear_iv_evolution
     223              : 
     224              :    Only support nonlinear induction for integer type
     225              :    1. neg
     226              :    2. mul by constant
     227              :    3. lshift/rshift by constant.
     228              : 
     229              :    For neg induction, return a fake step as integer -1.  */
     230              : static bool
     231       179494 : vect_is_nonlinear_iv_evolution (class loop* loop, stmt_vec_info stmt_info,
     232              :                                 gphi* loop_phi_node)
     233              : {
     234       179494 :   tree init_expr, ev_expr, result, op1, op2;
     235       179494 :   gimple* def;
     236              : 
     237       179494 :   if (gimple_phi_num_args (loop_phi_node) != 2)
     238              :     return false;
     239              : 
     240       179494 :   init_expr = PHI_ARG_DEF_FROM_EDGE (loop_phi_node, loop_preheader_edge (loop));
     241       179494 :   ev_expr = PHI_ARG_DEF_FROM_EDGE (loop_phi_node, loop_latch_edge (loop));
     242              : 
     243              :   /* Support nonlinear induction only for integer type.  */
     244       179494 :   if (!INTEGRAL_TYPE_P (TREE_TYPE (init_expr)))
     245              :     return false;
     246              : 
     247       112610 :   result = PHI_RESULT (loop_phi_node);
     248              : 
     249       112610 :   if (TREE_CODE (ev_expr) != SSA_NAME
     250       110021 :       || ((def = SSA_NAME_DEF_STMT (ev_expr)), false)
     251       112610 :       || !is_gimple_assign (def))
     252              :     return false;
     253              : 
     254       101489 :   enum tree_code t_code = gimple_assign_rhs_code (def);
     255       101489 :   tree step;
     256       101489 :   switch (t_code)
     257              :     {
     258         3533 :     case NEGATE_EXPR:
     259         3533 :       if (gimple_assign_rhs1 (def) != result)
     260              :         return false;
     261         3533 :       step = build_int_cst (TREE_TYPE (init_expr), -1);
     262         3533 :       STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_neg;
     263         3533 :       break;
     264              : 
     265        12311 :     case RSHIFT_EXPR:
     266        12311 :     case LSHIFT_EXPR:
     267        12311 :     case MULT_EXPR:
     268        12311 :       op1 = gimple_assign_rhs1 (def);
     269        12311 :       op2 = gimple_assign_rhs2 (def);
     270        12311 :       if (TREE_CODE (op2) != INTEGER_CST
     271         8251 :           || op1 != result)
     272              :         return false;
     273         7842 :       step = op2;
     274         7842 :       if (t_code == LSHIFT_EXPR)
     275          539 :         STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_shl;
     276         7303 :       else if (t_code == RSHIFT_EXPR)
     277         6302 :         STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_shr;
     278              :       /* NEGATE_EXPR and MULT_EXPR are both vect_step_op_mul.  */
     279              :       else
     280         1001 :         STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info) = vect_step_op_mul;
     281              :       break;
     282              : 
     283              :     default:
     284              :       return false;
     285              :     }
     286              : 
     287        11375 :   STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_info) = init_expr;
     288        11375 :   STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info) = step;
     289              : 
     290        11375 :   return true;
     291              : }
     292              : 
     293              : /* Returns true if Phi is a first-order recurrence. A first-order
     294              :    recurrence is a non-reduction recurrence relation in which the value of
     295              :    the recurrence in the current loop iteration equals a value defined in
     296              :    the previous iteration.  */
     297              : 
     298              : static bool
     299        70247 : vect_phi_first_order_recurrence_p (loop_vec_info loop_vinfo, class loop *loop,
     300              :                                    gphi *phi)
     301              : {
     302              :   /* A nested cycle isn't vectorizable as first order recurrence.  */
     303        70247 :   if (LOOP_VINFO_LOOP (loop_vinfo) != loop)
     304              :     return false;
     305              : 
     306              :   /* Ensure the loop latch definition is from within the loop.  */
     307        70102 :   edge latch = loop_latch_edge (loop);
     308        70102 :   tree ldef = PHI_ARG_DEF_FROM_EDGE (phi, latch);
     309        70102 :   if (TREE_CODE (ldef) != SSA_NAME
     310        67176 :       || SSA_NAME_IS_DEFAULT_DEF (ldef)
     311        67110 :       || is_a <gphi *> (SSA_NAME_DEF_STMT (ldef))
     312       130963 :       || !flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (ldef))))
     313              :     return false;
     314              : 
     315        60187 :   tree def = gimple_phi_result (phi);
     316              : 
     317              :   /* Ensure every use_stmt of the phi node is dominated by the latch
     318              :      definition.  */
     319        60187 :   imm_use_iterator imm_iter;
     320        60187 :   use_operand_p use_p;
     321        73265 :   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, def)
     322        72609 :     if (!is_gimple_debug (USE_STMT (use_p))
     323       141652 :         && (SSA_NAME_DEF_STMT (ldef) == USE_STMT (use_p)
     324        47616 :             || !vect_stmt_dominates_stmt_p (SSA_NAME_DEF_STMT (ldef),
     325              :                                             USE_STMT (use_p))))
     326        59531 :       return false;
     327              : 
     328              :   /* First-order recurrence autovectorization needs shuffle vector.  */
     329          656 :   tree scalar_type = TREE_TYPE (def);
     330          656 :   tree vectype = get_vectype_for_scalar_type (loop_vinfo, scalar_type);
     331          656 :   if (!vectype)
     332            6 :     return false;
     333              : 
     334              :   return true;
     335              : }
     336              : 
     337              : /* Function vect_analyze_scalar_cycles_1.
     338              : 
     339              :    Examine the cross iteration def-use cycles of scalar variables
     340              :    in LOOP.  LOOP_VINFO represents the loop that is now being
     341              :    considered for vectorization (can be LOOP, or an outer-loop
     342              :    enclosing LOOP).  SLP indicates there will be some subsequent
     343              :    slp analyses or not.  */
     344              : 
     345              : static void
     346       478846 : vect_analyze_scalar_cycles_1 (loop_vec_info loop_vinfo, class loop *loop)
     347              : {
     348       478846 :   basic_block bb = loop->header;
     349       478846 :   auto_vec<stmt_vec_info, 64> worklist;
     350       478846 :   gphi_iterator gsi;
     351              : 
     352       478846 :   DUMP_VECT_SCOPE ("vect_analyze_scalar_cycles");
     353              : 
     354              :   /* First - identify all inductions.  Reduction detection assumes that all the
     355              :      inductions have been identified, therefore, this order must not be
     356              :      changed.  */
     357      1706174 :   for (gsi = gsi_start_phis  (bb); !gsi_end_p (gsi); gsi_next (&gsi))
     358              :     {
     359      1227328 :       gphi *phi = gsi.phi ();
     360      1227328 :       tree access_fn = NULL;
     361      1227328 :       tree def = PHI_RESULT (phi);
     362      1227328 :       stmt_vec_info stmt_vinfo = loop_vinfo->lookup_stmt (phi);
     363              : 
     364              :       /* Skip virtual phi's.  The data dependences that are associated with
     365              :          virtual defs/uses (i.e., memory accesses) are analyzed elsewhere.  */
     366      2454656 :       if (virtual_operand_p (def))
     367       426145 :         continue;
     368              : 
     369              :       /* Skip already analyzed inner loop PHIs of double reductions.  */
     370       972810 :       if (VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_vinfo)))
     371         1041 :         continue;
     372              : 
     373       971769 :       if (dump_enabled_p ())
     374        44976 :         dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: %G",
     375              :                          (gimple *) phi);
     376              : 
     377       971769 :       STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_unknown_def_type;
     378              : 
     379              :       /* Analyze the evolution function.  */
     380       971769 :       access_fn = analyze_scalar_evolution (loop, def);
     381       971769 :       if (dump_enabled_p ())
     382        44976 :         dump_printf_loc (MSG_NOTE, vect_location,
     383              :                          "Access function of PHI: %T\n", access_fn);
     384       971769 :       if (access_fn)
     385       971769 :         STRIP_NOPS (access_fn);
     386              : 
     387      1142355 :       if ((!access_fn
     388       971769 :            || !vect_is_simple_iv_evolution (loop->num, access_fn, stmt_vinfo)
     389       789814 :            || (LOOP_VINFO_LOOP (loop_vinfo) != loop
     390        11947 :                && (TREE_CODE (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo))
     391              :                    != INTEGER_CST)))
     392              :           /* Only handle nonlinear iv for same loop.  */
     393      1153730 :           && (LOOP_VINFO_LOOP (loop_vinfo) != loop
     394       179494 :               || !vect_is_nonlinear_iv_evolution (loop, stmt_vinfo, phi)))
     395              :         {
     396       170586 :           worklist.safe_push (stmt_vinfo);
     397       170586 :           continue;
     398              :         }
     399              : 
     400       801183 :       gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo)
     401              :                   != NULL_TREE);
     402       801183 :       gcc_assert (STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo) != NULL_TREE);
     403              : 
     404       801183 :       if (dump_enabled_p ())
     405        39610 :         dump_printf_loc (MSG_NOTE, vect_location, "Detected induction.\n");
     406       801183 :       STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_induction_def;
     407              : 
     408              :       /* Mark if we have a non-linear IV.  */
     409       801183 :       LOOP_VINFO_NON_LINEAR_IV (loop_vinfo)
     410       801183 :         = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_vinfo) != vect_step_op_add;
     411              :     }
     412              : 
     413              : 
     414              :   /* Second - identify all reductions and nested cycles.  */
     415       649432 :   while (worklist.length () > 0)
     416              :     {
     417       170586 :       stmt_vec_info stmt_vinfo = worklist.pop ();
     418       170586 :       gphi *phi = as_a <gphi *> (stmt_vinfo->stmt);
     419       170586 :       tree def = PHI_RESULT (phi);
     420              : 
     421       170586 :       if (dump_enabled_p ())
     422         5366 :         dump_printf_loc (MSG_NOTE, vect_location, "Analyze phi: %G",
     423              :                          (gimple *) phi);
     424              : 
     425       341172 :       gcc_assert (!virtual_operand_p (def)
     426              :                   && STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_unknown_def_type);
     427              : 
     428       170586 :       gphi *double_reduc;
     429       170586 :       stmt_vec_info reduc_stmt_info
     430       170586 :         = vect_is_simple_reduction (loop_vinfo, stmt_vinfo, &double_reduc);
     431       170586 :       if (reduc_stmt_info && double_reduc)
     432              :         {
     433         1143 :           stmt_vec_info inner_phi_info
     434         1143 :               = loop_vinfo->lookup_stmt (double_reduc);
     435              :           /* ???  Pass down flag we're the inner loop of a double reduc.  */
     436         1143 :           stmt_vec_info inner_reduc_info
     437         1143 :             = vect_is_simple_reduction (loop_vinfo, inner_phi_info, NULL);
     438         1143 :           if (inner_reduc_info)
     439              :             {
     440         1041 :               STMT_VINFO_REDUC_DEF (stmt_vinfo) = reduc_stmt_info;
     441         1041 :               STMT_VINFO_REDUC_DEF (reduc_stmt_info) = stmt_vinfo;
     442         1041 :               STMT_VINFO_REDUC_DEF (inner_phi_info) = inner_reduc_info;
     443         1041 :               STMT_VINFO_REDUC_DEF (inner_reduc_info) = inner_phi_info;
     444         1041 :               if (dump_enabled_p ())
     445          130 :                 dump_printf_loc (MSG_NOTE, vect_location,
     446              :                                  "Detected double reduction.\n");
     447              : 
     448         1041 :               STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_double_reduction_def;
     449         1041 :               STMT_VINFO_DEF_TYPE (reduc_stmt_info) = vect_double_reduction_def;
     450         1041 :               STMT_VINFO_DEF_TYPE (inner_phi_info) = vect_nested_cycle;
     451              :               /* Make it accessible for SLP vectorization.  */
     452         1041 :               LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt_info);
     453              :             }
     454          102 :           else if (dump_enabled_p ())
     455           14 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     456              :                              "Unknown def-use cycle pattern.\n");
     457              :         }
     458       169443 :       else if (reduc_stmt_info)
     459              :         {
     460        99196 :           if (loop != LOOP_VINFO_LOOP (loop_vinfo))
     461              :             {
     462         2322 :               if (dump_enabled_p ())
     463          437 :                 dump_printf_loc (MSG_NOTE, vect_location,
     464              :                                  "Detected vectorizable nested cycle.\n");
     465              : 
     466         2322 :               STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_nested_cycle;
     467              :             }
     468              :           else
     469              :             {
     470        96874 :               STMT_VINFO_REDUC_DEF (stmt_vinfo) = reduc_stmt_info;
     471        96874 :               STMT_VINFO_REDUC_DEF (reduc_stmt_info) = stmt_vinfo;
     472        96874 :               if (dump_enabled_p ())
     473         4191 :                 dump_printf_loc (MSG_NOTE, vect_location,
     474              :                                  "Detected reduction.\n");
     475              : 
     476        96874 :               STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_reduction_def;
     477        96874 :               STMT_VINFO_DEF_TYPE (reduc_stmt_info) = vect_reduction_def;
     478        96874 :               LOOP_VINFO_REDUCTIONS (loop_vinfo).safe_push (reduc_stmt_info);
     479              :             }
     480              :         }
     481        70247 :       else if (vect_phi_first_order_recurrence_p (loop_vinfo, loop, phi))
     482          650 :         STMT_VINFO_DEF_TYPE (stmt_vinfo) = vect_first_order_recurrence;
     483              :       else
     484        69597 :         if (dump_enabled_p ())
     485          517 :           dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     486              :                            "Unknown def-use cycle pattern.\n");
     487              :     }
     488       478846 : }
     489              : 
     490              : 
     491              : /* Function vect_analyze_scalar_cycles.
     492              : 
     493              :    Examine the cross iteration def-use cycles of scalar variables, by
     494              :    analyzing the loop-header PHIs of scalar variables.  Classify each
     495              :    cycle as one of the following: invariant, induction, reduction, unknown.
     496              :    We do that for the loop represented by LOOP_VINFO, and also to its
     497              :    inner-loop, if exists.
     498              :    Examples for scalar cycles:
     499              : 
     500              :    Example1: reduction:
     501              : 
     502              :               loop1:
     503              :               for (i=0; i<N; i++)
     504              :                  sum += a[i];
     505              : 
     506              :    Example2: induction:
     507              : 
     508              :               loop2:
     509              :               for (i=0; i<N; i++)
     510              :                  a[i] = i;  */
     511              : 
     512              : static void
     513       472759 : vect_analyze_scalar_cycles (loop_vec_info loop_vinfo)
     514              : {
     515       472759 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
     516              : 
     517       472759 :   vect_analyze_scalar_cycles_1 (loop_vinfo, loop);
     518              : 
     519              :   /* When vectorizing an outer-loop, the inner-loop is executed sequentially.
     520              :      Reductions in such inner-loop therefore have different properties than
     521              :      the reductions in the nest that gets vectorized:
     522              :      1. When vectorized, they are executed in the same order as in the original
     523              :         scalar loop, so we can't change the order of computation when
     524              :         vectorizing them.
     525              :      2. FIXME: Inner-loop reductions can be used in the inner-loop, so the
     526              :         current checks are too strict.  */
     527              : 
     528       472759 :   if (loop->inner)
     529         6087 :     vect_analyze_scalar_cycles_1 (loop_vinfo, loop->inner);
     530       472759 : }
     531              : 
     532              : /* Function vect_get_loop_niters.
     533              : 
     534              :    Determine how many iterations the loop is executed and place it
     535              :    in NUMBER_OF_ITERATIONS.  Place the number of latch iterations
     536              :    in NUMBER_OF_ITERATIONSM1.  Place the condition under which the
     537              :    niter information holds in ASSUMPTIONS.
     538              : 
     539              :    Return the loop exit conditions.  */
     540              : 
     541              : 
     542              : static vec<gcond *>
     543       295316 : vect_get_loop_niters (class loop *loop, const_edge main_exit, tree *assumptions,
     544              :                       tree *number_of_iterations, tree *number_of_iterationsm1)
     545              : {
     546       295316 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
     547       295316 :   vec<gcond *> conds;
     548       590632 :   conds.create (exits.length ());
     549       295316 :   class tree_niter_desc niter_desc;
     550       295316 :   tree niter_assumptions, niter, may_be_zero;
     551              : 
     552       295316 :   *assumptions = boolean_true_node;
     553       295316 :   *number_of_iterationsm1 = chrec_dont_know;
     554       295316 :   *number_of_iterations = chrec_dont_know;
     555              : 
     556       295316 :   DUMP_VECT_SCOPE ("get_loop_niters");
     557              : 
     558       295316 :   if (exits.is_empty ())
     559            0 :     return conds;
     560              : 
     561       295316 :   if (dump_enabled_p ())
     562        15433 :     dump_printf_loc (MSG_NOTE, vect_location, "Loop has %d exits.\n",
     563              :                      exits.length ());
     564              : 
     565       295316 :   edge exit;
     566       295316 :   unsigned int i;
     567       719688 :   FOR_EACH_VEC_ELT (exits, i, exit)
     568              :     {
     569       424372 :       gcond *cond = get_loop_exit_condition (exit);
     570       424372 :       if (cond)
     571       424338 :         conds.safe_push (cond);
     572              : 
     573       424372 :       if (dump_enabled_p ())
     574        16757 :         dump_printf_loc (MSG_NOTE, vect_location, "Analyzing exit %d...\n", i);
     575              : 
     576       424372 :       if (exit != main_exit)
     577       189390 :         continue;
     578              : 
     579       295316 :       may_be_zero = NULL_TREE;
     580       295316 :       if (!number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
     581       295316 :           || chrec_contains_undetermined (niter_desc.niter))
     582        60334 :         continue;
     583              : 
     584       234982 :       niter_assumptions = niter_desc.assumptions;
     585       234982 :       may_be_zero = niter_desc.may_be_zero;
     586       234982 :       niter = niter_desc.niter;
     587              : 
     588       234982 :       if (may_be_zero && integer_zerop (may_be_zero))
     589              :         may_be_zero = NULL_TREE;
     590              : 
     591         9819 :       if (may_be_zero)
     592              :         {
     593         9819 :           if (COMPARISON_CLASS_P (may_be_zero))
     594              :             {
     595              :               /* Try to combine may_be_zero with assumptions, this can simplify
     596              :                  computation of niter expression.  */
     597         9819 :               if (niter_assumptions && !integer_nonzerop (niter_assumptions))
     598          972 :                 niter_assumptions = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
     599              :                                                  niter_assumptions,
     600              :                                                  fold_build1 (TRUTH_NOT_EXPR,
     601              :                                                               boolean_type_node,
     602              :                                                               may_be_zero));
     603              :               else
     604         8847 :                 niter = fold_build3 (COND_EXPR, TREE_TYPE (niter), may_be_zero,
     605              :                                      build_int_cst (TREE_TYPE (niter), 0),
     606              :                                      rewrite_to_non_trapping_overflow (niter));
     607              : 
     608       234982 :               may_be_zero = NULL_TREE;
     609              :             }
     610            0 :           else if (integer_nonzerop (may_be_zero))
     611              :             {
     612            0 :               *number_of_iterationsm1 = build_int_cst (TREE_TYPE (niter), 0);
     613            0 :               *number_of_iterations = build_int_cst (TREE_TYPE (niter), 1);
     614            0 :               continue;
     615              :             }
     616              :           else
     617            0 :             continue;
     618              :        }
     619              : 
     620              :       /* Loop assumptions are based off the normal exit.  */
     621       234982 :       *assumptions = niter_assumptions;
     622       234982 :       *number_of_iterationsm1 = niter;
     623              : 
     624              :       /* We want the number of loop header executions which is the number
     625              :          of latch executions plus one.
     626              :          ???  For UINT_MAX latch executions this number overflows to zero
     627              :          for loops like do { n++; } while (n != 0);  */
     628       234982 :       if (niter && !chrec_contains_undetermined (niter))
     629              :         {
     630       234982 :           niter = fold_build2 (PLUS_EXPR, TREE_TYPE (niter),
     631              :                                unshare_expr (niter),
     632              :                                build_int_cst (TREE_TYPE (niter), 1));
     633       234982 :           if (TREE_CODE (niter) == INTEGER_CST
     634       128951 :               && TREE_CODE (*number_of_iterationsm1) != INTEGER_CST)
     635              :             {
     636              :               /* If we manage to fold niter + 1 into INTEGER_CST even when
     637              :                  niter is some complex expression, ensure back
     638              :                  *number_of_iterationsm1 is an INTEGER_CST as well.  See
     639              :                  PR113210.  */
     640            0 :               *number_of_iterationsm1
     641            0 :                 = fold_build2 (PLUS_EXPR, TREE_TYPE (niter), niter,
     642              :                                build_minus_one_cst (TREE_TYPE (niter)));
     643              :             }
     644              :         }
     645       234982 :       *number_of_iterations = niter;
     646              :     }
     647              : 
     648       295316 :   if (dump_enabled_p ())
     649        15433 :     dump_printf_loc (MSG_NOTE, vect_location, "All loop exits successfully analyzed.\n");
     650              : 
     651       295316 :   return conds;
     652       295316 : }
     653              : 
     654              : /*  Determine the main loop exit for the vectorizer.  */
     655              : 
     656              : edge
     657       510536 : vec_init_loop_exit_info (class loop *loop)
     658              : {
     659              :   /* Before we begin we must first determine which exit is the main one and
     660              :      which are auxiliary exits.  */
     661       510536 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
     662      1015979 :   if (exits.length () == 0)
     663              :     return NULL;
     664       505443 :   if (exits.length () == 1)
     665       331694 :     return exits[0];
     666              : 
     667              :   /* If we have multiple exits, look for counting IV exit.
     668              :      Analyze all exits and return the last one we can analyze.  */
     669       173749 :   class tree_niter_desc niter_desc;
     670       173749 :   edge candidate = NULL;
     671       642241 :   for (edge exit : exits)
     672              :     {
     673       489659 :       if (!get_loop_exit_condition (exit))
     674              :         {
     675        21167 :           if (dump_enabled_p ())
     676           14 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     677              :                              "Unhandled loop exit detected.\n");
     678              :           return NULL;
     679              :         }
     680              : 
     681       468492 :       if (number_of_iterations_exit_assumptions (loop, exit, &niter_desc, NULL)
     682       468492 :           && !chrec_contains_undetermined (niter_desc.niter))
     683              :         {
     684       139299 :           tree may_be_zero = niter_desc.may_be_zero;
     685       139299 :           if ((integer_zerop (may_be_zero)
     686              :                /* As we are handling may_be_zero that's not false by
     687              :                   rewriting niter to may_be_zero ? 0 : niter we require
     688              :                   an empty latch.  */
     689       478965 :                || (single_pred_p (loop->latch)
     690        10272 :                    && exit->src == single_pred (loop->latch)
     691         2541 :                    && (integer_nonzerop (may_be_zero)
     692         2541 :                        || COMPARISON_CLASS_P (may_be_zero))))
     693       141840 :               && (!candidate
     694         5840 :                   || dominated_by_p (CDI_DOMINATORS, exit->src,
     695         5840 :                                      candidate->src)))
     696              :             candidate = exit;
     697              :         }
     698              :     }
     699              : 
     700              :   /* If no exit is analyzable by scalar evolution, we return the last exit
     701              :      under the assummption we are dealing with an uncounted loop.  */
     702       209571 :   if (!candidate && single_pred_p (loop->latch))
     703        35822 :     candidate = loop_exits_from_bb_p (loop, single_pred (loop->latch));
     704              : 
     705              :   return candidate;
     706       173749 : }
     707              : 
     708              : /* Function bb_in_loop_p
     709              : 
     710              :    Used as predicate for dfs order traversal of the loop bbs.  */
     711              : 
     712              : static bool
     713      2522623 : bb_in_loop_p (const_basic_block bb, const void *data)
     714              : {
     715      2522623 :   const class loop *const loop = (const class loop *)data;
     716      2522623 :   if (flow_bb_inside_loop_p (loop, bb))
     717              :     return true;
     718              :   return false;
     719              : }
     720              : 
     721              : /* Get and return the basic blocks of LOOP in DFS order.  Store the number of
     722              :    BBs in NBBS.  */
     723              : 
     724              : static basic_block *
     725       447668 : vect_get_loop_dfs_bbs (class loop *loop, unsigned int *nbbs)
     726              : {
     727              :   /* CHECKME: We want to visit all BBs before their successors (except for
     728              :      latch blocks, for which this assertion wouldn't hold).  In the simple
     729              :      case of the loop forms we allow, a dfs order of the BBs would the same
     730              :      as reversed postorder traversal, so we are safe.  */
     731       447668 :   basic_block *bbs = XCNEWVEC (basic_block, loop->num_nodes);
     732       895336 :   *nbbs = dfs_enumerate_from (loop->header, 0, bb_in_loop_p, bbs,
     733       447668 :                               loop->num_nodes, loop);
     734       447668 :   gcc_assert (*nbbs == loop->num_nodes);
     735       447668 :   return bbs;
     736              : }
     737              : 
     738              : /* Create and initialize a new loop_vec_info struct for LOOP_IN, as well as
     739              :    stmt_vec_info structs for all the stmts in LOOP_IN.  */
     740              : 
     741       550572 : _loop_vec_info::_loop_vec_info (class loop *loop_in, vec_info_shared *shared,
     742              :                                 basic_block *bbs_in)
     743              :   : vec_info (vec_info::loop, shared),
     744       550572 :     loop (loop_in),
     745       550572 :     num_itersm1 (NULL_TREE),
     746       550572 :     num_iters (NULL_TREE),
     747       550572 :     num_iters_unchanged (NULL_TREE),
     748       550572 :     num_iters_assumptions (NULL_TREE),
     749       550572 :     vector_costs (nullptr),
     750       550572 :     scalar_costs (nullptr),
     751       550572 :     th (0),
     752       550572 :     versioning_threshold (0),
     753       550572 :     main_loop_edge (nullptr),
     754       550572 :     skip_main_loop_edge (nullptr),
     755       550572 :     skip_this_loop_edge (nullptr),
     756       550572 :     reusable_accumulators (),
     757       550572 :     suggested_unroll_factor (1),
     758       550572 :     max_vectorization_factor (0),
     759       550572 :     mask_skip_niters (NULL_TREE),
     760       550572 :     mask_skip_niters_pfa_offset (NULL_TREE),
     761       550572 :     simd_if_cond (NULL_TREE),
     762       550572 :     unaligned_dr (NULL),
     763       550572 :     peeling_for_alignment (0),
     764       550572 :     ptr_mask (0),
     765       550572 :     max_spec_read_amount (0),
     766       550572 :     nonlinear_iv (false),
     767       550572 :     ivexpr_map (NULL),
     768       550572 :     scan_map (NULL),
     769       550572 :     inner_loop_cost_factor (param_vect_inner_loop_cost_factor),
     770       550572 :     vectorizable (false),
     771       550572 :     can_use_partial_vectors_p (true),
     772       550572 :     must_use_partial_vectors_p (false),
     773       550572 :     using_partial_vectors_p (false),
     774       550572 :     using_decrementing_iv_p (false),
     775       550572 :     using_select_vl_p (false),
     776       550572 :     allow_mutual_alignment (false),
     777       550572 :     peeling_for_gaps (false),
     778       550572 :     peeling_for_niter (false),
     779       550572 :     early_breaks (false),
     780       550572 :     loop_iv_cond (NULL),
     781       550572 :     user_unroll (false),
     782       550572 :     no_data_dependencies (false),
     783       550572 :     has_mask_store (false),
     784       550572 :     scalar_loop_scaling (profile_probability::uninitialized ()),
     785       550572 :     scalar_loop (NULL),
     786       550572 :     main_loop_info (NULL),
     787       550572 :     orig_loop_info (NULL),
     788       550572 :     epilogue_vinfo (NULL),
     789       550572 :     drs_advanced_by (NULL_TREE),
     790       550572 :     vec_loop_main_exit (NULL),
     791       550572 :     vec_epilogue_loop_main_exit (NULL),
     792       550572 :     scalar_loop_main_exit (NULL),
     793       550572 :     early_break_needs_epilogue (false),
     794       550572 :     early_break_niters_var (NULL)
     795              : {
     796       550572 :   nbbs = loop->num_nodes;
     797       550572 :   bbs = XNEWVEC (basic_block, nbbs);
     798       550572 :   memcpy (bbs, bbs_in, nbbs * sizeof (basic_block));
     799              : 
     800      1916123 :   for (unsigned int i = 0; i < nbbs; i++)
     801              :     {
     802      1365551 :       basic_block bb = bbs[i];
     803      1365551 :       gimple_stmt_iterator si;
     804              : 
     805      2813504 :       for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
     806              :         {
     807      1447953 :           gimple *phi = gsi_stmt (si);
     808      1447953 :           gimple_set_uid (phi, 0);
     809      1447953 :           add_stmt (phi);
     810              :         }
     811              : 
     812     12441230 :       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
     813              :         {
     814      9710128 :           gimple *stmt = gsi_stmt (si);
     815      9710128 :           gimple_set_uid (stmt, 0);
     816      9710128 :           if (is_gimple_debug (stmt) || is_a <glabel *> (stmt))
     817      4047437 :             continue;
     818      5662691 :           add_stmt (stmt);
     819              :           /* If .GOMP_SIMD_LANE call for the current loop has 3 arguments, the
     820              :              third argument is the #pragma omp simd if (x) condition, when 0,
     821              :              loop shouldn't be vectorized, when non-zero constant, it should
     822              :              be vectorized normally, otherwise versioned with vectorized loop
     823              :              done if the condition is non-zero at runtime.  */
     824      5662691 :           if (loop_in->simduid
     825        51225 :               && is_gimple_call (stmt)
     826         4892 :               && gimple_call_internal_p (stmt)
     827         4770 :               && gimple_call_internal_fn (stmt) == IFN_GOMP_SIMD_LANE
     828         4769 :               && gimple_call_num_args (stmt) >= 3
     829          104 :               && TREE_CODE (gimple_call_arg (stmt, 0)) == SSA_NAME
     830      5662795 :               && (loop_in->simduid
     831          104 :                   == SSA_NAME_VAR (gimple_call_arg (stmt, 0))))
     832              :             {
     833          104 :               tree arg = gimple_call_arg (stmt, 2);
     834          104 :               if (integer_zerop (arg) || TREE_CODE (arg) == SSA_NAME)
     835          104 :                 simd_if_cond = arg;
     836              :               else
     837            0 :                 gcc_assert (integer_nonzerop (arg));
     838              :             }
     839              :         }
     840              :     }
     841       550572 : }
     842              : 
     843              : /* Free all levels of rgroup CONTROLS.  */
     844              : 
     845              : void
     846      6031292 : release_vec_loop_controls (vec<rgroup_controls> *controls)
     847              : {
     848      6031292 :   rgroup_controls *rgc;
     849      6031292 :   unsigned int i;
     850      6056677 :   FOR_EACH_VEC_ELT (*controls, i, rgc)
     851        25385 :     rgc->controls.release ();
     852      6031292 :   controls->release ();
     853      6031292 : }
     854              : 
     855              : /* Free all memory used by the _loop_vec_info, as well as all the
     856              :    stmt_vec_info structs of all the stmts in the loop.  */
     857              : 
     858       550572 : _loop_vec_info::~_loop_vec_info ()
     859              : {
     860       550572 :   free (bbs);
     861              : 
     862       554833 :   delete ivexpr_map;
     863       550896 :   delete scan_map;
     864       550572 :   delete scalar_costs;
     865       550572 :   delete vector_costs;
     866       771779 :   for (auto reduc_info : reduc_infos)
     867       208066 :     delete reduc_info;
     868              : 
     869              :   /* When we release an epiloge vinfo that we do not intend to use
     870              :      avoid clearing AUX of the main loop which should continue to
     871              :      point to the main loop vinfo since otherwise we'll leak that.  */
     872       550572 :   if (loop->aux == this)
     873        66518 :     loop->aux = NULL;
     874       550572 : }
     875              : 
     876              : /* Return an invariant or register for EXPR and emit necessary
     877              :    computations in the LOOP_VINFO loop preheader.  */
     878              : 
     879              : tree
     880        21672 : cse_and_gimplify_to_preheader (loop_vec_info loop_vinfo, tree expr)
     881              : {
     882        21672 :   if (is_gimple_reg (expr)
     883        21672 :       || is_gimple_min_invariant (expr))
     884              :     return expr;
     885              : 
     886        14004 :   if (! loop_vinfo->ivexpr_map)
     887         4261 :     loop_vinfo->ivexpr_map = new hash_map<tree_operand_hash, tree>;
     888        14004 :   tree &cached = loop_vinfo->ivexpr_map->get_or_insert (expr);
     889        14004 :   if (! cached)
     890              :     {
     891         9151 :       gimple_seq stmts = NULL;
     892         9151 :       cached = force_gimple_operand (unshare_expr (expr),
     893              :                                      &stmts, true, NULL_TREE);
     894         9151 :       if (stmts)
     895              :         {
     896         8997 :           edge e = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
     897         8997 :           gsi_insert_seq_on_edge_immediate (e, stmts);
     898              :         }
     899              :     }
     900        14004 :   return cached;
     901              : }
     902              : 
     903              : /* Return true if we can use CMP_TYPE as the comparison type to produce
     904              :    all masks required to mask LOOP_VINFO.  */
     905              : 
     906              : static bool
     907       113815 : can_produce_all_loop_masks_p (loop_vec_info loop_vinfo, tree cmp_type)
     908              : {
     909       113815 :   rgroup_controls *rgm;
     910       113815 :   unsigned int i;
     911       129825 :   FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec, i, rgm)
     912       129825 :     if (rgm->type != NULL_TREE
     913       129825 :         && !direct_internal_fn_supported_p (IFN_WHILE_ULT,
     914              :                                             cmp_type, rgm->type,
     915              :                                             OPTIMIZE_FOR_SPEED))
     916              :       return false;
     917              :   return true;
     918              : }
     919              : 
     920              : /* Calculate the maximum number of scalars per iteration for every
     921              :    rgroup in LOOP_VINFO.  */
     922              : 
     923              : static unsigned int
     924        24287 : vect_get_max_nscalars_per_iter (loop_vec_info loop_vinfo)
     925              : {
     926        24287 :   unsigned int res = 1;
     927        24287 :   unsigned int i;
     928        24287 :   rgroup_controls *rgm;
     929        58053 :   FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec, i, rgm)
     930        33766 :     res = MAX (res, rgm->max_nscalars_per_iter);
     931        24287 :   return res;
     932              : }
     933              : 
     934              : /* Calculate the minimum precision necessary to represent:
     935              : 
     936              :       MAX_NITERS * FACTOR
     937              : 
     938              :    as an unsigned integer, where MAX_NITERS is the maximum number of
     939              :    loop header iterations for the original scalar form of LOOP_VINFO.  */
     940              : 
     941              : unsigned
     942        26836 : vect_min_prec_for_max_niters (loop_vec_info loop_vinfo, unsigned int factor)
     943              : {
     944        26836 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
     945              : 
     946              :   /* Get the maximum number of iterations that is representable
     947              :      in the counter type.  */
     948        26836 :   tree ni_type;
     949        26836 :   if (!LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
     950        26836 :     ni_type = TREE_TYPE (LOOP_VINFO_NITERSM1 (loop_vinfo));
     951              :   else
     952            0 :     ni_type = sizetype;
     953        26836 :   widest_int max_ni = wi::to_widest (TYPE_MAX_VALUE (ni_type)) + 1;
     954              : 
     955              :   /* Get a more refined estimate for the number of iterations.  */
     956        26836 :   widest_int max_back_edges;
     957        26836 :   if (max_loop_iterations (loop, &max_back_edges))
     958        26836 :     max_ni = wi::smin (max_ni, max_back_edges + 1);
     959              : 
     960              :   /* Work out how many bits we need to represent the limit.  */
     961        26836 :   return wi::min_precision (max_ni * factor, UNSIGNED);
     962        26836 : }
     963              : 
     964              : /* True if the loop needs peeling or partial vectors when vectorized.  */
     965              : 
     966              : static bool
     967       164481 : vect_need_peeling_or_partial_vectors_p (loop_vec_info loop_vinfo)
     968              : {
     969       164481 :   unsigned HOST_WIDE_INT const_vf;
     970              : 
     971       164481 :   if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
     972              :     return true;
     973              : 
     974        14617 :   loop_vec_info main_loop_vinfo
     975       163169 :     = (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
     976       163169 :        ? LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo) : loop_vinfo);
     977       163169 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
     978        82991 :       && LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo) >= 0)
     979              :     {
     980              :       /* Work out the (constant) number of iterations that need to be
     981              :          peeled for reasons other than niters.  */
     982        82940 :       unsigned int peel_niter
     983              :         = LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo);
     984        82940 :       return !multiple_p (LOOP_VINFO_INT_NITERS (loop_vinfo) - peel_niter,
     985        82940 :                           LOOP_VINFO_VECT_FACTOR (loop_vinfo));
     986              :     }
     987              : 
     988        80229 :   if (!LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo)
     989        80229 :       && LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant (&const_vf))
     990              :     {
     991              :       /* When the number of iterations is a multiple of the vectorization
     992              :          factor and we are not doing prologue or forced epilogue peeling
     993              :          the epilogue isn't necessary.  */
     994        79761 :       if (tree_ctz (LOOP_VINFO_NITERS (loop_vinfo))
     995       159522 :           >= (unsigned) exact_log2 (const_vf))
     996         1803 :         return false;
     997              :     }
     998              : 
     999              :   return true;
    1000              : }
    1001              : 
    1002              : /* Each statement in LOOP_VINFO can be masked where necessary.  Check
    1003              :    whether we can actually generate the masks required.  Return true if so,
    1004              :    storing the type of the scalar IV in LOOP_VINFO_RGROUP_COMPARE_TYPE.  */
    1005              : 
    1006              : static bool
    1007        24287 : vect_verify_full_masking (loop_vec_info loop_vinfo)
    1008              : {
    1009        24287 :   unsigned int min_ni_width;
    1010              : 
    1011              :   /* Use a normal loop if there are no statements that need masking.
    1012              :      This only happens in rare degenerate cases: it means that the loop
    1013              :      has no loads, no stores, and no live-out values.  */
    1014        24287 :   if (LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
    1015              :     return false;
    1016              : 
    1017              :   /* Produce the rgroup controls.  */
    1018        59747 :   for (auto mask : LOOP_VINFO_MASKS (loop_vinfo).mask_set)
    1019              :     {
    1020        35460 :       vec_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
    1021        35460 :       tree vectype = mask.first;
    1022        35460 :       unsigned nvectors = mask.second;
    1023              : 
    1024        46633 :       if (masks->rgc_vec.length () < nvectors)
    1025        26436 :         masks->rgc_vec.safe_grow_cleared (nvectors, true);
    1026        35460 :       rgroup_controls *rgm = &(*masks).rgc_vec[nvectors - 1];
    1027              :       /* The number of scalars per iteration and the number of vectors are
    1028              :          both compile-time constants.  */
    1029        35460 :       unsigned int nscalars_per_iter
    1030        35460 :           = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
    1031        35460 :                        LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
    1032              : 
    1033        35460 :       if (rgm->max_nscalars_per_iter < nscalars_per_iter)
    1034              :         {
    1035        28381 :           rgm->max_nscalars_per_iter = nscalars_per_iter;
    1036        28381 :           rgm->type = truth_type_for (vectype);
    1037        28381 :           rgm->factor = 1;
    1038              :         }
    1039              :     }
    1040              : 
    1041        24287 :   unsigned int max_nscalars_per_iter
    1042        24287 :     = vect_get_max_nscalars_per_iter (loop_vinfo);
    1043              : 
    1044              :   /* Work out how many bits we need to represent the limit.  */
    1045        24287 :   min_ni_width
    1046        24287 :     = vect_min_prec_for_max_niters (loop_vinfo, max_nscalars_per_iter);
    1047              : 
    1048              :   /* Find a scalar mode for which WHILE_ULT is supported.  */
    1049        24287 :   opt_scalar_int_mode cmp_mode_iter;
    1050        24287 :   tree cmp_type = NULL_TREE;
    1051        24287 :   tree iv_type = NULL_TREE;
    1052        24287 :   widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
    1053        24287 :   unsigned int iv_precision = UINT_MAX;
    1054              : 
    1055        24287 :   if (iv_limit != -1)
    1056        24287 :     iv_precision = wi::min_precision (iv_limit * max_nscalars_per_iter,
    1057              :                                       UNSIGNED);
    1058              : 
    1059       194296 :   FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
    1060              :     {
    1061       170009 :       unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
    1062       170009 :       if (cmp_bits >= min_ni_width
    1063       170009 :           && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
    1064              :         {
    1065       113815 :           tree this_type = build_nonstandard_integer_type (cmp_bits, true);
    1066       113815 :           if (this_type
    1067       113815 :               && can_produce_all_loop_masks_p (loop_vinfo, this_type))
    1068              :             {
    1069              :               /* Although we could stop as soon as we find a valid mode,
    1070              :                  there are at least two reasons why that's not always the
    1071              :                  best choice:
    1072              : 
    1073              :                  - An IV that's Pmode or wider is more likely to be reusable
    1074              :                    in address calculations than an IV that's narrower than
    1075              :                    Pmode.
    1076              : 
    1077              :                  - Doing the comparison in IV_PRECISION or wider allows
    1078              :                    a natural 0-based IV, whereas using a narrower comparison
    1079              :                    type requires mitigations against wrap-around.
    1080              : 
    1081              :                  Conversely, if the IV limit is variable, doing the comparison
    1082              :                  in a wider type than the original type can introduce
    1083              :                  unnecessary extensions, so picking the widest valid mode
    1084              :                  is not always a good choice either.
    1085              : 
    1086              :                  Here we prefer the first IV type that's Pmode or wider,
    1087              :                  and the first comparison type that's IV_PRECISION or wider.
    1088              :                  (The comparison type must be no wider than the IV type,
    1089              :                  to avoid extensions in the vector loop.)
    1090              : 
    1091              :                  ??? We might want to try continuing beyond Pmode for ILP32
    1092              :                  targets if CMP_BITS < IV_PRECISION.  */
    1093            0 :               iv_type = this_type;
    1094            0 :               if (!cmp_type || iv_precision > TYPE_PRECISION (cmp_type))
    1095              :                 cmp_type = this_type;
    1096            0 :               if (cmp_bits >= GET_MODE_BITSIZE (Pmode))
    1097              :                 break;
    1098              :             }
    1099              :         }
    1100              :     }
    1101              : 
    1102        24287 :   if (!cmp_type)
    1103              :     {
    1104        24287 :       LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.release ();
    1105        24287 :       return false;
    1106              :     }
    1107              : 
    1108            0 :   LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = cmp_type;
    1109            0 :   LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
    1110            0 :   LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_while_ult;
    1111            0 :   return true;
    1112        24287 : }
    1113              : 
    1114              : /* Each statement in LOOP_VINFO can be masked where necessary.  Check
    1115              :    whether we can actually generate AVX512 style masks.  Return true if so,
    1116              :    storing the type of the scalar IV in LOOP_VINFO_RGROUP_IV_TYPE.  */
    1117              : 
    1118              : static bool
    1119        24287 : vect_verify_full_masking_avx512 (loop_vec_info loop_vinfo)
    1120              : {
    1121              :   /* Produce differently organized rgc_vec and differently check
    1122              :      we can produce masks.  */
    1123              : 
    1124              :   /* Use a normal loop if there are no statements that need masking.
    1125              :      This only happens in rare degenerate cases: it means that the loop
    1126              :      has no loads, no stores, and no live-out values.  */
    1127        24287 :   if (LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
    1128              :     return false;
    1129              : 
    1130              :   /* For the decrementing IV we need to represent all values in
    1131              :      [0, niter + niter_skip] where niter_skip is the elements we
    1132              :      skip in the first iteration for prologue peeling.  */
    1133        24287 :   tree iv_type = NULL_TREE;
    1134        24287 :   widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
    1135        24287 :   unsigned int iv_precision = UINT_MAX;
    1136        24287 :   if (iv_limit != -1)
    1137        24287 :     iv_precision = wi::min_precision (iv_limit, UNSIGNED);
    1138              : 
    1139              :   /* First compute the type for the IV we use to track the remaining
    1140              :      scalar iterations.  */
    1141        24287 :   opt_scalar_int_mode cmp_mode_iter;
    1142        31895 :   FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
    1143              :     {
    1144        31895 :       unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
    1145        31895 :       if (cmp_bits >= iv_precision
    1146        31895 :           && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
    1147              :         {
    1148        24287 :           iv_type = build_nonstandard_integer_type (cmp_bits, true);
    1149        24287 :           if (iv_type)
    1150              :             break;
    1151              :         }
    1152              :     }
    1153        24287 :   if (!iv_type)
    1154              :     return false;
    1155              : 
    1156        24287 :   bool ok = true;
    1157              : 
    1158              :   /* Produce the rgroup controls.  */
    1159        51986 :   for (auto const &mask : LOOP_VINFO_MASKS (loop_vinfo).mask_set)
    1160              :     {
    1161        33885 :       vec_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
    1162        33885 :       tree vectype = mask.first;
    1163        33885 :       unsigned nvectors = mask.second;
    1164              : 
    1165              :       /* The number of scalars per iteration and the number of vectors are
    1166              :          both compile-time constants.  */
    1167        33885 :       unsigned int nscalars_per_iter
    1168        33885 :         = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
    1169        33885 :                      LOOP_VINFO_VECT_FACTOR (loop_vinfo)).to_constant ();
    1170              : 
    1171              :       /* We index the rgroup_controls vector with nscalars_per_iter
    1172              :          which we keep constant and instead have a varying nvectors,
    1173              :          remembering the vector mask with the fewest nV.  */
    1174        43483 :       if (masks->rgc_vec.length () < nscalars_per_iter)
    1175        24343 :         masks->rgc_vec.safe_grow_cleared (nscalars_per_iter, true);
    1176        33885 :       rgroup_controls *rgm = &(*masks).rgc_vec[nscalars_per_iter - 1];
    1177              : 
    1178              :       /* For now vect_get_loop_mask only supports integer mode masks
    1179              :          when we need to split it.  */
    1180        33885 :       tree mask_type = truth_type_for (vectype);
    1181        33885 :       if (GET_MODE_CLASS (TYPE_MODE (mask_type)) != MODE_INT
    1182        33885 :           || TYPE_PRECISION (TREE_TYPE (mask_type)) != 1)
    1183              :         {
    1184         6186 :           ok = false;
    1185         6186 :           break;
    1186              :         }
    1187              : 
    1188        27699 :       if (!rgm->type || rgm->factor > nvectors)
    1189              :         {
    1190        19918 :           rgm->type = mask_type;
    1191        19918 :           rgm->compare_type = NULL_TREE;
    1192        19918 :           rgm->max_nscalars_per_iter = nscalars_per_iter;
    1193        19918 :           rgm->factor = nvectors;
    1194        19918 :           rgm->bias_adjusted_ctrl = NULL_TREE;
    1195              :         }
    1196              :     }
    1197        24287 :   if (!ok)
    1198              :     {
    1199         6186 :       release_vec_loop_controls (&LOOP_VINFO_MASKS (loop_vinfo).rgc_vec);
    1200         6186 :       return false;
    1201              :     }
    1202              : 
    1203              :   /* There is no fixed compare type we are going to use but we have to
    1204              :      be able to get at one for each mask group.  */
    1205        18101 :   unsigned int min_ni_width
    1206        18101 :     = wi::min_precision (vect_max_vf (loop_vinfo), UNSIGNED);
    1207              : 
    1208        72999 :   for (auto &rgc : LOOP_VINFO_MASKS (loop_vinfo).rgc_vec)
    1209              :     {
    1210        18700 :       tree mask_type = rgc.type;
    1211        18700 :       if (!mask_type)
    1212          520 :         continue;
    1213              : 
    1214              :       /* If iv_type is usable as compare type use that - we can elide the
    1215              :          saturation in that case.   */
    1216        18180 :       if (TYPE_PRECISION (iv_type) >= min_ni_width)
    1217              :         {
    1218        18180 :           tree cmp_vectype
    1219        18180 :             = build_vector_type (iv_type, TYPE_VECTOR_SUBPARTS (mask_type));
    1220        18180 :           if (expand_vec_cmp_expr_p (cmp_vectype, mask_type, LT_EXPR))
    1221         6128 :             rgc.compare_type = cmp_vectype;
    1222              :         }
    1223        18180 :       if (!rgc.compare_type)
    1224        34602 :         FOR_EACH_MODE_IN_CLASS (cmp_mode_iter, MODE_INT)
    1225              :           {
    1226        34598 :             unsigned int cmp_bits = GET_MODE_BITSIZE (cmp_mode_iter.require ());
    1227        34598 :             if (cmp_bits >= min_ni_width
    1228        34598 :                 && targetm.scalar_mode_supported_p (cmp_mode_iter.require ()))
    1229              :               {
    1230        34586 :                 tree cmp_type = build_nonstandard_integer_type (cmp_bits, true);
    1231        34586 :                 if (!cmp_type)
    1232            0 :                   continue;
    1233              : 
    1234              :                 /* Check whether we can produce the mask with cmp_type.  */
    1235        34586 :                 tree cmp_vectype
    1236        34586 :                   = build_vector_type (cmp_type, TYPE_VECTOR_SUBPARTS (mask_type));
    1237        34586 :                 if (expand_vec_cmp_expr_p (cmp_vectype, mask_type, LT_EXPR))
    1238              :                   {
    1239        12048 :                     rgc.compare_type = cmp_vectype;
    1240        12048 :                     break;
    1241              :                   }
    1242              :               }
    1243              :         }
    1244        18180 :       if (!rgc.compare_type)
    1245              :         {
    1246              :           ok = false;
    1247              :           break;
    1248              :         }
    1249              :     }
    1250        18101 :   if (!ok)
    1251              :     {
    1252            4 :       release_vec_loop_controls (&LOOP_VINFO_MASKS (loop_vinfo).rgc_vec);
    1253            4 :       return false;
    1254              :     }
    1255              : 
    1256        18097 :   LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = error_mark_node;
    1257        18097 :   LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
    1258        18097 :   LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_avx512;
    1259        18097 :   return true;
    1260        24287 : }
    1261              : 
    1262              : /* Check whether we can use vector access with length based on precision
    1263              :    comparison.  So far, to keep it simple, we only allow the case that the
    1264              :    precision of the target supported length is larger than the precision
    1265              :    required by loop niters.  */
    1266              : 
    1267              : static bool
    1268            6 : vect_verify_loop_lens (loop_vec_info loop_vinfo)
    1269              : {
    1270            6 :   if (LOOP_VINFO_LENS (loop_vinfo).is_empty ())
    1271              :     return false;
    1272              : 
    1273            0 :   if (!VECTOR_MODE_P (loop_vinfo->vector_mode))
    1274              :     return false;
    1275              : 
    1276            0 :   machine_mode len_load_mode, len_store_mode;
    1277            0 :   if (!get_len_load_store_mode (loop_vinfo->vector_mode, true)
    1278            0 :          .exists (&len_load_mode))
    1279            0 :     return false;
    1280            0 :   if (!get_len_load_store_mode (loop_vinfo->vector_mode, false)
    1281            0 :          .exists (&len_store_mode))
    1282            0 :     return false;
    1283              : 
    1284            0 :   signed char partial_load_bias = internal_len_load_store_bias
    1285            0 :     (IFN_LEN_LOAD, len_load_mode);
    1286              : 
    1287            0 :   signed char partial_store_bias = internal_len_load_store_bias
    1288            0 :     (IFN_LEN_STORE, len_store_mode);
    1289              : 
    1290            0 :   gcc_assert (partial_load_bias == partial_store_bias);
    1291              : 
    1292            0 :   if (partial_load_bias == VECT_PARTIAL_BIAS_UNSUPPORTED)
    1293              :     return false;
    1294              : 
    1295              :   /* If the backend requires a bias of -1 for LEN_LOAD, we must not emit
    1296              :      len_loads with a length of zero.  In order to avoid that we prohibit
    1297              :      more than one loop length here.  */
    1298            0 :   if (partial_load_bias == -1
    1299            0 :       && LOOP_VINFO_LENS (loop_vinfo).length () > 1)
    1300              :     return false;
    1301              : 
    1302            0 :   LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo) = partial_load_bias;
    1303              : 
    1304            0 :   unsigned int max_nitems_per_iter = 1;
    1305            0 :   unsigned int i;
    1306            0 :   rgroup_controls *rgl;
    1307              :   /* Find the maximum number of items per iteration for every rgroup.  */
    1308            0 :   FOR_EACH_VEC_ELT (LOOP_VINFO_LENS (loop_vinfo), i, rgl)
    1309              :     {
    1310            0 :       unsigned nitems_per_iter = rgl->max_nscalars_per_iter * rgl->factor;
    1311            0 :       max_nitems_per_iter = MAX (max_nitems_per_iter, nitems_per_iter);
    1312              :     }
    1313              : 
    1314              :   /* Work out how many bits we need to represent the length limit.  */
    1315            0 :   unsigned int min_ni_prec
    1316            0 :     = vect_min_prec_for_max_niters (loop_vinfo, max_nitems_per_iter);
    1317              : 
    1318              :   /* Now use the maximum of below precisions for one suitable IV type:
    1319              :      - the IV's natural precision
    1320              :      - the precision needed to hold: the maximum number of scalar
    1321              :        iterations multiplied by the scale factor (min_ni_prec above)
    1322              :      - the Pmode precision
    1323              : 
    1324              :      If min_ni_prec is less than the precision of the current niters,
    1325              :      we prefer to still use the niters type.  Prefer to use Pmode and
    1326              :      wider IV to avoid narrow conversions.  */
    1327              : 
    1328            0 :   unsigned int ni_prec
    1329            0 :     = TYPE_PRECISION (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)));
    1330            0 :   min_ni_prec = MAX (min_ni_prec, ni_prec);
    1331            0 :   min_ni_prec = MAX (min_ni_prec, GET_MODE_BITSIZE (Pmode));
    1332              : 
    1333            0 :   tree iv_type = NULL_TREE;
    1334            0 :   opt_scalar_int_mode tmode_iter;
    1335            0 :   FOR_EACH_MODE_IN_CLASS (tmode_iter, MODE_INT)
    1336              :     {
    1337            0 :       scalar_mode tmode = tmode_iter.require ();
    1338            0 :       unsigned int tbits = GET_MODE_BITSIZE (tmode);
    1339              : 
    1340              :       /* ??? Do we really want to construct one IV whose precision exceeds
    1341              :          BITS_PER_WORD?  */
    1342            0 :       if (tbits > BITS_PER_WORD)
    1343              :         break;
    1344              : 
    1345              :       /* Find the first available standard integral type.  */
    1346            0 :       if (tbits >= min_ni_prec && targetm.scalar_mode_supported_p (tmode))
    1347              :         {
    1348            0 :           iv_type = build_nonstandard_integer_type (tbits, true);
    1349            0 :           break;
    1350              :         }
    1351              :     }
    1352              : 
    1353            0 :   if (!iv_type)
    1354              :     {
    1355            0 :       if (dump_enabled_p ())
    1356            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1357              :                          "can't vectorize with length-based partial vectors"
    1358              :                          " because there is no suitable iv type.\n");
    1359              :       return false;
    1360              :     }
    1361              : 
    1362            0 :   LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo) = iv_type;
    1363            0 :   LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo) = iv_type;
    1364            0 :   LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) = vect_partial_vectors_len;
    1365              : 
    1366            0 :   return true;
    1367              : }
    1368              : 
    1369              : /* Calculate the cost of one scalar iteration of the loop.  */
    1370              : static void
    1371       391551 : vect_compute_single_scalar_iteration_cost (loop_vec_info loop_vinfo)
    1372              : {
    1373       391551 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    1374       391551 :   basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
    1375       391551 :   int nbbs = loop->num_nodes, i;
    1376              : 
    1377       391551 :   DUMP_VECT_SCOPE ("vect_compute_single_scalar_iteration_cost");
    1378              : 
    1379              :   /* Gather costs for statements in the scalar loop.  */
    1380              : 
    1381      1349939 :   for (i = 0; i < nbbs; i++)
    1382              :     {
    1383       958388 :       gimple_stmt_iterator si;
    1384       958388 :       basic_block bb = bbs[i];
    1385              : 
    1386      7861650 :       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
    1387              :         {
    1388      5944874 :           gimple *stmt = gsi_stmt (si);
    1389      5944874 :           stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (stmt);
    1390              : 
    1391      5944874 :           if (!is_gimple_assign (stmt)
    1392              :               && !is_gimple_call (stmt)
    1393              :               && !is_a<gcond *> (stmt))
    1394      2181889 :             continue;
    1395              : 
    1396              :           /* Skip stmts that are not vectorized inside the loop.  */
    1397      3762985 :           stmt_vec_info vstmt_info = vect_stmt_to_vectorize (stmt_info);
    1398      3762985 :           if (!STMT_VINFO_RELEVANT_P (vstmt_info)
    1399      1860502 :               && (!STMT_VINFO_LIVE_P (vstmt_info)
    1400           51 :                   || !VECTORIZABLE_CYCLE_DEF
    1401              :                         (STMT_VINFO_DEF_TYPE (vstmt_info))))
    1402      1860502 :             continue;
    1403              : 
    1404      1902483 :           vect_cost_for_stmt kind;
    1405      1902483 :           if (STMT_VINFO_DATA_REF (stmt_info))
    1406              :             {
    1407       919594 :               if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
    1408              :                kind = scalar_load;
    1409              :              else
    1410       343103 :                kind = scalar_store;
    1411              :             }
    1412       982889 :           else if (vect_nop_conversion_p (stmt_info))
    1413        56416 :             continue;
    1414              :           else
    1415              :             kind = scalar_stmt;
    1416              : 
    1417              :           /* The target cost model applies the inner-loop frequency.  */
    1418      1846067 :           record_stmt_cost (&LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo),
    1419              :                             1, kind, stmt_info, 0, vect_body);
    1420              :         }
    1421              :     }
    1422              : 
    1423              :   /* Now accumulate cost.  */
    1424       391551 :   loop_vinfo->scalar_costs = init_cost (loop_vinfo, true);
    1425       391551 :   add_stmt_costs (loop_vinfo->scalar_costs,
    1426              :                   &LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo));
    1427       391551 :   loop_vinfo->scalar_costs->finish_cost (nullptr);
    1428       391551 : }
    1429              : 
    1430              : /* Function vect_analyze_loop_form.
    1431              : 
    1432              :    Verify that certain CFG restrictions hold, including:
    1433              :    - the loop has a pre-header
    1434              :    - the loop has a single entry
    1435              :    - nested loops can have only a single exit.
    1436              :    - the loop exit condition is simple enough
    1437              :    - the number of iterations can be analyzed, i.e, a countable loop.  The
    1438              :      niter could be analyzed under some assumptions.  */
    1439              : 
    1440              : opt_result
    1441       477849 : vect_analyze_loop_form (class loop *loop, gimple *loop_vectorized_call,
    1442              :                         vect_loop_form_info *info)
    1443              : {
    1444       477849 :   DUMP_VECT_SCOPE ("vect_analyze_loop_form");
    1445              : 
    1446       477849 :   edge exit_e = vec_init_loop_exit_info (loop);
    1447       477849 :   if (!exit_e)
    1448        30181 :     return opt_result::failure_at (vect_location,
    1449              :                                    "not vectorized:"
    1450              :                                    " Infinite loop detected.\n");
    1451       447668 :   if (loop_vectorized_call)
    1452              :     {
    1453        25548 :       tree arg = gimple_call_arg (loop_vectorized_call, 1);
    1454        25548 :       class loop *scalar_loop = get_loop (cfun, tree_to_shwi (arg));
    1455        25548 :       edge scalar_exit_e = vec_init_loop_exit_info (scalar_loop);
    1456        25548 :       if (!scalar_exit_e)
    1457            0 :         return opt_result::failure_at (vect_location,
    1458              :                                        "not vectorized:"
    1459              :                                        " could not determine main exit from"
    1460              :                                        " loop with multiple exits.\n");
    1461              :     }
    1462              : 
    1463       447668 :   info->loop_exit = exit_e;
    1464       447668 :   if (dump_enabled_p ())
    1465        16862 :       dump_printf_loc (MSG_NOTE, vect_location,
    1466              :                        "using as main loop exit: %d -> %d [AUX: %p]\n",
    1467        16862 :                        exit_e->src->index, exit_e->dest->index, exit_e->aux);
    1468              : 
    1469              :   /* Check if we have any control flow that doesn't leave the loop.  */
    1470       447668 :   unsigned int nbbs;
    1471       447668 :   info->bbs = vect_get_loop_dfs_bbs (loop, &nbbs);
    1472      1371212 :   for (unsigned i = 0; i < nbbs; i++)
    1473      1043668 :     if (EDGE_COUNT (info->bbs[i]->succs) != 1
    1474      1043668 :         && (EDGE_COUNT (info->bbs[i]->succs) != 2
    1475       654618 :             || !loop_exits_from_bb_p (info->bbs[i]->loop_father,
    1476              :                                       info->bbs[i])))
    1477       120124 :       return opt_result::failure_at (vect_location,
    1478              :                                      "not vectorized:"
    1479              :                                      " unsupported control flow in loop.\n");
    1480              : 
    1481              :   /* Check if we have any control flow that doesn't leave the loop.  */
    1482       328638 :   bool has_phi = false;
    1483       328638 :   for (unsigned i = 0; i < nbbs; i++)
    1484       328175 :     if (!gimple_seq_empty_p (phi_nodes (info->bbs[i])))
    1485              :       {
    1486              :         has_phi = true;
    1487              :         break;
    1488              :       }
    1489       327544 :   if (!has_phi)
    1490          463 :     return opt_result::failure_at (vect_location,
    1491              :                                    "not vectorized:"
    1492              :                                    " no scalar evolution detected in loop.\n");
    1493              : 
    1494              :   /* Different restrictions apply when we are considering an inner-most loop,
    1495              :      vs. an outer (nested) loop.
    1496              :      (FORNOW. May want to relax some of these restrictions in the future).  */
    1497              : 
    1498       327081 :   info->inner_loop_cond = NULL;
    1499       327081 :   if (!loop->inner)
    1500              :     {
    1501              :       /* Inner-most loop.  */
    1502              : 
    1503       306670 :       if (empty_block_p (loop->header))
    1504            0 :         return opt_result::failure_at (vect_location,
    1505              :                                        "not vectorized: empty loop.\n");
    1506              :     }
    1507              :   else
    1508              :     {
    1509        20411 :       class loop *innerloop = loop->inner;
    1510        20411 :       edge entryedge;
    1511              : 
    1512              :       /* Nested loop. We currently require that the loop is doubly-nested,
    1513              :          contains a single inner loop with a single exit to the block
    1514              :          with the single exit condition in the outer loop.
    1515              :          Vectorizable outer-loops look like this:
    1516              : 
    1517              :                         (pre-header)
    1518              :                            |
    1519              :                           header <---+
    1520              :                            |         |
    1521              :                           inner-loop |
    1522              :                            |         |
    1523              :                           tail ------+
    1524              :                            |
    1525              :                         (exit-bb)
    1526              : 
    1527              :          The inner-loop also has the properties expected of inner-most loops
    1528              :          as described above.  */
    1529              : 
    1530        20411 :       if ((loop->inner)->inner || (loop->inner)->next)
    1531         3091 :         return opt_result::failure_at (vect_location,
    1532              :                                        "not vectorized:"
    1533              :                                        " multiple nested loops.\n");
    1534              : 
    1535        17320 :       entryedge = loop_preheader_edge (innerloop);
    1536        17320 :       if (entryedge->src != loop->header
    1537        16786 :           || !single_exit (innerloop)
    1538        29240 :           || single_exit (innerloop)->dest != EDGE_PRED (loop->latch, 0)->src)
    1539         5712 :         return opt_result::failure_at (vect_location,
    1540              :                                        "not vectorized:"
    1541              :                                        " unsupported outerloop form.\n");
    1542              : 
    1543              :       /* Analyze the inner-loop.  */
    1544        11608 :       vect_loop_form_info inner;
    1545        11608 :       opt_result res = vect_analyze_loop_form (loop->inner, NULL, &inner);
    1546        11608 :       if (!res)
    1547              :         {
    1548          417 :           if (dump_enabled_p ())
    1549            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1550              :                              "not vectorized: Bad inner loop.\n");
    1551          417 :           return res;
    1552              :         }
    1553              : 
    1554              :       /* Don't support analyzing niter under assumptions for inner
    1555              :          loop.  */
    1556        11191 :       if (!integer_onep (inner.assumptions))
    1557          263 :         return opt_result::failure_at (vect_location,
    1558              :                                        "not vectorized: Bad inner loop.\n");
    1559              : 
    1560        10928 :       if (inner.number_of_iterations ==  chrec_dont_know
    1561        10928 :           || !expr_invariant_in_loop_p (loop, inner.number_of_iterations))
    1562         1867 :         return opt_result::failure_at (vect_location,
    1563              :                                        "not vectorized: inner-loop count not"
    1564              :                                        " invariant.\n");
    1565              : 
    1566         9061 :       if (dump_enabled_p ())
    1567         1062 :         dump_printf_loc (MSG_NOTE, vect_location,
    1568              :                          "Considering outer-loop vectorization.\n");
    1569         9061 :       info->inner_loop_cond = inner.conds[0];
    1570        11608 :     }
    1571              : 
    1572       315731 :   if (EDGE_COUNT (loop->header->preds) != 2)
    1573            0 :     return opt_result::failure_at (vect_location,
    1574              :                                    "not vectorized:"
    1575              :                                    " too many incoming edges.\n");
    1576              : 
    1577              :   /* We assume that the latch is empty.  */
    1578       315731 :   basic_block latch = loop->latch;
    1579       315731 :   do
    1580              :     {
    1581       315731 :       if (!empty_block_p (latch)
    1582       315731 :           || !gimple_seq_empty_p (phi_nodes (latch)))
    1583        20382 :         return opt_result::failure_at (vect_location,
    1584              :                                        "not vectorized: latch block not "
    1585              :                                        "empty.\n");
    1586       295349 :       latch = single_pred (latch);
    1587              :     }
    1588       590698 :   while (single_succ_p (latch));
    1589              : 
    1590              :   /* Make sure there is no abnormal exit.  */
    1591       295349 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
    1592      1310419 :   for (edge e : exits)
    1593              :     {
    1594       424405 :       if (e->flags & EDGE_ABNORMAL)
    1595           33 :         return opt_result::failure_at (vect_location,
    1596              :                                        "not vectorized:"
    1597              :                                        " abnormal loop exit edge.\n");
    1598              :     }
    1599              : 
    1600       295316 :   info->conds
    1601       295316 :     = vect_get_loop_niters (loop, exit_e, &info->assumptions,
    1602              :                             &info->number_of_iterations,
    1603       295316 :                             &info->number_of_iterationsm1);
    1604       295316 :   if (info->conds.is_empty ())
    1605           34 :     return opt_result::failure_at
    1606           34 :       (vect_location,
    1607              :        "not vectorized: complicated exit condition.\n");
    1608              : 
    1609              :   /* Determine what the primary and alternate exit conds are.  */
    1610       719620 :   for (unsigned i = 0; i < info->conds.length (); i++)
    1611              :     {
    1612       424338 :       gcond *cond = info->conds[i];
    1613       424338 :       if (exit_e->src == gimple_bb (cond))
    1614       295282 :         std::swap (info->conds[0], info->conds[i]);
    1615              :     }
    1616              : 
    1617       295282 :   if (chrec_contains_undetermined (info->number_of_iterations))
    1618              :     {
    1619        60300 :       if (dump_enabled_p ())
    1620          287 :         dump_printf_loc (MSG_NOTE, vect_location,
    1621              :                          "Loop being analyzed as uncounted.\n");
    1622        60300 :       if (loop->inner)
    1623          563 :         return opt_result::failure_at
    1624          563 :           (vect_location,
    1625              :            "not vectorized: outer loop vectorization of uncounted loops"
    1626              :            " is unsupported.\n");
    1627        59737 :       return opt_result::success ();
    1628              :     }
    1629              : 
    1630       234982 :   if (integer_zerop (info->assumptions))
    1631            4 :     return opt_result::failure_at
    1632            4 :       (info->conds[0],
    1633              :        "not vectorized: number of iterations cannot be computed.\n");
    1634              : 
    1635       234978 :   if (integer_zerop (info->number_of_iterations))
    1636           18 :     return opt_result::failure_at
    1637           18 :       (info->conds[0],
    1638              :        "not vectorized: number of iterations = 0.\n");
    1639              : 
    1640       234960 :   if (!(tree_fits_shwi_p (info->number_of_iterations)
    1641       128922 :         && tree_to_shwi (info->number_of_iterations) > 0))
    1642              :     {
    1643       106038 :       if (dump_enabled_p ())
    1644              :         {
    1645         2877 :           dump_printf_loc (MSG_NOTE, vect_location,
    1646              :                            "Symbolic number of iterations is ");
    1647         2877 :           dump_generic_expr (MSG_NOTE, TDF_DETAILS, info->number_of_iterations);
    1648         2877 :           dump_printf (MSG_NOTE, "\n");
    1649              :         }
    1650              :     }
    1651              : 
    1652       234960 :   return opt_result::success ();
    1653       295349 : }
    1654              : 
    1655              : /* Create a loop_vec_info for LOOP with SHARED and the
    1656              :    vect_analyze_loop_form result.  */
    1657              : 
    1658              : loop_vec_info
    1659       550572 : vect_create_loop_vinfo (class loop *loop, vec_info_shared *shared,
    1660              :                         const vect_loop_form_info *info,
    1661              :                         loop_vec_info orig_loop_info)
    1662              : {
    1663       550572 :   loop_vec_info loop_vinfo = new _loop_vec_info (loop, shared, info->bbs);
    1664       550572 :   LOOP_VINFO_NITERSM1 (loop_vinfo) = info->number_of_iterationsm1;
    1665       550572 :   LOOP_VINFO_NITERS (loop_vinfo) = info->number_of_iterations;
    1666       550572 :   LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = info->number_of_iterations;
    1667       550572 :   LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo) = orig_loop_info;
    1668       550572 :   if (orig_loop_info && LOOP_VINFO_EPILOGUE_P (orig_loop_info))
    1669          409 :     LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo)
    1670          409 :       = LOOP_VINFO_MAIN_LOOP_INFO (orig_loop_info);
    1671              :   else
    1672       550163 :     LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo) = orig_loop_info;
    1673              :   /* Also record the assumptions for versioning.  */
    1674       550572 :   if (!integer_onep (info->assumptions) && !orig_loop_info)
    1675        20454 :     LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo) = info->assumptions;
    1676              : 
    1677      2444697 :   for (gcond *cond : info->conds)
    1678              :     {
    1679       792981 :       stmt_vec_info loop_cond_info = loop_vinfo->lookup_stmt (cond);
    1680              :       /* Mark the statement as a condition.  */
    1681       792981 :       STMT_VINFO_DEF_TYPE (loop_cond_info) = vect_condition_def;
    1682              :     }
    1683              : 
    1684       550572 :   unsigned cond_id = 0;
    1685       550572 :   if (!LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
    1686       485676 :     LOOP_VINFO_LOOP_IV_COND (loop_vinfo) = info->conds[cond_id++];
    1687              : 
    1688       857877 :   for (; cond_id < info->conds.length (); cond_id ++)
    1689       307305 :     LOOP_VINFO_LOOP_CONDS (loop_vinfo).safe_push (info->conds[cond_id]);
    1690              : 
    1691       550572 :   LOOP_VINFO_MAIN_EXIT (loop_vinfo) = info->loop_exit;
    1692              : 
    1693              :   /* Check to see if we're vectorizing multiple exits.  */
    1694       550572 :   LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
    1695       550572 :     = !LOOP_VINFO_LOOP_CONDS (loop_vinfo).is_empty ();
    1696              : 
    1697              :   /* At the moment we can't support no epilogs for multiple exits, result of
    1698              :      the first compare should be masked by that of the second.  We can only
    1699              :      allow it if the early exits have the same live values.  for differing
    1700              :      values we have to calculate a third mask to disambiguate. */
    1701       550572 :   LOOP_VINFO_EARLY_BRK_NEEDS_EPILOG (loop_vinfo)
    1702       550572 :     = LOOP_VINFO_LOOP_CONDS (loop_vinfo).length () > 1;
    1703              : 
    1704       550572 :   if (info->inner_loop_cond)
    1705              :     {
    1706              :       /* If we have an estimate on the number of iterations of the inner
    1707              :          loop use that to limit the scale for costing, otherwise use
    1708              :          --param vect-inner-loop-cost-factor literally.  */
    1709         7326 :       widest_int nit;
    1710         7326 :       if (estimated_stmt_executions (loop->inner, &nit))
    1711         6035 :         LOOP_VINFO_INNER_LOOP_COST_FACTOR (loop_vinfo)
    1712         6035 :           = wi::smin (nit, param_vect_inner_loop_cost_factor).to_uhwi ();
    1713         7326 :     }
    1714              : 
    1715       550572 :   return loop_vinfo;
    1716              : }
    1717              : 
    1718              : 
    1719              : 
    1720              : /* Return true if we know that the iteration count is smaller than the
    1721              :    vectorization factor.  Return false if it isn't, or if we can't be sure
    1722              :    either way.  */
    1723              : 
    1724              : static bool
    1725       163473 : vect_known_niters_smaller_than_vf (loop_vec_info loop_vinfo)
    1726              : {
    1727       163473 :   unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
    1728              : 
    1729       163473 :   HOST_WIDE_INT max_niter;
    1730       163473 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
    1731        83168 :     max_niter = LOOP_VINFO_INT_NITERS (loop_vinfo);
    1732              :   else
    1733        80305 :     max_niter = max_stmt_executions_int (LOOP_VINFO_LOOP (loop_vinfo));
    1734              : 
    1735       163473 :   if (max_niter != -1 && (unsigned HOST_WIDE_INT) max_niter < assumed_vf)
    1736        11321 :     return true;
    1737              : 
    1738              :   return false;
    1739              : }
    1740              : 
    1741              : /* Analyze the cost of the loop described by LOOP_VINFO.  Decide if it
    1742              :    is worthwhile to vectorize.  Return 1 if definitely yes, 0 if
    1743              :    definitely no, or -1 if it's worth retrying.  */
    1744              : 
    1745              : static int
    1746       163487 : vect_analyze_loop_costing (loop_vec_info loop_vinfo,
    1747              :                            unsigned *suggested_unroll_factor)
    1748              : {
    1749       163487 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    1750       163487 :   unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
    1751              : 
    1752              :   /* Only loops that can handle partially-populated vectors can have iteration
    1753              :      counts less than the vectorization factor.  */
    1754       163487 :   if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    1755       163487 :       && vect_known_niters_smaller_than_vf (loop_vinfo))
    1756              :     {
    1757        11311 :       if (dump_enabled_p ())
    1758          265 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1759              :                          "not vectorized: iteration count smaller than "
    1760              :                          "vectorization factor.\n");
    1761              :       return 0;
    1762              :     }
    1763              : 
    1764              :   /* If we know the number of iterations we can do better, for the
    1765              :      epilogue we can also decide whether the main loop leaves us
    1766              :      with enough iterations, preferring a smaller vector epilog then
    1767              :      also possibly used for the case we skip the vector loop.  */
    1768       152176 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
    1769              :     {
    1770        73152 :       widest_int scalar_niters
    1771        73152 :         = wi::to_widest (LOOP_VINFO_NITERSM1 (loop_vinfo)) + 1;
    1772        73152 :       if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
    1773              :         {
    1774         3000 :           loop_vec_info orig_loop_vinfo
    1775              :             = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
    1776         3000 :           loop_vec_info main_loop_vinfo
    1777              :             = LOOP_VINFO_MAIN_LOOP_INFO (loop_vinfo);
    1778         3000 :           unsigned lowest_vf
    1779         3000 :             = constant_lower_bound (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo));
    1780         3000 :           int prolog_peeling = 0;
    1781         3000 :           if (!vect_use_loop_mask_for_alignment_p (main_loop_vinfo))
    1782         3000 :             prolog_peeling = LOOP_VINFO_PEELING_FOR_ALIGNMENT (main_loop_vinfo);
    1783         3000 :           if (prolog_peeling >= 0
    1784         3000 :               && known_eq (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo),
    1785              :                            lowest_vf))
    1786              :             {
    1787         5988 :               unsigned gap
    1788         2994 :                 = LOOP_VINFO_PEELING_FOR_GAPS (main_loop_vinfo) ? 1 : 0;
    1789         5988 :               scalar_niters = ((scalar_niters - gap - prolog_peeling)
    1790         5988 :                                % lowest_vf + gap);
    1791              :             }
    1792              :         }
    1793              :       /* Reject vectorizing for a single scalar iteration, even if
    1794              :          we could in principle implement that using partial vectors.
    1795              :          But allow such vectorization if VF == 1 in case we do not
    1796              :          need to peel for gaps (if we need, avoid vectorization for
    1797              :          reasons of code footprint).  */
    1798        73152 :       unsigned peeling_gap = LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo);
    1799        73152 :       if (scalar_niters <= peeling_gap + 1
    1800        73152 :           && (assumed_vf > 1 || peeling_gap != 0))
    1801              :         {
    1802          694 :           if (dump_enabled_p ())
    1803          162 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1804              :                              "not vectorized: loop only has a single "
    1805              :                              "scalar iteration.\n");
    1806              :           return 0;
    1807              :         }
    1808              : 
    1809        72458 :       if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    1810              :         {
    1811              :           /* Check that the loop processes at least one full vector.  */
    1812        72445 :           poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    1813        72445 :           if (known_lt (scalar_niters, vf))
    1814              :             {
    1815          403 :               if (dump_enabled_p ())
    1816          347 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1817              :                                  "loop does not have enough iterations "
    1818              :                                  "to support vectorization.\n");
    1819          443 :               return 0;
    1820              :             }
    1821              : 
    1822              :           /* If we need to peel an extra epilogue iteration to handle data
    1823              :              accesses with gaps, check that there are enough scalar iterations
    1824              :              available.
    1825              : 
    1826              :              The check above is redundant with this one when peeling for gaps,
    1827              :              but the distinction is useful for diagnostics.  */
    1828        72042 :           if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
    1829        72360 :               && known_le (scalar_niters, vf))
    1830              :             {
    1831           40 :               if (dump_enabled_p ())
    1832            9 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1833              :                                  "loop does not have enough iterations "
    1834              :                                  "to support peeling for gaps.\n");
    1835              :               return 0;
    1836              :             }
    1837              :         }
    1838        73152 :     }
    1839              : 
    1840              :   /* If using the "very cheap" model. reject cases in which we'd keep
    1841              :      a copy of the scalar code (even if we might be able to vectorize it).  */
    1842       151039 :   if (loop_cost_model (loop) == VECT_COST_MODEL_VERY_CHEAP
    1843       151039 :       && (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
    1844        79001 :           || LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)))
    1845              :     {
    1846          721 :       if (dump_enabled_p ())
    1847            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1848              :                          "some scalar iterations would need to be peeled\n");
    1849              :       return 0;
    1850              :     }
    1851              : 
    1852       150318 :   int min_profitable_iters, min_profitable_estimate;
    1853       150318 :   vect_estimate_min_profitable_iters (loop_vinfo, &min_profitable_iters,
    1854              :                                       &min_profitable_estimate,
    1855              :                                       suggested_unroll_factor);
    1856              : 
    1857       150318 :   if (min_profitable_iters < 0)
    1858              :     {
    1859        25190 :       if (dump_enabled_p ())
    1860           38 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1861              :                          "not vectorized: vectorization not profitable.\n");
    1862        25190 :       if (dump_enabled_p ())
    1863           38 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1864              :                          "not vectorized: vector version will never be "
    1865              :                          "profitable.\n");
    1866              :       return -1;
    1867              :     }
    1868              : 
    1869       125128 :   int min_scalar_loop_bound = (param_min_vect_loop_bound
    1870       125128 :                                * assumed_vf);
    1871              : 
    1872              :   /* Use the cost model only if it is more conservative than user specified
    1873              :      threshold.  */
    1874       125128 :   unsigned int th = (unsigned) MAX (min_scalar_loop_bound,
    1875              :                                     min_profitable_iters);
    1876              : 
    1877       125128 :   LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = th;
    1878              : 
    1879        66475 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    1880       191603 :       && LOOP_VINFO_INT_NITERS (loop_vinfo) < th)
    1881              :     {
    1882          597 :       if (dump_enabled_p ())
    1883            2 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1884              :                          "not vectorized: vectorization not profitable.\n");
    1885          597 :       if (dump_enabled_p ())
    1886            2 :         dump_printf_loc (MSG_NOTE, vect_location,
    1887              :                          "not vectorized: iteration count smaller than user "
    1888              :                          "specified loop bound parameter or minimum profitable "
    1889              :                          "iterations (whichever is more conservative).\n");
    1890              :       return 0;
    1891              :     }
    1892              : 
    1893              :   /* The static profitablity threshold min_profitable_estimate includes
    1894              :      the cost of having to check at runtime whether the scalar loop
    1895              :      should be used instead.  If it turns out that we don't need or want
    1896              :      such a check, the threshold we should use for the static estimate
    1897              :      is simply the point at which the vector loop becomes more profitable
    1898              :      than the scalar loop.  */
    1899       124531 :   if (min_profitable_estimate > min_profitable_iters
    1900        29171 :       && !LOOP_REQUIRES_VERSIONING (loop_vinfo)
    1901        28565 :       && !LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
    1902          639 :       && !LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
    1903       125170 :       && !vect_apply_runtime_profitability_check_p (loop_vinfo))
    1904              :     {
    1905           14 :       if (dump_enabled_p ())
    1906            8 :         dump_printf_loc (MSG_NOTE, vect_location, "no need for a runtime"
    1907              :                          " choice between the scalar and vector loops\n");
    1908           14 :       min_profitable_estimate = min_profitable_iters;
    1909              :     }
    1910              : 
    1911              :   /* If the vector loop needs multiple iterations to be beneficial then
    1912              :      things are probably too close to call, and the conservative thing
    1913              :      would be to stick with the scalar code.  */
    1914       124531 :   if (loop_cost_model (loop) == VECT_COST_MODEL_VERY_CHEAP
    1915        63306 :       && !LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    1916       149323 :       && min_profitable_estimate > (int) vect_vf_for_cost (loop_vinfo))
    1917              :     {
    1918        16088 :       if (dump_enabled_p ())
    1919          225 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1920              :                          "one iteration of the vector loop would be"
    1921              :                          " more expensive than the equivalent number of"
    1922              :                          " iterations of the scalar loop\n");
    1923              :       return 0;
    1924              :     }
    1925              : 
    1926       108443 :   HOST_WIDE_INT estimated_niter;
    1927              : 
    1928              :   /* If we are vectorizing an epilogue then we know the maximum number of
    1929              :      scalar iterations it will cover is at least one lower than the
    1930              :      vectorization factor of the main loop.  */
    1931       108443 :   if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
    1932        13180 :     estimated_niter
    1933        13180 :       = vect_vf_for_cost (LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo)) - 1;
    1934              :   else
    1935              :     {
    1936        95263 :       estimated_niter = estimated_stmt_executions_int (loop);
    1937        95263 :       if (estimated_niter == -1)
    1938        31715 :         estimated_niter = likely_max_stmt_executions_int (loop);
    1939              :     }
    1940        44895 :   if (estimated_niter != -1
    1941       105483 :       && ((unsigned HOST_WIDE_INT) estimated_niter
    1942       105483 :           < MAX (th, (unsigned) min_profitable_estimate)))
    1943              :     {
    1944         4837 :       if (dump_enabled_p ())
    1945           38 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1946              :                          "not vectorized: estimated iteration count too "
    1947              :                          "small.\n");
    1948         4837 :       if (dump_enabled_p ())
    1949           38 :         dump_printf_loc (MSG_NOTE, vect_location,
    1950              :                          "not vectorized: estimated iteration count smaller "
    1951              :                          "than specified loop bound parameter or minimum "
    1952              :                          "profitable iterations (whichever is more "
    1953              :                          "conservative).\n");
    1954              :       return -1;
    1955              :     }
    1956              : 
    1957              :   /* As we cannot use a runtime check to gate profitability for uncounted
    1958              :      loops require either an estimate or if none, at least a profitable
    1959              :      vectorization within the first vector iteration (that condition
    1960              :      will practically never be true due to the required epilog and
    1961              :      likely alignment prologue).   */
    1962       103606 :   if (LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo)
    1963          177 :       && estimated_niter == -1
    1964       103744 :       && min_profitable_estimate > (int) vect_vf_for_cost (loop_vinfo))
    1965              :     {
    1966          120 :       if (dump_enabled_p ())
    1967            2 :         dump_printf_loc (MSG_NOTE, vect_location,
    1968              :                          "not vectorized: no loop iteration estimate on the "
    1969              :                          "uncounted loop and not trivially profitable.\n");
    1970              :       return -1;
    1971              :     }
    1972              : 
    1973              :   return 1;
    1974              : }
    1975              : 
    1976              : /* Gather data references in LOOP with body BBS and store them into
    1977              :    *DATAREFS.  */
    1978              : 
    1979              : static opt_result
    1980       282809 : vect_get_datarefs_in_loop (loop_p loop,
    1981              :                            const vect_loop_form_info &loop_form_info,
    1982              :                            vec<data_reference_p> *datarefs)
    1983              : {
    1984       846871 :   for (unsigned i = 0; i < loop->num_nodes; i++)
    1985      1255490 :     for (gimple_stmt_iterator gsi = gsi_start_bb (loop_form_info.bbs[i]);
    1986      5399443 :          !gsi_end_p (gsi); gsi_next (&gsi))
    1987              :       {
    1988      4835381 :         gimple *stmt = gsi_stmt (gsi);
    1989      4835381 :         if (is_gimple_debug (stmt))
    1990      2259456 :           continue;
    1991              : 
    1992              :         /* An uncounted loop doesn't have analyzed niters.  Don't record
    1993              :            nowrap assumptions for it.
    1994              :            ??? We could probably make this work by adding a virtual
    1995              :            early-break exit that guards the type bound?  */
    1996      2576061 :         bool record_nowrap_assumptions = true;
    1997      2576061 :         if (!loop_form_info.number_of_iterations
    1998      5152122 :             || chrec_contains_undetermined
    1999      2576061 :             (loop_form_info.number_of_iterations))
    2000              :           record_nowrap_assumptions = false;
    2001              : 
    2002              :         /* Don't record assumptions for nested loops until we can
    2003              :            express assumptions WRT outer loop and their niter.  */
    2004      2576061 :         if (loop->inner)
    2005       122390 :           record_nowrap_assumptions = false;
    2006              : 
    2007      2576061 :         opt_result res = vect_find_stmt_data_reference
    2008      2576061 :           (loop, stmt, datarefs, NULL, 0, record_nowrap_assumptions);
    2009      2576061 :         if (!res)
    2010              :           {
    2011        63819 :             if (is_gimple_call (stmt) && loop->safelen)
    2012              :               {
    2013          412 :                 tree fndecl = gimple_call_fndecl (stmt), op;
    2014          412 :                 if (fndecl == NULL_TREE
    2015          412 :                     && gimple_call_internal_p (stmt, IFN_MASK_CALL))
    2016              :                   {
    2017            0 :                     fndecl = gimple_call_arg (stmt, 0);
    2018            0 :                     gcc_checking_assert (TREE_CODE (fndecl) == ADDR_EXPR);
    2019            0 :                     fndecl = TREE_OPERAND (fndecl, 0);
    2020            0 :                     gcc_checking_assert (TREE_CODE (fndecl) == FUNCTION_DECL);
    2021              :                   }
    2022          412 :                 if (fndecl != NULL_TREE)
    2023              :                   {
    2024          375 :                     cgraph_node *node = cgraph_node::get (fndecl);
    2025          375 :                     if (node != NULL && node->simd_clones != NULL)
    2026              :                       {
    2027          137 :                         unsigned int j, n = gimple_call_num_args (stmt);
    2028          565 :                         for (j = 0; j < n; j++)
    2029              :                           {
    2030          292 :                             op = gimple_call_arg (stmt, j);
    2031          292 :                             if (DECL_P (op)
    2032          292 :                                 || (REFERENCE_CLASS_P (op)
    2033            0 :                                     && get_base_address (op)))
    2034              :                               break;
    2035              :                           }
    2036          137 :                         op = gimple_call_lhs (stmt);
    2037              :                         /* Ignore #pragma omp declare simd functions
    2038              :                            if they don't have data references in the
    2039              :                            call stmt itself.  */
    2040          273 :                         if (j == n
    2041          137 :                             && !(op
    2042          124 :                                  && (DECL_P (op)
    2043          124 :                                      || (REFERENCE_CLASS_P (op)
    2044            0 :                                          && get_base_address (op)))))
    2045          136 :                           continue;
    2046              :                       }
    2047              :                   }
    2048              :               }
    2049        63683 :             return res;
    2050              :           }
    2051              :         /* If dependence analysis will give up due to the limit on the
    2052              :            number of datarefs stop here and fail fatally.  */
    2053      4444052 :         if (datarefs->length ()
    2054      1931810 :             > (unsigned)param_loop_max_datarefs_for_datadeps)
    2055            0 :           return opt_result::failure_at (stmt, "exceeded param "
    2056              :                                          "loop-max-datarefs-for-datadeps\n");
    2057              :       }
    2058       219126 :   return opt_result::success ();
    2059              : }
    2060              : 
    2061              : /* Gather no-wrap bounds from SHARED's datarefs and accumulate them in
    2062              :    one assumption.  Validate this assumption, as well as INFO's niter
    2063              :    assumption and return an error on failure.
    2064              :    If the assumptions are valid, reset loop properties as well as
    2065              :    scev's hashtable and return success.  */
    2066              : 
    2067              : static opt_result
    2068       219126 : vect_build_assumptions (class loop *loop, vec_info_shared *shared,
    2069              :                         vect_loop_form_info *info)
    2070              : {
    2071       219126 :   tree niterm1 = info->number_of_iterationsm1;
    2072       219126 :   bool niter_known = niterm1 && !chrec_contains_undetermined (niterm1);
    2073              : 
    2074       219126 :   tree nowrap_assum = NULL_TREE;
    2075       219126 :   tree bound_min = NULL_TREE;
    2076              : 
    2077       219126 :   unsigned int i;
    2078       219126 :   struct data_reference *dr;
    2079              : 
    2080              :   /* Build the minimum over all nowrap bounds.  */
    2081       777178 :   FOR_EACH_VEC_ELT (shared->datarefs, i, dr)
    2082              :     {
    2083       558052 :       tree bound = DR_NOWRAP_BOUND (dr);
    2084       558052 :       if (!bound)
    2085       556798 :         continue;
    2086              : 
    2087              :       /* Use scev's function to MIN two bounds.  */
    2088         1254 :       scev_combine_nowrap_bounds (&bound_min, bound);
    2089              :     }
    2090              : 
    2091       219126 :   gcc_assert (!bound_min || niter_known);
    2092              : 
    2093              :   /* Build "NITER - 1 <= BOUND_MIN".  */
    2094       219126 :   if (bound_min)
    2095              :     {
    2096          905 :       unsigned prec = MAX (TYPE_PRECISION (TREE_TYPE (niterm1)),
    2097              :                            TYPE_PRECISION (TREE_TYPE (bound_min)));
    2098          905 :       tree t = build_nonstandard_integer_type (prec, 1);
    2099          905 :       nowrap_assum = fold_build2 (LE_EXPR, boolean_type_node,
    2100              :                                   fold_convert (t, niterm1),
    2101              :                                   fold_convert (t, bound_min));
    2102              : 
    2103              :       /* Try to simplify the assumption with ranger.  */
    2104          905 :       value_range vr (TREE_TYPE (nowrap_assum));
    2105          905 :       tree better_assum;
    2106          905 :       if (get_range_query (cfun)->range_on_edge
    2107          905 :           (vr, loop_preheader_edge (loop), nowrap_assum)
    2108         1810 :           && vr.singleton_p (&better_assum))
    2109          193 :         nowrap_assum = better_assum;
    2110          905 :     }
    2111              : 
    2112              :   /* Combine nowrap assumptions and niter assumption.  */
    2113          905 :   if (nowrap_assum)
    2114              :     {
    2115          905 :       if (dump_enabled_p ())
    2116           21 :         dump_printf_loc (MSG_NOTE, vect_location,
    2117              :                          "adding no-wrap assumption: %T\n", nowrap_assum);
    2118              : 
    2119          905 :       if (info->assumptions && !integer_onep (info->assumptions))
    2120          253 :         nowrap_assum = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
    2121              :                                     info->assumptions, nowrap_assum);
    2122          905 :       info->assumptions = nowrap_assum;
    2123              :     }
    2124              : 
    2125       219126 :   if (integer_zerop (info->assumptions))
    2126          125 :     return opt_result::failure_at
    2127          125 :       (vect_location,
    2128              :        "not vectorized: number of iterations cannot be computed.\n");
    2129              : 
    2130       219001 :   if (!integer_onep (info->assumptions))
    2131              :     {
    2132         7825 :       if (dump_enabled_p ())
    2133              :         {
    2134           87 :           dump_printf_loc (MSG_NOTE, vect_location,
    2135              :                            "Loop to be versioned with assumption ");
    2136           87 :           dump_generic_expr (MSG_NOTE, TDF_SLIM, info->assumptions);
    2137           87 :           dump_printf (MSG_NOTE, "\n");
    2138              :         }
    2139              : 
    2140              :       /* We consider to vectorize this loop by versioning it under
    2141              :          some assumptions.  In order to do this, we need to clear
    2142              :          existing information computed by scev and niter analyzer.  */
    2143         7825 :       scev_reset_htab ();
    2144         7825 :       free_numbers_of_iterations_estimates (loop);
    2145              :       /* Also set flag for this loop so that following scev and niter
    2146              :          analysis are done under the assumptions.  */
    2147         7825 :       loop_constraint_set (loop, LOOP_C_FINITE);
    2148              :     }
    2149              :   else
    2150              :     /* Clear the existing niter information to make sure the nonwrapping flag
    2151              :        will be calculated and set propriately.  */
    2152       211176 :     free_numbers_of_iterations_estimates (loop);
    2153              : 
    2154       219001 :   return opt_result::success ();
    2155              : }
    2156              : 
    2157              : 
    2158              : /* Determine if operating on full vectors for LOOP_VINFO might leave
    2159              :    some scalar iterations still to do.  If so, decide how we should
    2160              :    handle those scalar iterations.  The possibilities are:
    2161              : 
    2162              :    (1) Make LOOP_VINFO operate on partial vectors instead of full vectors.
    2163              :        In this case:
    2164              : 
    2165              :          LOOP_VINFO_USING_PARTIAL_VECTORS_P == true
    2166              :          LOOP_VINFO_PEELING_FOR_NITER == false
    2167              : 
    2168              :    (2) Make LOOP_VINFO operate on full vectors and use an epilogue loop
    2169              :        to handle the remaining scalar iterations.  In this case:
    2170              : 
    2171              :          LOOP_VINFO_USING_PARTIAL_VECTORS_P == false
    2172              :          LOOP_VINFO_PEELING_FOR_NITER == true
    2173              : 
    2174              :    The MASKED_P argument specifies to what extent
    2175              :    param_vect_partial_vector_usage is to be honored.  For MASKED_P == 0
    2176              :    no partial vectors are to be used, for MASKED_P == -1 it's
    2177              :    param_vect_partial_vector_usage that gets to decide whether we may
    2178              :    consider partial vector usage.  For MASKED_P == 1 partial vectors
    2179              :    may be used if possible.
    2180              : 
    2181              :  */
    2182              : 
    2183              : static opt_result
    2184       164481 : vect_determine_partial_vectors_and_peeling (loop_vec_info loop_vinfo,
    2185              :                                             int masked_p)
    2186              : {
    2187              :   /* Determine whether there would be any scalar iterations left over.  */
    2188       164481 :   bool need_peeling_or_partial_vectors_p
    2189       164481 :     = vect_need_peeling_or_partial_vectors_p (loop_vinfo);
    2190              : 
    2191              :   /* Decide whether to vectorize the loop with partial vectors.  */
    2192       164481 :   LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2193       164481 :   if (masked_p == 0
    2194       164481 :       || (masked_p == -1 && param_vect_partial_vector_usage == 0))
    2195              :     /* If requested explicitly do not use partial vectors.  */
    2196              :     LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2197          231 :   else if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2198           71 :            && LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo))
    2199            0 :     LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = true;
    2200          231 :   else if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2201           71 :            && need_peeling_or_partial_vectors_p)
    2202              :     {
    2203              :       /* For partial-vector-usage=1, try to push the handling of partial
    2204              :          vectors to the epilogue, with the main loop continuing to operate
    2205              :          on full vectors.
    2206              : 
    2207              :          If we are unrolling we also do not want to use partial vectors. This
    2208              :          is to avoid the overhead of generating multiple masks and also to
    2209              :          avoid having to execute entire iterations of FALSE masked instructions
    2210              :          when dealing with one or less full iterations.
    2211              : 
    2212              :          ??? We could then end up failing to use partial vectors if we
    2213              :          decide to peel iterations into a prologue, and if the main loop
    2214              :          then ends up processing fewer than VF iterations.  */
    2215           48 :       if ((param_vect_partial_vector_usage == 1
    2216           15 :            || loop_vinfo->suggested_unroll_factor > 1)
    2217           33 :           && !LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2218           70 :           && !vect_known_niters_smaller_than_vf (loop_vinfo))
    2219              :         ;
    2220              :       else
    2221           36 :         LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = true;
    2222              :     }
    2223              : 
    2224       164481 :   if (LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2225            0 :       && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    2226            0 :     return opt_result::failure_at (vect_location,
    2227              :                                    "not vectorized: loop needs but cannot "
    2228              :                                    "use partial vectors\n");
    2229              : 
    2230       164481 :   if (dump_enabled_p ())
    2231        13494 :     dump_printf_loc (MSG_NOTE, vect_location,
    2232              :                      "operating on %s vectors%s.\n",
    2233        13494 :                      LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    2234              :                      ? "partial" : "full",
    2235        13494 :                      LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2236              :                      ? " for epilogue loop" : "");
    2237              : 
    2238       164481 :   LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
    2239       328962 :     = (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    2240       164481 :        && need_peeling_or_partial_vectors_p);
    2241              : 
    2242       164481 :   return opt_result::success ();
    2243              : }
    2244              : 
    2245              : /* Function vect_analyze_loop_2.
    2246              : 
    2247              :    Apply a set of analyses on LOOP specified by LOOP_VINFO, the different
    2248              :    analyses will record information in some members of LOOP_VINFO.  FATAL
    2249              :    indicates if some analysis meets fatal error.  If one non-NULL pointer
    2250              :    SUGGESTED_UNROLL_FACTOR is provided, it's intent to be filled with one
    2251              :    worked out suggested unroll factor, while one NULL pointer shows it's
    2252              :    going to apply the suggested unroll factor.
    2253              :    SINGLE_LANE_SLP_DONE_FOR_SUGGESTED_UF is to hold whether single-lane
    2254              :    slp was forced when the suggested unroll factor was worked out.  */
    2255              : static opt_result
    2256       549875 : vect_analyze_loop_2 (loop_vec_info loop_vinfo, int masked_p, bool &fatal,
    2257              :                      unsigned *suggested_unroll_factor,
    2258              :                      bool& single_lane_slp_done_for_suggested_uf)
    2259              : {
    2260       549875 :   opt_result ok = opt_result::success ();
    2261       549875 :   int res;
    2262       549875 :   unsigned int max_vf = MAX_VECTORIZATION_FACTOR;
    2263       549875 :   loop_vec_info orig_loop_vinfo = NULL;
    2264              : 
    2265              :   /* If we are dealing with an epilogue then orig_loop_vinfo points to the
    2266              :      loop_vec_info of the first vectorized loop.  */
    2267       549875 :   if (LOOP_VINFO_EPILOGUE_P (loop_vinfo))
    2268        15144 :     orig_loop_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
    2269              :   else
    2270              :     orig_loop_vinfo = loop_vinfo;
    2271        15144 :   gcc_assert (orig_loop_vinfo);
    2272              : 
    2273              :   /* We can't mask on niters for uncounted loops due to unknown upper bound.  */
    2274       549875 :   if (LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
    2275        64896 :     LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2276              : 
    2277              :   /* The first group of checks is independent of the vector size.  */
    2278       549875 :   fatal = true;
    2279              : 
    2280       549875 :   if (LOOP_VINFO_SIMD_IF_COND (loop_vinfo)
    2281       549875 :       && integer_zerop (LOOP_VINFO_SIMD_IF_COND (loop_vinfo)))
    2282            5 :     return opt_result::failure_at (vect_location,
    2283              :                                    "not vectorized: simd if(0)\n");
    2284              : 
    2285              :   /* Find all data references in the loop (which correspond to vdefs/vuses)
    2286              :      and analyze their evolution in the loop.  */
    2287              : 
    2288       549870 :   loop_p loop = LOOP_VINFO_LOOP (loop_vinfo);
    2289              : 
    2290              :   /* Check the data references.  */
    2291       549870 :   loop_vinfo->shared->check_datarefs ();
    2292              : 
    2293              :   /* Analyze the data references and also adjust the minimal
    2294              :      vectorization factor according to the loads and stores.  */
    2295              : 
    2296       549870 :   ok = vect_analyze_data_refs (loop_vinfo, &fatal);
    2297       549870 :   if (!ok)
    2298              :     {
    2299        77111 :       if (dump_enabled_p ())
    2300         1413 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2301              :                          "bad data references.\n");
    2302        77111 :       return ok;
    2303              :     }
    2304              : 
    2305              :   /* Check if we are applying unroll factor now.  */
    2306       472759 :   bool applying_suggested_uf = loop_vinfo->suggested_unroll_factor > 1;
    2307       472759 :   gcc_assert (!applying_suggested_uf || !suggested_unroll_factor);
    2308              : 
    2309              :   /* When single-lane SLP was forced and we are applying suggested unroll
    2310              :      factor, keep that decision here.  */
    2311       945518 :   bool force_single_lane = (applying_suggested_uf
    2312       472759 :                             && single_lane_slp_done_for_suggested_uf);
    2313              : 
    2314              :   /* Classify all cross-iteration scalar data-flow cycles.
    2315              :      Cross-iteration cycles caused by virtual phis are analyzed separately.  */
    2316       472759 :   vect_analyze_scalar_cycles (loop_vinfo);
    2317              : 
    2318       472759 :   vect_pattern_recog (loop_vinfo);
    2319              : 
    2320              :   /* Analyze the access patterns of the data-refs in the loop (consecutive,
    2321              :      complex, etc.). FORNOW: Only handle consecutive access pattern.  */
    2322              : 
    2323       472759 :   ok = vect_analyze_data_ref_accesses (loop_vinfo, NULL);
    2324       472759 :   if (!ok)
    2325              :     {
    2326         8354 :       if (dump_enabled_p ())
    2327          294 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2328              :                          "bad data access.\n");
    2329         8354 :       return ok;
    2330              :     }
    2331              : 
    2332              :   /* Data-flow analysis to detect stmts that do not need to be vectorized.  */
    2333              : 
    2334       464405 :   ok = vect_mark_stmts_to_be_vectorized (loop_vinfo, &fatal);
    2335       464405 :   if (!ok)
    2336              :     {
    2337        47590 :       if (dump_enabled_p ())
    2338          414 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2339              :                          "unexpected pattern.\n");
    2340        47590 :       return ok;
    2341              :     }
    2342              : 
    2343              :   /* While the rest of the analysis below depends on it in some way.  */
    2344       416815 :   fatal = false;
    2345              : 
    2346              :   /* Analyze data dependences between the data-refs in the loop
    2347              :      and adjust the maximum vectorization factor according to
    2348              :      the dependences.
    2349              :      FORNOW: fail at the first data dependence that we encounter.  */
    2350              : 
    2351       416815 :   ok = vect_analyze_data_ref_dependences (loop_vinfo, &max_vf);
    2352       416815 :   if (!ok)
    2353              :     {
    2354        25264 :       if (dump_enabled_p ())
    2355          608 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2356              :                          "bad data dependence.\n");
    2357        25264 :       return ok;
    2358              :     }
    2359       391551 :   LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo) = max_vf;
    2360              : 
    2361              :   /* Compute the scalar iteration cost.  */
    2362       391551 :   vect_compute_single_scalar_iteration_cost (loop_vinfo);
    2363              : 
    2364       391551 :   bool saved_can_use_partial_vectors_p
    2365              :     = LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo);
    2366              : 
    2367              :   /* This is the point where we can re-start analysis with single-lane
    2368              :      SLP forced.  */
    2369       539103 : start_over:
    2370              : 
    2371              :   /* Check the SLP opportunities in the loop, analyze and build
    2372              :      SLP trees.  */
    2373      1078206 :   ok = vect_analyze_slp (loop_vinfo, loop_vinfo->stmt_vec_infos.length (),
    2374              :                          force_single_lane);
    2375       539103 :   if (!ok)
    2376        19370 :     return ok;
    2377              : 
    2378              :   /* If there are any SLP instances mark them as pure_slp and compute
    2379              :      the overall vectorization factor.  */
    2380       519733 :   if (!vect_make_slp_decision (loop_vinfo))
    2381        70255 :     return opt_result::failure_at (vect_location, "no stmts to vectorize.\n");
    2382              : 
    2383       449478 :   if (dump_enabled_p ())
    2384        21388 :     dump_printf_loc (MSG_NOTE, vect_location, "Loop contains only SLP stmts\n");
    2385              : 
    2386              :   /* Dump the vectorization factor from the SLP decision.  */
    2387       449478 :   if (dump_enabled_p ())
    2388              :     {
    2389        21388 :       dump_printf_loc (MSG_NOTE, vect_location, "vectorization factor = ");
    2390        21388 :       dump_dec (MSG_NOTE, LOOP_VINFO_VECT_FACTOR (loop_vinfo));
    2391        21388 :       dump_printf (MSG_NOTE, "\n");
    2392              :     }
    2393              : 
    2394              :   /* We don't expect to have to roll back to anything other than an empty
    2395              :      set of rgroups.  */
    2396       449478 :   gcc_assert (LOOP_VINFO_MASKS (loop_vinfo).is_empty ());
    2397              : 
    2398              :   /* Apply the suggested unrolling factor, this was determined by the backend
    2399              :      during finish_cost the first time we ran the analysis for this
    2400              :      vector mode.  */
    2401       449478 :   if (applying_suggested_uf)
    2402          478 :     LOOP_VINFO_VECT_FACTOR (loop_vinfo) *= loop_vinfo->suggested_unroll_factor;
    2403              : 
    2404              :   /* Now the vectorization factor is final.  */
    2405       449478 :   poly_uint64 vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    2406       449478 :   gcc_assert (known_ne (vectorization_factor, 0U));
    2407              : 
    2408              :   /* Optimize the SLP graph with the vectorization factor fixed.  */
    2409       449478 :   vect_optimize_slp (loop_vinfo);
    2410              : 
    2411              :   /* Gather the loads reachable from the SLP graph entries.  */
    2412       449478 :   vect_gather_slp_loads (loop_vinfo);
    2413              : 
    2414       449478 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && dump_enabled_p ())
    2415              :     {
    2416        15398 :       dump_printf_loc (MSG_NOTE, vect_location,
    2417              :                        "vectorization_factor = ");
    2418        15398 :       dump_dec (MSG_NOTE, vectorization_factor);
    2419        15398 :       dump_printf (MSG_NOTE, ", niters = %wd\n",
    2420        15398 :                    LOOP_VINFO_INT_NITERS (loop_vinfo));
    2421              :     }
    2422              : 
    2423       449478 :   if (max_vf != MAX_VECTORIZATION_FACTOR
    2424       449478 :       && maybe_lt (max_vf, LOOP_VINFO_VECT_FACTOR (loop_vinfo)))
    2425           44 :     return opt_result::failure_at (vect_location, "bad data dependence.\n");
    2426              : 
    2427       449434 :   loop_vinfo->vector_costs = init_cost (loop_vinfo, false);
    2428              : 
    2429              :   /* Analyze the alignment of the data-refs in the loop.  */
    2430       449434 :   vect_analyze_data_refs_alignment (loop_vinfo);
    2431              : 
    2432              :   /* Prune the list of ddrs to be tested at run-time by versioning for alias.
    2433              :      It is important to call pruning after vect_analyze_data_ref_accesses,
    2434              :      since we use grouping information gathered by interleaving analysis.  */
    2435       449434 :   ok = vect_prune_runtime_alias_test_list (loop_vinfo);
    2436       449434 :   if (!ok)
    2437        17612 :     return ok;
    2438              : 
    2439              :   /* Do not invoke vect_enhance_data_refs_alignment for epilogue
    2440              :      vectorization, since we do not want to add extra peeling or
    2441              :      add versioning for alignment.  */
    2442       431822 :   if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
    2443              :     /* This pass will decide on using loop versioning and/or loop peeling in
    2444              :        order to enhance the alignment of data references in the loop.  */
    2445       415622 :     ok = vect_enhance_data_refs_alignment (loop_vinfo);
    2446       431822 :   if (!ok)
    2447         3650 :     return ok;
    2448              : 
    2449              :   /* Analyze operations in the SLP instances.  We can't simply
    2450              :      remove unsupported SLP instances as this makes the above
    2451              :      SLP kind detection invalid and might also affect the VF.  */
    2452       428172 :   if (! vect_slp_analyze_operations (loop_vinfo))
    2453              :     {
    2454       263691 :       ok = opt_result::failure_at (vect_location,
    2455              :                                    "unsupported SLP instances\n");
    2456       263691 :       goto again;
    2457              :     }
    2458              : 
    2459              :   /* For now, we don't expect to mix both masking and length approaches for one
    2460              :      loop, disable it if both are recorded.  */
    2461       164481 :   if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2462        24293 :       && !LOOP_VINFO_MASKS (loop_vinfo).is_empty ()
    2463       188768 :       && !LOOP_VINFO_LENS (loop_vinfo).is_empty ())
    2464              :     {
    2465            0 :       if (dump_enabled_p ())
    2466            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2467              :                          "can't vectorize a loop with partial vectors"
    2468              :                          " because we don't expect to mix different"
    2469              :                          " approaches with partial vectors for the"
    2470              :                          " same loop.\n");
    2471            0 :       LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2472              :     }
    2473              : 
    2474              :   /* If we still have the option of using partial vectors,
    2475              :      check whether we can generate the necessary loop controls.  */
    2476       164481 :   if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
    2477              :     {
    2478        24293 :       if (!LOOP_VINFO_MASKS (loop_vinfo).is_empty ())
    2479              :         {
    2480        24287 :           if (!vect_verify_full_masking (loop_vinfo)
    2481        24287 :               && !vect_verify_full_masking_avx512 (loop_vinfo))
    2482         6190 :             LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2483              :         }
    2484              :       else /* !LOOP_VINFO_LENS (loop_vinfo).is_empty () */
    2485            6 :         if (!vect_verify_loop_lens (loop_vinfo))
    2486            6 :           LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2487              :     }
    2488              : 
    2489              :   /* Decide whether this loop_vinfo should use partial vectors or peeling,
    2490              :      assuming that the loop will be used as a main loop.  We will redo
    2491              :      this analysis later if we instead decide to use the loop as an
    2492              :      epilogue loop.  */
    2493       164481 :   ok = vect_determine_partial_vectors_and_peeling (loop_vinfo, masked_p);
    2494       164481 :   if (!ok)
    2495            0 :     return ok;
    2496              : 
    2497              :   /* If we're vectorizing a loop that uses length "controls" and
    2498              :      can iterate more than once, we apply decrementing IV approach
    2499              :      in loop control.  */
    2500       164481 :   if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    2501           36 :       && LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo) == vect_partial_vectors_len
    2502            0 :       && LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo) == 0
    2503       164481 :       && !(LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    2504            0 :            && known_le (LOOP_VINFO_INT_NITERS (loop_vinfo),
    2505              :                         LOOP_VINFO_VECT_FACTOR (loop_vinfo))))
    2506            0 :     LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo) = true;
    2507              : 
    2508              :   /* If a loop uses length controls and has a decrementing loop control IV,
    2509              :      we will normally pass that IV through a MIN_EXPR to calcaluate the
    2510              :      basis for the length controls.  E.g. in a loop that processes one
    2511              :      element per scalar iteration, the number of elements would be
    2512              :      MIN_EXPR <N, VF>, where N is the number of scalar iterations left.
    2513              : 
    2514              :      This MIN_EXPR approach allows us to use pointer IVs with an invariant
    2515              :      step, since only the final iteration of the vector loop can have
    2516              :      inactive lanes.
    2517              : 
    2518              :      However, some targets have a dedicated instruction for calculating the
    2519              :      preferred length, given the total number of elements that still need to
    2520              :      be processed.  This is encapsulated in the SELECT_VL internal function.
    2521              : 
    2522              :      If the target supports SELECT_VL, we can use it instead of MIN_EXPR
    2523              :      to determine the basis for the length controls.  However, unlike the
    2524              :      MIN_EXPR calculation, the SELECT_VL calculation can decide to make
    2525              :      lanes inactive in any iteration of the vector loop, not just the last
    2526              :      iteration.  This SELECT_VL approach therefore requires us to use pointer
    2527              :      IVs with variable steps.
    2528              : 
    2529              :      Once we've decided how many elements should be processed by one
    2530              :      iteration of the vector loop, we need to populate the rgroup controls.
    2531              :      If a loop has multiple rgroups, we need to make sure that those rgroups
    2532              :      "line up" (that is, they must be consistent about which elements are
    2533              :      active and which aren't).  This is done by vect_adjust_loop_lens_control.
    2534              : 
    2535              :      In principle, it would be possible to use vect_adjust_loop_lens_control
    2536              :      on either the result of a MIN_EXPR or the result of a SELECT_VL.
    2537              :      However:
    2538              : 
    2539              :      (1) In practice, it only makes sense to use SELECT_VL when a vector
    2540              :          operation will be controlled directly by the result.  It is not
    2541              :          worth using SELECT_VL if it would only be the input to other
    2542              :          calculations.
    2543              : 
    2544              :      (2) If we use SELECT_VL for an rgroup that has N controls, each associated
    2545              :          pointer IV will need N updates by a variable amount (N-1 updates
    2546              :          within the iteration and 1 update to move to the next iteration).
    2547              : 
    2548              :      Because of this, we prefer to use the MIN_EXPR approach whenever there
    2549              :      is more than one length control.
    2550              : 
    2551              :      In addition, SELECT_VL always operates to a granularity of 1 unit.
    2552              :      If we wanted to use it to control an SLP operation on N consecutive
    2553              :      elements, we would need to make the SELECT_VL inputs measure scalar
    2554              :      iterations (rather than elements) and then multiply the SELECT_VL
    2555              :      result by N.  But using SELECT_VL this way is inefficient because
    2556              :      of (1) above.
    2557              : 
    2558              :      2. We don't apply SELECT_VL on single-rgroup when both (1) and (2) are
    2559              :         satisfied:
    2560              : 
    2561              :      (1). LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) is true.
    2562              :      (2). LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant () is true.
    2563              : 
    2564              :      Since SELECT_VL (variable step) will make SCEV analysis failed and then
    2565              :      we will fail to gain benefits of following unroll optimizations. We prefer
    2566              :      using the MIN_EXPR approach in this situation.  */
    2567       164481 :   if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo))
    2568              :     {
    2569            0 :       tree iv_type = LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo);
    2570            0 :       if (LOOP_VINFO_LENS (loop_vinfo).length () == 1
    2571            0 :           && LOOP_VINFO_LENS (loop_vinfo)[0].factor == 1
    2572            0 :           && (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    2573              :               || !LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant ()))
    2574            0 :         LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = true;
    2575              : 
    2576            0 :       if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
    2577            0 :         for (auto rgc : LOOP_VINFO_LENS (loop_vinfo))
    2578            0 :           if (rgc.type
    2579            0 :               && !direct_internal_fn_supported_p (IFN_SELECT_VL,
    2580              :                                                   rgc.type, iv_type,
    2581              :                                                   OPTIMIZE_FOR_SPEED))
    2582              :             {
    2583            0 :               LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = false;
    2584            0 :               break;
    2585              :             }
    2586              : 
    2587              :       /* If any of the SLP instances cover more than a single lane
    2588              :          we cannot use .SELECT_VL at the moment, even if the number
    2589              :          of lanes is uniform throughout the SLP graph.  */
    2590            0 :       if (LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo))
    2591            0 :         for (slp_instance inst : LOOP_VINFO_SLP_INSTANCES (loop_vinfo))
    2592            0 :           if (SLP_TREE_LANES (SLP_INSTANCE_TREE (inst)) != 1
    2593            0 :               && !(SLP_INSTANCE_KIND (inst) == slp_inst_kind_store
    2594            0 :                    && SLP_INSTANCE_TREE (inst)->ldst_lanes))
    2595              :             {
    2596            0 :               LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = false;
    2597            0 :               break;
    2598              :             }
    2599              :     }
    2600              : 
    2601              :   /* If we're vectorizing an epilogue loop, the vectorized loop either needs
    2602              :      to be able to handle fewer than VF scalars, or needs to have a lower VF
    2603              :      than the main loop.  */
    2604       164481 :   if (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2605        14695 :       && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    2606              :     {
    2607        14681 :       poly_uint64 unscaled_vf
    2608        14681 :         = exact_div (LOOP_VINFO_VECT_FACTOR (orig_loop_vinfo),
    2609              :                      orig_loop_vinfo->suggested_unroll_factor);
    2610        14681 :       if (maybe_ge (LOOP_VINFO_VECT_FACTOR (loop_vinfo), unscaled_vf))
    2611          406 :         return opt_result::failure_at (vect_location,
    2612              :                                        "Vectorization factor too high for"
    2613              :                                        " epilogue loop.\n");
    2614              :     }
    2615              : 
    2616              :   /* If the epilogue needs peeling for gaps but the main loop doesn't give
    2617              :      up on the epilogue.  */
    2618       164075 :   if (LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2619        14289 :       && LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
    2620           73 :       && (LOOP_VINFO_PEELING_FOR_GAPS (orig_loop_vinfo)
    2621              :           != LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)))
    2622            4 :     return opt_result::failure_at (vect_location,
    2623              :                                    "Epilogue loop requires peeling for gaps "
    2624              :                                    "but main loop does not.\n");
    2625              : 
    2626              :   /* If an epilogue loop is required make sure we can create one.  */
    2627       164071 :   if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
    2628       162768 :       || LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo)
    2629        58959 :       || LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
    2630              :     {
    2631       106702 :       if (dump_enabled_p ())
    2632         6305 :         dump_printf_loc (MSG_NOTE, vect_location, "epilog loop required\n");
    2633       106702 :       if (!vect_can_advance_ivs_p (loop_vinfo)
    2634       212820 :           || !slpeel_can_duplicate_loop_p (loop,
    2635              :                                            LOOP_VINFO_MAIN_EXIT (loop_vinfo),
    2636       106118 :                                            LOOP_VINFO_MAIN_EXIT (loop_vinfo)))
    2637              :         {
    2638          584 :           ok = opt_result::failure_at (vect_location,
    2639              :                                        "not vectorized: can't create required "
    2640              :                                        "epilog loop\n");
    2641          584 :           goto again;
    2642              :         }
    2643              :     }
    2644              : 
    2645              :   /* Check the costings of the loop make vectorizing worthwhile.  */
    2646       163487 :   res = vect_analyze_loop_costing (loop_vinfo, suggested_unroll_factor);
    2647       163487 :   if (res < 0 && !param_vect_allow_possibly_not_worthwhile_vectorizations)
    2648              :     {
    2649        30147 :       ok = opt_result::failure_at (vect_location,
    2650              :                                    "Loop costings may not be worthwhile.\n");
    2651        30147 :       goto again;
    2652              :     }
    2653       133340 :   if (!res)
    2654        29854 :     return opt_result::failure_at (vect_location,
    2655              :                                    "Loop costings not worthwhile.\n");
    2656              : 
    2657              :   /* During peeling, we need to check if number of loop iterations is
    2658              :      enough for both peeled prolog loop and vector loop.  This check
    2659              :      can be merged along with threshold check of loop versioning, so
    2660              :      increase threshold for this case if necessary.
    2661              : 
    2662              :      If we are analyzing an epilogue we still want to check what its
    2663              :      versioning threshold would be.  If we decide to vectorize the epilogues we
    2664              :      will want to use the lowest versioning threshold of all epilogues and main
    2665              :      loop.  This will enable us to enter a vectorized epilogue even when
    2666              :      versioning the loop.  We can't simply check whether the epilogue requires
    2667              :      versioning though since we may have skipped some versioning checks when
    2668              :      analyzing the epilogue.  For instance, checks for alias versioning will be
    2669              :      skipped when dealing with epilogues as we assume we already checked them
    2670              :      for the main loop.  So instead we always check the 'orig_loop_vinfo'.  */
    2671       103486 :   if (LOOP_REQUIRES_VERSIONING (orig_loop_vinfo))
    2672              :     {
    2673         9427 :       poly_uint64 niters_th = 0;
    2674         9427 :       unsigned int th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
    2675              : 
    2676         9427 :       if (!vect_use_loop_mask_for_alignment_p (loop_vinfo))
    2677              :         {
    2678              :           /* Niters for peeled prolog loop.  */
    2679         9427 :           if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
    2680              :             {
    2681          115 :               dr_vec_info *dr_info = LOOP_VINFO_UNALIGNED_DR (loop_vinfo);
    2682          115 :               tree vectype = STMT_VINFO_VECTYPE (dr_info->stmt);
    2683          115 :               niters_th += TYPE_VECTOR_SUBPARTS (vectype) - 1;
    2684              :             }
    2685              :           else
    2686         9312 :             niters_th += LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
    2687              :         }
    2688              : 
    2689              :       /* Niters for one vector iteration, excluding a header-only iteration.  */
    2690         9427 :       if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    2691         9423 :         niters_th += LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    2692         9427 :       if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
    2693           55 :         niters_th += 1;
    2694              :       /* One additional iteration because of peeling for gap.  */
    2695         9427 :       if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo))
    2696           75 :         niters_th += 1;
    2697              : 
    2698              :       /*  Use the same condition as vect_transform_loop to decide when to use
    2699              :           the cost to determine a versioning threshold.  */
    2700         9427 :       if (vect_apply_runtime_profitability_check_p (loop_vinfo)
    2701         9427 :           && ordered_p (th, niters_th))
    2702         6976 :         niters_th = ordered_max (poly_uint64 (th), niters_th);
    2703              : 
    2704         9427 :       LOOP_VINFO_VERSIONING_THRESHOLD (loop_vinfo) = niters_th;
    2705              :     }
    2706              : 
    2707       103486 :   gcc_assert (known_eq (vectorization_factor,
    2708              :                         LOOP_VINFO_VECT_FACTOR (loop_vinfo)));
    2709              : 
    2710       103486 :   single_lane_slp_done_for_suggested_uf = force_single_lane;
    2711              : 
    2712              :   /* Ok to vectorize!  */
    2713       103486 :   LOOP_VINFO_VECTORIZABLE_P (loop_vinfo) = 1;
    2714       103486 :   return opt_result::success ();
    2715              : 
    2716       294422 : again:
    2717              :   /* Ensure that "ok" is false (with an opt_problem if dumping is enabled).  */
    2718       294422 :   gcc_assert (!ok);
    2719              : 
    2720              :   /* Try again with single-lane SLP.  */
    2721       294422 :   if (force_single_lane)
    2722       145866 :     return ok;
    2723              : 
    2724              :   /* If we are applying suggested unroll factor, we don't need to
    2725              :      re-try any more as we want to keep the SLP mode fixed.  */
    2726       148556 :   if (applying_suggested_uf)
    2727           10 :     return ok;
    2728              : 
    2729              :   /* Likewise if the grouped loads or stores in the SLP cannot be handled
    2730              :      via interleaving or lane instructions.  */
    2731              :   slp_instance instance;
    2732              :   slp_tree node;
    2733              :   unsigned i, j;
    2734       396605 :   FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
    2735              :     {
    2736       249053 :       if (SLP_TREE_DEF_TYPE (SLP_INSTANCE_TREE (instance)) != vect_internal_def)
    2737            0 :         continue;
    2738              : 
    2739       249053 :       stmt_vec_info vinfo;
    2740       249053 :       vinfo = SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance))[0];
    2741       249053 :       if (!vinfo || !STMT_VINFO_GROUPED_ACCESS (vinfo))
    2742       246160 :         continue;
    2743         2893 :       vinfo = DR_GROUP_FIRST_ELEMENT (vinfo);
    2744         2893 :       unsigned int size = DR_GROUP_SIZE (vinfo);
    2745         2893 :       tree vectype = SLP_TREE_VECTYPE (SLP_INSTANCE_TREE (instance));
    2746         2893 :       if (vect_store_lanes_supported (vectype, size, false) == IFN_LAST
    2747         5096 :          && ! known_eq (TYPE_VECTOR_SUBPARTS (vectype), 1U)
    2748         5780 :          && ! vect_grouped_store_supported (vectype, size))
    2749          684 :         return opt_result::failure_at (vinfo->stmt,
    2750              :                                        "unsupported grouped store\n");
    2751       251846 :       FOR_EACH_VEC_ELT (SLP_INSTANCE_LOADS (instance), j, node)
    2752              :         {
    2753         2423 :           vinfo = SLP_TREE_REPRESENTATIVE (node);
    2754         2423 :           if (STMT_VINFO_GROUPED_ACCESS (vinfo))
    2755              :             {
    2756         2108 :               vinfo = DR_GROUP_FIRST_ELEMENT (vinfo);
    2757         2108 :               bool single_element_p = !DR_GROUP_NEXT_ELEMENT (vinfo);
    2758         2108 :               size = DR_GROUP_SIZE (vinfo);
    2759         2108 :               vectype = SLP_TREE_VECTYPE (node);
    2760         2108 :               if (vect_load_lanes_supported (vectype, size, false) == IFN_LAST
    2761         2108 :                   && ! vect_grouped_load_supported (vectype, single_element_p,
    2762              :                                                     size))
    2763          310 :                 return opt_result::failure_at (vinfo->stmt,
    2764              :                                                "unsupported grouped load\n");
    2765              :             }
    2766              :         }
    2767              :     }
    2768              : 
    2769              :   /* Roll back state appropriately.  Force single-lane SLP this time.  */
    2770       147552 :   force_single_lane = true;
    2771       147552 :   if (dump_enabled_p ())
    2772         4066 :     dump_printf_loc (MSG_NOTE, vect_location,
    2773              :                      "re-trying with single-lane SLP\n");
    2774              : 
    2775              :   /* Reset the vectorization factor.  */
    2776       147552 :   LOOP_VINFO_VECT_FACTOR (loop_vinfo) = 0;
    2777              :   /* Free the SLP instances.  */
    2778       395602 :   FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), j, instance)
    2779       248050 :     vect_free_slp_instance (instance);
    2780       147552 :   LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
    2781              :   /* Reset altered state on stmts.  */
    2782       706051 :   for (i = 0; i < LOOP_VINFO_LOOP (loop_vinfo)->num_nodes; ++i)
    2783              :     {
    2784       410947 :       basic_block bb = LOOP_VINFO_BBS (loop_vinfo)[i];
    2785       410947 :       for (gimple_stmt_iterator si = gsi_start_phis (bb);
    2786       744770 :            !gsi_end_p (si); gsi_next (&si))
    2787              :         {
    2788       333823 :           stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (gsi_stmt (si));
    2789       333823 :           if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
    2790       333823 :               || STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    2791              :             {
    2792              :               /* vectorizable_reduction adjusts reduction stmt def-types,
    2793              :                  restore them to that of the PHI.  */
    2794        27384 :               STMT_VINFO_DEF_TYPE (STMT_VINFO_REDUC_DEF (stmt_info))
    2795        27384 :                 = STMT_VINFO_DEF_TYPE (stmt_info);
    2796        27384 :               STMT_VINFO_DEF_TYPE (vect_stmt_to_vectorize
    2797              :                                         (STMT_VINFO_REDUC_DEF (stmt_info)))
    2798        27384 :                 = STMT_VINFO_DEF_TYPE (stmt_info);
    2799              :             }
    2800              :         }
    2801              :     }
    2802              :   /* Free optimized alias test DDRS.  */
    2803       147552 :   LOOP_VINFO_LOWER_BOUNDS (loop_vinfo).truncate (0);
    2804       147552 :   LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).release ();
    2805       147552 :   LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).release ();
    2806              :   /* Reset target cost data.  */
    2807       147552 :   delete loop_vinfo->vector_costs;
    2808       147552 :   loop_vinfo->vector_costs = nullptr;
    2809              :   /* Reset accumulated rgroup information.  */
    2810       147552 :   LOOP_VINFO_MASKS (loop_vinfo).mask_set.empty ();
    2811       147552 :   release_vec_loop_controls (&LOOP_VINFO_MASKS (loop_vinfo).rgc_vec);
    2812       147552 :   release_vec_loop_controls (&LOOP_VINFO_LENS (loop_vinfo));
    2813              :   /* Reset assorted flags.  */
    2814       147552 :   LOOP_VINFO_PEELING_FOR_NITER (loop_vinfo) = false;
    2815       147552 :   LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = false;
    2816       147552 :   LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo) = 0;
    2817       147552 :   LOOP_VINFO_VERSIONING_THRESHOLD (loop_vinfo) = 0;
    2818       147552 :   LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    2819       147552 :     = saved_can_use_partial_vectors_p;
    2820       147552 :   LOOP_VINFO_MUST_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2821       147552 :   LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo) = false;
    2822       147552 :   LOOP_VINFO_USING_SELECT_VL_P (loop_vinfo) = false;
    2823       147552 :   LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo) = false;
    2824              : 
    2825       147552 :   if (loop_vinfo->scan_map)
    2826          122 :     loop_vinfo->scan_map->empty ();
    2827              : 
    2828       147552 :   goto start_over;
    2829              : }
    2830              : 
    2831              : /* Return true if vectorizing a loop using NEW_LOOP_VINFO appears
    2832              :    to be better than vectorizing it using OLD_LOOP_VINFO.  Assume that
    2833              :    OLD_LOOP_VINFO is better unless something specifically indicates
    2834              :    otherwise.
    2835              : 
    2836              :    Note that this deliberately isn't a partial order.  */
    2837              : 
    2838              : static bool
    2839        36542 : vect_better_loop_vinfo_p (loop_vec_info new_loop_vinfo,
    2840              :                           loop_vec_info old_loop_vinfo)
    2841              : {
    2842        36542 :   struct loop *loop = LOOP_VINFO_LOOP (new_loop_vinfo);
    2843        36542 :   gcc_assert (LOOP_VINFO_LOOP (old_loop_vinfo) == loop);
    2844              : 
    2845        36542 :   poly_int64 new_vf = LOOP_VINFO_VECT_FACTOR (new_loop_vinfo);
    2846        36542 :   poly_int64 old_vf = LOOP_VINFO_VECT_FACTOR (old_loop_vinfo);
    2847              : 
    2848              :   /* Always prefer a VF of loop->simdlen over any other VF.  */
    2849        36542 :   if (loop->simdlen)
    2850              :     {
    2851            0 :       bool new_simdlen_p = known_eq (new_vf, loop->simdlen);
    2852            0 :       bool old_simdlen_p = known_eq (old_vf, loop->simdlen);
    2853            0 :       if (new_simdlen_p != old_simdlen_p)
    2854              :         return new_simdlen_p;
    2855              :     }
    2856              : 
    2857        36542 :   const auto *old_costs = old_loop_vinfo->vector_costs;
    2858        36542 :   const auto *new_costs = new_loop_vinfo->vector_costs;
    2859        36542 :   if (loop_vec_info main_loop = LOOP_VINFO_ORIG_LOOP_INFO (old_loop_vinfo))
    2860         1594 :     return new_costs->better_epilogue_loop_than_p (old_costs, main_loop);
    2861              : 
    2862        34948 :   return new_costs->better_main_loop_than_p (old_costs);
    2863              : }
    2864              : 
    2865              : /* Decide whether to replace OLD_LOOP_VINFO with NEW_LOOP_VINFO.  Return
    2866              :    true if we should.  */
    2867              : 
    2868              : static bool
    2869        36542 : vect_joust_loop_vinfos (loop_vec_info new_loop_vinfo,
    2870              :                         loop_vec_info old_loop_vinfo)
    2871              : {
    2872        36542 :   if (!vect_better_loop_vinfo_p (new_loop_vinfo, old_loop_vinfo))
    2873              :     return false;
    2874              : 
    2875         1483 :   if (dump_enabled_p ())
    2876           23 :     dump_printf_loc (MSG_NOTE, vect_location,
    2877              :                      "***** Preferring vector mode %s to vector mode %s\n",
    2878           23 :                      GET_MODE_NAME (new_loop_vinfo->vector_mode),
    2879           23 :                      GET_MODE_NAME (old_loop_vinfo->vector_mode));
    2880              :   return true;
    2881              : }
    2882              : 
    2883              : /* Analyze LOOP with VECTOR_MODES[MODE_I] and as epilogue if ORIG_LOOP_VINFO is
    2884              :    not NULL.  When MASKED_P is not -1 override the default
    2885              :    LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P with it.
    2886              :    Set AUTODETECTED_VECTOR_MODE if VOIDmode and advance MODE_I to the next
    2887              :    mode useful to analyze.
    2888              :    Return the loop_vinfo on success and wrapped null on failure.  */
    2889              : 
    2890              : static opt_loop_vec_info
    2891       549397 : vect_analyze_loop_1 (class loop *loop, vec_info_shared *shared,
    2892              :                      const vect_loop_form_info *loop_form_info,
    2893              :                      loop_vec_info orig_loop_vinfo,
    2894              :                      const vector_modes &vector_modes, unsigned &mode_i,
    2895              :                      int masked_p,
    2896              :                      machine_mode &autodetected_vector_mode,
    2897              :                      bool &fatal)
    2898              : {
    2899       549397 :   loop_vec_info loop_vinfo
    2900       549397 :     = vect_create_loop_vinfo (loop, shared, loop_form_info, orig_loop_vinfo);
    2901              : 
    2902       549397 :   shared->used_vector_modes.empty ();
    2903              : 
    2904       549397 :   machine_mode vector_mode = vector_modes[mode_i];
    2905       549397 :   loop_vinfo->vector_mode = vector_mode;
    2906       549397 :   unsigned int suggested_unroll_factor = 1;
    2907       549397 :   bool single_lane_slp_done_for_suggested_uf = false;
    2908              : 
    2909              :   /* Run the main analysis.  */
    2910       549397 :   opt_result res = vect_analyze_loop_2 (loop_vinfo, masked_p, fatal,
    2911              :                                         &suggested_unroll_factor,
    2912              :                                         single_lane_slp_done_for_suggested_uf);
    2913       549397 :   if (dump_enabled_p ())
    2914        21460 :     dump_printf_loc (MSG_NOTE, vect_location,
    2915              :                      "***** Analysis %s with vector mode %s\n",
    2916        21460 :                      res ? "succeeded" : "failed",
    2917        21460 :                      GET_MODE_NAME (loop_vinfo->vector_mode));
    2918              : 
    2919       549397 :   auto user_unroll = LOOP_VINFO_LOOP (loop_vinfo)->unroll;
    2920       549397 :   if (res && !LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    2921              :       /* Check to see if the user wants to unroll or if the target wants to.  */
    2922       643493 :       && (suggested_unroll_factor > 1 || user_unroll > 1))
    2923              :     {
    2924          504 :       if (suggested_unroll_factor == 1)
    2925              :         {
    2926           66 :           int assumed_vf = vect_vf_for_cost (loop_vinfo);
    2927           66 :           suggested_unroll_factor = user_unroll / assumed_vf;
    2928           66 :           if (suggested_unroll_factor > 1)
    2929              :             {
    2930           40 :               if (dump_enabled_p ())
    2931           20 :                 dump_printf_loc (MSG_NOTE, vect_location,
    2932              :                          "setting unroll factor to %d based on user requested "
    2933              :                          "unroll factor %d and suggested vectorization "
    2934              :                          "factor: %d\n",
    2935              :                          suggested_unroll_factor, user_unroll, assumed_vf);
    2936              :             }
    2937              :         }
    2938              : 
    2939          504 :         if (suggested_unroll_factor > 1)
    2940              :           {
    2941          478 :             if (dump_enabled_p ())
    2942           82 :               dump_printf_loc (MSG_NOTE, vect_location,
    2943              :                          "***** Re-trying analysis for unrolling"
    2944              :                          " with unroll factor %d and %s slp.\n",
    2945              :                          suggested_unroll_factor,
    2946              :                          single_lane_slp_done_for_suggested_uf
    2947              :                          ? "single-lane" : "");
    2948          478 :             loop_vec_info unroll_vinfo
    2949          478 :                 = vect_create_loop_vinfo (loop, shared, loop_form_info, NULL);
    2950          478 :             unroll_vinfo->vector_mode = vector_mode;
    2951          478 :             unroll_vinfo->suggested_unroll_factor = suggested_unroll_factor;
    2952          478 :             opt_result new_res
    2953          478 :               = vect_analyze_loop_2 (unroll_vinfo, masked_p, fatal, NULL,
    2954              :                                      single_lane_slp_done_for_suggested_uf);
    2955          478 :             if (new_res)
    2956              :               {
    2957          419 :                 delete loop_vinfo;
    2958              :                 loop_vinfo = unroll_vinfo;
    2959              :               }
    2960              :             else
    2961           59 :               delete unroll_vinfo;
    2962              :           }
    2963              : 
    2964              :         /* Record that we have honored a user unroll factor.  */
    2965          504 :         LOOP_VINFO_USER_UNROLL (loop_vinfo) = user_unroll > 1;
    2966              :     }
    2967              : 
    2968              :   /* Remember the autodetected vector mode.  */
    2969       549397 :   if (vector_mode == VOIDmode)
    2970       219001 :     autodetected_vector_mode = loop_vinfo->vector_mode;
    2971              : 
    2972              :   /* Advance mode_i, first skipping modes that would result in the
    2973              :      same analysis result.  */
    2974      2131107 :   while (mode_i + 1 < vector_modes.length ()
    2975      1416151 :          && vect_chooses_same_modes_p (loop_vinfo,
    2976       625296 :                                        vector_modes[mode_i + 1]))
    2977              :     {
    2978       241458 :       if (dump_enabled_p ())
    2979        12906 :         dump_printf_loc (MSG_NOTE, vect_location,
    2980              :                          "***** The result for vector mode %s would"
    2981              :                          " be the same\n",
    2982        12906 :                          GET_MODE_NAME (vector_modes[mode_i + 1]));
    2983       241458 :       mode_i += 1;
    2984              :     }
    2985       549397 :   if (mode_i + 1 < vector_modes.length ()
    2986       933235 :       && vect_chooses_same_modes_p (autodetected_vector_mode,
    2987       383838 :                                     vector_modes[mode_i + 1]))
    2988              :     {
    2989          475 :       if (dump_enabled_p ())
    2990           25 :         dump_printf_loc (MSG_NOTE, vect_location,
    2991              :                          "***** Skipping vector mode %s, which would"
    2992              :                          " repeat the analysis for %s\n",
    2993           25 :                          GET_MODE_NAME (vector_modes[mode_i + 1]),
    2994           25 :                          GET_MODE_NAME (autodetected_vector_mode));
    2995          475 :       mode_i += 1;
    2996              :     }
    2997       549397 :   mode_i++;
    2998              : 
    2999       549397 :   if (!res)
    3000              :     {
    3001       446330 :       delete loop_vinfo;
    3002       446330 :       if (fatal)
    3003        42907 :         gcc_checking_assert (orig_loop_vinfo == NULL);
    3004       446330 :       return opt_loop_vec_info::propagate_failure (res);
    3005              :     }
    3006              : 
    3007       103067 :   return opt_loop_vec_info::success (loop_vinfo);
    3008              : }
    3009              : 
    3010              : /* Function vect_analyze_loop.
    3011              : 
    3012              :    Apply a set of analyses on LOOP, and create a loop_vec_info struct
    3013              :    for it.  The different analyses will record information in the
    3014              :    loop_vec_info struct.  */
    3015              : opt_loop_vec_info
    3016       488891 : vect_analyze_loop (class loop *loop, gimple *loop_vectorized_call,
    3017              :                    vec_info_shared *shared)
    3018              : {
    3019       488891 :   DUMP_VECT_SCOPE ("analyze_loop_nest");
    3020              : 
    3021       488891 :   if (loop_outer (loop)
    3022       488891 :       && loop_vec_info_for_loop (loop_outer (loop))
    3023       489457 :       && LOOP_VINFO_VECTORIZABLE_P (loop_vec_info_for_loop (loop_outer (loop))))
    3024          566 :     return opt_loop_vec_info::failure_at (vect_location,
    3025              :                                           "outer-loop already vectorized.\n");
    3026              : 
    3027       488325 :   if (!find_loop_nest (loop, &shared->loop_nest))
    3028        23359 :     return opt_loop_vec_info::failure_at
    3029        23359 :       (vect_location,
    3030              :        "not vectorized: loop nest containing two or more consecutive inner"
    3031              :        " loops cannot be vectorized\n");
    3032              : 
    3033              :   /* Analyze the loop form.  */
    3034       464966 :   vect_loop_form_info loop_form_info;
    3035       464966 :   opt_result res = vect_analyze_loop_form (loop, loop_vectorized_call,
    3036              :                                            &loop_form_info);
    3037       464966 :   if (!res)
    3038              :     {
    3039       182157 :       if (dump_enabled_p ())
    3040         1559 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3041              :                          "bad loop form.\n");
    3042       182157 :       return opt_loop_vec_info::propagate_failure (res);
    3043              :     }
    3044              : 
    3045       282809 :   res = vect_get_datarefs_in_loop (loop, loop_form_info,
    3046              :                                    &shared->datarefs);
    3047       282809 :   if (!res)
    3048              :     {
    3049        63683 :       if (dump_enabled_p ())
    3050         1648 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3051              :                          "not vectorized: loop contains function "
    3052              :                          "calls or data references that cannot "
    3053              :                          "be analyzed\n");
    3054        63683 :       return opt_loop_vec_info::propagate_failure (res);
    3055              :     }
    3056       219126 :   shared->save_datarefs ();
    3057              : 
    3058       219126 :   res = vect_build_assumptions (loop, shared, &loop_form_info);
    3059       219126 :   if (!res)
    3060          125 :     return opt_loop_vec_info::propagate_failure (res);
    3061              : 
    3062       219001 :   auto_vector_modes vector_modes;
    3063              :   /* Autodetect first vector size we try.  */
    3064       219001 :   vector_modes.safe_push (VOIDmode);
    3065       219001 :   unsigned int autovec_flags
    3066       438002 :     = targetm.vectorize.autovectorize_vector_modes (&vector_modes,
    3067       219001 :                                                     loop->simdlen != 0);
    3068       219001 :   bool pick_lowest_cost_p = ((autovec_flags & VECT_COMPARE_COSTS)
    3069       219001 :                              && !unlimited_cost_model (loop));
    3070       219001 :   machine_mode autodetected_vector_mode = VOIDmode;
    3071       219001 :   opt_loop_vec_info first_loop_vinfo = opt_loop_vec_info::success (NULL);
    3072       219001 :   unsigned int mode_i = 0;
    3073       219001 :   unsigned HOST_WIDE_INT simdlen = loop->simdlen;
    3074              : 
    3075              :   /* Keep track of the VF for each mode.  Initialize all to 0 which indicates
    3076              :      a mode has not been analyzed.  */
    3077       219001 :   auto_vec<poly_uint64, 8> cached_vf_per_mode;
    3078      2214476 :   for (unsigned i = 0; i < vector_modes.length (); ++i)
    3079       888237 :     cached_vf_per_mode.safe_push (0);
    3080              : 
    3081              :   /* First determine the main loop vectorization mode, either the first
    3082              :      one that works, starting with auto-detecting the vector mode and then
    3083              :      following the targets order of preference, or the one with the
    3084              :      lowest cost if pick_lowest_cost_p.  */
    3085       849505 :   while (1)
    3086              :     {
    3087       534253 :       bool fatal;
    3088       534253 :       unsigned int last_mode_i = mode_i;
    3089              :       /* Set cached VF to -1 prior to analysis, which indicates a mode has
    3090              :          failed.  */
    3091       534253 :       cached_vf_per_mode[last_mode_i] = -1;
    3092       534253 :       opt_loop_vec_info loop_vinfo
    3093       534253 :         = vect_analyze_loop_1 (loop, shared, &loop_form_info,
    3094              :                                NULL, vector_modes, mode_i, -1,
    3095              :                                autodetected_vector_mode, fatal);
    3096       534253 :       if (fatal)
    3097              :         break;
    3098              : 
    3099       491346 :       if (loop_vinfo)
    3100              :         {
    3101              :           /*  Analysis has been successful so update the VF value.  The
    3102              :               VF should always be a multiple of unroll_factor and we want to
    3103              :               capture the original VF here.  */
    3104        94096 :           cached_vf_per_mode[last_mode_i]
    3105        94096 :             = exact_div (LOOP_VINFO_VECT_FACTOR (loop_vinfo),
    3106        94096 :                          loop_vinfo->suggested_unroll_factor);
    3107              :           /* Once we hit the desired simdlen for the first time,
    3108              :              discard any previous attempts.  */
    3109        94096 :           if (simdlen
    3110        94096 :               && known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), simdlen))
    3111              :             {
    3112           59 :               delete first_loop_vinfo;
    3113        94096 :               first_loop_vinfo = opt_loop_vec_info::success (NULL);
    3114        94096 :               simdlen = 0;
    3115              :             }
    3116        94037 :           else if (pick_lowest_cost_p
    3117        78790 :                    && first_loop_vinfo
    3118       128985 :                    && vect_joust_loop_vinfos (loop_vinfo, first_loop_vinfo))
    3119              :             {
    3120              :               /* Pick loop_vinfo over first_loop_vinfo.  */
    3121         1306 :               delete first_loop_vinfo;
    3122         1306 :               first_loop_vinfo = opt_loop_vec_info::success (NULL);
    3123              :             }
    3124        94096 :           if (first_loop_vinfo == NULL)
    3125              :             first_loop_vinfo = loop_vinfo;
    3126              :           else
    3127              :             {
    3128        33644 :               delete loop_vinfo;
    3129        33644 :               loop_vinfo = opt_loop_vec_info::success (NULL);
    3130              :             }
    3131              : 
    3132              :           /* Commit to first_loop_vinfo if we have no reason to try
    3133              :              alternatives.  */
    3134        94096 :           if (!simdlen && !pick_lowest_cost_p)
    3135              :             break;
    3136              :         }
    3137       476049 :       if (mode_i == vector_modes.length ()
    3138       476049 :           || autodetected_vector_mode == VOIDmode)
    3139              :         break;
    3140              : 
    3141              :       /* Try the next biggest vector size.  */
    3142       315252 :       if (dump_enabled_p ())
    3143         5391 :         dump_printf_loc (MSG_NOTE, vect_location,
    3144              :                          "***** Re-trying analysis with vector mode %s\n",
    3145         5391 :                          GET_MODE_NAME (vector_modes[mode_i]));
    3146       315252 :     }
    3147       219001 :   if (!first_loop_vinfo)
    3148       159860 :     return opt_loop_vec_info::propagate_failure (res);
    3149              : 
    3150        59141 :   if (dump_enabled_p ())
    3151        10089 :     dump_printf_loc (MSG_NOTE, vect_location,
    3152              :                      "***** Choosing vector mode %s\n",
    3153        10089 :                      GET_MODE_NAME (first_loop_vinfo->vector_mode));
    3154              : 
    3155              :   /* Only vectorize epilogues if PARAM_VECT_EPILOGUES_NOMASK is
    3156              :      enabled, SIMDUID is not set, it is the innermost loop and we have
    3157              :      either already found the loop's SIMDLEN or there was no SIMDLEN to
    3158              :      begin with.
    3159              :      TODO: Enable epilogue vectorization for loops with SIMDUID set.  */
    3160        59141 :   bool vect_epilogues = (!simdlen
    3161        59139 :                          && loop->inner == NULL
    3162        58571 :                          && param_vect_epilogues_nomask
    3163        57429 :                          && LOOP_VINFO_PEELING_FOR_NITER (first_loop_vinfo)
    3164              :                            /* No code motion support for multiple epilogues so for now
    3165              :                               not supported when multiple exits.  */
    3166        28489 :                          && !LOOP_VINFO_EARLY_BREAKS (first_loop_vinfo)
    3167        27947 :                          && !loop->simduid
    3168        85234 :                          && loop_cost_model (loop) > VECT_COST_MODEL_VERY_CHEAP);
    3169        59141 :   if (!vect_epilogues)
    3170        45005 :     return first_loop_vinfo;
    3171              : 
    3172              :   /* Now analyze first_loop_vinfo for epilogue vectorization.  */
    3173              : 
    3174              :   /* For epilogues start the analysis from the first mode.  The motivation
    3175              :      behind starting from the beginning comes from cases where the VECTOR_MODES
    3176              :      array may contain length-agnostic and length-specific modes.  Their
    3177              :      ordering is not guaranteed, so we could end up picking a mode for the main
    3178              :      loop that is after the epilogue's optimal mode.  */
    3179        14136 :   int masked_p = -1;
    3180        14136 :   if (!unlimited_cost_model (loop)
    3181        14136 :       && (first_loop_vinfo->vector_costs->suggested_epilogue_mode (masked_p)
    3182              :           != VOIDmode))
    3183              :     {
    3184            5 :       vector_modes[0]
    3185            5 :         = first_loop_vinfo->vector_costs->suggested_epilogue_mode (masked_p);
    3186            5 :       cached_vf_per_mode[0] = 0;
    3187              :     }
    3188              :   else
    3189        14131 :     vector_modes[0] = autodetected_vector_mode;
    3190        14136 :   mode_i = 0;
    3191              : 
    3192        14180 :   bool supports_partial_vectors = (param_vect_partial_vector_usage != 0
    3193        14136 :                                    || masked_p == 1);
    3194              :   if (supports_partial_vectors
    3195           44 :       && !partial_vectors_supported_p ()
    3196           44 :       && !LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (first_loop_vinfo))
    3197              :     supports_partial_vectors = false;
    3198        14136 :   poly_uint64 first_vinfo_vf = LOOP_VINFO_VECT_FACTOR (first_loop_vinfo);
    3199              : 
    3200        14136 :   loop_vec_info orig_loop_vinfo = first_loop_vinfo;
    3201        14336 :   do
    3202              :     {
    3203              :       /* Let the user override what the target suggests.  */
    3204        14236 :       if (OPTION_SET_P (param_vect_partial_vector_usage))
    3205           71 :         masked_p = -1;
    3206              : 
    3207        54799 :       while (1)
    3208              :         {
    3209              :           /* If the target does not support partial vectors we can shorten the
    3210              :              number of modes to analyze for the epilogue as we know we can't
    3211              :              pick a mode that would lead to a VF at least as big as the
    3212              :              FIRST_VINFO_VF.  */
    3213        72902 :           if (!supports_partial_vectors
    3214        54799 :               && maybe_ge (cached_vf_per_mode[mode_i], first_vinfo_vf))
    3215              :             {
    3216        25725 :               mode_i++;
    3217        51450 :               if (mode_i == vector_modes.length ())
    3218              :                 break;
    3219        32033 :               continue;
    3220              :             }
    3221              :           /* We would need an exhaustive search to find all modes we
    3222              :              skipped but that would lead to the same result as the
    3223              :              analysis it was skipped for and where we'd could check
    3224              :              cached_vf_per_mode against.
    3225              :              Check for the autodetected mode, which is the common
    3226              :              situation on x86 which does not perform cost comparison.  */
    3227        43004 :           if (!supports_partial_vectors
    3228        29036 :               && maybe_ge (cached_vf_per_mode[0], first_vinfo_vf)
    3229        57237 :               && vect_chooses_same_modes_p (autodetected_vector_mode,
    3230        28163 :                                             vector_modes[mode_i]))
    3231              :             {
    3232        13930 :               mode_i++;
    3233        27860 :               if (mode_i == vector_modes.length ())
    3234              :                 break;
    3235        13930 :               continue;
    3236              :             }
    3237              : 
    3238        15144 :           if (dump_enabled_p ())
    3239         3716 :             dump_printf_loc (MSG_NOTE, vect_location,
    3240              :                              "***** Re-trying epilogue analysis with vector "
    3241         3716 :                              "mode %s\n", GET_MODE_NAME (vector_modes[mode_i]));
    3242              : 
    3243        15144 :           bool fatal;
    3244        15144 :           opt_loop_vec_info loop_vinfo
    3245        15144 :             = vect_analyze_loop_1 (loop, shared, &loop_form_info,
    3246              :                                    orig_loop_vinfo,
    3247              :                                    vector_modes, mode_i, masked_p,
    3248              :                                    autodetected_vector_mode, fatal);
    3249        15144 :           if (fatal)
    3250              :             break;
    3251              : 
    3252        15144 :           if (loop_vinfo)
    3253              :             {
    3254         8971 :               if (pick_lowest_cost_p
    3255         5542 :                   && orig_loop_vinfo->epilogue_vinfo
    3256        10565 :                   && vect_joust_loop_vinfos (loop_vinfo,
    3257         1594 :                                              orig_loop_vinfo->epilogue_vinfo))
    3258              :                 {
    3259          177 :                   gcc_assert (vect_epilogues);
    3260          177 :                   delete orig_loop_vinfo->epilogue_vinfo;
    3261          177 :                   orig_loop_vinfo->epilogue_vinfo = nullptr;
    3262              :                 }
    3263         8971 :               if (!orig_loop_vinfo->epilogue_vinfo)
    3264         7554 :                 orig_loop_vinfo->epilogue_vinfo = loop_vinfo;
    3265              :               else
    3266              :                 {
    3267         1417 :                   delete loop_vinfo;
    3268         1417 :                   loop_vinfo = opt_loop_vec_info::success (NULL);
    3269              :                 }
    3270              : 
    3271              :               /* For now only allow one epilogue loop, but allow
    3272              :                  pick_lowest_cost_p to replace it, so commit to the
    3273              :                  first epilogue if we have no reason to try alternatives.  */
    3274         8971 :               if (!pick_lowest_cost_p)
    3275              :                 break;
    3276              :             }
    3277              : 
    3278              :           /* Revert back to the default from the suggested preferred
    3279              :              epilogue vectorization mode.  */
    3280        11715 :           masked_p = -1;
    3281        23430 :           if (mode_i == vector_modes.length ())
    3282              :             break;
    3283              :         }
    3284              : 
    3285        14236 :       orig_loop_vinfo = orig_loop_vinfo->epilogue_vinfo;
    3286        14236 :       if (!orig_loop_vinfo)
    3287              :         break;
    3288              : 
    3289              :       /* When we selected a first vectorized epilogue, see if the target
    3290              :          suggests to have another one.  */
    3291         7377 :       masked_p = -1;
    3292         7377 :       if (!unlimited_cost_model (loop)
    3293         3954 :           && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (orig_loop_vinfo)
    3294        11324 :           && (orig_loop_vinfo->vector_costs->suggested_epilogue_mode (masked_p)
    3295              :               != VOIDmode))
    3296              :         {
    3297          200 :           vector_modes[0]
    3298          100 :             = orig_loop_vinfo->vector_costs->suggested_epilogue_mode (masked_p);
    3299          100 :           cached_vf_per_mode[0] = 0;
    3300          100 :           mode_i = 0;
    3301              :         }
    3302              :       else
    3303              :         break;
    3304          100 :     }
    3305              :   while (1);
    3306              : 
    3307        14136 :   if (first_loop_vinfo->epilogue_vinfo)
    3308              :     {
    3309         7286 :       poly_uint64 lowest_th
    3310         7286 :         = LOOP_VINFO_VERSIONING_THRESHOLD (first_loop_vinfo);
    3311         7286 :       loop_vec_info epilog_vinfo = first_loop_vinfo->epilogue_vinfo;
    3312         7377 :       do
    3313              :         {
    3314         7377 :           poly_uint64 th = LOOP_VINFO_VERSIONING_THRESHOLD (epilog_vinfo);
    3315         7377 :           gcc_assert (!LOOP_REQUIRES_VERSIONING (epilog_vinfo)
    3316              :                       || maybe_ne (lowest_th, 0U));
    3317              :           /* Keep track of the known smallest versioning threshold.  */
    3318         7377 :           if (ordered_p (lowest_th, th))
    3319         7377 :             lowest_th = ordered_min (lowest_th, th);
    3320         7377 :           epilog_vinfo = epilog_vinfo->epilogue_vinfo;
    3321              :         }
    3322         7377 :       while (epilog_vinfo);
    3323         7286 :       LOOP_VINFO_VERSIONING_THRESHOLD (first_loop_vinfo) = lowest_th;
    3324         7286 :       if (dump_enabled_p ())
    3325         1614 :         dump_printf_loc (MSG_NOTE, vect_location,
    3326              :                          "***** Choosing epilogue vector mode %s\n",
    3327         1614 :                          GET_MODE_NAME
    3328              :                            (first_loop_vinfo->epilogue_vinfo->vector_mode));
    3329              :     }
    3330              : 
    3331        14136 :   return first_loop_vinfo;
    3332       464966 : }
    3333              : 
    3334              : /* Return true if there is an in-order reduction function for CODE, storing
    3335              :    it in *REDUC_FN if so.  */
    3336              : 
    3337              : static bool
    3338         5650 : fold_left_reduction_fn (code_helper code, internal_fn *reduc_fn)
    3339              : {
    3340              :   /* We support MINUS_EXPR by negating the operand.  This also preserves an
    3341              :      initial -0.0 since -0.0 - 0.0 (neutral op for MINUS_EXPR) == -0.0 +
    3342              :      (-0.0) = -0.0.  */
    3343         5650 :   if (code == PLUS_EXPR || code == MINUS_EXPR)
    3344              :     {
    3345         4947 :       *reduc_fn = IFN_FOLD_LEFT_PLUS;
    3346            0 :       return true;
    3347              :     }
    3348              :   return false;
    3349              : }
    3350              : 
    3351              : /* Function reduction_fn_for_scalar_code
    3352              : 
    3353              :    Input:
    3354              :    CODE - tree_code of a reduction operations.
    3355              : 
    3356              :    Output:
    3357              :    REDUC_FN - the corresponding internal function to be used to reduce the
    3358              :       vector of partial results into a single scalar result, or IFN_LAST
    3359              :       if the operation is a supported reduction operation, but does not have
    3360              :       such an internal function.
    3361              : 
    3362              :    Return FALSE if CODE currently cannot be vectorized as reduction.  */
    3363              : 
    3364              : bool
    3365      2340305 : reduction_fn_for_scalar_code (code_helper code, internal_fn *reduc_fn)
    3366              : {
    3367      2340305 :   if (code.is_tree_code ())
    3368      2340247 :     switch (tree_code (code))
    3369              :       {
    3370        14581 :       case MAX_EXPR:
    3371        14581 :         *reduc_fn = IFN_REDUC_MAX;
    3372        14581 :         return true;
    3373              : 
    3374        51227 :       case MIN_EXPR:
    3375        51227 :         *reduc_fn = IFN_REDUC_MIN;
    3376        51227 :         return true;
    3377              : 
    3378      1285537 :       case PLUS_EXPR:
    3379      1285537 :         *reduc_fn = IFN_REDUC_PLUS;
    3380      1285537 :         return true;
    3381              : 
    3382       251742 :       case BIT_AND_EXPR:
    3383       251742 :         *reduc_fn = IFN_REDUC_AND;
    3384       251742 :         return true;
    3385              : 
    3386       272031 :       case BIT_IOR_EXPR:
    3387       272031 :         *reduc_fn = IFN_REDUC_IOR;
    3388       272031 :         return true;
    3389              : 
    3390        45776 :       case BIT_XOR_EXPR:
    3391        45776 :         *reduc_fn = IFN_REDUC_XOR;
    3392        45776 :         return true;
    3393              : 
    3394       419353 :       case MULT_EXPR:
    3395       419353 :       case MINUS_EXPR:
    3396       419353 :         *reduc_fn = IFN_LAST;
    3397       419353 :         return true;
    3398              : 
    3399              :       default:
    3400              :         return false;
    3401              :       }
    3402              :   else
    3403           58 :     switch (combined_fn (code))
    3404              :       {
    3405           34 :       CASE_CFN_FMAX:
    3406           34 :         *reduc_fn = IFN_REDUC_FMAX;
    3407           34 :         return true;
    3408              : 
    3409           24 :       CASE_CFN_FMIN:
    3410           24 :         *reduc_fn = IFN_REDUC_FMIN;
    3411           24 :         return true;
    3412              : 
    3413              :       default:
    3414              :         return false;
    3415              :       }
    3416              : }
    3417              : 
    3418              : /* Set *SBOOL_FN to the corresponding function working on vector masks
    3419              :    for REDUC_FN.  Return true if that exists, false otherwise.  */
    3420              : 
    3421              : static bool
    3422            0 : sbool_reduction_fn_for_fn (internal_fn reduc_fn, internal_fn *sbool_fn)
    3423              : {
    3424            0 :   switch (reduc_fn)
    3425              :     {
    3426            0 :     case IFN_REDUC_AND:
    3427            0 :       *sbool_fn = IFN_REDUC_SBOOL_AND;
    3428            0 :       return true;
    3429            0 :     case IFN_REDUC_IOR:
    3430            0 :       *sbool_fn = IFN_REDUC_SBOOL_IOR;
    3431            0 :       return true;
    3432            0 :     case IFN_REDUC_XOR:
    3433            0 :       *sbool_fn = IFN_REDUC_SBOOL_XOR;
    3434            0 :       return true;
    3435              :     default:
    3436              :       return false;
    3437              :     }
    3438              : }
    3439              : 
    3440              : /* If there is a neutral value X such that a reduction would not be affected
    3441              :    by the introduction of additional X elements, return that X, otherwise
    3442              :    return null.  CODE is the code of the reduction and SCALAR_TYPE is type
    3443              :    of the scalar elements.  If the reduction has just a single initial value
    3444              :    then INITIAL_VALUE is that value, otherwise it is null.
    3445              :    If AS_INITIAL is TRUE the value is supposed to be used as initial value.
    3446              :    In that case no signed zero is returned.  */
    3447              : 
    3448              : tree
    3449        76675 : neutral_op_for_reduction (tree scalar_type, code_helper code,
    3450              :                           tree initial_value, bool as_initial)
    3451              : {
    3452        76675 :   if (code.is_tree_code ())
    3453        76617 :     switch (tree_code (code))
    3454              :       {
    3455        14258 :       case DOT_PROD_EXPR:
    3456        14258 :       case SAD_EXPR:
    3457        14258 :       case MINUS_EXPR:
    3458        14258 :       case BIT_IOR_EXPR:
    3459        14258 :       case BIT_XOR_EXPR:
    3460        14258 :         return build_zero_cst (scalar_type);
    3461        55749 :       case WIDEN_SUM_EXPR:
    3462        55749 :       case PLUS_EXPR:
    3463        55749 :         if (!as_initial && HONOR_SIGNED_ZEROS (scalar_type))
    3464          104 :           return build_real (scalar_type, dconstm0);
    3465              :         else
    3466        55645 :           return build_zero_cst (scalar_type);
    3467              : 
    3468         2316 :       case MULT_EXPR:
    3469         2316 :         return build_one_cst (scalar_type);
    3470              : 
    3471         1613 :       case BIT_AND_EXPR:
    3472         1613 :         return build_all_ones_cst (scalar_type);
    3473              : 
    3474              :       case MAX_EXPR:
    3475              :       case MIN_EXPR:
    3476              :         return initial_value;
    3477              : 
    3478          463 :       default:
    3479          463 :         return NULL_TREE;
    3480              :       }
    3481              :   else
    3482           58 :     switch (combined_fn (code))
    3483              :       {
    3484              :       CASE_CFN_FMIN:
    3485              :       CASE_CFN_FMAX:
    3486              :         return initial_value;
    3487              : 
    3488            0 :       default:
    3489            0 :         return NULL_TREE;
    3490              :       }
    3491              : }
    3492              : 
    3493              : /* Error reporting helper for vect_is_simple_reduction below.  GIMPLE statement
    3494              :    STMT is printed with a message MSG. */
    3495              : 
    3496              : static void
    3497          581 : report_vect_op (dump_flags_t msg_type, gimple *stmt, const char *msg)
    3498              : {
    3499          581 :   dump_printf_loc (msg_type, vect_location, "%s%G", msg, stmt);
    3500          581 : }
    3501              : 
    3502              : /* Return true if we need an in-order reduction for operation CODE
    3503              :    on type TYPE.  NEED_WRAPPING_INTEGRAL_OVERFLOW is true if integer
    3504              :    overflow must wrap.  */
    3505              : 
    3506              : bool
    3507       369433 : needs_fold_left_reduction_p (tree type, code_helper code)
    3508              : {
    3509              :   /* CHECKME: check for !flag_finite_math_only too?  */
    3510       369433 :   if (SCALAR_FLOAT_TYPE_P (type))
    3511              :     {
    3512        98651 :       if (code.is_tree_code ())
    3513        98597 :         switch (tree_code (code))
    3514              :           {
    3515              :           case MIN_EXPR:
    3516              :           case MAX_EXPR:
    3517              :             return false;
    3518              : 
    3519        97985 :           default:
    3520        97985 :             return !flag_associative_math;
    3521              :           }
    3522              :       else
    3523           54 :         switch (combined_fn (code))
    3524              :           {
    3525              :           CASE_CFN_FMIN:
    3526              :           CASE_CFN_FMAX:
    3527              :             return false;
    3528              : 
    3529            2 :           default:
    3530            2 :             return !flag_associative_math;
    3531              :           }
    3532              :     }
    3533              : 
    3534       270782 :   if (INTEGRAL_TYPE_P (type))
    3535       270672 :     return (!code.is_tree_code ()
    3536       270672 :             || !operation_no_trapping_overflow (type, tree_code (code)));
    3537              : 
    3538          110 :   if (SAT_FIXED_POINT_TYPE_P (type))
    3539              :     return true;
    3540              : 
    3541              :   return false;
    3542              : }
    3543              : 
    3544              : /* Return true if the reduction PHI in LOOP with latch arg LOOP_ARG and
    3545              :    has a handled computation expression.  Store the main reduction
    3546              :    operation in *CODE.  */
    3547              : 
    3548              : static bool
    3549       105832 : check_reduction_path (dump_user_location_t loc, loop_p loop, gphi *phi,
    3550              :                       tree loop_arg, code_helper *code,
    3551              :                       vec<std::pair<ssa_op_iter, use_operand_p> > &path,
    3552              :                       bool inner_loop_of_double_reduc)
    3553              : {
    3554       105832 :   auto_bitmap visited;
    3555       105832 :   tree lookfor = PHI_RESULT (phi);
    3556       105832 :   ssa_op_iter curri;
    3557       105832 :   use_operand_p curr = op_iter_init_phiuse (&curri, phi, SSA_OP_USE);
    3558       220285 :   while (USE_FROM_PTR (curr) != loop_arg)
    3559         8621 :     curr = op_iter_next_use (&curri);
    3560       105832 :   curri.i = curri.numops;
    3561       983649 :   do
    3562              :     {
    3563       983649 :       path.safe_push (std::make_pair (curri, curr));
    3564       983649 :       tree use = USE_FROM_PTR (curr);
    3565       983649 :       if (use == lookfor)
    3566              :         break;
    3567       878388 :       gimple *def = SSA_NAME_DEF_STMT (use);
    3568       878388 :       if (gimple_nop_p (def)
    3569       878388 :           || ! flow_bb_inside_loop_p (loop, gimple_bb (def)))
    3570              :         {
    3571       247394 : pop:
    3572       738325 :           do
    3573              :             {
    3574       738325 :               std::pair<ssa_op_iter, use_operand_p> x = path.pop ();
    3575       738325 :               curri = x.first;
    3576       738325 :               curr = x.second;
    3577       808771 :               do
    3578       808771 :                 curr = op_iter_next_use (&curri);
    3579              :               /* Skip already visited or non-SSA operands (from iterating
    3580              :                  over PHI args).  */
    3581              :               while (curr != NULL_USE_OPERAND_P
    3582      1126040 :                      && (TREE_CODE (USE_FROM_PTR (curr)) != SSA_NAME
    3583       279277 :                          || ! bitmap_set_bit (visited,
    3584       279277 :                                               SSA_NAME_VERSION
    3585              :                                                 (USE_FROM_PTR (curr)))));
    3586              :             }
    3587      1476650 :           while (curr == NULL_USE_OPERAND_P && ! path.is_empty ());
    3588       247394 :           if (curr == NULL_USE_OPERAND_P)
    3589              :             break;
    3590              :         }
    3591              :       else
    3592              :         {
    3593       740026 :           if (gimple_code (def) == GIMPLE_PHI)
    3594        75661 :             curr = op_iter_init_phiuse (&curri, as_a <gphi *>(def), SSA_OP_USE);
    3595              :           else
    3596       664365 :             curr = op_iter_init_use (&curri, def, SSA_OP_USE);
    3597              :           while (curr != NULL_USE_OPERAND_P
    3598       885162 :                  && (TREE_CODE (USE_FROM_PTR (curr)) != SSA_NAME
    3599       770206 :                      || ! bitmap_set_bit (visited,
    3600       770206 :                                           SSA_NAME_VERSION
    3601              :                                             (USE_FROM_PTR (curr)))))
    3602       145136 :             curr = op_iter_next_use (&curri);
    3603       740026 :           if (curr == NULL_USE_OPERAND_P)
    3604       109032 :             goto pop;
    3605              :         }
    3606              :     }
    3607              :   while (1);
    3608       105832 :   if (dump_file && (dump_flags & TDF_DETAILS))
    3609              :     {
    3610         4339 :       dump_printf_loc (MSG_NOTE, loc, "reduction path: ");
    3611         4339 :       unsigned i;
    3612         4339 :       std::pair<ssa_op_iter, use_operand_p> *x;
    3613        14786 :       FOR_EACH_VEC_ELT (path, i, x)
    3614        10447 :         dump_printf (MSG_NOTE, "%T ", USE_FROM_PTR (x->second));
    3615         4339 :       dump_printf (MSG_NOTE, "\n");
    3616              :     }
    3617              : 
    3618              :   /* Check whether the reduction path detected is valid.  */
    3619       105832 :   bool fail = path.length () == 0;
    3620       105832 :   bool neg = false;
    3621       105832 :   int sign = -1;
    3622       105832 :   *code = ERROR_MARK;
    3623       227393 :   for (unsigned i = 1; i < path.length (); ++i)
    3624              :     {
    3625       128875 :       gimple *use_stmt = USE_STMT (path[i].second);
    3626       128875 :       gimple_match_op op;
    3627       128875 :       if (!gimple_extract_op (use_stmt, &op))
    3628              :         {
    3629              :           fail = true;
    3630         7314 :           break;
    3631              :         }
    3632       127958 :       unsigned int opi = op.num_ops;
    3633       127958 :       if (gassign *assign = dyn_cast<gassign *> (use_stmt))
    3634              :         {
    3635              :           /* The following make sure we can compute the operand index
    3636              :              easily plus it mostly disallows chaining via COND_EXPR condition
    3637              :              operands.  */
    3638       198546 :           for (opi = 0; opi < op.num_ops; ++opi)
    3639       197314 :             if (gimple_assign_rhs1_ptr (assign) + opi == path[i].second->use)
    3640              :               break;
    3641              :         }
    3642         6244 :       else if (gcall *call = dyn_cast<gcall *> (use_stmt))
    3643              :         {
    3644        12497 :           for (opi = 0; opi < op.num_ops; ++opi)
    3645        12497 :             if (gimple_call_arg_ptr (call, opi) == path[i].second->use)
    3646              :               break;
    3647              :         }
    3648       127958 :       if (opi == op.num_ops)
    3649              :         {
    3650              :           fail = true;
    3651              :           break;
    3652              :         }
    3653       126726 :       op.code = canonicalize_code (op.code, op.type);
    3654       126726 :       if (op.code == MINUS_EXPR)
    3655              :         {
    3656         5682 :           op.code = PLUS_EXPR;
    3657              :           /* Track whether we negate the reduction value each iteration.  */
    3658         5682 :           if (op.ops[1] == op.ops[opi])
    3659           34 :             neg = ! neg;
    3660              :         }
    3661       121044 :       else if (op.code == IFN_COND_SUB)
    3662              :         {
    3663            9 :           op.code = IFN_COND_ADD;
    3664              :           /* Track whether we negate the reduction value each iteration.  */
    3665            9 :           if (op.ops[2] == op.ops[opi])
    3666            0 :             neg = ! neg;
    3667              :         }
    3668              :       /* For an FMA the reduction code is the PLUS if the addition chain
    3669              :          is the reduction.  */
    3670       121035 :       else if (op.code == IFN_FMA && opi == 2)
    3671           35 :         op.code = PLUS_EXPR;
    3672       126726 :       if (CONVERT_EXPR_CODE_P (op.code)
    3673       126726 :           && tree_nop_conversion_p (op.type, TREE_TYPE (op.ops[0])))
    3674              :         ;
    3675       121100 :       else if (*code == ERROR_MARK)
    3676              :         {
    3677       103223 :           *code = op.code;
    3678       103223 :           sign = TYPE_SIGN (op.type);
    3679              :         }
    3680        17877 :       else if (op.code != *code)
    3681              :         {
    3682              :           fail = true;
    3683              :           break;
    3684              :         }
    3685        16253 :       else if ((op.code == MIN_EXPR
    3686        16097 :                 || op.code == MAX_EXPR)
    3687        16266 :                && sign != TYPE_SIGN (op.type))
    3688              :         {
    3689              :           fail = true;
    3690              :           break;
    3691              :         }
    3692              :       /* Check there's only a single stmt the op is used on.  For the
    3693              :          not value-changing tail and the last stmt allow out-of-loop uses,
    3694              :          but not when this is the inner loop of a double reduction.
    3695              :          ???  We could relax this and handle arbitrary live stmts by
    3696              :          forcing a scalar epilogue for example.  */
    3697       125099 :       imm_use_iterator imm_iter;
    3698       125099 :       use_operand_p use_p;
    3699       125099 :       gimple *op_use_stmt;
    3700       125099 :       unsigned cnt = 0;
    3701       131306 :       bool cond_fn_p = op.code.is_internal_fn ()
    3702         6207 :         && (conditional_internal_fn_code (internal_fn (op.code))
    3703       125099 :             != ERROR_MARK);
    3704              : 
    3705       299159 :       FOR_EACH_IMM_USE_STMT (op_use_stmt, imm_iter, op.ops[opi])
    3706              :         {
    3707              :           /* In case of a COND_OP (mask, op1, op2, op1) reduction we should
    3708              :              have op1 twice (once as definition, once as else) in the same
    3709              :              operation.  Enforce this.  */
    3710       174060 :           if (cond_fn_p && op_use_stmt == use_stmt)
    3711              :             {
    3712         6121 :               gcall *call = as_a<gcall *> (use_stmt);
    3713         6121 :               unsigned else_pos
    3714         6121 :                 = internal_fn_else_index (internal_fn (op.code));
    3715         6121 :               if (gimple_call_arg (call, else_pos) != op.ops[opi])
    3716              :                 {
    3717              :                   fail = true;
    3718              :                   break;
    3719              :                 }
    3720        30605 :               for (unsigned int j = 0; j < gimple_call_num_args (call); ++j)
    3721              :                 {
    3722        24484 :                   if (j == else_pos)
    3723         6121 :                     continue;
    3724        18363 :                   if (gimple_call_arg (call, j) == op.ops[opi])
    3725         6121 :                     cnt++;
    3726              :                 }
    3727              :             }
    3728       167939 :           else if (!is_gimple_debug (op_use_stmt)
    3729       167939 :                    && ((*code != ERROR_MARK || inner_loop_of_double_reduc)
    3730         2838 :                        || flow_bb_inside_loop_p (loop,
    3731         2838 :                                                  gimple_bb (op_use_stmt))))
    3732       245179 :             FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
    3733       122594 :               cnt++;
    3734       125099 :         }
    3735              : 
    3736       125099 :       if (cnt != 1)
    3737              :         {
    3738              :           fail = true;
    3739              :           break;
    3740              :         }
    3741              :     }
    3742       113728 :   return ! fail && ! neg && *code != ERROR_MARK;
    3743       105832 : }
    3744              : 
    3745              : bool
    3746           21 : check_reduction_path (dump_user_location_t loc, loop_p loop, gphi *phi,
    3747              :                       tree loop_arg, enum tree_code code)
    3748              : {
    3749           21 :   auto_vec<std::pair<ssa_op_iter, use_operand_p> > path;
    3750           21 :   code_helper code_;
    3751           21 :   return (check_reduction_path (loc, loop, phi, loop_arg, &code_, path, false)
    3752           21 :           && code_ == code);
    3753           21 : }
    3754              : 
    3755              : 
    3756              : 
    3757              : /* Function vect_is_simple_reduction
    3758              : 
    3759              :    (1) Detect a cross-iteration def-use cycle that represents a simple
    3760              :    reduction computation.  We look for the following pattern:
    3761              : 
    3762              :    loop_header:
    3763              :      a1 = phi < a0, a2 >
    3764              :      a3 = ...
    3765              :      a2 = operation (a3, a1)
    3766              : 
    3767              :    or
    3768              : 
    3769              :    a3 = ...
    3770              :    loop_header:
    3771              :      a1 = phi < a0, a2 >
    3772              :      a2 = operation (a3, a1)
    3773              : 
    3774              :    such that:
    3775              :    1. operation is commutative and associative and it is safe to
    3776              :       change the order of the computation
    3777              :    2. no uses for a2 in the loop (a2 is used out of the loop)
    3778              :    3. no uses of a1 in the loop besides the reduction operation
    3779              :    4. no uses of a1 outside the loop.
    3780              : 
    3781              :    Conditions 1,4 are tested here.
    3782              :    Conditions 2,3 are tested in vect_mark_stmts_to_be_vectorized.
    3783              : 
    3784              :    (2) Detect a cross-iteration def-use cycle in nested loops, i.e.,
    3785              :    nested cycles.
    3786              : 
    3787              :    (3) Detect cycles of phi nodes in outer-loop vectorization, i.e., double
    3788              :    reductions:
    3789              : 
    3790              :      a1 = phi < a0, a2 >
    3791              :      inner loop (def of a3)
    3792              :      a2 = phi < a3 >
    3793              : 
    3794              :    (4) Detect condition expressions, ie:
    3795              :      for (int i = 0; i < N; i++)
    3796              :        if (a[i] < val)
    3797              :         ret_val = a[i];
    3798              : 
    3799              : */
    3800              : 
    3801              : static stmt_vec_info
    3802       171729 : vect_is_simple_reduction (loop_vec_info loop_info, stmt_vec_info phi_info,
    3803              :                           gphi **double_reduc)
    3804              : {
    3805       171729 :   gphi *phi = as_a <gphi *> (phi_info->stmt);
    3806       171729 :   gimple *phi_use_stmt = NULL;
    3807       171729 :   imm_use_iterator imm_iter;
    3808       171729 :   use_operand_p use_p;
    3809              : 
    3810              :   /* When double_reduc is NULL we are testing the inner loop of a
    3811              :      double reduction.  */
    3812       171729 :   bool inner_loop_of_double_reduc = double_reduc == NULL;
    3813       171729 :   if (double_reduc)
    3814       170586 :     *double_reduc = NULL;
    3815       171729 :   STMT_VINFO_REDUC_TYPE (phi_info) = TREE_CODE_REDUCTION;
    3816              : 
    3817       171729 :   tree phi_name = PHI_RESULT (phi);
    3818              :   /* ???  If there are no uses of the PHI result the inner loop reduction
    3819              :      won't be detected as possibly double-reduction by vectorizable_reduction
    3820              :      because that tries to walk the PHI arg from the preheader edge which
    3821              :      can be constant.  See PR60382.  */
    3822       171729 :   if (has_zero_uses (phi_name))
    3823              :     return NULL;
    3824       171597 :   class loop *loop = (gimple_bb (phi))->loop_father;
    3825       171597 :   unsigned nphi_def_loop_uses = 0;
    3826       474272 :   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, phi_name)
    3827              :     {
    3828       315217 :       gimple *use_stmt = USE_STMT (use_p);
    3829       315217 :       if (is_gimple_debug (use_stmt))
    3830        86791 :         continue;
    3831              : 
    3832       228426 :       if (!flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
    3833              :         {
    3834        12542 :           if (dump_enabled_p ())
    3835           31 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3836              :                              "intermediate value used outside loop.\n");
    3837              : 
    3838        12542 :           return NULL;
    3839              :         }
    3840              : 
    3841              :       /* In case of a COND_OP (mask, op1, op2, op1) reduction we might have
    3842              :          op1 twice (once as definition, once as else) in the same operation.
    3843              :          Only count it as one. */
    3844       215884 :       if (use_stmt != phi_use_stmt)
    3845              :         {
    3846       209403 :           nphi_def_loop_uses++;
    3847       209403 :           phi_use_stmt = use_stmt;
    3848              :         }
    3849        12542 :     }
    3850              : 
    3851       159055 :   tree latch_def = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
    3852       159055 :   if (TREE_CODE (latch_def) != SSA_NAME)
    3853              :     {
    3854         1659 :       if (dump_enabled_p ())
    3855           12 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3856              :                          "reduction: not ssa_name: %T\n", latch_def);
    3857              :       return NULL;
    3858              :     }
    3859              : 
    3860       157396 :   stmt_vec_info def_stmt_info = loop_info->lookup_def (latch_def);
    3861       157396 :   if (!def_stmt_info
    3862       157396 :       || !flow_bb_inside_loop_p (loop, gimple_bb (def_stmt_info->stmt)))
    3863              :     return NULL;
    3864              : 
    3865       157219 :   bool nested_in_vect_loop
    3866       157219 :     = flow_loop_nested_p (LOOP_VINFO_LOOP (loop_info), loop);
    3867       157219 :   unsigned nlatch_def_loop_uses = 0;
    3868       157219 :   auto_vec<gphi *, 3> lcphis;
    3869       620604 :   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, latch_def)
    3870              :     {
    3871       463385 :       gimple *use_stmt = USE_STMT (use_p);
    3872       463385 :       if (is_gimple_debug (use_stmt))
    3873       144005 :         continue;
    3874       319380 :       if (flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
    3875       199263 :         nlatch_def_loop_uses++;
    3876              :       else
    3877              :         /* We can have more than one loop-closed PHI.  */
    3878       120117 :         lcphis.safe_push (as_a <gphi *> (use_stmt));
    3879       157219 :     }
    3880              : 
    3881              :   /* If we are vectorizing an inner reduction we are executing that
    3882              :      in the original order only in case we are not dealing with a
    3883              :      double reduction.  */
    3884       157219 :   if (nested_in_vect_loop && !inner_loop_of_double_reduc)
    3885              :     {
    3886         2322 :       if (dump_enabled_p ())
    3887          437 :         report_vect_op (MSG_NOTE, def_stmt_info->stmt,
    3888              :                         "detected nested cycle: ");
    3889              :       return def_stmt_info;
    3890              :     }
    3891              : 
    3892              :   /* When the inner loop of a double reduction ends up with more than
    3893              :      one loop-closed PHI we have failed to classify alternate such
    3894              :      PHIs as double reduction, leading to wrong code.  See PR103237.  */
    3895       156028 :   if (inner_loop_of_double_reduc && lcphis.length () != 1)
    3896              :     {
    3897            1 :       if (dump_enabled_p ())
    3898            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3899              :                          "unhandle double reduction\n");
    3900              :       return NULL;
    3901              :     }
    3902              : 
    3903              :   /* If this isn't a nested cycle or if the nested cycle reduction value
    3904              :      is used outside of the inner loop we cannot handle uses of the reduction
    3905              :      value.  */
    3906       154896 :   if (nlatch_def_loop_uses > 1 || nphi_def_loop_uses > 1)
    3907              :     {
    3908        47682 :       if (dump_enabled_p ())
    3909          432 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3910              :                          "reduction used in loop.\n");
    3911              :       return NULL;
    3912              :     }
    3913              : 
    3914              :   /* If DEF_STMT is a phi node itself, we expect it to have a single argument
    3915              :      defined in the inner loop.  */
    3916       107214 :   if (gphi *def_stmt = dyn_cast <gphi *> (def_stmt_info->stmt))
    3917              :     {
    3918         1403 :       tree op1 = PHI_ARG_DEF (def_stmt, 0);
    3919         1403 :       if (gimple_phi_num_args (def_stmt) != 1
    3920         1403 :           || TREE_CODE (op1) != SSA_NAME)
    3921              :         {
    3922           94 :           if (dump_enabled_p ())
    3923            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3924              :                              "unsupported phi node definition.\n");
    3925              : 
    3926              :           return NULL;
    3927              :         }
    3928              : 
    3929              :       /* Verify there is an inner cycle composed of the PHI phi_use_stmt
    3930              :          and the latch definition op1.  */
    3931         1309 :       gimple *def1 = SSA_NAME_DEF_STMT (op1);
    3932         1309 :       if (gimple_bb (def1)
    3933         1309 :           && flow_bb_inside_loop_p (loop, gimple_bb (def_stmt))
    3934         1309 :           && loop->inner
    3935         1255 :           && flow_bb_inside_loop_p (loop->inner, gimple_bb (def1))
    3936         1255 :           && (is_gimple_assign (def1) || is_gimple_call (def1))
    3937         1246 :           && is_a <gphi *> (phi_use_stmt)
    3938         1234 :           && flow_bb_inside_loop_p (loop->inner, gimple_bb (phi_use_stmt))
    3939         1234 :           && (op1 == PHI_ARG_DEF_FROM_EDGE (phi_use_stmt,
    3940              :                                             loop_latch_edge (loop->inner)))
    3941       159671 :           && lcphis.length () == 1)
    3942              :         {
    3943         1143 :           if (dump_enabled_p ())
    3944          144 :             report_vect_op (MSG_NOTE, def_stmt,
    3945              :                             "detected double reduction: ");
    3946              : 
    3947         1143 :           *double_reduc = as_a <gphi *> (phi_use_stmt);
    3948         1143 :           return def_stmt_info;
    3949              :         }
    3950              : 
    3951              :       return NULL;
    3952              :     }
    3953              : 
    3954              :   /* Look for the expression computing latch_def from then loop PHI result.  */
    3955       105811 :   auto_vec<std::pair<ssa_op_iter, use_operand_p> > path;
    3956       105811 :   code_helper code;
    3957       105811 :   if (check_reduction_path (vect_location, loop, phi, latch_def, &code,
    3958              :                             path, inner_loop_of_double_reduc))
    3959              :     {
    3960        97915 :       STMT_VINFO_REDUC_CODE (phi_info) = code;
    3961        97915 :       if (code == COND_EXPR && !nested_in_vect_loop)
    3962         8568 :         STMT_VINFO_REDUC_TYPE (phi_info) = COND_REDUCTION;
    3963              : 
    3964              :       /* Fill in STMT_VINFO_REDUC_IDX.  */
    3965        97915 :       unsigned i;
    3966       315404 :       for (i = path.length () - 1; i >= 1; --i)
    3967              :         {
    3968       119574 :           gimple *stmt = USE_STMT (path[i].second);
    3969       119574 :           stmt_vec_info stmt_info = loop_info->lookup_stmt (stmt);
    3970       119574 :           gimple_match_op op;
    3971       119574 :           if (!gimple_extract_op (stmt, &op))
    3972            0 :             gcc_unreachable ();
    3973       119574 :           if (gassign *assign = dyn_cast<gassign *> (stmt))
    3974       113354 :             STMT_VINFO_REDUC_IDX (stmt_info)
    3975       113354 :               = path[i].second->use - gimple_assign_rhs1_ptr (assign);
    3976              :           else
    3977              :             {
    3978         6220 :               gcall *call = as_a<gcall *> (stmt);
    3979         6220 :               STMT_VINFO_REDUC_IDX (stmt_info)
    3980         6220 :                 = path[i].second->use - gimple_call_arg_ptr (call, 0);
    3981              :             }
    3982              :         }
    3983        97915 :       if (dump_enabled_p ())
    3984         4321 :         dump_printf_loc (MSG_NOTE, vect_location,
    3985              :                          "reduction: detected reduction\n");
    3986              : 
    3987              :       return def_stmt_info;
    3988              :     }
    3989              : 
    3990         7896 :   if (dump_enabled_p ())
    3991           99 :     dump_printf_loc (MSG_NOTE, vect_location,
    3992              :                      "reduction: unknown pattern\n");
    3993              : 
    3994              :   return NULL;
    3995       263030 : }
    3996              : 
    3997              : /* Estimate the number of peeled epilogue iterations for LOOP_VINFO.
    3998              :    PEEL_ITERS_PROLOGUE is the number of peeled prologue iterations,
    3999              :    or -1 if not known.  */
    4000              : 
    4001              : static int
    4002       531436 : vect_get_peel_iters_epilogue (loop_vec_info loop_vinfo, int peel_iters_prologue)
    4003              : {
    4004       531436 :   int assumed_vf = vect_vf_for_cost (loop_vinfo);
    4005       531436 :   if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) || peel_iters_prologue == -1)
    4006              :     {
    4007       220537 :       if (dump_enabled_p ())
    4008         4672 :         dump_printf_loc (MSG_NOTE, vect_location,
    4009              :                          "cost model: epilogue peel iters set to vf/2 "
    4010              :                          "because loop iterations are unknown .\n");
    4011       220537 :       return assumed_vf / 2;
    4012              :     }
    4013              :   else
    4014              :     {
    4015       310899 :       int niters = LOOP_VINFO_INT_NITERS (loop_vinfo);
    4016       310899 :       peel_iters_prologue = MIN (niters, peel_iters_prologue);
    4017       310899 :       int peel_iters_epilogue = (niters - peel_iters_prologue) % assumed_vf;
    4018              :       /* If we need to peel for gaps, but no peeling is required, we have to
    4019              :          peel VF iterations.  */
    4020       310899 :       if (LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) && !peel_iters_epilogue)
    4021       531436 :         peel_iters_epilogue = assumed_vf;
    4022              :       return peel_iters_epilogue;
    4023              :     }
    4024              : }
    4025              : 
    4026              : /* Calculate cost of peeling the scalar loop PEEL_ITERS_PROLOGUE times for
    4027              :    a prologue and the corresponding times for the epilogue.  */
    4028              : int
    4029       400167 : vect_get_known_peeling_cost (loop_vec_info loop_vinfo, int peel_iters_prologue)
    4030              : {
    4031       400167 :   int retval = 0;
    4032              : 
    4033       400167 :   int peel_iters_epilogue
    4034       400167 :     = vect_get_peel_iters_epilogue (loop_vinfo, peel_iters_prologue);
    4035              : 
    4036       400167 :   if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
    4037              :     {
    4038              :       /* If peeled iterations are known but number of scalar loop
    4039              :          iterations are unknown, count a taken branch per peeled loop.  */
    4040       150861 :       if (peel_iters_prologue > 0)
    4041        90473 :         retval = builtin_vectorization_cost (cond_branch_taken, NULL_TREE, 0);
    4042       150861 :       if (peel_iters_epilogue > 0)
    4043       150708 :         retval += builtin_vectorization_cost (cond_branch_taken, NULL_TREE, 0);
    4044              :     }
    4045              : 
    4046       800334 :   retval += ((peel_iters_prologue + peel_iters_epilogue)
    4047       400167 :              * loop_vinfo->scalar_costs->body_cost ());
    4048       800334 :   retval += (((peel_iters_prologue != 0) + (peel_iters_epilogue != 0))
    4049       400167 :              * loop_vinfo->scalar_costs->outside_cost ());
    4050              : 
    4051       400167 :   return retval;
    4052              : }
    4053              : 
    4054              : /* Return the count for SI in PEEL_ITERS scalar iterations, including the
    4055              :    inner-loop frequency.  */
    4056              : 
    4057              : static int
    4058       323482 : vect_scalar_peeling_stmt_count (loop_vec_info loop_vinfo,
    4059              :                                 const stmt_info_for_cost &si, int peel_iters)
    4060              : {
    4061       323482 :   int count = si.count;
    4062       323482 :   if (si.stmt_info && stmt_in_inner_loop_p (loop_vinfo, si.stmt_info))
    4063          384 :     count *= LOOP_VINFO_INNER_LOOP_COST_FACTOR (loop_vinfo);
    4064       323482 :   return count * peel_iters;
    4065              : }
    4066              : 
    4067              : /* Function vect_estimate_min_profitable_iters
    4068              : 
    4069              :    Return the number of iterations required for the vector version of the
    4070              :    loop to be profitable relative to the cost of the scalar version of the
    4071              :    loop.
    4072              : 
    4073              :    *RET_MIN_PROFITABLE_NITERS is a cost model profitability threshold
    4074              :    of iterations for vectorization.  -1 value means loop vectorization
    4075              :    is not profitable.  This returned value may be used for dynamic
    4076              :    profitability check.
    4077              : 
    4078              :    *RET_MIN_PROFITABLE_ESTIMATE is a profitability threshold to be used
    4079              :    for static check against estimated number of iterations.  */
    4080              : 
    4081              : static void
    4082       150318 : vect_estimate_min_profitable_iters (loop_vec_info loop_vinfo,
    4083              :                                     int *ret_min_profitable_niters,
    4084              :                                     int *ret_min_profitable_estimate,
    4085              :                                     unsigned *suggested_unroll_factor)
    4086              : {
    4087       150318 :   int min_profitable_iters;
    4088       150318 :   int min_profitable_estimate;
    4089       150318 :   int peel_iters_prologue;
    4090       150318 :   int peel_iters_epilogue;
    4091       150318 :   unsigned vec_inside_cost = 0;
    4092       150318 :   int vec_outside_cost = 0;
    4093       150318 :   unsigned vec_prologue_cost = 0;
    4094       150318 :   unsigned vec_epilogue_cost = 0;
    4095       150318 :   int scalar_single_iter_cost = 0;
    4096       150318 :   int scalar_outside_cost = 0;
    4097       150318 :   int assumed_vf = vect_vf_for_cost (loop_vinfo);
    4098       150318 :   int npeel = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
    4099       150318 :   vector_costs *target_cost_data = loop_vinfo->vector_costs;
    4100              : 
    4101              :   /* Cost model disabled.  */
    4102       150318 :   if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
    4103              :     {
    4104        18739 :       if (dump_enabled_p ())
    4105        11285 :         dump_printf_loc (MSG_NOTE, vect_location, "cost model disabled.\n");
    4106        18739 :       *ret_min_profitable_niters = 0;
    4107        18739 :       *ret_min_profitable_estimate = 0;
    4108        18739 :       return;
    4109              :     }
    4110              : 
    4111              :   /* Requires loop versioning tests to handle misalignment.  */
    4112       131579 :   if (LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
    4113              :     {
    4114              :       /*  FIXME: Make cost depend on complexity of individual check.  */
    4115           18 :       unsigned len = LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ();
    4116           18 :       (void) add_stmt_cost (target_cost_data, len, scalar_stmt, vect_prologue);
    4117           18 :       if (dump_enabled_p ())
    4118            2 :         dump_printf (MSG_NOTE,
    4119              :                      "cost model: Adding cost of checks for loop "
    4120              :                      "versioning to treat misalignment.\n");
    4121              :     }
    4122              : 
    4123              :   /* Requires loop versioning with alias checks.  */
    4124       131579 :   if (LOOP_REQUIRES_VERSIONING_FOR_ALIAS (loop_vinfo))
    4125              :     {
    4126              :       /*  FIXME: Make cost depend on complexity of individual check.  */
    4127         7291 :       unsigned len = LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo).length ();
    4128         7291 :       (void) add_stmt_cost (target_cost_data, len, scalar_stmt, vect_prologue);
    4129         7291 :       len = LOOP_VINFO_CHECK_UNEQUAL_ADDRS (loop_vinfo).length ();
    4130            4 :       if (len)
    4131              :         /* Count LEN - 1 ANDs and LEN comparisons.  */
    4132            4 :         (void) add_stmt_cost (target_cost_data, len * 2 - 1,
    4133              :                               scalar_stmt, vect_prologue);
    4134         7291 :       len = LOOP_VINFO_LOWER_BOUNDS (loop_vinfo).length ();
    4135         1259 :       if (len)
    4136              :         {
    4137              :           /* Count LEN - 1 ANDs and LEN comparisons.  */
    4138         1259 :           unsigned int nstmts = len * 2 - 1;
    4139              :           /* +1 for each bias that needs adding.  */
    4140         2518 :           for (unsigned int i = 0; i < len; ++i)
    4141         1259 :             if (!LOOP_VINFO_LOWER_BOUNDS (loop_vinfo)[i].unsigned_p)
    4142          146 :               nstmts += 1;
    4143         1259 :           (void) add_stmt_cost (target_cost_data, nstmts,
    4144              :                                 scalar_stmt, vect_prologue);
    4145              :         }
    4146         7291 :       if (dump_enabled_p ())
    4147           32 :         dump_printf (MSG_NOTE,
    4148              :                      "cost model: Adding cost of checks for loop "
    4149              :                      "versioning aliasing.\n");
    4150              :     }
    4151              : 
    4152              :   /* Requires loop versioning with niter checks.  */
    4153       131579 :   if (LOOP_REQUIRES_VERSIONING_FOR_NITERS (loop_vinfo))
    4154              :     {
    4155          958 :       tree assum = LOOP_VINFO_NITERS_ASSUMPTIONS (loop_vinfo);
    4156              : 
    4157              :       /* Count all involved statements in the assumption.
    4158              :          ??? This might over-count in case we CSE later.  */
    4159         6704 :       auto count_stmts = [] (tree *t, int *walk, void *nstmts) -> tree
    4160              :         {
    4161         5746 :           if (!EXPR_P (*t) || is_gimple_val (*t))
    4162         2849 :             *walk = 0;
    4163              :           else
    4164         2897 :             (*(int *) nstmts)++;
    4165         5746 :           return NULL_TREE;
    4166              :         };
    4167              : 
    4168          958 :       int nstmts = 0;
    4169          958 :       walk_tree_without_duplicates (&assum, count_stmts, &nstmts);
    4170              : 
    4171          958 :       (void) add_stmt_cost (target_cost_data, nstmts, scalar_stmt,
    4172              :                             NULL, NULL, NULL_TREE, 0, vect_prologue);
    4173          958 :       if (dump_enabled_p ())
    4174            1 :         dump_printf (MSG_NOTE,
    4175              :                      "cost model: Adding cost of checks for loop "
    4176              :                      "versioning niters.\n");
    4177              :     }
    4178              : 
    4179       131579 :   if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
    4180         8185 :     (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
    4181              :                           vect_prologue);
    4182              : 
    4183              :   /* Count statements in scalar loop.  Using this as scalar cost for a single
    4184              :      iteration for now.
    4185              : 
    4186              :      TODO: Add outer loop support.
    4187              : 
    4188              :      TODO: Consider assigning different costs to different scalar
    4189              :      statements.  */
    4190              : 
    4191       131579 :   scalar_single_iter_cost = loop_vinfo->scalar_costs->total_cost ();
    4192              : 
    4193              :   /* Add additional cost for the peeled instructions in prologue and epilogue
    4194              :      loop.  (For fully-masked loops there will be no peeling.)
    4195              : 
    4196              :      FORNOW: If we don't know the value of peel_iters for prologue or epilogue
    4197              :      at compile-time - we assume it's vf/2 (the worst would be vf-1).
    4198              : 
    4199              :      TODO: Build an expression that represents peel_iters for prologue and
    4200              :      epilogue to be used in a run-time test.  */
    4201              : 
    4202       131579 :   bool prologue_need_br_taken_cost = false;
    4203       131579 :   bool prologue_need_br_not_taken_cost = false;
    4204              : 
    4205              :   /* Calculate peel_iters_prologue.  */
    4206       131579 :   if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
    4207              :     peel_iters_prologue = 0;
    4208       131579 :   else if (npeel < 0)
    4209              :     {
    4210          282 :       peel_iters_prologue = assumed_vf / 2;
    4211          282 :       if (dump_enabled_p ())
    4212           11 :         dump_printf (MSG_NOTE, "cost model: "
    4213              :                      "prologue peel iters set to vf/2.\n");
    4214              : 
    4215              :       /* If peeled iterations are unknown, count a taken branch and a not taken
    4216              :          branch per peeled loop.  Even if scalar loop iterations are known,
    4217              :          vector iterations are not known since peeled prologue iterations are
    4218              :          not known.  Hence guards remain the same.  */
    4219              :       prologue_need_br_taken_cost = true;
    4220              :       prologue_need_br_not_taken_cost = true;
    4221              :     }
    4222              :   else
    4223              :     {
    4224       131297 :       peel_iters_prologue = npeel;
    4225       131297 :       if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && peel_iters_prologue > 0)
    4226              :         /* If peeled iterations are known but number of scalar loop
    4227              :            iterations are unknown, count a taken branch per peeled loop.  */
    4228       131579 :         prologue_need_br_taken_cost = true;
    4229              :     }
    4230              : 
    4231       131579 :   bool epilogue_need_br_taken_cost = false;
    4232       131579 :   bool epilogue_need_br_not_taken_cost = false;
    4233              : 
    4234              :   /* Calculate peel_iters_epilogue.  */
    4235       131579 :   if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4236              :     /* We need to peel exactly one iteration for gaps.  */
    4237           28 :     peel_iters_epilogue = LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) ? 1 : 0;
    4238       131551 :   else if (npeel < 0)
    4239              :     {
    4240              :       /* If peeling for alignment is unknown, loop bound of main loop
    4241              :          becomes unknown.  */
    4242          282 :       peel_iters_epilogue = assumed_vf / 2;
    4243          282 :       if (dump_enabled_p ())
    4244           11 :         dump_printf (MSG_NOTE, "cost model: "
    4245              :                      "epilogue peel iters set to vf/2 because "
    4246              :                      "peeling for alignment is unknown.\n");
    4247              : 
    4248              :       /* See the same reason above in peel_iters_prologue calculation.  */
    4249              :       epilogue_need_br_taken_cost = true;
    4250              :       epilogue_need_br_not_taken_cost = true;
    4251              :     }
    4252              :   else
    4253              :     {
    4254       131269 :       peel_iters_epilogue = vect_get_peel_iters_epilogue (loop_vinfo, npeel);
    4255       131269 :       if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo) && peel_iters_epilogue > 0)
    4256              :         /* If peeled iterations are known but number of scalar loop
    4257              :            iterations are unknown, count a taken branch per peeled loop.  */
    4258       131579 :         epilogue_need_br_taken_cost = true;
    4259              :     }
    4260              : 
    4261              :   /* The way we cummulate peeling costs into the vector prologue/epilogue
    4262              :      cost is a bit awkward given we cannot reuse scalar_costs which is
    4263              :      already computed and also because it cannot take into account any
    4264              :      epilogue vectorization we'll carry out in the end.  */
    4265              : 
    4266       131579 :   stmt_info_for_cost *si;
    4267       131579 :   int j;
    4268              :   /* Add costs associated with peel_iters_prologue.  */
    4269       131579 :   if (peel_iters_prologue)
    4270         1083 :     FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
    4271              :       {
    4272          785 :         int count = vect_scalar_peeling_stmt_count (loop_vinfo, *si,
    4273              :                                                     peel_iters_prologue);
    4274          785 :         (void) add_stmt_cost (target_cost_data, count, si->kind,
    4275              :                               si->stmt_info, si->node, si->vectype,
    4276              :                               si->misalign, vect_prologue);
    4277              :       }
    4278              : 
    4279              :   /* Add costs associated with peel_iters_epilogue.  */
    4280       131579 :   if (peel_iters_epilogue)
    4281       404476 :     FOR_EACH_VEC_ELT (LOOP_VINFO_SCALAR_ITERATION_COST (loop_vinfo), j, si)
    4282              :       {
    4283       322697 :         int count = vect_scalar_peeling_stmt_count (loop_vinfo, *si,
    4284              :                                                     peel_iters_epilogue);
    4285       322697 :         (void) add_stmt_cost (target_cost_data, count, si->kind,
    4286              :                               si->stmt_info, si->node, si->vectype,
    4287              :                               si->misalign, vect_epilogue);
    4288              :       }
    4289              : 
    4290              :   /* Add possible cond_branch_taken/cond_branch_not_taken cost.  */
    4291              : 
    4292       131579 :   if (prologue_need_br_taken_cost)
    4293          282 :     (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
    4294              :                           vect_prologue);
    4295              : 
    4296       131579 :   if (prologue_need_br_not_taken_cost)
    4297          282 :     (void) add_stmt_cost (target_cost_data, 1,
    4298              :                           cond_branch_not_taken, vect_prologue);
    4299              : 
    4300       131579 :   if (epilogue_need_br_taken_cost)
    4301        69055 :     (void) add_stmt_cost (target_cost_data, 1, cond_branch_taken,
    4302              :                           vect_epilogue);
    4303              : 
    4304       131579 :   if (epilogue_need_br_not_taken_cost)
    4305          282 :     (void) add_stmt_cost (target_cost_data, 1,
    4306              :                           cond_branch_not_taken, vect_epilogue);
    4307              : 
    4308              :   /* Take care of special costs for rgroup controls of partial vectors.  */
    4309           28 :   if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
    4310       131607 :       && (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
    4311              :           == vect_partial_vectors_avx512))
    4312              :     {
    4313              :       /* Calculate how many masks we need to generate.  */
    4314           28 :       unsigned int num_masks = 0;
    4315           28 :       bool need_saturation = false;
    4316          115 :       for (auto rgm : LOOP_VINFO_MASKS (loop_vinfo).rgc_vec)
    4317           31 :         if (rgm.type)
    4318              :           {
    4319           28 :             unsigned nvectors = rgm.factor;
    4320           28 :             num_masks += nvectors;
    4321           28 :             if (TYPE_PRECISION (TREE_TYPE (rgm.compare_type))
    4322           28 :                 < TYPE_PRECISION (LOOP_VINFO_RGROUP_IV_TYPE (loop_vinfo)))
    4323           10 :               need_saturation = true;
    4324              :           }
    4325              : 
    4326              :       /* ???  The target isn't able to identify the costs below as
    4327              :          producing masks so it cannot penaltize cases where we'd run
    4328              :          out of mask registers for example.  */
    4329              : 
    4330              :       /* ???  We are also failing to account for smaller vector masks
    4331              :          we generate by splitting larger masks in vect_get_mask.  */
    4332              : 
    4333              :       /* In the worst case, we need to generate each mask in the prologue
    4334              :          and in the loop body.  We need one splat per group and one
    4335              :          compare per mask.
    4336              : 
    4337              :          Sometimes the prologue mask will fold to a constant,
    4338              :          so the actual prologue cost might be smaller.  However, it's
    4339              :          simpler and safer to use the worst-case cost; if this ends up
    4340              :          being the tie-breaker between vectorizing or not, then it's
    4341              :          probably better not to vectorize.  */
    4342           28 :       (void) add_stmt_cost (target_cost_data,
    4343              :                             num_masks
    4344           28 :                             + LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.length (),
    4345              :                             vector_stmt, NULL, NULL, NULL_TREE, 0,
    4346              :                             vect_prologue);
    4347           56 :       (void) add_stmt_cost (target_cost_data,
    4348              :                             num_masks
    4349           56 :                             + LOOP_VINFO_MASKS (loop_vinfo).rgc_vec.length (),
    4350              :                             vector_stmt, NULL, NULL, NULL_TREE, 0, vect_body);
    4351              : 
    4352              :       /* When we need saturation we need it both in the prologue and
    4353              :          the epilogue.  */
    4354           28 :       if (need_saturation)
    4355              :         {
    4356           10 :           (void) add_stmt_cost (target_cost_data, 1, scalar_stmt,
    4357              :                                 NULL, NULL, NULL_TREE, 0, vect_prologue);
    4358           10 :           (void) add_stmt_cost (target_cost_data, 1, scalar_stmt,
    4359              :                                 NULL, NULL, NULL_TREE, 0, vect_body);
    4360              :         }
    4361              :     }
    4362            0 :   else if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
    4363       131551 :            && (LOOP_VINFO_PARTIAL_VECTORS_STYLE (loop_vinfo)
    4364              :                == vect_partial_vectors_while_ult))
    4365              :     {
    4366              :       /* Calculate how many masks we need to generate.  */
    4367              :       unsigned int num_masks = 0;
    4368              :       rgroup_controls *rgm;
    4369              :       unsigned int num_vectors_m1;
    4370            0 :       FOR_EACH_VEC_ELT (LOOP_VINFO_MASKS (loop_vinfo).rgc_vec,
    4371              :                         num_vectors_m1, rgm)
    4372            0 :         if (rgm->type)
    4373            0 :           num_masks += num_vectors_m1 + 1;
    4374            0 :       gcc_assert (num_masks > 0);
    4375              : 
    4376              :       /* In the worst case, we need to generate each mask in the prologue
    4377              :          and in the loop body.  One of the loop body mask instructions
    4378              :          replaces the comparison in the scalar loop, and since we don't
    4379              :          count the scalar comparison against the scalar body, we shouldn't
    4380              :          count that vector instruction against the vector body either.
    4381              : 
    4382              :          Sometimes we can use unpacks instead of generating prologue
    4383              :          masks and sometimes the prologue mask will fold to a constant,
    4384              :          so the actual prologue cost might be smaller.  However, it's
    4385              :          simpler and safer to use the worst-case cost; if this ends up
    4386              :          being the tie-breaker between vectorizing or not, then it's
    4387              :          probably better not to vectorize.  */
    4388            0 :       (void) add_stmt_cost (target_cost_data, num_masks,
    4389              :                             vector_stmt, NULL, NULL, NULL_TREE, 0,
    4390              :                             vect_prologue);
    4391            0 :       (void) add_stmt_cost (target_cost_data, num_masks - 1,
    4392              :                             vector_stmt, NULL, NULL, NULL_TREE, 0,
    4393              :                             vect_body);
    4394              :     }
    4395       131551 :   else if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
    4396              :     {
    4397              :       /* Referring to the functions vect_set_loop_condition_partial_vectors
    4398              :          and vect_set_loop_controls_directly, we need to generate each
    4399              :          length in the prologue and in the loop body if required. Although
    4400              :          there are some possible optimizations, we consider the worst case
    4401              :          here.  */
    4402              : 
    4403            0 :       bool niters_known_p = LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo);
    4404            0 :       signed char partial_load_store_bias
    4405              :         = LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo);
    4406            0 :       bool need_iterate_p
    4407            0 :         = (!LOOP_VINFO_EPILOGUE_P (loop_vinfo)
    4408            0 :            && !vect_known_niters_smaller_than_vf (loop_vinfo));
    4409              : 
    4410              :       /* Calculate how many statements to be added.  */
    4411            0 :       unsigned int prologue_stmts = 0;
    4412            0 :       unsigned int body_stmts = 0;
    4413              : 
    4414            0 :       rgroup_controls *rgc;
    4415            0 :       unsigned int num_vectors_m1;
    4416            0 :       FOR_EACH_VEC_ELT (LOOP_VINFO_LENS (loop_vinfo), num_vectors_m1, rgc)
    4417            0 :         if (rgc->type)
    4418              :           {
    4419              :             /* May need one SHIFT for nitems_total computation.  */
    4420            0 :             unsigned nitems = rgc->max_nscalars_per_iter * rgc->factor;
    4421            0 :             if (nitems != 1 && !niters_known_p)
    4422            0 :               prologue_stmts += 1;
    4423              : 
    4424              :             /* May need one MAX and one MINUS for wrap around.  */
    4425            0 :             if (vect_rgroup_iv_might_wrap_p (loop_vinfo, rgc))
    4426            0 :               prologue_stmts += 2;
    4427              : 
    4428              :             /* Need one MAX and one MINUS for each batch limit excepting for
    4429              :                the 1st one.  */
    4430            0 :             prologue_stmts += num_vectors_m1 * 2;
    4431              : 
    4432            0 :             unsigned int num_vectors = num_vectors_m1 + 1;
    4433              : 
    4434              :             /* Need to set up lengths in prologue, only one MIN required
    4435              :                for each since start index is zero.  */
    4436            0 :             prologue_stmts += num_vectors;
    4437              : 
    4438              :             /* If we have a non-zero partial load bias, we need one PLUS
    4439              :                to adjust the load length.  */
    4440            0 :             if (partial_load_store_bias != 0)
    4441            0 :               body_stmts += 1;
    4442              : 
    4443            0 :             unsigned int length_update_cost = 0;
    4444            0 :             if (LOOP_VINFO_USING_DECREMENTING_IV_P (loop_vinfo))
    4445              :               /* For decrement IV style, Each only need a single SELECT_VL
    4446              :                  or MIN since beginning to calculate the number of elements
    4447              :                  need to be processed in current iteration.  */
    4448              :               length_update_cost = 1;
    4449              :             else
    4450              :               /* For increment IV stype, Each may need two MINs and one MINUS to
    4451              :                  update lengths in body for next iteration.  */
    4452            0 :               length_update_cost = 3;
    4453              : 
    4454            0 :             if (need_iterate_p)
    4455            0 :               body_stmts += length_update_cost * num_vectors;
    4456              :           }
    4457              : 
    4458            0 :       (void) add_stmt_cost (target_cost_data, prologue_stmts,
    4459              :                             scalar_stmt, vect_prologue);
    4460            0 :       (void) add_stmt_cost (target_cost_data, body_stmts,
    4461              :                             scalar_stmt, vect_body);
    4462              :     }
    4463              : 
    4464              :   /* FORNOW: The scalar outside cost is incremented in one of the
    4465              :      following ways:
    4466              : 
    4467              :      1. The vectorizer checks for alignment and aliasing and generates
    4468              :      a condition that allows dynamic vectorization.  A cost model
    4469              :      check is ANDED with the versioning condition.  Hence scalar code
    4470              :      path now has the added cost of the versioning check.
    4471              : 
    4472              :        if (cost > th & versioning_check)
    4473              :          jmp to vector code
    4474              : 
    4475              :      Hence run-time scalar is incremented by not-taken branch cost.
    4476              : 
    4477              :      2. The vectorizer then checks if a prologue is required.  If the
    4478              :      cost model check was not done before during versioning, it has to
    4479              :      be done before the prologue check.
    4480              : 
    4481              :        if (cost <= th)
    4482              :          prologue = scalar_iters
    4483              :        if (prologue == 0)
    4484              :          jmp to vector code
    4485              :        else
    4486              :          execute prologue
    4487              :        if (prologue == num_iters)
    4488              :          go to exit
    4489              : 
    4490              :      Hence the run-time scalar cost is incremented by a taken branch,
    4491              :      plus a not-taken branch, plus a taken branch cost.
    4492              : 
    4493              :      3. The vectorizer then checks if an epilogue is required.  If the
    4494              :      cost model check was not done before during prologue check, it
    4495              :      has to be done with the epilogue check.
    4496              : 
    4497              :        if (prologue == 0)
    4498              :          jmp to vector code
    4499              :        else
    4500              :          execute prologue
    4501              :        if (prologue == num_iters)
    4502              :          go to exit
    4503              :        vector code:
    4504              :          if ((cost <= th) | (scalar_iters-prologue-epilogue == 0))
    4505              :            jmp to epilogue
    4506              : 
    4507              :      Hence the run-time scalar cost should be incremented by 2 taken
    4508              :      branches.
    4509              : 
    4510              :      TODO: The back end may reorder the BBS's differently and reverse
    4511              :      conditions/branch directions.  Change the estimates below to
    4512              :      something more reasonable.  */
    4513              : 
    4514              :   /* If the number of iterations is known and we do not do versioning, we can
    4515              :      decide whether to vectorize at compile time.  Hence the scalar version
    4516              :      do not carry cost model guard costs.  */
    4517        61642 :   if (!LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
    4518       193221 :       || LOOP_REQUIRES_VERSIONING (loop_vinfo))
    4519              :     {
    4520              :       /* Cost model check occurs at versioning.  */
    4521        71046 :       if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
    4522         8185 :         scalar_outside_cost += vect_get_stmt_cost (cond_branch_not_taken);
    4523              :       else
    4524              :         {
    4525              :           /* Cost model check occurs at prologue generation.  */
    4526        62861 :           if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) < 0)
    4527          155 :             scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken)
    4528          155 :               + vect_get_stmt_cost (cond_branch_not_taken);
    4529              :           /* Cost model check occurs at epilogue generation.  */
    4530              :           else
    4531        62706 :             scalar_outside_cost += 2 * vect_get_stmt_cost (cond_branch_taken);
    4532              :         }
    4533              :     }
    4534              : 
    4535              :   /* Complete the target-specific cost calculations.  */
    4536       131579 :   loop_vinfo->vector_costs->finish_cost (loop_vinfo->scalar_costs);
    4537       131579 :   vec_prologue_cost = loop_vinfo->vector_costs->prologue_cost ();
    4538       131579 :   vec_inside_cost = loop_vinfo->vector_costs->body_cost ();
    4539       131579 :   vec_epilogue_cost = loop_vinfo->vector_costs->epilogue_cost ();
    4540       131579 :   if (suggested_unroll_factor)
    4541       131170 :     *suggested_unroll_factor
    4542       131170 :       = loop_vinfo->vector_costs->suggested_unroll_factor ();
    4543              : 
    4544       131170 :   if (suggested_unroll_factor && *suggested_unroll_factor > 1
    4545          438 :       && LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo) != MAX_VECTORIZATION_FACTOR
    4546            0 :       && !known_le (LOOP_VINFO_VECT_FACTOR (loop_vinfo) *
    4547              :                     *suggested_unroll_factor,
    4548              :                     LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo)))
    4549              :     {
    4550            0 :       if (dump_enabled_p ())
    4551            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    4552              :                          "can't unroll as unrolled vectorization factor larger"
    4553              :                          " than maximum vectorization factor: "
    4554              :                          HOST_WIDE_INT_PRINT_UNSIGNED "\n",
    4555              :                          LOOP_VINFO_MAX_VECT_FACTOR (loop_vinfo));
    4556            0 :       *suggested_unroll_factor = 1;
    4557              :     }
    4558              : 
    4559       131579 :   vec_outside_cost = (int)(vec_prologue_cost + vec_epilogue_cost);
    4560              : 
    4561       131579 :   if (dump_enabled_p ())
    4562              :     {
    4563         1255 :       dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
    4564         1255 :       dump_printf (MSG_NOTE, "  Vector inside of loop cost: %d\n",
    4565              :                    vec_inside_cost);
    4566         1255 :       dump_printf (MSG_NOTE, "  Vector prologue cost: %d\n",
    4567              :                    vec_prologue_cost);
    4568         1255 :       dump_printf (MSG_NOTE, "  Vector epilogue cost: %d\n",
    4569              :                    vec_epilogue_cost);
    4570         1255 :       dump_printf (MSG_NOTE, "  Scalar iteration cost: %d\n",
    4571              :                    scalar_single_iter_cost);
    4572         1255 :       dump_printf (MSG_NOTE, "  Scalar outside cost: %d\n",
    4573              :                    scalar_outside_cost);
    4574         1255 :       dump_printf (MSG_NOTE, "  Vector outside cost: %d\n",
    4575              :                    vec_outside_cost);
    4576         1255 :       dump_printf (MSG_NOTE, "  prologue iterations: %d\n",
    4577              :                    peel_iters_prologue);
    4578         1255 :       dump_printf (MSG_NOTE, "  epilogue iterations: %d\n",
    4579              :                    peel_iters_epilogue);
    4580              :     }
    4581              : 
    4582              :   /* Calculate number of iterations required to make the vector version
    4583              :      profitable, relative to the loop bodies only.  The following condition
    4584              :      must hold true:
    4585              :      SIC * niters + SOC > VIC * ((niters - NPEEL) / VF) + VOC
    4586              :      where
    4587              :      SIC = scalar iteration cost, VIC = vector iteration cost,
    4588              :      VOC = vector outside cost, VF = vectorization factor,
    4589              :      NPEEL = prologue iterations + epilogue iterations,
    4590              :      SOC = scalar outside cost for run time cost model check.  */
    4591              : 
    4592       131579 :   int saving_per_viter = (scalar_single_iter_cost * assumed_vf
    4593       131579 :                           - vec_inside_cost);
    4594       131579 :   if (saving_per_viter <= 0)
    4595              :     {
    4596        25190 :       if (LOOP_VINFO_LOOP (loop_vinfo)->force_vectorize)
    4597            0 :         warning_at (vect_location.get_location_t (), OPT_Wopenmp_simd,
    4598              :                     "vectorization did not happen for a simd loop");
    4599              : 
    4600        25190 :       if (dump_enabled_p ())
    4601           38 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    4602              :                          "cost model: the vector iteration cost = %d "
    4603              :                          "divided by the scalar iteration cost = %d "
    4604              :                          "is greater or equal to the vectorization factor = %d"
    4605              :                          ".\n",
    4606              :                          vec_inside_cost, scalar_single_iter_cost, assumed_vf);
    4607        25190 :       *ret_min_profitable_niters = -1;
    4608        25190 :       *ret_min_profitable_estimate = -1;
    4609        25190 :       return;
    4610              :     }
    4611              : 
    4612              :   /* ??? The "if" arm is written to handle all cases; see below for what
    4613              :      we would do for !LOOP_VINFO_USING_PARTIAL_VECTORS_P.  */
    4614       106389 :   if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4615              :     {
    4616              :       /* Rewriting the condition above in terms of the number of
    4617              :          vector iterations (vniters) rather than the number of
    4618              :          scalar iterations (niters) gives:
    4619              : 
    4620              :          SIC * (vniters * VF + NPEEL) + SOC > VIC * vniters + VOC
    4621              : 
    4622              :          <==> vniters * (SIC * VF - VIC) > VOC - SIC * NPEEL - SOC
    4623              : 
    4624              :          For integer N, X and Y when X > 0:
    4625              : 
    4626              :          N * X > Y <==> N >= (Y /[floor] X) + 1.  */
    4627           20 :       int outside_overhead = (vec_outside_cost
    4628           20 :                               - scalar_single_iter_cost * peel_iters_prologue
    4629           20 :                               - scalar_single_iter_cost * peel_iters_epilogue
    4630              :                               - scalar_outside_cost);
    4631              :       /* We're only interested in cases that require at least one
    4632              :          vector iteration.  */
    4633           20 :       int min_vec_niters = 1;
    4634           20 :       if (outside_overhead > 0)
    4635           16 :         min_vec_niters = outside_overhead / saving_per_viter + 1;
    4636              : 
    4637           20 :       if (dump_enabled_p ())
    4638            8 :         dump_printf (MSG_NOTE, "  Minimum number of vector iterations: %d\n",
    4639              :                      min_vec_niters);
    4640              : 
    4641           20 :       if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4642              :         {
    4643              :           /* Now that we know the minimum number of vector iterations,
    4644              :              find the minimum niters for which the scalar cost is larger:
    4645              : 
    4646              :              SIC * niters > VIC * vniters + VOC - SOC
    4647              : 
    4648              :              We know that the minimum niters is no more than
    4649              :              vniters * VF + NPEEL, but it might be (and often is) less
    4650              :              than that if a partial vector iteration is cheaper than the
    4651              :              equivalent scalar code.  */
    4652           20 :           int threshold = (vec_inside_cost * min_vec_niters
    4653           20 :                            + vec_outside_cost
    4654           20 :                            - scalar_outside_cost);
    4655           20 :           if (threshold <= 0)
    4656              :             min_profitable_iters = 1;
    4657              :           else
    4658           20 :             min_profitable_iters = threshold / scalar_single_iter_cost + 1;
    4659              :         }
    4660              :       else
    4661              :         /* Convert the number of vector iterations into a number of
    4662              :            scalar iterations.  */
    4663            0 :         min_profitable_iters = (min_vec_niters * assumed_vf
    4664            0 :                                 + peel_iters_prologue
    4665              :                                 + peel_iters_epilogue);
    4666              :     }
    4667              :   else
    4668              :     {
    4669       106369 :       min_profitable_iters = ((vec_outside_cost - scalar_outside_cost)
    4670       106369 :                               * assumed_vf
    4671       106369 :                               - vec_inside_cost * peel_iters_prologue
    4672       106369 :                               - vec_inside_cost * peel_iters_epilogue);
    4673       106369 :       if (min_profitable_iters <= 0)
    4674              :         min_profitable_iters = 0;
    4675              :       else
    4676              :         {
    4677        89709 :           min_profitable_iters /= saving_per_viter;
    4678              : 
    4679        89709 :           if ((scalar_single_iter_cost * assumed_vf * min_profitable_iters)
    4680        89709 :               <= (((int) vec_inside_cost * min_profitable_iters)
    4681        89709 :                   + (((int) vec_outside_cost - scalar_outside_cost)
    4682              :                      * assumed_vf)))
    4683        89709 :             min_profitable_iters++;
    4684              :         }
    4685              :     }
    4686              : 
    4687       106389 :   if (dump_enabled_p ())
    4688         1217 :     dump_printf (MSG_NOTE,
    4689              :                  "  Calculated minimum iters for profitability: %d\n",
    4690              :                  min_profitable_iters);
    4691              : 
    4692       106389 :   if (!LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
    4693       106369 :       && min_profitable_iters < (assumed_vf + peel_iters_prologue))
    4694              :     /* We want the vectorized loop to execute at least once.  */
    4695              :     min_profitable_iters = assumed_vf + peel_iters_prologue;
    4696        24503 :   else if (min_profitable_iters < peel_iters_prologue)
    4697              :     /* For LOOP_VINFO_USING_PARTIAL_VECTORS_P, we need to ensure the
    4698              :        vectorized loop executes at least once.  */
    4699              :     min_profitable_iters = peel_iters_prologue;
    4700              : 
    4701       106389 :   if (dump_enabled_p ())
    4702         1217 :     dump_printf_loc (MSG_NOTE, vect_location,
    4703              :                      "  Runtime profitability threshold = %d\n",
    4704              :                      min_profitable_iters);
    4705              : 
    4706       106389 :   *ret_min_profitable_niters = min_profitable_iters;
    4707              : 
    4708              :   /* Calculate number of iterations required to make the vector version
    4709              :      profitable, relative to the loop bodies only.
    4710              : 
    4711              :      Non-vectorized variant is SIC * niters and it must win over vector
    4712              :      variant on the expected loop trip count.  The following condition must hold true:
    4713              :      SIC * niters > VIC * ((niters - NPEEL) / VF) + VOC + SOC  */
    4714              : 
    4715       106389 :   if (vec_outside_cost <= 0)
    4716              :     min_profitable_estimate = 0;
    4717              :   /* ??? This "else if" arm is written to handle all cases; see below for
    4718              :      what we would do for !LOOP_VINFO_USING_PARTIAL_VECTORS_P.  */
    4719        94679 :   else if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4720              :     {
    4721              :       /* This is a repeat of the code above, but with + SOC rather
    4722              :          than - SOC.  */
    4723           20 :       int outside_overhead = (vec_outside_cost
    4724           20 :                               - scalar_single_iter_cost * peel_iters_prologue
    4725           20 :                               - scalar_single_iter_cost * peel_iters_epilogue
    4726              :                               + scalar_outside_cost);
    4727           20 :       int min_vec_niters = 1;
    4728           20 :       if (outside_overhead > 0)
    4729           20 :         min_vec_niters = outside_overhead / saving_per_viter + 1;
    4730              : 
    4731           20 :       if (LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
    4732              :         {
    4733           20 :           int threshold = (vec_inside_cost * min_vec_niters
    4734           20 :                            + vec_outside_cost
    4735           20 :                            + scalar_outside_cost);
    4736           20 :           min_profitable_estimate = threshold / scalar_single_iter_cost + 1;
    4737              :         }
    4738              :       else
    4739              :         min_profitable_estimate = (min_vec_niters * assumed_vf
    4740              :                                    + peel_iters_prologue
    4741              :                                    + peel_iters_epilogue);
    4742              :     }
    4743              :   else
    4744              :     {
    4745        94659 :       min_profitable_estimate = ((vec_outside_cost + scalar_outside_cost)
    4746        94659 :                                  * assumed_vf
    4747        94659 :                                  - vec_inside_cost * peel_iters_prologue
    4748        94659 :                                  - vec_inside_cost * peel_iters_epilogue)
    4749        94659 :                                  / ((scalar_single_iter_cost * assumed_vf)
    4750              :                                    - vec_inside_cost);
    4751              :     }
    4752       106389 :   min_profitable_estimate = MAX (min_profitable_estimate, min_profitable_iters);
    4753       106389 :   if (dump_enabled_p ())
    4754         1217 :     dump_printf_loc (MSG_NOTE, vect_location,
    4755              :                      "  Static estimate profitability threshold = %d\n",
    4756              :                      min_profitable_estimate);
    4757              : 
    4758       106389 :   *ret_min_profitable_estimate = min_profitable_estimate;
    4759              : }
    4760              : 
    4761              : /* Writes into SEL a mask for a vec_perm, equivalent to a vec_shr by OFFSET
    4762              :    vector elements (not bits) for a vector with NELT elements.  */
    4763              : static void
    4764         2120 : calc_vec_perm_mask_for_shift (unsigned int offset, unsigned int nelt,
    4765              :                               vec_perm_builder *sel)
    4766              : {
    4767              :   /* The encoding is a single stepped pattern.  Any wrap-around is handled
    4768              :      by vec_perm_indices.  */
    4769         2120 :   sel->new_vector (nelt, 1, 3);
    4770         8480 :   for (unsigned int i = 0; i < 3; i++)
    4771         6360 :     sel->quick_push (i + offset);
    4772         2120 : }
    4773              : 
    4774              : /* Checks whether the target supports whole-vector shifts for vectors of mode
    4775              :    MODE.  This is the case if _either_ the platform handles vec_shr_optab, _or_
    4776              :    it supports vec_perm_const with masks for all necessary shift amounts.  */
    4777              : static bool
    4778        13752 : have_whole_vector_shift (machine_mode mode)
    4779              : {
    4780        13752 :   if (can_implement_p (vec_shr_optab, mode))
    4781              :     return true;
    4782              : 
    4783              :   /* Variable-length vectors should be handled via the optab.  */
    4784           63 :   unsigned int nelt;
    4785          126 :   if (!GET_MODE_NUNITS (mode).is_constant (&nelt))
    4786              :     return false;
    4787              : 
    4788           63 :   vec_perm_builder sel;
    4789           63 :   vec_perm_indices indices;
    4790          315 :   for (unsigned int i = nelt / 2; i >= 1; i /= 2)
    4791              :     {
    4792          252 :       calc_vec_perm_mask_for_shift (i, nelt, &sel);
    4793          252 :       indices.new_vector (sel, 2, nelt);
    4794          252 :       if (!can_vec_perm_const_p (mode, mode, indices, false))
    4795              :         return false;
    4796              :     }
    4797              :   return true;
    4798           63 : }
    4799              : 
    4800              : /* Return true if (a) STMT_INFO is a DOT_PROD_EXPR reduction whose
    4801              :    multiplication operands have differing signs and (b) we intend
    4802              :    to emulate the operation using a series of signed DOT_PROD_EXPRs.
    4803              :    See vect_emulate_mixed_dot_prod for the actual sequence used.  */
    4804              : 
    4805              : static bool
    4806         2540 : vect_is_emulated_mixed_dot_prod (slp_tree slp_node)
    4807              : {
    4808         2540 :   stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (slp_node);
    4809         2540 :   gassign *assign = dyn_cast<gassign *> (stmt_info->stmt);
    4810         2085 :   if (!assign || gimple_assign_rhs_code (assign) != DOT_PROD_EXPR)
    4811              :     return false;
    4812              : 
    4813          916 :   tree rhs1 = gimple_assign_rhs1 (assign);
    4814          916 :   tree rhs2 = gimple_assign_rhs2 (assign);
    4815          916 :   if (TYPE_SIGN (TREE_TYPE (rhs1)) == TYPE_SIGN (TREE_TYPE (rhs2)))
    4816              :     return false;
    4817              : 
    4818          645 :   return !directly_supported_p (DOT_PROD_EXPR,
    4819              :                                 SLP_TREE_VECTYPE (slp_node),
    4820          215 :                                 SLP_TREE_VECTYPE
    4821              :                                   (SLP_TREE_CHILDREN (slp_node)[0]),
    4822          215 :                                 optab_vector_mixed_sign);
    4823              : }
    4824              : 
    4825              : /* TODO: Close dependency between vect_model_*_cost and vectorizable_*
    4826              :    functions. Design better to avoid maintenance issues.  */
    4827              : 
    4828              : /* Function vect_model_reduction_cost.
    4829              : 
    4830              :    Models cost for a reduction operation, including the vector ops
    4831              :    generated within the strip-mine loop in some cases, the initial
    4832              :    definition before the loop, and the epilogue code that must be generated.  */
    4833              : 
    4834              : static void
    4835        71034 : vect_model_reduction_cost (loop_vec_info loop_vinfo,
    4836              :                            slp_tree node, internal_fn reduc_fn,
    4837              :                            vect_reduction_type reduction_type,
    4838              :                            int ncopies, stmt_vector_for_cost *cost_vec)
    4839              : {
    4840        71034 :   int prologue_cost = 0, epilogue_cost = 0, inside_cost = 0;
    4841        71034 :   tree vectype;
    4842        71034 :   machine_mode mode;
    4843        71034 :   class loop *loop = NULL;
    4844              : 
    4845        71034 :   if (loop_vinfo)
    4846        71034 :     loop = LOOP_VINFO_LOOP (loop_vinfo);
    4847              : 
    4848              :   /* Condition reductions generate two reductions in the loop.  */
    4849        71034 :   if (reduction_type == COND_REDUCTION)
    4850          365 :     ncopies *= 2;
    4851              : 
    4852        71034 :   vectype = SLP_TREE_VECTYPE (node);
    4853        71034 :   mode = TYPE_MODE (vectype);
    4854        71034 :   stmt_vec_info orig_stmt_info
    4855        71034 :     = vect_orig_stmt (SLP_TREE_REPRESENTATIVE (node));
    4856              : 
    4857        71034 :   gimple_match_op op;
    4858        71034 :   if (!gimple_extract_op (orig_stmt_info->stmt, &op))
    4859            0 :     gcc_unreachable ();
    4860              : 
    4861        71034 :   if (reduction_type == EXTRACT_LAST_REDUCTION)
    4862              :     /* No extra instructions are needed in the prologue.  The loop body
    4863              :        operations are costed in vectorizable_condition.  */
    4864              :     inside_cost = 0;
    4865        71034 :   else if (reduction_type == FOLD_LEFT_REDUCTION)
    4866              :     {
    4867              :       /* No extra instructions needed in the prologue.  */
    4868         4809 :       prologue_cost = 0;
    4869              : 
    4870         4809 :       if (reduc_fn != IFN_LAST)
    4871              :         /* Count one reduction-like operation per vector.  */
    4872            0 :         inside_cost = record_stmt_cost (cost_vec, ncopies, vec_to_scalar,
    4873              :                                         node, 0, vect_body);
    4874              :       else
    4875              :         {
    4876              :           /* Use NCOPIES deconstructs and NELEMENTS scalar ops.  */
    4877         4809 :           unsigned int nelements = ncopies * vect_nunits_for_cost (vectype);
    4878         4809 :           inside_cost = record_stmt_cost (cost_vec, ncopies,
    4879              :                                           vec_deconstruct, node, 0,
    4880              :                                           vect_body);
    4881         4809 :           inside_cost += record_stmt_cost (cost_vec, nelements,
    4882              :                                            scalar_stmt, node, 0,
    4883              :                                            vect_body);
    4884              :         }
    4885              :     }
    4886              :   else
    4887              :     {
    4888              :       /* Add in the cost of the initial definitions.  */
    4889        66225 :       int prologue_stmts;
    4890        66225 :       if (reduction_type == COND_REDUCTION)
    4891              :         /* For cond reductions we have four vectors: initial index, step,
    4892              :            initial result of the data reduction, initial value of the index
    4893              :            reduction.  */
    4894              :         prologue_stmts = 4;
    4895              :       else
    4896              :         /* We need the initial reduction value.  */
    4897        65860 :         prologue_stmts = 1;
    4898        66225 :       prologue_cost += record_stmt_cost (cost_vec, prologue_stmts,
    4899              :                                          scalar_to_vec, node, 0,
    4900              :                                          vect_prologue);
    4901              :     }
    4902              : 
    4903              :   /* Determine cost of epilogue code.
    4904              : 
    4905              :      We have a reduction operator that will reduce the vector in one statement.
    4906              :      Also requires scalar extract.  */
    4907              : 
    4908        71034 :   if (!loop || !nested_in_vect_loop_p (loop, orig_stmt_info))
    4909              :     {
    4910        70850 :       if (reduc_fn != IFN_LAST)
    4911              :         {
    4912        50362 :           if (reduction_type == COND_REDUCTION)
    4913              :             {
    4914              :               /* An EQ stmt and an COND_EXPR stmt.  */
    4915           18 :               epilogue_cost += record_stmt_cost (cost_vec, 2,
    4916              :                                                  vector_stmt, node, 0,
    4917              :                                                  vect_epilogue);
    4918              :               /* Reduction of the max index and a reduction of the found
    4919              :                  values.  */
    4920           18 :               epilogue_cost += record_stmt_cost (cost_vec, 2,
    4921              :                                                  vec_to_scalar, node, 0,
    4922              :                                                  vect_epilogue);
    4923              :               /* A broadcast of the max value.  */
    4924           18 :               epilogue_cost += record_stmt_cost (cost_vec, 1,
    4925              :                                                  scalar_to_vec, node, 0,
    4926              :                                                  vect_epilogue);
    4927              :             }
    4928              :           else
    4929              :             {
    4930        50344 :               epilogue_cost += record_stmt_cost (cost_vec, 1, vector_stmt,
    4931              :                                                  node, 0, vect_epilogue);
    4932        50344 :               epilogue_cost += record_stmt_cost (cost_vec, 1,
    4933              :                                                  vec_to_scalar, node, 0,
    4934              :                                                  vect_epilogue);
    4935              :             }
    4936              :         }
    4937        20488 :       else if (reduction_type == COND_REDUCTION)
    4938              :         {
    4939          347 :           unsigned estimated_nunits = vect_nunits_for_cost (vectype);
    4940              :           /* Extraction of scalar elements.  */
    4941          347 :           epilogue_cost += record_stmt_cost (cost_vec, 2,
    4942              :                                              vec_deconstruct, node, 0,
    4943              :                                              vect_epilogue);
    4944              :           /* Scalar max reductions via COND_EXPR / MAX_EXPR.  */
    4945          347 :           epilogue_cost += record_stmt_cost (cost_vec,
    4946          347 :                                              2 * estimated_nunits - 3,
    4947              :                                              scalar_stmt, node, 0,
    4948              :                                              vect_epilogue);
    4949              :         }
    4950        20141 :       else if (reduction_type == EXTRACT_LAST_REDUCTION
    4951        20141 :                || reduction_type == FOLD_LEFT_REDUCTION)
    4952              :         /* No extra instructions need in the epilogue.  */
    4953              :         ;
    4954              :       else
    4955              :         {
    4956        15332 :           int vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
    4957        15332 :           tree bitsize = TYPE_SIZE (op.type);
    4958        15332 :           int element_bitsize = tree_to_uhwi (bitsize);
    4959        15332 :           int nelements = vec_size_in_bits / element_bitsize;
    4960              : 
    4961        15332 :           if (op.code == COND_EXPR)
    4962           31 :             op.code = MAX_EXPR;
    4963              : 
    4964              :           /* We have a whole vector shift available.  */
    4965         2527 :           if (VECTOR_MODE_P (mode)
    4966        15332 :               && directly_supported_p (op.code, vectype)
    4967        27258 :               && have_whole_vector_shift (mode))
    4968              :             {
    4969              :               /* Final reduction via vector shifts and the reduction operator.
    4970              :                  Also requires scalar extract.  */
    4971        35778 :               epilogue_cost += record_stmt_cost (cost_vec,
    4972        23852 :                                                  exact_log2 (nelements) * 2,
    4973              :                                                  vector_stmt, node, 0,
    4974              :                                                  vect_epilogue);
    4975        11926 :               epilogue_cost += record_stmt_cost (cost_vec, 1,
    4976              :                                                  vec_to_scalar, node, 0,
    4977              :                                                  vect_epilogue);
    4978              :             }
    4979              :           else
    4980              :             /* Use extracts and reduction op for final reduction.  For N
    4981              :                elements, we have N extracts and N-1 reduction ops.  */
    4982         3406 :             epilogue_cost += record_stmt_cost (cost_vec,
    4983         3406 :                                                nelements + nelements - 1,
    4984              :                                                vector_stmt, node, 0,
    4985              :                                                vect_epilogue);
    4986              :         }
    4987              :     }
    4988              : 
    4989        71034 :   if (dump_enabled_p ())
    4990         3146 :     dump_printf (MSG_NOTE,
    4991              :                  "vect_model_reduction_cost: inside_cost = %d, "
    4992              :                  "prologue_cost = %d, epilogue_cost = %d .\n", inside_cost,
    4993              :                  prologue_cost, epilogue_cost);
    4994        71034 : }
    4995              : 
    4996              : /* SEQ is a sequence of instructions that initialize the reduction
    4997              :    described by REDUC_INFO.  Emit them in the appropriate place.  */
    4998              : 
    4999              : static void
    5000          459 : vect_emit_reduction_init_stmts (loop_vec_info loop_vinfo,
    5001              :                                 vect_reduc_info reduc_info, gimple *seq)
    5002              : {
    5003          459 :   if (VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info))
    5004              :     {
    5005              :       /* When reusing an accumulator from the main loop, we only need
    5006              :          initialization instructions if the main loop can be skipped.
    5007              :          In that case, emit the initialization instructions at the end
    5008              :          of the guard block that does the skip.  */
    5009           18 :       edge skip_edge = loop_vinfo->skip_main_loop_edge;
    5010           18 :       gcc_assert (skip_edge);
    5011           18 :       gimple_stmt_iterator gsi = gsi_last_bb (skip_edge->src);
    5012           18 :       gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
    5013              :     }
    5014              :   else
    5015              :     {
    5016              :       /* The normal case: emit the initialization instructions on the
    5017              :          preheader edge.  */
    5018          441 :       class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    5019          441 :       gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), seq);
    5020              :     }
    5021          459 : }
    5022              : 
    5023              : /* Get at the initial defs for the reduction PHIs for REDUC_INFO,
    5024              :    which performs a reduction involving GROUP_SIZE scalar statements.
    5025              :    NUMBER_OF_VECTORS is the number of vector defs to create.  If NEUTRAL_OP
    5026              :    is nonnull, introducing extra elements of that value will not change the
    5027              :    result.  */
    5028              : 
    5029              : static void
    5030        21968 : get_initial_defs_for_reduction (loop_vec_info loop_vinfo,
    5031              :                                 vect_reduc_info reduc_info,
    5032              :                                 tree vector_type,
    5033              :                                 vec<tree> *vec_oprnds,
    5034              :                                 unsigned int number_of_vectors,
    5035              :                                 unsigned int group_size, tree neutral_op)
    5036              : {
    5037        21968 :   vec<tree> &initial_values = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info);
    5038        21968 :   unsigned HOST_WIDE_INT nunits;
    5039        21968 :   unsigned j, number_of_places_left_in_vector;
    5040        21968 :   unsigned int i;
    5041              : 
    5042        43936 :   gcc_assert (group_size == initial_values.length () || neutral_op);
    5043              : 
    5044              :   /* NUMBER_OF_COPIES is the number of times we need to use the same values in
    5045              :      created vectors. It is greater than 1 if unrolling is performed.
    5046              : 
    5047              :      For example, we have two scalar operands, s1 and s2 (e.g., group of
    5048              :      strided accesses of size two), while NUNITS is four (i.e., four scalars
    5049              :      of this type can be packed in a vector).  The output vector will contain
    5050              :      two copies of each scalar operand: {s1, s2, s1, s2}.  (NUMBER_OF_COPIES
    5051              :      will be 2).
    5052              : 
    5053              :      If GROUP_SIZE > NUNITS, the scalars will be split into several
    5054              :      vectors containing the operands.
    5055              : 
    5056              :      For example, NUNITS is four as before, and the group size is 8
    5057              :      (s1, s2, ..., s8).  We will create two vectors {s1, s2, s3, s4} and
    5058              :      {s5, s6, s7, s8}.  */
    5059              : 
    5060        21968 :   if (!TYPE_VECTOR_SUBPARTS (vector_type).is_constant (&nunits))
    5061              :     nunits = group_size;
    5062              : 
    5063        21968 :   tree vector_elt_type = TREE_TYPE (vector_type);
    5064        21968 :   number_of_places_left_in_vector = nunits;
    5065        21968 :   bool constant_p = true;
    5066        21968 :   tree_vector_builder elts (vector_type, nunits, 1);
    5067        21968 :   elts.quick_grow (nunits);
    5068        21968 :   gimple_seq ctor_seq = NULL;
    5069        21968 :   if (neutral_op
    5070        43321 :       && !useless_type_conversion_p (vector_elt_type,
    5071        21353 :                                      TREE_TYPE (neutral_op)))
    5072              :     {
    5073          248 :       if (VECTOR_BOOLEAN_TYPE_P (vector_type))
    5074          227 :         neutral_op = gimple_build (&ctor_seq, COND_EXPR,
    5075              :                                    vector_elt_type,
    5076              :                                    neutral_op,
    5077              :                                    build_all_ones_cst (vector_elt_type),
    5078              :                                    build_zero_cst (vector_elt_type));
    5079              :       else
    5080           21 :         neutral_op = gimple_convert (&ctor_seq, vector_elt_type, neutral_op);
    5081              :     }
    5082       206180 :   for (j = 0; j < nunits * number_of_vectors; ++j)
    5083              :     {
    5084       184212 :       tree op;
    5085       184212 :       i = j % group_size;
    5086              : 
    5087              :       /* Get the def before the loop.  In reduction chain we have only
    5088              :          one initial value.  Else we have as many as PHIs in the group.  */
    5089       184212 :       if (i >= initial_values.length () || (j > i && neutral_op))
    5090              :         op = neutral_op;
    5091              :       else
    5092              :         {
    5093        51970 :           if (!useless_type_conversion_p (vector_elt_type,
    5094        25985 :                                           TREE_TYPE (initial_values[i])))
    5095              :             {
    5096          263 :               if (VECTOR_BOOLEAN_TYPE_P (vector_type))
    5097          478 :                 initial_values[i] = gimple_build (&ctor_seq, COND_EXPR,
    5098              :                                                   vector_elt_type,
    5099          239 :                                                   initial_values[i],
    5100              :                                                   build_all_ones_cst
    5101              :                                                     (vector_elt_type),
    5102              :                                                   build_zero_cst
    5103              :                                                     (vector_elt_type));
    5104              :               else
    5105           48 :                 initial_values[i] = gimple_convert (&ctor_seq,
    5106              :                                                     vector_elt_type,
    5107           24 :                                                     initial_values[i]);
    5108              :             }
    5109        25985 :           op = initial_values[i];
    5110              :         }
    5111              : 
    5112              :       /* Create 'vect_ = {op0,op1,...,opn}'.  */
    5113       184212 :       number_of_places_left_in_vector--;
    5114       184212 :       elts[nunits - number_of_places_left_in_vector - 1] = op;
    5115       184212 :       if (!CONSTANT_CLASS_P (op))
    5116         2495 :         constant_p = false;
    5117              : 
    5118       184212 :       if (number_of_places_left_in_vector == 0)
    5119              :         {
    5120        23629 :           tree init;
    5121        47258 :           if (constant_p && !neutral_op
    5122        46943 :               ? multiple_p (TYPE_VECTOR_SUBPARTS (vector_type), nunits)
    5123        23629 :               : known_eq (TYPE_VECTOR_SUBPARTS (vector_type), nunits))
    5124              :             /* Build the vector directly from ELTS.  */
    5125        23629 :             init = gimple_build_vector (&ctor_seq, &elts);
    5126            0 :           else if (neutral_op)
    5127              :             {
    5128              :               /* Build a vector of the neutral value and shift the
    5129              :                  other elements into place.  */
    5130            0 :               init = gimple_build_vector_from_val (&ctor_seq, vector_type,
    5131              :                                                    neutral_op);
    5132            0 :               int k = nunits;
    5133            0 :               while (k > 0 && operand_equal_p (elts[k - 1], neutral_op))
    5134            0 :                 k -= 1;
    5135            0 :               while (k > 0)
    5136              :                 {
    5137            0 :                   k -= 1;
    5138            0 :                   init = gimple_build (&ctor_seq, CFN_VEC_SHL_INSERT,
    5139            0 :                                        vector_type, init, elts[k]);
    5140              :                 }
    5141              :             }
    5142              :           else
    5143              :             {
    5144              :               /* First time round, duplicate ELTS to fill the
    5145              :                  required number of vectors.  */
    5146            0 :               duplicate_and_interleave (loop_vinfo, &ctor_seq, vector_type,
    5147              :                                         elts, number_of_vectors, *vec_oprnds);
    5148            0 :               break;
    5149              :             }
    5150        23629 :           vec_oprnds->quick_push (init);
    5151              : 
    5152        23629 :           number_of_places_left_in_vector = nunits;
    5153        23629 :           elts.new_vector (vector_type, nunits, 1);
    5154        23629 :           elts.quick_grow (nunits);
    5155        23629 :           constant_p = true;
    5156              :         }
    5157              :     }
    5158        21968 :   if (ctor_seq != NULL)
    5159          459 :     vect_emit_reduction_init_stmts (loop_vinfo, reduc_info, ctor_seq);
    5160        21968 : }
    5161              : 
    5162              : vect_reduc_info
    5163       216325 : info_for_reduction (loop_vec_info loop_vinfo, slp_tree node)
    5164              : {
    5165       216325 :   gcc_assert (node);
    5166       216325 :   if (node->cycle_info.id == -1)
    5167              :     return NULL;
    5168       211356 :   return loop_vinfo->reduc_infos[node->cycle_info.id];
    5169              : }
    5170              : 
    5171              : /* See if LOOP_VINFO is an epilogue loop whose main loop had a reduction that
    5172              :    REDUC_INFO can build on.  Adjust REDUC_INFO and return true if so, otherwise
    5173              :    return false.  */
    5174              : 
    5175              : static bool
    5176        21511 : vect_find_reusable_accumulator (loop_vec_info loop_vinfo,
    5177              :                                 vect_reduc_info reduc_info, tree vectype)
    5178              : {
    5179        21511 :   loop_vec_info main_loop_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
    5180        21511 :   if (!main_loop_vinfo)
    5181              :     return false;
    5182              : 
    5183         4504 :   if (VECT_REDUC_INFO_TYPE (reduc_info) != TREE_CODE_REDUCTION)
    5184              :     return false;
    5185              : 
    5186              :   /* We are not set up to handle vector bools when they are not mapped
    5187              :      to vector integer data types.  */
    5188         4486 :   if (VECTOR_BOOLEAN_TYPE_P (vectype)
    5189         4538 :       && GET_MODE_CLASS (TYPE_MODE (vectype)) != MODE_VECTOR_INT)
    5190              :     return false;
    5191              : 
    5192         4484 :   unsigned int num_phis = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info).length ();
    5193         4484 :   auto_vec<tree, 16> main_loop_results (num_phis);
    5194         4484 :   auto_vec<tree, 16> initial_values (num_phis);
    5195         4484 :   if (edge main_loop_edge = loop_vinfo->main_loop_edge)
    5196              :     {
    5197              :       /* The epilogue loop can be entered either from the main loop or
    5198              :          from an earlier guard block.  */
    5199         4335 :       edge skip_edge = loop_vinfo->skip_main_loop_edge;
    5200        17360 :       for (tree incoming_value : VECT_REDUC_INFO_INITIAL_VALUES (reduc_info))
    5201              :         {
    5202              :           /* Look for:
    5203              : 
    5204              :                INCOMING_VALUE = phi<MAIN_LOOP_RESULT(main loop),
    5205              :                                     INITIAL_VALUE(guard block)>.  */
    5206         4355 :           gcc_assert (TREE_CODE (incoming_value) == SSA_NAME);
    5207              : 
    5208         4355 :           gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (incoming_value));
    5209         4355 :           gcc_assert (gimple_bb (phi) == main_loop_edge->dest);
    5210              : 
    5211         4355 :           tree from_main_loop = PHI_ARG_DEF_FROM_EDGE (phi, main_loop_edge);
    5212         4355 :           tree from_skip = PHI_ARG_DEF_FROM_EDGE (phi, skip_edge);
    5213              : 
    5214         4355 :           main_loop_results.quick_push (from_main_loop);
    5215         4355 :           initial_values.quick_push (from_skip);
    5216              :         }
    5217              :     }
    5218              :   else
    5219              :     /* The main loop dominates the epilogue loop.  */
    5220          149 :     main_loop_results.splice (VECT_REDUC_INFO_INITIAL_VALUES (reduc_info));
    5221              : 
    5222              :   /* See if the main loop has the kind of accumulator we need.  */
    5223         4484 :   vect_reusable_accumulator *accumulator
    5224         4484 :     = main_loop_vinfo->reusable_accumulators.get (main_loop_results[0]);
    5225         4484 :   if (!accumulator
    5226         8956 :       || num_phis != VECT_REDUC_INFO_SCALAR_RESULTS (accumulator->reduc_info).length ()
    5227        13440 :       || !std::equal (main_loop_results.begin (), main_loop_results.end (),
    5228              :                       VECT_REDUC_INFO_SCALAR_RESULTS (accumulator->reduc_info).begin ()))
    5229              :     return false;
    5230              : 
    5231              :   /* Handle the case where we can reduce wider vectors to narrower ones.  */
    5232         4478 :   tree old_vectype = TREE_TYPE (accumulator->reduc_input);
    5233         4478 :   unsigned HOST_WIDE_INT m;
    5234         4478 :   if (!constant_multiple_p (TYPE_VECTOR_SUBPARTS (old_vectype),
    5235         4478 :                             TYPE_VECTOR_SUBPARTS (vectype), &m))
    5236            0 :     return false;
    5237              :   /* Check the intermediate vector types and operations are available.  */
    5238         4478 :   tree prev_vectype = old_vectype;
    5239         4478 :   poly_uint64 intermediate_nunits = TYPE_VECTOR_SUBPARTS (old_vectype);
    5240        13060 :   while (known_gt (intermediate_nunits, TYPE_VECTOR_SUBPARTS (vectype)))
    5241              :     {
    5242         4628 :       intermediate_nunits = exact_div (intermediate_nunits, 2);
    5243         4628 :       tree intermediate_vectype = get_related_vectype_for_scalar_type
    5244         4628 :         (TYPE_MODE (vectype), TREE_TYPE (vectype), intermediate_nunits);
    5245         9256 :       if (!intermediate_vectype
    5246         4628 :           || !directly_supported_p (VECT_REDUC_INFO_CODE (reduc_info),
    5247              :                                     intermediate_vectype)
    5248         8732 :           || !can_vec_extract (TYPE_MODE (prev_vectype),
    5249         8216 :                                TYPE_MODE (intermediate_vectype)).exists ()
    5250              :           /* We could actually extract VLA vectors but bit_field_ref and
    5251              :              friends aren't yet prepared for it.  */
    5252         8732 :           || !TYPE_VECTOR_SUBPARTS (intermediate_vectype).is_constant ())
    5253              :         return false;
    5254              :       prev_vectype = intermediate_vectype;
    5255              :     }
    5256              : 
    5257              :   /* Non-SLP reductions might apply an adjustment after the reduction
    5258              :      operation, in order to simplify the initialization of the accumulator.
    5259              :      If the epilogue loop carries on from where the main loop left off,
    5260              :      it should apply the same adjustment to the final reduction result.
    5261              : 
    5262              :      If the epilogue loop can also be entered directly (rather than via
    5263              :      the main loop), we need to be able to handle that case in the same way,
    5264              :      with the same adjustment.  (In principle we could add a PHI node
    5265              :      to select the correct adjustment, but in practice that shouldn't be
    5266              :      necessary.)  */
    5267         3954 :   tree main_adjustment
    5268         3954 :     = VECT_REDUC_INFO_EPILOGUE_ADJUSTMENT (accumulator->reduc_info);
    5269         3954 :   if (loop_vinfo->main_loop_edge && main_adjustment)
    5270              :     {
    5271         3336 :       gcc_assert (num_phis == 1);
    5272         3336 :       tree initial_value = initial_values[0];
    5273              :       /* Check that we can use INITIAL_VALUE as the adjustment and
    5274              :          initialize the accumulator with a neutral value instead.  */
    5275         3336 :       if (!operand_equal_p (initial_value, main_adjustment))
    5276              :         return false;
    5277         3326 :       initial_values[0] = VECT_REDUC_INFO_NEUTRAL_OP (reduc_info);
    5278              :     }
    5279         3944 :   VECT_REDUC_INFO_EPILOGUE_ADJUSTMENT (reduc_info) = main_adjustment;
    5280         3944 :   VECT_REDUC_INFO_INITIAL_VALUES (reduc_info).truncate (0);
    5281         3944 :   VECT_REDUC_INFO_INITIAL_VALUES (reduc_info).splice (initial_values);
    5282         3944 :   VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info) = accumulator;
    5283         3944 :   return true;
    5284         4484 : }
    5285              : 
    5286              : /* Reduce the vector VEC_DEF down to VECTYPE with reduction operation
    5287              :    CODE emitting stmts before GSI.  Returns a vector def of VECTYPE.  */
    5288              : 
    5289              : static tree
    5290         3989 : vect_create_partial_epilog (tree vec_def, tree vectype, code_helper code,
    5291              :                             gimple_seq *seq)
    5292              : {
    5293         3989 :   gcc_assert (!VECTOR_BOOLEAN_TYPE_P (TREE_TYPE (vec_def))
    5294              :               || (GET_MODE_CLASS (TYPE_MODE (TREE_TYPE (vec_def)))
    5295              :                   == MODE_VECTOR_INT));
    5296         3989 :   unsigned nunits = TYPE_VECTOR_SUBPARTS (TREE_TYPE (vec_def)).to_constant ();
    5297         3989 :   unsigned nunits1 = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
    5298         3989 :   tree stype = TREE_TYPE (vectype);
    5299         3989 :   tree new_temp = vec_def;
    5300         8121 :   while (nunits > nunits1)
    5301              :     {
    5302         4132 :       nunits /= 2;
    5303         4132 :       tree vectype1 = get_related_vectype_for_scalar_type (TYPE_MODE (vectype),
    5304         4132 :                                                            stype, nunits);
    5305         4132 :       unsigned int bitsize = tree_to_uhwi (TYPE_SIZE (vectype1));
    5306              : 
    5307              :       /* The target has to make sure we support lowpart/highpart
    5308              :          extraction, either via direct vector extract or through
    5309              :          an integer mode punning.  */
    5310         4132 :       tree dst1, dst2;
    5311         4132 :       gimple *epilog_stmt;
    5312         4132 :       if (can_vec_extract (TYPE_MODE (TREE_TYPE (new_temp)),
    5313         8264 :                            TYPE_MODE (vectype1)).exists ())
    5314              :         {
    5315              :           /* Extract sub-vectors directly once vec_extract becomes
    5316              :              a conversion optab.  */
    5317         4132 :           dst1 = make_ssa_name (vectype1);
    5318         4132 :           epilog_stmt
    5319         8264 :               = gimple_build_assign (dst1, BIT_FIELD_REF,
    5320              :                                      build3 (BIT_FIELD_REF, vectype1,
    5321         4132 :                                              new_temp, TYPE_SIZE (vectype1),
    5322              :                                              bitsize_int (0)));
    5323         4132 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5324         4132 :           dst2 =  make_ssa_name (vectype1);
    5325         4132 :           epilog_stmt
    5326         4132 :               = gimple_build_assign (dst2, BIT_FIELD_REF,
    5327              :                                      build3 (BIT_FIELD_REF, vectype1,
    5328         4132 :                                              new_temp, TYPE_SIZE (vectype1),
    5329         4132 :                                              bitsize_int (bitsize)));
    5330         4132 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5331              :         }
    5332              :       else
    5333              :         {
    5334              :           /* Extract via punning to appropriately sized integer mode
    5335              :              vector.  */
    5336            0 :           tree eltype = build_nonstandard_integer_type (bitsize, 1);
    5337            0 :           tree etype = build_vector_type (eltype, 2);
    5338            0 :           gcc_assert (can_vec_extract (TYPE_MODE (etype),
    5339              :                                        TYPE_MODE (eltype)).exists ());
    5340            0 :           tree tem = make_ssa_name (etype);
    5341            0 :           epilog_stmt = gimple_build_assign (tem, VIEW_CONVERT_EXPR,
    5342              :                                              build1 (VIEW_CONVERT_EXPR,
    5343              :                                                      etype, new_temp));
    5344            0 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5345            0 :           new_temp = tem;
    5346            0 :           tem = make_ssa_name (eltype);
    5347            0 :           epilog_stmt
    5348            0 :               = gimple_build_assign (tem, BIT_FIELD_REF,
    5349              :                                      build3 (BIT_FIELD_REF, eltype,
    5350            0 :                                              new_temp, TYPE_SIZE (eltype),
    5351              :                                              bitsize_int (0)));
    5352            0 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5353            0 :           dst1 = make_ssa_name (vectype1);
    5354            0 :           epilog_stmt = gimple_build_assign (dst1, VIEW_CONVERT_EXPR,
    5355              :                                              build1 (VIEW_CONVERT_EXPR,
    5356              :                                                      vectype1, tem));
    5357            0 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5358            0 :           tem = make_ssa_name (eltype);
    5359            0 :           epilog_stmt
    5360            0 :               = gimple_build_assign (tem, BIT_FIELD_REF,
    5361              :                                      build3 (BIT_FIELD_REF, eltype,
    5362            0 :                                              new_temp, TYPE_SIZE (eltype),
    5363            0 :                                              bitsize_int (bitsize)));
    5364            0 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5365            0 :           dst2 =  make_ssa_name (vectype1);
    5366            0 :           epilog_stmt = gimple_build_assign (dst2, VIEW_CONVERT_EXPR,
    5367              :                                              build1 (VIEW_CONVERT_EXPR,
    5368              :                                                      vectype1, tem));
    5369            0 :           gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5370              :         }
    5371              : 
    5372         4132 :       new_temp = gimple_build (seq, code, vectype1, dst1, dst2);
    5373              :     }
    5374         3989 :   if (!useless_type_conversion_p (vectype, TREE_TYPE (new_temp)))
    5375              :     {
    5376           46 :       tree dst3 = make_ssa_name (vectype);
    5377           46 :       gimple *epilog_stmt = gimple_build_assign (dst3, VIEW_CONVERT_EXPR,
    5378              :                                                  build1 (VIEW_CONVERT_EXPR,
    5379              :                                                          vectype, new_temp));
    5380           46 :       gimple_seq_add_stmt_without_update (seq, epilog_stmt);
    5381           46 :       new_temp = dst3;
    5382              :     }
    5383              : 
    5384         3989 :   return new_temp;
    5385              : }
    5386              : 
    5387              : /* Function vect_create_epilog_for_reduction
    5388              : 
    5389              :    Create code at the loop-epilog to finalize the result of a reduction
    5390              :    computation.
    5391              : 
    5392              :    STMT_INFO is the scalar reduction stmt that is being vectorized.
    5393              :    SLP_NODE is an SLP node containing a group of reduction statements. The
    5394              :      first one in this group is STMT_INFO.
    5395              :    SLP_NODE_INSTANCE is the SLP node instance containing SLP_NODE
    5396              :    REDUC_INDEX says which rhs operand of the STMT_INFO is the reduction phi
    5397              :      (counting from 0)
    5398              :    LOOP_EXIT is the edge to update in the merge block.  In the case of a single
    5399              :      exit this edge is always the main loop exit.
    5400              : 
    5401              :    This function:
    5402              :    1. Completes the reduction def-use cycles.
    5403              :    2. "Reduces" each vector of partial results VECT_DEFS into a single result,
    5404              :       by calling the function specified by REDUC_FN if available, or by
    5405              :       other means (whole-vector shifts or a scalar loop).
    5406              :       The function also creates a new phi node at the loop exit to preserve
    5407              :       loop-closed form, as illustrated below.
    5408              : 
    5409              :      The flow at the entry to this function:
    5410              : 
    5411              :         loop:
    5412              :           vec_def = phi <vec_init, null>        # REDUCTION_PHI
    5413              :           VECT_DEF = vector_stmt                # vectorized form of STMT_INFO
    5414              :           s_loop = scalar_stmt                  # (scalar) STMT_INFO
    5415              :         loop_exit:
    5416              :           s_out0 = phi <s_loop>                 # (scalar) EXIT_PHI
    5417              :           use <s_out0>
    5418              :           use <s_out0>
    5419              : 
    5420              :      The above is transformed by this function into:
    5421              : 
    5422              :         loop:
    5423              :           vec_def = phi <vec_init, VECT_DEF>    # REDUCTION_PHI
    5424              :           VECT_DEF = vector_stmt                # vectorized form of STMT_INFO
    5425              :           s_loop = scalar_stmt                  # (scalar) STMT_INFO
    5426              :         loop_exit:
    5427              :           s_out0 = phi <s_loop>                 # (scalar) EXIT_PHI
    5428              :           v_out1 = phi <VECT_DEF>               # NEW_EXIT_PHI
    5429              :           v_out2 = reduce <v_out1>
    5430              :           s_out3 = extract_field <v_out2, 0>
    5431              :           s_out4 = adjust_result <s_out3>
    5432              :           use <s_out4>
    5433              :           use <s_out4>
    5434              : */
    5435              : 
    5436              : static void
    5437        22244 : vect_create_epilog_for_reduction (loop_vec_info loop_vinfo,
    5438              :                                   stmt_vec_info stmt_info,
    5439              :                                   slp_tree slp_node,
    5440              :                                   slp_instance slp_node_instance,
    5441              :                                   edge loop_exit)
    5442              : {
    5443        22244 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    5444        22244 :   code_helper code = VECT_REDUC_INFO_CODE (reduc_info);
    5445        22244 :   internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    5446        22244 :   tree vectype;
    5447        22244 :   machine_mode mode;
    5448        22244 :   basic_block exit_bb;
    5449        22244 :   gimple *new_phi = NULL, *phi = NULL;
    5450        22244 :   gimple_stmt_iterator exit_gsi;
    5451        22244 :   tree new_temp = NULL_TREE, new_name, new_scalar_dest;
    5452        22244 :   gimple *epilog_stmt = NULL;
    5453        22244 :   gimple *exit_phi;
    5454        22244 :   tree def;
    5455        22244 :   tree orig_name, scalar_result;
    5456        22244 :   imm_use_iterator imm_iter;
    5457        22244 :   use_operand_p use_p;
    5458        22244 :   gimple *use_stmt;
    5459        22244 :   auto_vec<tree> reduc_inputs;
    5460        22244 :   int j, i;
    5461        22244 :   vec<tree> &scalar_results = VECT_REDUC_INFO_SCALAR_RESULTS (reduc_info);
    5462        22244 :   unsigned int k;
    5463              :   /* SLP reduction without reduction chain, e.g.,
    5464              :      # a1 = phi <a2, a0>
    5465              :      # b1 = phi <b2, b0>
    5466              :      a2 = operation (a1)
    5467              :      b2 = operation (b1)  */
    5468        22244 :   const bool slp_reduc = !reduc_info->is_reduc_chain;
    5469        22244 :   tree induction_index = NULL_TREE;
    5470              : 
    5471        22244 :   unsigned int group_size = SLP_TREE_LANES (slp_node);
    5472              : 
    5473        22244 :   bool double_reduc = false;
    5474        22244 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    5475        22244 :   if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    5476              :     {
    5477            0 :       double_reduc = true;
    5478            0 :       gcc_assert (slp_reduc);
    5479              :     }
    5480              : 
    5481        22244 :   vectype = VECT_REDUC_INFO_VECTYPE (reduc_info);
    5482        22244 :   gcc_assert (vectype);
    5483        22244 :   mode = TYPE_MODE (vectype);
    5484              : 
    5485        22244 :   tree induc_val = NULL_TREE;
    5486        22244 :   tree adjustment_def = NULL;
    5487              :   /* Optimize: for induction condition reduction, if we can't use zero
    5488              :      for induc_val, use initial_def.  */
    5489        22244 :   if (VECT_REDUC_INFO_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
    5490           62 :     induc_val = VECT_REDUC_INFO_INDUC_COND_INITIAL_VAL (reduc_info);
    5491        22182 :   else if (double_reduc)
    5492              :     ;
    5493              :   else
    5494        22182 :     adjustment_def = VECT_REDUC_INFO_EPILOGUE_ADJUSTMENT (reduc_info);
    5495              : 
    5496        22244 :   stmt_vec_info single_live_out_stmt[] = { stmt_info };
    5497        22244 :   array_slice<const stmt_vec_info> live_out_stmts = single_live_out_stmt;
    5498        22244 :   if (slp_reduc)
    5499              :     /* All statements produce live-out values.  */
    5500        44018 :     live_out_stmts = SLP_TREE_SCALAR_STMTS (slp_node);
    5501              : 
    5502        22244 :   unsigned vec_num
    5503        22244 :     = SLP_TREE_VEC_DEFS (slp_node_instance->reduc_phis).length ();
    5504              : 
    5505              :   /* For cond reductions we want to create a new vector (INDEX_COND_EXPR)
    5506              :      which is updated with the current index of the loop for every match of
    5507              :      the original loop's cond_expr (VEC_STMT).  This results in a vector
    5508              :      containing the last time the condition passed for that vector lane.
    5509              :      The first match will be a 1 to allow 0 to be used for non-matching
    5510              :      indexes.  If there are no matches at all then the vector will be all
    5511              :      zeroes.
    5512              : 
    5513              :      PR92772: This algorithm is broken for architectures that support
    5514              :      masked vectors, but do not provide fold_extract_last.  */
    5515        22244 :   if (VECT_REDUC_INFO_TYPE (reduc_info) == COND_REDUCTION)
    5516              :     {
    5517           99 :       gcc_assert (!double_reduc);
    5518           99 :       auto_vec<std::pair<tree, bool>, 2> ccompares;
    5519           99 :       slp_tree cond_node = slp_node_instance->root;
    5520          207 :       while (cond_node != slp_node_instance->reduc_phis)
    5521              :         {
    5522          108 :           stmt_vec_info cond_info = SLP_TREE_REPRESENTATIVE (cond_node);
    5523          108 :           if (gimple_assign_rhs_code (cond_info->stmt) == COND_EXPR)
    5524              :             {
    5525          108 :               gimple *vec_stmt
    5526          108 :                 = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (cond_node)[0]);
    5527          108 :               gcc_assert (gimple_assign_rhs_code (vec_stmt) == VEC_COND_EXPR);
    5528          108 :               ccompares.safe_push
    5529          108 :                 (std::make_pair (gimple_assign_rhs1 (vec_stmt),
    5530          108 :                                  SLP_TREE_REDUC_IDX (cond_node) == 2));
    5531              :             }
    5532          108 :           int slp_reduc_idx = SLP_TREE_REDUC_IDX (cond_node);
    5533          108 :           cond_node = SLP_TREE_CHILDREN (cond_node)[slp_reduc_idx];
    5534              :         }
    5535           99 :       gcc_assert (ccompares.length () != 0);
    5536              : 
    5537           99 :       tree indx_before_incr, indx_after_incr;
    5538           99 :       poly_uint64 nunits_out = TYPE_VECTOR_SUBPARTS (vectype);
    5539           99 :       int scalar_precision
    5540           99 :         = GET_MODE_PRECISION (SCALAR_TYPE_MODE (TREE_TYPE (vectype)));
    5541           99 :       tree cr_index_scalar_type = make_unsigned_type (scalar_precision);
    5542           99 :       tree cr_index_vector_type = get_related_vectype_for_scalar_type
    5543           99 :         (TYPE_MODE (vectype), cr_index_scalar_type,
    5544              :          TYPE_VECTOR_SUBPARTS (vectype));
    5545              : 
    5546              :       /* First we create a simple vector induction variable which starts
    5547              :          with the values {1,2,3,...} (SERIES_VECT) and increments by the
    5548              :          vector size (STEP).  */
    5549              : 
    5550              :       /* Create a {1,2,3,...} vector.  */
    5551           99 :       tree series_vect = build_index_vector (cr_index_vector_type, 1, 1);
    5552              : 
    5553              :       /* Create a vector of the step value.  */
    5554           99 :       tree step = build_int_cst (cr_index_scalar_type, nunits_out);
    5555           99 :       tree vec_step = build_vector_from_val (cr_index_vector_type, step);
    5556              : 
    5557              :       /* Create an induction variable.  */
    5558           99 :       gimple_stmt_iterator incr_gsi;
    5559           99 :       bool insert_after;
    5560           99 :       vect_iv_increment_position (LOOP_VINFO_MAIN_EXIT (loop_vinfo),
    5561              :                                   &incr_gsi, &insert_after);
    5562           99 :       create_iv (series_vect, PLUS_EXPR, vec_step, NULL_TREE, loop, &incr_gsi,
    5563              :                  insert_after, &indx_before_incr, &indx_after_incr);
    5564              : 
    5565              :       /* Next create a new phi node vector (NEW_PHI_TREE) which starts
    5566              :          filled with zeros (VEC_ZERO).  */
    5567              : 
    5568              :       /* Create a vector of 0s.  */
    5569           99 :       tree zero = build_zero_cst (cr_index_scalar_type);
    5570           99 :       tree vec_zero = build_vector_from_val (cr_index_vector_type, zero);
    5571              : 
    5572              :       /* Create a vector phi node.  */
    5573           99 :       tree new_phi_tree = make_ssa_name (cr_index_vector_type);
    5574           99 :       new_phi = create_phi_node (new_phi_tree, loop->header);
    5575           99 :       add_phi_arg (as_a <gphi *> (new_phi), vec_zero,
    5576              :                    loop_preheader_edge (loop), UNKNOWN_LOCATION);
    5577              : 
    5578              :       /* Now take the condition from the loops original cond_exprs
    5579              :          and produce a new cond_exprs (INDEX_COND_EXPR) which for
    5580              :          every match uses values from the induction variable
    5581              :          (INDEX_BEFORE_INCR) otherwise uses values from the phi node
    5582              :          (NEW_PHI_TREE).
    5583              :          Finally, we update the phi (NEW_PHI_TREE) to take the value of
    5584              :          the new cond_expr (INDEX_COND_EXPR).  */
    5585           99 :       gimple_seq stmts = NULL;
    5586          306 :       for (int i = ccompares.length () - 1; i != -1; --i)
    5587              :         {
    5588          108 :           tree ccompare = ccompares[i].first;
    5589          108 :           if (ccompares[i].second)
    5590           81 :             new_phi_tree = gimple_build (&stmts, VEC_COND_EXPR,
    5591              :                                          cr_index_vector_type,
    5592              :                                          ccompare,
    5593              :                                          indx_before_incr, new_phi_tree);
    5594              :           else
    5595           27 :             new_phi_tree = gimple_build (&stmts, VEC_COND_EXPR,
    5596              :                                          cr_index_vector_type,
    5597              :                                          ccompare,
    5598              :                                          new_phi_tree, indx_before_incr);
    5599              :         }
    5600           99 :       gsi_insert_seq_before (&incr_gsi, stmts, GSI_SAME_STMT);
    5601              : 
    5602              :       /* Update the phi with the vec cond.  */
    5603           99 :       induction_index = new_phi_tree;
    5604           99 :       add_phi_arg (as_a <gphi *> (new_phi), induction_index,
    5605              :                    loop_latch_edge (loop), UNKNOWN_LOCATION);
    5606           99 :     }
    5607              : 
    5608              :   /* 2. Create epilog code.
    5609              :         The reduction epilog code operates across the elements of the vector
    5610              :         of partial results computed by the vectorized loop.
    5611              :         The reduction epilog code consists of:
    5612              : 
    5613              :         step 1: compute the scalar result in a vector (v_out2)
    5614              :         step 2: extract the scalar result (s_out3) from the vector (v_out2)
    5615              :         step 3: adjust the scalar result (s_out3) if needed.
    5616              : 
    5617              :         Step 1 can be accomplished using one the following three schemes:
    5618              :           (scheme 1) using reduc_fn, if available.
    5619              :           (scheme 2) using whole-vector shifts, if available.
    5620              :           (scheme 3) using a scalar loop. In this case steps 1+2 above are
    5621              :                      combined.
    5622              : 
    5623              :           The overall epilog code looks like this:
    5624              : 
    5625              :           s_out0 = phi <s_loop>         # original EXIT_PHI
    5626              :           v_out1 = phi <VECT_DEF>       # NEW_EXIT_PHI
    5627              :           v_out2 = reduce <v_out1>              # step 1
    5628              :           s_out3 = extract_field <v_out2, 0>    # step 2
    5629              :           s_out4 = adjust_result <s_out3>       # step 3
    5630              : 
    5631              :           (step 3 is optional, and steps 1 and 2 may be combined).
    5632              :           Lastly, the uses of s_out0 are replaced by s_out4.  */
    5633              : 
    5634              : 
    5635              :   /* 2.1 Create new loop-exit-phis to preserve loop-closed form:
    5636              :          v_out1 = phi <VECT_DEF>
    5637              :          Store them in NEW_PHIS.  */
    5638              :   /* We need to reduce values in all exits.  */
    5639        22244 :   exit_bb = loop_exit->dest;
    5640        22244 :   exit_gsi = gsi_after_labels (exit_bb);
    5641        22244 :   reduc_inputs.create (vec_num);
    5642        68403 :   for (unsigned i = 0; i < vec_num; i++)
    5643              :     {
    5644        23915 :       gimple_seq stmts = NULL;
    5645        23915 :       def = vect_get_slp_vect_def (slp_node, i);
    5646        23915 :       tree new_def = copy_ssa_name (def);
    5647        23915 :       phi = create_phi_node (new_def, exit_bb);
    5648        23915 :       if (LOOP_VINFO_MAIN_EXIT (loop_vinfo) == loop_exit)
    5649        23885 :         SET_PHI_ARG_DEF (phi, loop_exit->dest_idx, def);
    5650              :       else
    5651              :         {
    5652           63 :           for (unsigned k = 0; k < gimple_phi_num_args (phi); k++)
    5653           33 :             SET_PHI_ARG_DEF (phi, k, def);
    5654              :         }
    5655        23915 :       new_def = gimple_convert (&stmts, vectype, new_def);
    5656        23915 :       reduc_inputs.quick_push (new_def);
    5657        23915 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5658              :     }
    5659              : 
    5660              :   /* 2.2 Get the original scalar reduction variable as defined in the loop.
    5661              :          In case STMT is a "pattern-stmt" (i.e. - it represents a reduction
    5662              :          pattern), the scalar-def is taken from the original stmt that the
    5663              :          pattern-stmt (STMT) replaces.  */
    5664              : 
    5665        23100 :   tree scalar_dest = gimple_get_lhs (vect_orig_stmt (stmt_info)->stmt);
    5666        22244 :   tree scalar_type = TREE_TYPE (scalar_dest);
    5667        22244 :   scalar_results.truncate (0);
    5668        22244 :   scalar_results.reserve_exact (group_size);
    5669        22244 :   new_scalar_dest = vect_create_destination_var (scalar_dest, NULL);
    5670              : 
    5671              :   /* True if we should implement SLP_REDUC using native reduction operations
    5672              :      instead of scalar operations.  */
    5673        22244 :   const bool direct_slp_reduc
    5674        22244 :     = (reduc_fn != IFN_LAST
    5675        22244 :        && slp_reduc
    5676        22244 :        && !TYPE_VECTOR_SUBPARTS (vectype).is_constant ());
    5677              : 
    5678              :   /* If signed overflow is undefined we might need to perform reduction
    5679              :      computations in an unsigned type.  */
    5680        22244 :   tree compute_vectype = vectype;
    5681        22244 :   if (ANY_INTEGRAL_TYPE_P (vectype)
    5682        15096 :       && TYPE_OVERFLOW_UNDEFINED (vectype)
    5683         5599 :       && code.is_tree_code ()
    5684        27843 :       && arith_code_with_undefined_signed_overflow ((tree_code) code))
    5685         4135 :     compute_vectype = unsigned_type_for (vectype);
    5686              : 
    5687              :   /* In case of reduction chain, e.g.,
    5688              :      # a1 = phi <a3, a0>
    5689              :      a2 = operation (a1)
    5690              :      a3 = operation (a2),
    5691              : 
    5692              :      we may end up with more than one vector result.  Here we reduce them
    5693              :      to one vector.
    5694              : 
    5695              :      The same is true for a SLP reduction, e.g.,
    5696              :      # a1 = phi <a2, a0>
    5697              :      # b1 = phi <b2, b0>
    5698              :      a2 = operation (a1)
    5699              :      b2 = operation (a2),
    5700              : 
    5701              :      where we can end up with more than one vector as well.  We can
    5702              :      easily accumulate vectors when the number of vector elements is
    5703              :      a multiple of the SLP group size.
    5704              : 
    5705              :      The same is true if we couldn't use a single defuse cycle.  */
    5706        22244 :   if ((!slp_reduc
    5707              :        || direct_slp_reduc
    5708              :        || (slp_reduc
    5709        22244 :            && constant_multiple_p (TYPE_VECTOR_SUBPARTS (vectype), group_size)))
    5710        44488 :       && reduc_inputs.length () > 1)
    5711              :     {
    5712          565 :       gimple_seq stmts = NULL;
    5713          565 :       tree single_input = reduc_inputs[0];
    5714          565 :       if (compute_vectype != vectype)
    5715          171 :         single_input = gimple_build (&stmts, VIEW_CONVERT_EXPR,
    5716              :                                      compute_vectype, single_input);
    5717         2081 :       for (k = 1; k < reduc_inputs.length (); k++)
    5718              :         {
    5719         1516 :           tree input = gimple_build (&stmts, VIEW_CONVERT_EXPR,
    5720         1516 :                                      compute_vectype, reduc_inputs[k]);
    5721         1516 :           single_input = gimple_build (&stmts, code, compute_vectype,
    5722              :                                        single_input, input);
    5723              :         }
    5724          565 :       if (compute_vectype != vectype)
    5725          171 :         single_input = gimple_build (&stmts, VIEW_CONVERT_EXPR,
    5726              :                                      vectype, single_input);
    5727          565 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5728              : 
    5729          565 :       reduc_inputs.truncate (0);
    5730          565 :       reduc_inputs.safe_push (single_input);
    5731              :     }
    5732              : 
    5733        22244 :   tree orig_reduc_input = reduc_inputs[0];
    5734              : 
    5735              :   /* If this loop is an epilogue loop that can be skipped after the
    5736              :      main loop, we can only share a reduction operation between the
    5737              :      main loop and the epilogue if we put it at the target of the
    5738              :      skip edge.
    5739              : 
    5740              :      We can still reuse accumulators if this check fails.  Doing so has
    5741              :      the minor(?) benefit of making the epilogue loop's scalar result
    5742              :      independent of the main loop's scalar result.  */
    5743        22244 :   bool unify_with_main_loop_p = false;
    5744        22244 :   if (VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info)
    5745         3944 :       && loop_vinfo->skip_this_loop_edge
    5746         3778 :       && single_succ_p (exit_bb)
    5747        22261 :       && single_succ (exit_bb) == loop_vinfo->skip_this_loop_edge->dest)
    5748              :     {
    5749           17 :       unify_with_main_loop_p = true;
    5750              : 
    5751           17 :       basic_block reduc_block = loop_vinfo->skip_this_loop_edge->dest;
    5752           17 :       reduc_inputs[0] = make_ssa_name (vectype);
    5753           17 :       gphi *new_phi = create_phi_node (reduc_inputs[0], reduc_block);
    5754           17 :       add_phi_arg (new_phi, orig_reduc_input, single_succ_edge (exit_bb),
    5755              :                    UNKNOWN_LOCATION);
    5756           17 :       add_phi_arg (new_phi,
    5757           17 :                    VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info)->reduc_input,
    5758              :                    loop_vinfo->skip_this_loop_edge, UNKNOWN_LOCATION);
    5759           17 :       exit_gsi = gsi_after_labels (reduc_block);
    5760              :     }
    5761              : 
    5762              :   /* Shouldn't be used beyond this point.  */
    5763        22244 :   exit_bb = nullptr;
    5764              : 
    5765              :   /* If we are operating on a mask vector and do not support direct mask
    5766              :      reduction, work on a bool data vector instead of a mask vector.  */
    5767        22244 :   if (VECTOR_BOOLEAN_TYPE_P (vectype)
    5768          235 :       && VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info)
    5769        22429 :       && vectype != VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info))
    5770              :     {
    5771          185 :       compute_vectype = vectype = VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info);
    5772          185 :       gimple_seq stmts = NULL;
    5773          378 :       for (unsigned i = 0; i < reduc_inputs.length (); ++i)
    5774          386 :         reduc_inputs[i] = gimple_build (&stmts, VEC_COND_EXPR, vectype,
    5775          193 :                                         reduc_inputs[i],
    5776              :                                         build_one_cst (vectype),
    5777              :                                         build_zero_cst (vectype));
    5778          185 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5779              :     }
    5780              : 
    5781        22244 :   if (VECT_REDUC_INFO_TYPE (reduc_info) == COND_REDUCTION
    5782           99 :       && reduc_fn != IFN_LAST)
    5783              :     {
    5784              :       /* For condition reductions, we have a vector (REDUC_INPUTS 0) containing
    5785              :          various data values where the condition matched and another vector
    5786              :          (INDUCTION_INDEX) containing all the indexes of those matches.  We
    5787              :          need to extract the last matching index (which will be the index with
    5788              :          highest value) and use this to index into the data vector.
    5789              :          For the case where there were no matches, the data vector will contain
    5790              :          all default values and the index vector will be all zeros.  */
    5791              : 
    5792              :       /* Get various versions of the type of the vector of indexes.  */
    5793           14 :       tree index_vec_type = TREE_TYPE (induction_index);
    5794           14 :       gcc_checking_assert (TYPE_UNSIGNED (index_vec_type));
    5795           14 :       tree index_scalar_type = TREE_TYPE (index_vec_type);
    5796           14 :       tree index_vec_cmp_type = truth_type_for (index_vec_type);
    5797              : 
    5798              :       /* Get an unsigned integer version of the type of the data vector.  */
    5799           14 :       int scalar_precision
    5800           14 :         = GET_MODE_PRECISION (SCALAR_TYPE_MODE (scalar_type));
    5801           14 :       tree scalar_type_unsigned = make_unsigned_type (scalar_precision);
    5802           14 :       tree vectype_unsigned = get_same_sized_vectype (scalar_type_unsigned,
    5803              :                                                 vectype);
    5804              : 
    5805              :       /* First we need to create a vector (ZERO_VEC) of zeros and another
    5806              :          vector (MAX_INDEX_VEC) filled with the last matching index, which we
    5807              :          can create using a MAX reduction and then expanding.
    5808              :          In the case where the loop never made any matches, the max index will
    5809              :          be zero.  */
    5810              : 
    5811              :       /* Vector of {0, 0, 0,...}.  */
    5812           14 :       tree zero_vec = build_zero_cst (vectype);
    5813              : 
    5814              :       /* Find maximum value from the vector of found indexes.  */
    5815           14 :       tree max_index = make_ssa_name (index_scalar_type);
    5816           14 :       gcall *max_index_stmt = gimple_build_call_internal (IFN_REDUC_MAX,
    5817              :                                                           1, induction_index);
    5818           14 :       gimple_call_set_lhs (max_index_stmt, max_index);
    5819           14 :       gsi_insert_before (&exit_gsi, max_index_stmt, GSI_SAME_STMT);
    5820              : 
    5821              :       /* Vector of {max_index, max_index, max_index,...}.  */
    5822           14 :       tree max_index_vec = make_ssa_name (index_vec_type);
    5823           14 :       tree max_index_vec_rhs = build_vector_from_val (index_vec_type,
    5824              :                                                       max_index);
    5825           14 :       gimple *max_index_vec_stmt = gimple_build_assign (max_index_vec,
    5826              :                                                         max_index_vec_rhs);
    5827           14 :       gsi_insert_before (&exit_gsi, max_index_vec_stmt, GSI_SAME_STMT);
    5828              : 
    5829              :       /* Next we compare the new vector (MAX_INDEX_VEC) full of max indexes
    5830              :          with the vector (INDUCTION_INDEX) of found indexes, choosing values
    5831              :          from the data vector (REDUC_INPUTS 0) for matches, 0 (ZERO_VEC)
    5832              :          otherwise.  Only one value should match, resulting in a vector
    5833              :          (VEC_COND) with one data value and the rest zeros.
    5834              :          In the case where the loop never made any matches, every index will
    5835              :          match, resulting in a vector with all data values (which will all be
    5836              :          the default value).  */
    5837              : 
    5838              :       /* Compare the max index vector to the vector of found indexes to find
    5839              :          the position of the max value.  */
    5840           14 :       tree vec_compare = make_ssa_name (index_vec_cmp_type);
    5841           14 :       gimple *vec_compare_stmt = gimple_build_assign (vec_compare, EQ_EXPR,
    5842              :                                                       induction_index,
    5843              :                                                       max_index_vec);
    5844           14 :       gsi_insert_before (&exit_gsi, vec_compare_stmt, GSI_SAME_STMT);
    5845              : 
    5846              :       /* Use the compare to choose either values from the data vector or
    5847              :          zero.  */
    5848           14 :       tree vec_cond = make_ssa_name (vectype);
    5849           14 :       gimple *vec_cond_stmt = gimple_build_assign (vec_cond, VEC_COND_EXPR,
    5850              :                                                    vec_compare,
    5851           14 :                                                    reduc_inputs[0],
    5852              :                                                    zero_vec);
    5853           14 :       gsi_insert_before (&exit_gsi, vec_cond_stmt, GSI_SAME_STMT);
    5854              : 
    5855              :       /* Finally we need to extract the data value from the vector (VEC_COND)
    5856              :          into a scalar (MATCHED_DATA_REDUC).  Logically we want to do a OR
    5857              :          reduction, but because this doesn't exist, we can use a MAX reduction
    5858              :          instead.  The data value might be signed or a float so we need to cast
    5859              :          it first.
    5860              :          In the case where the loop never made any matches, the data values are
    5861              :          all identical, and so will reduce down correctly.  */
    5862              : 
    5863              :       /* Make the matched data values unsigned.  */
    5864           14 :       tree vec_cond_cast = make_ssa_name (vectype_unsigned);
    5865           14 :       tree vec_cond_cast_rhs = build1 (VIEW_CONVERT_EXPR, vectype_unsigned,
    5866              :                                        vec_cond);
    5867           14 :       gimple *vec_cond_cast_stmt = gimple_build_assign (vec_cond_cast,
    5868              :                                                         VIEW_CONVERT_EXPR,
    5869              :                                                         vec_cond_cast_rhs);
    5870           14 :       gsi_insert_before (&exit_gsi, vec_cond_cast_stmt, GSI_SAME_STMT);
    5871              : 
    5872              :       /* Reduce down to a scalar value.  */
    5873           14 :       tree data_reduc = make_ssa_name (scalar_type_unsigned);
    5874           14 :       gcall *data_reduc_stmt = gimple_build_call_internal (IFN_REDUC_MAX,
    5875              :                                                            1, vec_cond_cast);
    5876           14 :       gimple_call_set_lhs (data_reduc_stmt, data_reduc);
    5877           14 :       gsi_insert_before (&exit_gsi, data_reduc_stmt, GSI_SAME_STMT);
    5878              : 
    5879              :       /* Convert the reduced value back to the result type and set as the
    5880              :          result.  */
    5881           14 :       gimple_seq stmts = NULL;
    5882           14 :       new_temp = gimple_build (&stmts, VIEW_CONVERT_EXPR, scalar_type,
    5883              :                                data_reduc);
    5884           14 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5885           14 :       scalar_results.safe_push (new_temp);
    5886           14 :     }
    5887        22230 :   else if (VECT_REDUC_INFO_TYPE (reduc_info) == COND_REDUCTION
    5888           85 :            && reduc_fn == IFN_LAST)
    5889              :     {
    5890              :       /* Condition reduction without supported IFN_REDUC_MAX.  Generate
    5891              :          idx = 0;
    5892              :          idx_val = induction_index[0];
    5893              :          val = data_reduc[0];
    5894              :          for (idx = 0, val = init, i = 0; i < nelts; ++i)
    5895              :            if (induction_index[i] > idx_val)
    5896              :              val = data_reduc[i], idx_val = induction_index[i];
    5897              :          return val;  */
    5898              : 
    5899           85 :       tree data_eltype = TREE_TYPE (vectype);
    5900           85 :       tree idx_eltype = TREE_TYPE (TREE_TYPE (induction_index));
    5901           85 :       unsigned HOST_WIDE_INT el_size = tree_to_uhwi (TYPE_SIZE (idx_eltype));
    5902           85 :       poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (TREE_TYPE (induction_index));
    5903              :       /* Enforced by vectorizable_reduction, which ensures we have target
    5904              :          support before allowing a conditional reduction on variable-length
    5905              :          vectors.  */
    5906           85 :       unsigned HOST_WIDE_INT v_size = el_size * nunits.to_constant ();
    5907           85 :       tree idx_val = NULL_TREE, val = NULL_TREE;
    5908          511 :       for (unsigned HOST_WIDE_INT off = 0; off < v_size; off += el_size)
    5909              :         {
    5910          426 :           tree old_idx_val = idx_val;
    5911          426 :           tree old_val = val;
    5912          426 :           idx_val = make_ssa_name (idx_eltype);
    5913          426 :           epilog_stmt = gimple_build_assign (idx_val, BIT_FIELD_REF,
    5914              :                                              build3 (BIT_FIELD_REF, idx_eltype,
    5915              :                                                      induction_index,
    5916          426 :                                                      bitsize_int (el_size),
    5917          426 :                                                      bitsize_int (off)));
    5918          426 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5919          426 :           val = make_ssa_name (data_eltype);
    5920          852 :           epilog_stmt = gimple_build_assign (val, BIT_FIELD_REF,
    5921              :                                              build3 (BIT_FIELD_REF,
    5922              :                                                      data_eltype,
    5923          426 :                                                      reduc_inputs[0],
    5924          426 :                                                      bitsize_int (el_size),
    5925          426 :                                                      bitsize_int (off)));
    5926          426 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5927          426 :           if (off != 0)
    5928              :             {
    5929          341 :               tree new_idx_val = idx_val;
    5930          341 :               if (off != v_size - el_size)
    5931              :                 {
    5932          256 :                   new_idx_val = make_ssa_name (idx_eltype);
    5933          256 :                   epilog_stmt = gimple_build_assign (new_idx_val,
    5934              :                                                      MAX_EXPR, idx_val,
    5935              :                                                      old_idx_val);
    5936          256 :                   gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5937              :                 }
    5938          341 :               tree cond = make_ssa_name (boolean_type_node);
    5939          341 :               epilog_stmt = gimple_build_assign (cond, GT_EXPR,
    5940              :                                                  idx_val, old_idx_val);
    5941          341 :               gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5942          341 :               tree new_val = make_ssa_name (data_eltype);
    5943          341 :               epilog_stmt = gimple_build_assign (new_val, COND_EXPR,
    5944              :                                                  cond, val, old_val);
    5945          341 :               gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5946          341 :               idx_val = new_idx_val;
    5947          341 :               val = new_val;
    5948              :             }
    5949              :         }
    5950              :       /* Convert the reduced value back to the result type and set as the
    5951              :          result.  */
    5952           85 :       gimple_seq stmts = NULL;
    5953           85 :       val = gimple_convert (&stmts, scalar_type, val);
    5954           85 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5955           85 :       scalar_results.safe_push (val);
    5956           85 :     }
    5957              : 
    5958              :   /* 2.3 Create the reduction code, using one of the three schemes described
    5959              :          above. In SLP we simply need to extract all the elements from the
    5960              :          vector (without reducing them), so we use scalar shifts.  */
    5961        22145 :   else if (reduc_fn != IFN_LAST && (!slp_reduc || group_size == 1))
    5962              :     {
    5963        20319 :       tree tmp;
    5964        20319 :       tree vec_elem_type;
    5965              : 
    5966              :       /* Case 1:  Create:
    5967              :          v_out2 = reduc_expr <v_out1>  */
    5968              : 
    5969        20319 :       if (dump_enabled_p ())
    5970         1573 :         dump_printf_loc (MSG_NOTE, vect_location,
    5971              :                          "Reduce using direct vector reduction.\n");
    5972              : 
    5973        20319 :       gimple_seq stmts = NULL;
    5974        20319 :       vec_elem_type = TREE_TYPE (vectype);
    5975        20319 :       new_temp = gimple_build (&stmts, as_combined_fn (reduc_fn),
    5976        20319 :                                vec_elem_type, reduc_inputs[0]);
    5977        20319 :       new_temp = gimple_convert (&stmts, scalar_type, new_temp);
    5978        20319 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    5979              : 
    5980        20319 :       if ((VECT_REDUC_INFO_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
    5981           62 :           && induc_val)
    5982              :         {
    5983              :           /* Earlier we set the initial value to be a vector if induc_val
    5984              :              values.  Check the result and if it is induc_val then replace
    5985              :              with the original initial value, unless induc_val is
    5986              :              the same as initial_def already.  */
    5987           60 :           tree zcompare = make_ssa_name (boolean_type_node);
    5988           60 :           epilog_stmt = gimple_build_assign (zcompare, EQ_EXPR,
    5989              :                                              new_temp, induc_val);
    5990           60 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5991           60 :           tree initial_def = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info)[0];
    5992           60 :           tmp = make_ssa_name (new_scalar_dest);
    5993           60 :           epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
    5994              :                                              initial_def, new_temp);
    5995           60 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    5996           60 :           new_temp = tmp;
    5997              :         }
    5998              : 
    5999        20319 :       scalar_results.safe_push (new_temp);
    6000        20319 :     }
    6001         1627 :   else if (direct_slp_reduc)
    6002              :     {
    6003              :       /* Here we create one vector for each of the GROUP_SIZE results,
    6004              :          with the elements for other SLP statements replaced with the
    6005              :          neutral value.  We can then do a normal reduction on each vector.  */
    6006              : 
    6007              :       /* Enforced by vectorizable_reduction.  */
    6008              :       gcc_assert (reduc_inputs.length () == 1);
    6009              :       gcc_assert (pow2p_hwi (group_size));
    6010              : 
    6011              :       gimple_seq seq = NULL;
    6012              : 
    6013              :       /* Build a vector {0, 1, 2, ...}, with the same number of elements
    6014              :          and the same element size as VECTYPE.  */
    6015              :       tree index = build_index_vector (vectype, 0, 1);
    6016              :       tree index_type = TREE_TYPE (index);
    6017              :       tree index_elt_type = TREE_TYPE (index_type);
    6018              :       tree mask_type = truth_type_for (index_type);
    6019              : 
    6020              :       /* Create a vector that, for each element, identifies which of
    6021              :          the results should use it.  */
    6022              :       tree index_mask = build_int_cst (index_elt_type, group_size - 1);
    6023              :       index = gimple_build (&seq, BIT_AND_EXPR, index_type, index,
    6024              :                             build_vector_from_val (index_type, index_mask));
    6025              : 
    6026              :       /* Get a neutral vector value.  This is simply a splat of the neutral
    6027              :          scalar value if we have one, otherwise the initial scalar value
    6028              :          is itself a neutral value.  */
    6029              :       tree vector_identity = NULL_TREE;
    6030              :       tree neutral_op = neutral_op_for_reduction (TREE_TYPE (vectype), code,
    6031              :                                                   NULL_TREE, false);
    6032              :       if (neutral_op)
    6033              :         vector_identity = gimple_build_vector_from_val (&seq, vectype,
    6034              :                                                         neutral_op);
    6035              :       for (unsigned int i = 0; i < group_size; ++i)
    6036              :         {
    6037              :           /* If there's no universal neutral value, we can use the
    6038              :              initial scalar value from the original PHI.  This is used
    6039              :              for MIN and MAX reduction, for example.  */
    6040              :           if (!neutral_op)
    6041              :             {
    6042              :               tree scalar_value
    6043              :                 = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info)[i];
    6044              :               scalar_value = gimple_convert (&seq, TREE_TYPE (vectype),
    6045              :                                              scalar_value);
    6046              :               vector_identity = gimple_build_vector_from_val (&seq, vectype,
    6047              :                                                               scalar_value);
    6048              :             }
    6049              : 
    6050              :           /* Calculate the equivalent of:
    6051              : 
    6052              :              sel[j] = (index[j] == i);
    6053              : 
    6054              :              which selects the elements of REDUC_INPUTS[0] that should
    6055              :              be included in the result.  */
    6056              :           tree compare_val = build_int_cst (index_elt_type, i);
    6057              :           compare_val = build_vector_from_val (index_type, compare_val);
    6058              :           tree sel = gimple_build (&seq, EQ_EXPR, mask_type,
    6059              :                                    index, compare_val);
    6060              : 
    6061              :           /* Calculate the equivalent of:
    6062              : 
    6063              :              vec = seq ? reduc_inputs[0] : vector_identity;
    6064              : 
    6065              :              VEC is now suitable for a full vector reduction.  */
    6066              :           tree vec = gimple_build (&seq, VEC_COND_EXPR, vectype,
    6067              :                                    sel, reduc_inputs[0], vector_identity);
    6068              : 
    6069              :           /* Do the reduction and convert it to the appropriate type.  */
    6070              :           tree scalar = gimple_build (&seq, as_combined_fn (reduc_fn),
    6071              :                                       TREE_TYPE (vectype), vec);
    6072              :           scalar = gimple_convert (&seq, scalar_type, scalar);
    6073              :           scalar_results.safe_push (scalar);
    6074              :         }
    6075              :       gsi_insert_seq_before (&exit_gsi, seq, GSI_SAME_STMT);
    6076              :     }
    6077              :   else
    6078              :     {
    6079         1627 :       bool reduce_with_shift;
    6080         1627 :       tree vec_temp;
    6081              : 
    6082         1627 :       gcc_assert (slp_reduc || reduc_inputs.length () == 1);
    6083              : 
    6084              :       /* See if the target wants to do the final (shift) reduction
    6085              :          in a vector mode of smaller size and first reduce upper/lower
    6086              :          halves against each other.  */
    6087         1826 :       enum machine_mode mode1 = mode;
    6088         1826 :       tree stype = TREE_TYPE (vectype);
    6089         1826 :       if (compute_vectype != vectype)
    6090              :         {
    6091          459 :           stype = unsigned_type_for (stype);
    6092          459 :           gimple_seq stmts = NULL;
    6093          976 :           for (unsigned i = 0; i < reduc_inputs.length (); ++i)
    6094              :             {
    6095          517 :               tree new_temp = gimple_build (&stmts, VIEW_CONVERT_EXPR,
    6096          517 :                                             compute_vectype, reduc_inputs[i]);
    6097          517 :               reduc_inputs[i] = new_temp;
    6098              :             }
    6099          459 :           gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6100              :         }
    6101         1826 :       unsigned nunits = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
    6102         1826 :       unsigned nunits1 = nunits;
    6103         1826 :       if ((mode1 = targetm.vectorize.split_reduction (mode)) != mode
    6104         1826 :           && reduc_inputs.length () == 1)
    6105              :         {
    6106           42 :           nunits1 = GET_MODE_NUNITS (mode1).to_constant ();
    6107              :           /* For SLP reductions we have to make sure lanes match up, but
    6108              :              since we're doing individual element final reduction reducing
    6109              :              vector width here is even more important.
    6110              :              ???  We can also separate lanes with permutes, for the common
    6111              :              case of power-of-two group-size odd/even extracts would work.  */
    6112           42 :           if (slp_reduc && nunits != nunits1)
    6113              :             {
    6114           42 :               nunits1 = least_common_multiple (nunits1, group_size);
    6115           84 :               gcc_assert (exact_log2 (nunits1) != -1 && nunits1 <= nunits);
    6116              :             }
    6117              :         }
    6118         1784 :       else if (!slp_reduc
    6119         1784 :                && (mode1 = targetm.vectorize.split_reduction (mode)) != mode)
    6120            0 :         nunits1 = GET_MODE_NUNITS (mode1).to_constant ();
    6121              : 
    6122         1826 :       tree vectype1 = compute_vectype;
    6123         1826 :       if (mode1 != mode)
    6124              :         {
    6125           48 :           vectype1 = get_related_vectype_for_scalar_type (TYPE_MODE (vectype),
    6126           48 :                                                           stype, nunits1);
    6127              :           /* First reduce the vector to the desired vector size we should
    6128              :              do shift reduction on by combining upper and lower halves.  */
    6129           48 :           gimple_seq stmts = NULL;
    6130           48 :           new_temp = vect_create_partial_epilog (reduc_inputs[0], vectype1,
    6131              :                                                  code, &stmts);
    6132           48 :           gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6133           48 :           reduc_inputs[0] = new_temp;
    6134              :         }
    6135              : 
    6136         1826 :       reduce_with_shift = have_whole_vector_shift (mode1);
    6137          755 :       if (!VECTOR_MODE_P (mode1)
    6138         2579 :           || !directly_supported_p (code, vectype1))
    6139              :         reduce_with_shift = false;
    6140              : 
    6141         1809 :       if (reduce_with_shift && (!slp_reduc || group_size == 1))
    6142              :         {
    6143         1557 :           int element_bitsize = vector_element_bits (vectype1);
    6144              :           /* Enforced by vectorizable_reduction, which disallows SLP reductions
    6145              :              for variable-length vectors and also requires direct target support
    6146              :              for loop reductions.  */
    6147         1557 :           int nelements = TYPE_VECTOR_SUBPARTS (vectype1).to_constant ();
    6148         1557 :           vec_perm_builder sel;
    6149         1557 :           vec_perm_indices indices;
    6150              : 
    6151         1557 :           int elt_offset;
    6152              : 
    6153         1557 :           tree zero_vec = build_zero_cst (vectype1);
    6154              :           /* Case 2: Create:
    6155              :              for (offset = nelements/2; offset >= 1; offset/=2)
    6156              :                 {
    6157              :                   Create:  va' = vec_shift <va, offset>
    6158              :                   Create:  va = vop <va, va'>
    6159              :                 }  */
    6160              : 
    6161         1557 :           if (dump_enabled_p ())
    6162          384 :             dump_printf_loc (MSG_NOTE, vect_location,
    6163              :                              "Reduce using vector shifts\n");
    6164              : 
    6165         1557 :           gimple_seq stmts = NULL;
    6166         1557 :           new_temp = gimple_convert (&stmts, vectype1, reduc_inputs[0]);
    6167         1557 :           for (elt_offset = nelements / 2;
    6168         3425 :                elt_offset >= 1;
    6169         1868 :                elt_offset /= 2)
    6170              :             {
    6171         1868 :               calc_vec_perm_mask_for_shift (elt_offset, nelements, &sel);
    6172         1868 :               indices.new_vector (sel, 2, nelements);
    6173         1868 :               tree mask = vect_gen_perm_mask_any (vectype1, indices);
    6174         1868 :               new_name = gimple_build (&stmts, VEC_PERM_EXPR, vectype1,
    6175              :                                        new_temp, zero_vec, mask);
    6176         1868 :               new_temp = gimple_build (&stmts, code,
    6177              :                                        vectype1, new_name, new_temp);
    6178              :             }
    6179              : 
    6180              :           /* 2.4  Extract the final scalar result.  Create:
    6181              :              s_out3 = extract_field <v_out2, bitpos>  */
    6182              : 
    6183         1557 :           if (dump_enabled_p ())
    6184          384 :             dump_printf_loc (MSG_NOTE, vect_location,
    6185              :                              "extract scalar result\n");
    6186              : 
    6187         1557 :           new_temp = gimple_build (&stmts, BIT_FIELD_REF, TREE_TYPE (vectype1),
    6188         1557 :                                    new_temp, bitsize_int (element_bitsize),
    6189         1557 :                                    bitsize_zero_node);
    6190         1557 :           new_temp = gimple_convert (&stmts, scalar_type, new_temp);
    6191         1557 :           gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6192         1557 :           scalar_results.safe_push (new_temp);
    6193         1557 :         }
    6194              :       else
    6195              :         {
    6196              :           /* Case 3: Create:
    6197              :              s = extract_field <v_out2, 0>
    6198              :              for (offset = element_size;
    6199              :                   offset < vector_size;
    6200              :                   offset += element_size;)
    6201              :                {
    6202              :                  Create:  s' = extract_field <v_out2, offset>
    6203              :                  Create:  s = op <s, s'>  // For non SLP cases
    6204              :                }  */
    6205              : 
    6206          269 :           if (dump_enabled_p ())
    6207          144 :             dump_printf_loc (MSG_NOTE, vect_location,
    6208              :                              "Reduce using scalar code.\n");
    6209              : 
    6210          269 :           tree compute_type = TREE_TYPE (vectype1);
    6211          269 :           unsigned element_bitsize = vector_element_bits (vectype1);
    6212          269 :           unsigned vec_size_in_bits = element_bitsize
    6213          269 :             * TYPE_VECTOR_SUBPARTS (vectype1).to_constant ();
    6214          269 :           tree bitsize = bitsize_int (element_bitsize);
    6215          269 :           gimple_seq stmts = NULL;
    6216          693 :           FOR_EACH_VEC_ELT (reduc_inputs, i, vec_temp)
    6217              :             {
    6218          424 :               unsigned bit_offset;
    6219          848 :               new_temp = gimple_build (&stmts, BIT_FIELD_REF, compute_type,
    6220          424 :                                        vec_temp, bitsize, bitsize_zero_node);
    6221              : 
    6222              :               /* In SLP we don't need to apply reduction operation, so we just
    6223              :                  collect s' values in SCALAR_RESULTS.  */
    6224          424 :               if (slp_reduc)
    6225          414 :                 scalar_results.safe_push (new_temp);
    6226              : 
    6227          424 :               for (bit_offset = element_bitsize;
    6228         1424 :                    bit_offset < vec_size_in_bits;
    6229         1000 :                    bit_offset += element_bitsize)
    6230              :                 {
    6231         1000 :                   tree bitpos = bitsize_int (bit_offset);
    6232         1000 :                   new_name = gimple_build (&stmts, BIT_FIELD_REF,
    6233              :                                            compute_type, vec_temp,
    6234              :                                            bitsize, bitpos);
    6235         1000 :                   if (slp_reduc)
    6236              :                     {
    6237              :                       /* In SLP we don't need to apply reduction operation, so
    6238              :                          we just collect s' values in SCALAR_RESULTS.  */
    6239          990 :                       new_temp = new_name;
    6240          990 :                       scalar_results.safe_push (new_name);
    6241              :                     }
    6242              :                   else
    6243           10 :                     new_temp = gimple_build (&stmts, code, compute_type,
    6244              :                                              new_name, new_temp);
    6245              :                 }
    6246              :             }
    6247              : 
    6248              :           /* The only case where we need to reduce scalar results in a SLP
    6249              :              reduction, is unrolling.  If the size of SCALAR_RESULTS is
    6250              :              greater than GROUP_SIZE, we reduce them combining elements modulo
    6251              :              GROUP_SIZE.  */
    6252          269 :           if (slp_reduc)
    6253              :             {
    6254          259 :               tree res, first_res, new_res;
    6255              : 
    6256              :               /* Reduce multiple scalar results in case of SLP unrolling.  */
    6257          921 :               for (j = group_size; scalar_results.iterate (j, &res);
    6258              :                    j++)
    6259              :                 {
    6260          662 :                   first_res = scalar_results[j % group_size];
    6261          662 :                   new_res = gimple_build (&stmts, code, compute_type,
    6262              :                                           first_res, res);
    6263          662 :                   scalar_results[j % group_size] = new_res;
    6264              :                 }
    6265          259 :               scalar_results.truncate (group_size);
    6266         1260 :               for (k = 0; k < group_size; k++)
    6267         1484 :                 scalar_results[k] = gimple_convert (&stmts, scalar_type,
    6268          742 :                                                     scalar_results[k]);
    6269              :             }
    6270              :           else
    6271              :             {
    6272              :               /* Reduction chain - we have one scalar to keep in
    6273              :                  SCALAR_RESULTS.  */
    6274           10 :               new_temp = gimple_convert (&stmts, scalar_type, new_temp);
    6275           10 :               scalar_results.safe_push (new_temp);
    6276              :             }
    6277              : 
    6278          269 :           gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6279              :         }
    6280              : 
    6281         1826 :       if ((VECT_REDUC_INFO_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
    6282            0 :           && induc_val)
    6283              :         {
    6284              :           /* Earlier we set the initial value to be a vector if induc_val
    6285              :              values.  Check the result and if it is induc_val then replace
    6286              :              with the original initial value, unless induc_val is
    6287              :              the same as initial_def already.  */
    6288            0 :           tree zcompare = make_ssa_name (boolean_type_node);
    6289            0 :           epilog_stmt = gimple_build_assign (zcompare, EQ_EXPR,
    6290            0 :                                              scalar_results[0], induc_val);
    6291            0 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    6292            0 :           tree initial_def = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info)[0];
    6293            0 :           tree tmp = make_ssa_name (new_scalar_dest);
    6294            0 :           epilog_stmt = gimple_build_assign (tmp, COND_EXPR, zcompare,
    6295            0 :                                              initial_def, scalar_results[0]);
    6296            0 :           gsi_insert_before (&exit_gsi, epilog_stmt, GSI_SAME_STMT);
    6297            0 :           scalar_results[0] = tmp;
    6298              :         }
    6299              :     }
    6300              : 
    6301              :   /* 2.5 Adjust the final result by the initial value of the reduction
    6302              :          variable. (When such adjustment is not needed, then
    6303              :          'adjustment_def' is zero).  For example, if code is PLUS we create:
    6304              :          new_temp = loop_exit_def + adjustment_def  */
    6305              : 
    6306        22244 :   if (adjustment_def)
    6307              :     {
    6308        15584 :       gcc_assert (!slp_reduc || group_size == 1);
    6309        15584 :       gimple_seq stmts = NULL;
    6310        15584 :       if (double_reduc)
    6311              :         {
    6312            0 :           gcc_assert (VECTOR_TYPE_P (TREE_TYPE (adjustment_def)));
    6313            0 :           adjustment_def = gimple_convert (&stmts, vectype, adjustment_def);
    6314            0 :           new_temp = gimple_build (&stmts, code, vectype,
    6315            0 :                                    reduc_inputs[0], adjustment_def);
    6316              :         }
    6317              :       else
    6318              :         {
    6319        15584 :           new_temp = scalar_results[0];
    6320        15584 :           gcc_assert (TREE_CODE (TREE_TYPE (adjustment_def)) != VECTOR_TYPE);
    6321        15584 :           adjustment_def = gimple_convert (&stmts, TREE_TYPE (compute_vectype),
    6322              :                                            adjustment_def);
    6323        15584 :           new_temp = gimple_convert (&stmts, TREE_TYPE (compute_vectype),
    6324              :                                      new_temp);
    6325        15584 :           new_temp = gimple_build (&stmts, code, TREE_TYPE (compute_vectype),
    6326              :                                    new_temp, adjustment_def);
    6327        15584 :           new_temp = gimple_convert (&stmts, scalar_type, new_temp);
    6328              :         }
    6329              : 
    6330        15584 :       epilog_stmt = gimple_seq_last_stmt (stmts);
    6331        15584 :       gsi_insert_seq_before (&exit_gsi, stmts, GSI_SAME_STMT);
    6332        15584 :       scalar_results[0] = new_temp;
    6333              :     }
    6334              : 
    6335              :   /* Record this operation if it could be reused by the epilogue loop.  */
    6336        22244 :   if (VECT_REDUC_INFO_TYPE (reduc_info) == TREE_CODE_REDUCTION
    6337        22244 :       && reduc_inputs.length () == 1)
    6338        22030 :     loop_vinfo->reusable_accumulators.put (scalar_results[0],
    6339              :                                            { orig_reduc_input, reduc_info });
    6340              : 
    6341              :   /* 2.6  Handle the loop-exit phis.  Replace the uses of scalar loop-exit
    6342              :           phis with new adjusted scalar results, i.e., replace use <s_out0>
    6343              :           with use <s_out4>.
    6344              : 
    6345              :      Transform:
    6346              :         loop_exit:
    6347              :           s_out0 = phi <s_loop>                 # (scalar) EXIT_PHI
    6348              :           v_out1 = phi <VECT_DEF>               # NEW_EXIT_PHI
    6349              :           v_out2 = reduce <v_out1>
    6350              :           s_out3 = extract_field <v_out2, 0>
    6351              :           s_out4 = adjust_result <s_out3>
    6352              :           use <s_out0>
    6353              :           use <s_out0>
    6354              : 
    6355              :      into:
    6356              : 
    6357              :         loop_exit:
    6358              :           s_out0 = phi <s_loop>                 # (scalar) EXIT_PHI
    6359              :           v_out1 = phi <VECT_DEF>               # NEW_EXIT_PHI
    6360              :           v_out2 = reduce <v_out1>
    6361              :           s_out3 = extract_field <v_out2, 0>
    6362              :           s_out4 = adjust_result <s_out3>
    6363              :           use <s_out4>
    6364              :           use <s_out4> */
    6365              : 
    6366        44488 :   gcc_assert (live_out_stmts.size () == scalar_results.length ());
    6367        22244 :   auto_vec<gimple *> phis;
    6368        44971 :   for (k = 0; k < live_out_stmts.size (); k++)
    6369              :     {
    6370        22727 :       stmt_vec_info scalar_stmt_info = vect_orig_stmt (live_out_stmts[k]);
    6371        22727 :       tree scalar_dest = gimple_get_lhs (scalar_stmt_info->stmt);
    6372              : 
    6373              :       /* Find the loop-closed-use at the loop exit of the original scalar
    6374              :          result.  (The reduction result is expected to have two immediate uses,
    6375              :          one at the latch block, and one at the loop exit).  Note with
    6376              :          early break we can have two exit blocks, so pick the correct PHI.  */
    6377        91984 :       FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
    6378        69257 :         if (!is_gimple_debug (USE_STMT (use_p))
    6379        69257 :             && !flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
    6380              :           {
    6381        22726 :             gcc_assert (is_a <gphi *> (USE_STMT (use_p)));
    6382        22726 :             if (gimple_bb (USE_STMT (use_p)) == loop_exit->dest)
    6383        22712 :               phis.safe_push (USE_STMT (use_p));
    6384        22727 :           }
    6385              : 
    6386        45439 :       FOR_EACH_VEC_ELT (phis, i, exit_phi)
    6387              :         {
    6388              :           /* Replace the uses:  */
    6389        22712 :           orig_name = PHI_RESULT (exit_phi);
    6390              : 
    6391              :           /* Look for a single use at the target of the skip edge.  */
    6392        22712 :           if (unify_with_main_loop_p)
    6393              :             {
    6394           30 :               use_operand_p use_p;
    6395           30 :               gimple *user;
    6396           30 :               if (!single_imm_use (orig_name, &use_p, &user))
    6397            0 :                 gcc_unreachable ();
    6398           30 :               orig_name = gimple_get_lhs (user);
    6399              :             }
    6400              : 
    6401        22712 :           scalar_result = scalar_results[k];
    6402        61214 :           FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, orig_name)
    6403              :             {
    6404        38502 :               gphi *use_phi = dyn_cast <gphi *> (use_stmt);
    6405        77048 :               FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
    6406              :                 {
    6407        38524 :                   if (use_phi
    6408        38524 :                       && (phi_arg_edge_from_use (use_p)->flags & EDGE_ABNORMAL))
    6409              :                     {
    6410            0 :                       gcc_assert (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_name));
    6411            0 :                       SSA_NAME_OCCURS_IN_ABNORMAL_PHI (scalar_result) = 1;
    6412              :                     }
    6413        38524 :                   SET_USE (use_p, scalar_result);
    6414              :                 }
    6415        38502 :               update_stmt (use_stmt);
    6416        22712 :             }
    6417              :         }
    6418              : 
    6419        22727 :       phis.truncate (0);
    6420              :     }
    6421        22244 : }
    6422              : 
    6423              : /* Return a vector of type VECTYPE that is equal to the vector select
    6424              :    operation "MASK ? VEC : IDENTITY".  Insert the select statements
    6425              :    before GSI.  */
    6426              : 
    6427              : static tree
    6428            9 : merge_with_identity (gimple_stmt_iterator *gsi, tree mask, tree vectype,
    6429              :                      tree vec, tree identity)
    6430              : {
    6431            9 :   tree cond = make_temp_ssa_name (vectype, NULL, "cond");
    6432            9 :   gimple *new_stmt = gimple_build_assign (cond, VEC_COND_EXPR,
    6433              :                                           mask, vec, identity);
    6434            9 :   gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
    6435            9 :   return cond;
    6436              : }
    6437              : 
    6438              : /* Successively apply CODE to each element of VECTOR_RHS, in left-to-right
    6439              :    order, starting with LHS.  Insert the extraction statements before GSI and
    6440              :    associate the new scalar SSA names with variable SCALAR_DEST.
    6441              :    If MASK is nonzero mask the input and then operate on it unconditionally.
    6442              :    Return the SSA name for the result.  */
    6443              : 
    6444              : static tree
    6445         1372 : vect_expand_fold_left (gimple_stmt_iterator *gsi, tree scalar_dest,
    6446              :                        tree_code code, tree lhs, tree vector_rhs,
    6447              :                        tree mask)
    6448              : {
    6449         1372 :   tree vectype = TREE_TYPE (vector_rhs);
    6450         1372 :   tree scalar_type = TREE_TYPE (vectype);
    6451         1372 :   tree bitsize = TYPE_SIZE (scalar_type);
    6452         1372 :   unsigned HOST_WIDE_INT vec_size_in_bits = tree_to_uhwi (TYPE_SIZE (vectype));
    6453         1372 :   unsigned HOST_WIDE_INT element_bitsize = tree_to_uhwi (bitsize);
    6454              : 
    6455              :   /* Re-create a VEC_COND_EXPR to mask the input here in order to be able
    6456              :      to perform an unconditional element-wise reduction of it.  */
    6457         1372 :   if (mask)
    6458              :     {
    6459           76 :       tree masked_vector_rhs = make_temp_ssa_name (vectype, NULL,
    6460              :                                                    "masked_vector_rhs");
    6461           76 :       tree neutral_op = neutral_op_for_reduction (scalar_type, code, NULL_TREE,
    6462              :                                                   false);
    6463           76 :       tree vector_identity = build_vector_from_val (vectype, neutral_op);
    6464           76 :       gassign *select = gimple_build_assign (masked_vector_rhs, VEC_COND_EXPR,
    6465              :                                              mask, vector_rhs, vector_identity);
    6466           76 :       gsi_insert_before (gsi, select, GSI_SAME_STMT);
    6467           76 :       vector_rhs = masked_vector_rhs;
    6468              :     }
    6469              : 
    6470         1372 :   for (unsigned HOST_WIDE_INT bit_offset = 0;
    6471         5644 :        bit_offset < vec_size_in_bits;
    6472         4272 :        bit_offset += element_bitsize)
    6473              :     {
    6474         4272 :       tree bitpos = bitsize_int (bit_offset);
    6475         4272 :       tree rhs = build3 (BIT_FIELD_REF, scalar_type, vector_rhs,
    6476              :                          bitsize, bitpos);
    6477              : 
    6478         4272 :       gassign *stmt = gimple_build_assign (scalar_dest, rhs);
    6479         4272 :       rhs = make_ssa_name (scalar_dest, stmt);
    6480         4272 :       gimple_assign_set_lhs (stmt, rhs);
    6481         4272 :       gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
    6482              :       /* Fold the vector extract, combining it with a previous reversal
    6483              :          like seen in PR90579.  */
    6484         4272 :       auto gsi2 = gsi_for_stmt (stmt);
    6485         4272 :       if (fold_stmt (&gsi2, follow_all_ssa_edges))
    6486          450 :         update_stmt (gsi_stmt  (gsi2));
    6487              : 
    6488         4272 :       stmt = gimple_build_assign (scalar_dest, code, lhs, rhs);
    6489         4272 :       tree new_name = make_ssa_name (scalar_dest, stmt);
    6490         4272 :       gimple_assign_set_lhs (stmt, new_name);
    6491         4272 :       gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
    6492         4272 :       lhs = new_name;
    6493              :     }
    6494         1372 :   return lhs;
    6495              : }
    6496              : 
    6497              : /* Get a masked internal function equivalent to REDUC_FN.  VECTYPE_IN is the
    6498              :    type of the vector input.  */
    6499              : 
    6500              : static internal_fn
    6501         3337 : get_masked_reduction_fn (internal_fn reduc_fn, tree vectype_in)
    6502              : {
    6503         3337 :   internal_fn mask_reduc_fn;
    6504         3337 :   internal_fn mask_len_reduc_fn;
    6505              : 
    6506         3337 :   switch (reduc_fn)
    6507              :     {
    6508            0 :     case IFN_FOLD_LEFT_PLUS:
    6509            0 :       mask_reduc_fn = IFN_MASK_FOLD_LEFT_PLUS;
    6510            0 :       mask_len_reduc_fn = IFN_MASK_LEN_FOLD_LEFT_PLUS;
    6511            0 :       break;
    6512              : 
    6513              :     default:
    6514              :       return IFN_LAST;
    6515              :     }
    6516              : 
    6517            0 :   if (direct_internal_fn_supported_p (mask_reduc_fn, vectype_in,
    6518              :                                       OPTIMIZE_FOR_SPEED))
    6519              :     return mask_reduc_fn;
    6520            0 :   if (direct_internal_fn_supported_p (mask_len_reduc_fn, vectype_in,
    6521              :                                       OPTIMIZE_FOR_SPEED))
    6522            0 :     return mask_len_reduc_fn;
    6523              :   return IFN_LAST;
    6524              : }
    6525              : 
    6526              : /* Perform an in-order reduction (FOLD_LEFT_REDUCTION).  STMT_INFO is the
    6527              :    statement that sets the live-out value.  REDUC_DEF_STMT is the phi
    6528              :    statement.  CODE is the operation performed by STMT_INFO and OPS are
    6529              :    its scalar operands.  REDUC_INDEX is the index of the operand in
    6530              :    OPS that is set by REDUC_DEF_STMT.  REDUC_FN is the function that
    6531              :    implements in-order reduction, or IFN_LAST if we should open-code it.
    6532              :    VECTYPE_IN is the type of the vector input.  MASKS specifies the masks
    6533              :    that should be used to control the operation in a fully-masked loop.  */
    6534              : 
    6535              : static bool
    6536         1021 : vectorize_fold_left_reduction (loop_vec_info loop_vinfo,
    6537              :                                stmt_vec_info stmt_info,
    6538              :                                gimple_stmt_iterator *gsi, slp_tree slp_node,
    6539              :                                code_helper code, internal_fn reduc_fn,
    6540              :                                int num_ops, tree vectype_in, int reduc_index)
    6541              : {
    6542         1021 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    6543         1021 :   tree vectype_out = SLP_TREE_VECTYPE (slp_node);
    6544         1021 :   internal_fn mask_reduc_fn = get_masked_reduction_fn (reduc_fn, vectype_in);
    6545              : 
    6546         1021 :   gcc_assert (!nested_in_vect_loop_p (loop, stmt_info));
    6547              : 
    6548         1021 :   bool is_cond_op = false;
    6549         1021 :   if (!code.is_tree_code ())
    6550              :     {
    6551           29 :       code = conditional_internal_fn_code (internal_fn (code));
    6552           29 :       gcc_assert (code != ERROR_MARK);
    6553              :       is_cond_op = true;
    6554              :     }
    6555              : 
    6556         1021 :   gcc_assert (TREE_CODE_LENGTH (tree_code (code)) == binary_op);
    6557              : 
    6558         1021 :   gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (vectype_out),
    6559              :                         TYPE_VECTOR_SUBPARTS (vectype_in)));
    6560              : 
    6561              :   /* ???  We should, when transforming the cycle PHI, record the existing
    6562              :      scalar def as vector def so looking up the vector def works.  This
    6563              :      would also allow generalizing this for reduction paths of length > 1
    6564              :      and/or SLP reductions.  */
    6565         1021 :   slp_tree reduc_node = SLP_TREE_CHILDREN (slp_node)[reduc_index];
    6566         1021 :   stmt_vec_info reduc_var_def = SLP_TREE_SCALAR_STMTS (reduc_node)[0];
    6567         1021 :   tree reduc_var = gimple_get_lhs (STMT_VINFO_STMT (reduc_var_def));
    6568              : 
    6569              :   /* The operands either come from a binary operation or an IFN_COND operation.
    6570              :      The former is a gimple assign with binary rhs and the latter is a
    6571              :      gimple call with four arguments.  */
    6572         1021 :   gcc_assert (num_ops == 2 || num_ops == 4);
    6573              : 
    6574         1021 :   auto_vec<tree> vec_oprnds0, vec_opmask;
    6575         1021 :   vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[(is_cond_op ? 2 : 0)
    6576         1021 :                                                   + (1 - reduc_index)],
    6577              :                                                   &vec_oprnds0);
    6578              :   /* For an IFN_COND_OP we also need the vector mask operand.  */
    6579         1021 :   if (is_cond_op)
    6580           29 :     vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[0], &vec_opmask);
    6581              : 
    6582              :   /* The transform below relies on preserving the original scalar PHI
    6583              :      and its latch def which we replace.  So work backwards from there.  */
    6584         1021 :   tree scalar_dest
    6585         1021 :     = gimple_phi_arg_def_from_edge (as_a <gphi *> (STMT_VINFO_STMT
    6586              :                                                      (reduc_var_def)),
    6587         1021 :                                     loop_latch_edge (loop));
    6588         1021 :   stmt_vec_info scalar_dest_def_info
    6589         1021 :     = vect_stmt_to_vectorize (loop_vinfo->lookup_def (scalar_dest));
    6590         1021 :   tree scalar_type = TREE_TYPE (scalar_dest);
    6591              : 
    6592         1021 :   int vec_num = vec_oprnds0.length ();
    6593         1021 :   tree vec_elem_type = TREE_TYPE (vectype_out);
    6594         1021 :   gcc_checking_assert (useless_type_conversion_p (scalar_type, vec_elem_type));
    6595              : 
    6596         1021 :   tree vector_identity = NULL_TREE;
    6597         1021 :   if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
    6598              :     {
    6599            2 :       vector_identity = build_zero_cst (vectype_out);
    6600            2 :       if (!HONOR_SIGNED_ZEROS (vectype_out))
    6601              :         ;
    6602              :       else
    6603              :         {
    6604            2 :           gcc_assert (!HONOR_SIGN_DEPENDENT_ROUNDING (vectype_out));
    6605            2 :           vector_identity = const_unop (NEGATE_EXPR, vectype_out,
    6606              :                                         vector_identity);
    6607              :         }
    6608              :     }
    6609              : 
    6610         1021 :   tree scalar_dest_var = vect_create_destination_var (scalar_dest, NULL);
    6611         1021 :   int i;
    6612         1021 :   tree def0;
    6613         3414 :   FOR_EACH_VEC_ELT (vec_oprnds0, i, def0)
    6614              :     {
    6615         1372 :       gimple *new_stmt;
    6616         1372 :       tree mask = NULL_TREE;
    6617         1372 :       tree len = NULL_TREE;
    6618         1372 :       tree bias = NULL_TREE;
    6619         1372 :       if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
    6620              :         {
    6621            9 :           tree loop_mask
    6622            9 :             = vect_get_mask (loop_vinfo, gsi, vec_num, vectype_in, i);
    6623            9 :           if (is_cond_op)
    6624            9 :             mask = prepare_vec_mask (loop_vinfo, TREE_TYPE (loop_mask),
    6625            9 :                                      loop_mask, vec_opmask[i], gsi);
    6626              :           else
    6627              :             mask = loop_mask;
    6628              :         }
    6629         1363 :       else if (is_cond_op)
    6630           67 :         mask = vec_opmask[i];
    6631         1372 :       if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
    6632              :         {
    6633            0 :           len
    6634            0 :             = vect_get_len (loop_vinfo, gsi, vec_num, vectype_in, i, 1, false);
    6635            0 :           signed char biasval = LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo);
    6636            0 :           bias = build_int_cst (intQI_type_node, biasval);
    6637            0 :           if (!is_cond_op)
    6638            0 :             mask = build_minus_one_cst (truth_type_for (vectype_in));
    6639              :         }
    6640              : 
    6641              :       /* Handle MINUS by adding the negative.  */
    6642         1372 :       if (reduc_fn != IFN_LAST && code == MINUS_EXPR)
    6643              :         {
    6644            0 :           tree negated = make_ssa_name (vectype_out);
    6645            0 :           new_stmt = gimple_build_assign (negated, NEGATE_EXPR, def0);
    6646            0 :           gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
    6647            0 :           def0 = negated;
    6648              :         }
    6649              : 
    6650            9 :       if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
    6651         1381 :           && mask && mask_reduc_fn == IFN_LAST)
    6652            9 :         def0 = merge_with_identity (gsi, mask, vectype_out, def0,
    6653              :                                     vector_identity);
    6654              : 
    6655              :       /* On the first iteration the input is simply the scalar phi
    6656              :          result, and for subsequent iterations it is the output of
    6657              :          the preceding operation.  */
    6658         1372 :       if (reduc_fn != IFN_LAST || (mask && mask_reduc_fn != IFN_LAST))
    6659              :         {
    6660            0 :           if (mask && len && mask_reduc_fn == IFN_MASK_LEN_FOLD_LEFT_PLUS)
    6661            0 :             new_stmt = gimple_build_call_internal (mask_reduc_fn, 5, reduc_var,
    6662              :                                                    def0, mask, len, bias);
    6663            0 :           else if (mask && mask_reduc_fn == IFN_MASK_FOLD_LEFT_PLUS)
    6664            0 :             new_stmt = gimple_build_call_internal (mask_reduc_fn, 3, reduc_var,
    6665              :                                                    def0, mask);
    6666              :           else
    6667            0 :             new_stmt = gimple_build_call_internal (reduc_fn, 2, reduc_var,
    6668              :                                                    def0);
    6669              :           /* For chained SLP reductions the output of the previous reduction
    6670              :              operation serves as the input of the next. For the final statement
    6671              :              the output cannot be a temporary - we reuse the original
    6672              :              scalar destination of the last statement.  */
    6673            0 :           if (i != vec_num - 1)
    6674              :             {
    6675            0 :               gimple_set_lhs (new_stmt, scalar_dest_var);
    6676            0 :               reduc_var = make_ssa_name (scalar_dest_var, new_stmt);
    6677            0 :               gimple_set_lhs (new_stmt, reduc_var);
    6678              :             }
    6679              :         }
    6680              :       else
    6681              :         {
    6682         1372 :           reduc_var = vect_expand_fold_left (gsi, scalar_dest_var,
    6683              :                                              tree_code (code), reduc_var, def0,
    6684              :                                              mask);
    6685         1372 :           new_stmt = SSA_NAME_DEF_STMT (reduc_var);
    6686              :           /* Remove the statement, so that we can use the same code paths
    6687              :              as for statements that we've just created.  */
    6688         1372 :           gimple_stmt_iterator tmp_gsi = gsi_for_stmt (new_stmt);
    6689         1372 :           gsi_remove (&tmp_gsi, true);
    6690              :         }
    6691              : 
    6692         1372 :       if (i == vec_num - 1)
    6693              :         {
    6694         1021 :           gimple_set_lhs (new_stmt, scalar_dest);
    6695         1021 :           vect_finish_replace_stmt (loop_vinfo,
    6696              :                                     scalar_dest_def_info,
    6697              :                                     new_stmt);
    6698              :         }
    6699              :       else
    6700          351 :         vect_finish_stmt_generation (loop_vinfo,
    6701              :                                      scalar_dest_def_info,
    6702              :                                      new_stmt, gsi);
    6703              : 
    6704         1372 :       slp_node->push_vec_def (new_stmt);
    6705              :     }
    6706              : 
    6707         1021 :   return true;
    6708         1021 : }
    6709              : 
    6710              : /* Function is_nonwrapping_integer_induction.
    6711              : 
    6712              :    Check if STMT_VINFO (which is part of loop LOOP) both increments and
    6713              :    does not cause overflow.  */
    6714              : 
    6715              : static bool
    6716          414 : is_nonwrapping_integer_induction (stmt_vec_info stmt_vinfo, class loop *loop)
    6717              : {
    6718          414 :   gphi *phi = as_a <gphi *> (stmt_vinfo->stmt);
    6719          414 :   tree base = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (stmt_vinfo);
    6720          414 :   tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_vinfo);
    6721          414 :   tree lhs_type = TREE_TYPE (gimple_phi_result (phi));
    6722          414 :   widest_int ni, max_loop_value, lhs_max;
    6723          414 :   wi::overflow_type overflow = wi::OVF_NONE;
    6724              : 
    6725              :   /* Make sure this is a regular induction.  */
    6726          414 :   if (STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_vinfo) != vect_step_op_add)
    6727              :     return false;
    6728              : 
    6729              :   /* Make sure the loop is integer based.  */
    6730          408 :   if (TREE_CODE (base) != INTEGER_CST
    6731          109 :       || TREE_CODE (step) != INTEGER_CST)
    6732              :     return false;
    6733              : 
    6734              :   /* Check that the max size of the loop will not wrap.  */
    6735              : 
    6736          109 :   if (TYPE_OVERFLOW_UNDEFINED (lhs_type))
    6737              :     return true;
    6738              : 
    6739            8 :   if (! max_stmt_executions (loop, &ni))
    6740              :     return false;
    6741              : 
    6742            8 :   max_loop_value = wi::mul (wi::to_widest (step), ni, TYPE_SIGN (lhs_type),
    6743            8 :                             &overflow);
    6744            8 :   if (overflow)
    6745              :     return false;
    6746              : 
    6747            8 :   max_loop_value = wi::add (wi::to_widest (base), max_loop_value,
    6748           16 :                             TYPE_SIGN (lhs_type), &overflow);
    6749            8 :   if (overflow)
    6750              :     return false;
    6751              : 
    6752            8 :   return (wi::min_precision (max_loop_value, TYPE_SIGN (lhs_type))
    6753            8 :           <= TYPE_PRECISION (lhs_type));
    6754          414 : }
    6755              : 
    6756              : /* Check if masking can be supported by inserting a conditional expression.
    6757              :    CODE is the code for the operation.  COND_FN is the conditional internal
    6758              :    function, if it exists.  VECTYPE_IN is the type of the vector input.  */
    6759              : static bool
    6760         6271 : use_mask_by_cond_expr_p (code_helper code, internal_fn cond_fn,
    6761              :                          tree vectype_in)
    6762              : {
    6763         6271 :   if (cond_fn != IFN_LAST
    6764         6271 :       && direct_internal_fn_supported_p (cond_fn, vectype_in,
    6765              :                                          OPTIMIZE_FOR_SPEED))
    6766              :     return false;
    6767              : 
    6768         4537 :   if (code.is_tree_code ())
    6769         4517 :     switch (tree_code (code))
    6770              :       {
    6771          457 :       case DOT_PROD_EXPR:
    6772          457 :       case SAD_EXPR:
    6773          457 :         return true;
    6774              : 
    6775              :       default:
    6776              :         break;
    6777              :       }
    6778              :   return false;
    6779              : }
    6780              : 
    6781              : /* Insert a conditional expression to enable masked vectorization.  CODE is the
    6782              :    code for the operation.  VOP is the array of operands.  MASK is the loop
    6783              :    mask.  GSI is a statement iterator used to place the new conditional
    6784              :    expression.  */
    6785              : static void
    6786            4 : build_vect_cond_expr (code_helper code, tree vop[3], tree mask,
    6787              :                       gimple_stmt_iterator *gsi)
    6788              : {
    6789            4 :   switch (tree_code (code))
    6790              :     {
    6791            4 :     case DOT_PROD_EXPR:
    6792            4 :       {
    6793            4 :         tree vectype = TREE_TYPE (vop[1]);
    6794            4 :         tree zero = build_zero_cst (vectype);
    6795            4 :         tree masked_op1 = make_temp_ssa_name (vectype, NULL, "masked_op1");
    6796            4 :         gassign *select = gimple_build_assign (masked_op1, VEC_COND_EXPR,
    6797              :                                                mask, vop[1], zero);
    6798            4 :         gsi_insert_before (gsi, select, GSI_SAME_STMT);
    6799            4 :         vop[1] = masked_op1;
    6800            4 :         break;
    6801              :       }
    6802              : 
    6803            0 :     case SAD_EXPR:
    6804            0 :       {
    6805            0 :         tree vectype = TREE_TYPE (vop[1]);
    6806            0 :         tree masked_op1 = make_temp_ssa_name (vectype, NULL, "masked_op1");
    6807            0 :         gassign *select = gimple_build_assign (masked_op1, VEC_COND_EXPR,
    6808              :                                                mask, vop[1], vop[0]);
    6809            0 :         gsi_insert_before (gsi, select, GSI_SAME_STMT);
    6810            0 :         vop[1] = masked_op1;
    6811            0 :         break;
    6812              :       }
    6813              : 
    6814            0 :     default:
    6815            0 :       gcc_unreachable ();
    6816              :     }
    6817            4 : }
    6818              : 
    6819              : /* Given an operation with CODE in loop reduction path whose reduction PHI is
    6820              :    specified by REDUC_INFO, the operation has TYPE of scalar result, and its
    6821              :    input vectype is represented by VECTYPE_IN. The vectype of vectorized result
    6822              :    may be different from VECTYPE_IN, either in base type or vectype lanes,
    6823              :    lane-reducing operation is the case.  This function check if it is possible,
    6824              :    and how to perform partial vectorization on the operation in the context
    6825              :    of LOOP_VINFO.  It returns whether partial vectors are possible.  The
    6826              :    caller is responsible to register the usage appropriately.  */
    6827              : 
    6828              : static bool
    6829         4428 : vect_reduction_update_partial_vector_usage (loop_vec_info loop_vinfo,
    6830              :                                             vect_reduc_info reduc_info,
    6831              :                                             code_helper code, tree type,
    6832              :                                             tree vectype_in)
    6833              : {
    6834         4428 :   enum vect_reduction_type reduc_type = VECT_REDUC_INFO_TYPE (reduc_info);
    6835         4428 :   internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    6836         4428 :   internal_fn cond_fn
    6837         1157 :     = ((code.is_internal_fn ()
    6838         1157 :         && internal_fn_mask_index ((internal_fn)code) != -1)
    6839         4428 :        ? (internal_fn)code : get_conditional_internal_fn (code, type));
    6840              : 
    6841         4428 :   if (reduc_type != FOLD_LEFT_REDUCTION
    6842         3498 :       && !use_mask_by_cond_expr_p (code, cond_fn, vectype_in)
    6843         7762 :       && (cond_fn == IFN_LAST
    6844         3334 :           || !direct_internal_fn_supported_p (cond_fn, vectype_in,
    6845              :                                               OPTIMIZE_FOR_SPEED)))
    6846              :     {
    6847         2112 :       if (dump_enabled_p ())
    6848          104 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6849              :                          "can't operate on partial vectors because"
    6850              :                          " no conditional operation is available.\n");
    6851         2112 :       LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    6852              :     }
    6853         2316 :   else if (reduc_type == FOLD_LEFT_REDUCTION
    6854         2316 :            && reduc_fn == IFN_LAST
    6855         2316 :            && !expand_vec_cond_expr_p (vectype_in, truth_type_for (vectype_in)))
    6856              :     {
    6857            0 :       if (dump_enabled_p ())
    6858            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6859              :                         "can't operate on partial vectors because"
    6860              :                         " no conditional operation is available.\n");
    6861            0 :       LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    6862              :     }
    6863         2316 :   else if (reduc_type == FOLD_LEFT_REDUCTION
    6864          930 :            && internal_fn_mask_index (reduc_fn) == -1
    6865          930 :            && FLOAT_TYPE_P (vectype_in)
    6866         3246 :            && HONOR_SIGN_DEPENDENT_ROUNDING (vectype_in))
    6867              :     {
    6868            0 :       if (dump_enabled_p ())
    6869            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6870              :                          "can't operate on partial vectors because"
    6871              :                          " signed zeros cannot be preserved.\n");
    6872            0 :       LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
    6873              :     }
    6874              :   else
    6875              :     return true;
    6876              :   return false;
    6877              : }
    6878              : 
    6879              : /* Check if STMT_INFO is a lane-reducing operation that can be vectorized in
    6880              :    the context of LOOP_VINFO, and vector cost will be recorded in COST_VEC,
    6881              :    and the analysis is for slp if SLP_NODE is not NULL.
    6882              : 
    6883              :    For a lane-reducing operation, the loop reduction path that it lies in,
    6884              :    may contain normal operation, or other lane-reducing operation of different
    6885              :    input type size, an example as:
    6886              : 
    6887              :      int sum = 0;
    6888              :      for (i)
    6889              :        {
    6890              :          ...
    6891              :          sum += d0[i] * d1[i];       // dot-prod <vector(16) char>
    6892              :          sum += w[i];                // widen-sum <vector(16) char>
    6893              :          sum += abs(s0[i] - s1[i]);  // sad <vector(8) short>
    6894              :          sum += n[i];                // normal <vector(4) int>
    6895              :          ...
    6896              :        }
    6897              : 
    6898              :    Vectorization factor is essentially determined by operation whose input
    6899              :    vectype has the most lanes ("vector(16) char" in the example), while we
    6900              :    need to choose input vectype with the least lanes ("vector(4) int" in the
    6901              :    example) to determine effective number of vector reduction PHIs.  */
    6902              : 
    6903              : bool
    6904       407863 : vectorizable_lane_reducing (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
    6905              :                             slp_tree slp_node, stmt_vector_for_cost *cost_vec)
    6906              : {
    6907       407863 :   gimple *stmt = stmt_info->stmt;
    6908              : 
    6909       407863 :   if (!lane_reducing_stmt_p (stmt))
    6910              :     return false;
    6911              : 
    6912          788 :   tree type = TREE_TYPE (gimple_assign_lhs (stmt));
    6913              : 
    6914          788 :   if (!INTEGRAL_TYPE_P (type) && !SCALAR_FLOAT_TYPE_P (type))
    6915              :     return false;
    6916              : 
    6917              :   /* Do not try to vectorize bit-precision reductions.  */
    6918          788 :   if (!type_has_mode_precision_p (type))
    6919              :     return false;
    6920              : 
    6921          788 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    6922              : 
    6923              :   /* TODO: Support lane-reducing operation that does not directly participate
    6924              :      in loop reduction.  */
    6925          788 :   if (!reduc_info)
    6926              :     return false;
    6927              : 
    6928              :   /* Lane-reducing pattern inside any inner loop of LOOP_VINFO is not
    6929              :      recognized.  */
    6930          788 :   gcc_assert (!nested_in_vect_loop_p (LOOP_VINFO_LOOP (loop_vinfo), stmt_info));
    6931          788 :   gcc_assert (VECT_REDUC_INFO_TYPE (reduc_info) == TREE_CODE_REDUCTION);
    6932              : 
    6933         3152 :   for (int i = 0; i < (int) gimple_num_ops (stmt) - 1; i++)
    6934              :     {
    6935         2364 :       slp_tree slp_op;
    6936         2364 :       tree op;
    6937         2364 :       tree vectype;
    6938         2364 :       enum vect_def_type dt;
    6939              : 
    6940         2364 :       if (!vect_is_simple_use (loop_vinfo, slp_node, i, &op,
    6941              :                                &slp_op, &dt, &vectype))
    6942              :         {
    6943            0 :           if (dump_enabled_p ())
    6944            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6945              :                              "use not simple.\n");
    6946            0 :           return false;
    6947              :         }
    6948              : 
    6949         2364 :       if (!vectype)
    6950              :         {
    6951           15 :           vectype = get_vectype_for_scalar_type (loop_vinfo, TREE_TYPE (op),
    6952              :                                                  slp_op);
    6953           15 :           if (!vectype)
    6954              :             return false;
    6955              :         }
    6956              : 
    6957         2364 :       if (!vect_maybe_update_slp_op_vectype (slp_op, vectype))
    6958              :         {
    6959            0 :           if (dump_enabled_p ())
    6960            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6961              :                              "incompatible vector types for invariants\n");
    6962              :           return false;
    6963              :         }
    6964              : 
    6965         2364 :       if (i == STMT_VINFO_REDUC_IDX (stmt_info))
    6966          788 :         continue;
    6967              : 
    6968              :       /* There should be at most one cycle def in the stmt.  */
    6969         1576 :       if (VECTORIZABLE_CYCLE_DEF (dt))
    6970              :         return false;
    6971              :     }
    6972              : 
    6973          788 :   slp_tree node_in = SLP_TREE_CHILDREN (slp_node)[0];
    6974          788 :   tree vectype_in = SLP_TREE_VECTYPE (node_in);
    6975          788 :   gcc_assert (vectype_in);
    6976              : 
    6977              :   /* Compute number of effective vector statements for costing from the
    6978              :      number of input lanes allow for excess lanes in the last input vector.  */
    6979          788 :   unsigned int ncopies_for_cost, excess_elts;
    6980          788 :   if (!vect_get_num_copies_for_invariant (loop_vinfo, node_in,
    6981              :                                           &ncopies_for_cost,
    6982              :                                           &excess_elts))
    6983              :     {
    6984            0 :       if (dump_enabled_p ())
    6985            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    6986              :                          "incompatible vector types for invariants\n");
    6987              :       return false;
    6988              :     }
    6989          788 :   gcc_assert (ncopies_for_cost >= 1);
    6990              : 
    6991          788 :   if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
    6992              :     {
    6993          164 :       enum tree_code code = gimple_assign_rhs_code (stmt);
    6994          164 :       if (vect_reduction_update_partial_vector_usage (loop_vinfo, reduc_info,
    6995          164 :                                                       code, type, vectype_in))
    6996              :         {
    6997          164 :           internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    6998          164 :           internal_fn mask_reduc_fn
    6999          164 :             = get_masked_reduction_fn (reduc_fn, vectype_in);
    7000          164 :           if (mask_reduc_fn == IFN_MASK_LEN_FOLD_LEFT_PLUS)
    7001            0 :             vect_record_len (loop_vinfo, ncopies_for_cost, vectype_in, 1);
    7002              :           else
    7003          164 :             vect_record_mask (loop_vinfo, ncopies_for_cost, vectype_in,
    7004              :                               NULL_TREE);
    7005              :         }
    7006              :     }
    7007              : 
    7008          788 :   if (vect_is_emulated_mixed_dot_prod (slp_node))
    7009              :     {
    7010              :       /* We need extra two invariants: one that contains the minimum signed
    7011              :          value and one that contains half of its negative.  */
    7012           15 :       int prologue_stmts = 2;
    7013           15 :       unsigned cost = record_stmt_cost (cost_vec, prologue_stmts,
    7014              :                                         scalar_to_vec, slp_node, 0,
    7015              :                                         vect_prologue);
    7016           15 :       if (dump_enabled_p ())
    7017            0 :         dump_printf (MSG_NOTE, "vectorizable_lane_reducing: "
    7018              :                      "extra prologue_cost = %d .\n", cost);
    7019              : 
    7020              :       /* Three dot-products and a subtraction.  */
    7021           15 :       ncopies_for_cost *= 4;
    7022              :     }
    7023              : 
    7024          788 :   record_stmt_cost (cost_vec, (int) ncopies_for_cost, vector_stmt, slp_node,
    7025              :                     0, vect_body);
    7026              : 
    7027              :   /* Transform via vect_transform_reduction.  */
    7028          788 :   SLP_TREE_TYPE (slp_node) = reduc_vec_info_type;
    7029          788 :   return true;
    7030              : }
    7031              : 
    7032              : /* Function vectorizable_reduction.
    7033              : 
    7034              :    Check if STMT_INFO performs a reduction operation that can be vectorized.
    7035              :    If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
    7036              :    stmt to replace it, put it in VEC_STMT, and insert it at GSI.
    7037              :    Return true if STMT_INFO is vectorizable in this way.
    7038              : 
    7039              :    This function also handles reduction idioms (patterns) that have been
    7040              :    recognized in advance during vect_pattern_recog.  In this case, STMT_INFO
    7041              :    may be of this form:
    7042              :      X = pattern_expr (arg0, arg1, ..., X)
    7043              :    and its STMT_VINFO_RELATED_STMT points to the last stmt in the original
    7044              :    sequence that had been detected and replaced by the pattern-stmt
    7045              :    (STMT_INFO).
    7046              : 
    7047              :    This function also handles reduction of condition expressions, for example:
    7048              :      for (int i = 0; i < N; i++)
    7049              :        if (a[i] < value)
    7050              :          last = a[i];
    7051              :    This is handled by vectorising the loop and creating an additional vector
    7052              :    containing the loop indexes for which "a[i] < value" was true.  In the
    7053              :    function epilogue this is reduced to a single max value and then used to
    7054              :    index into the vector of results.
    7055              : 
    7056              :    In some cases of reduction patterns, the type of the reduction variable X is
    7057              :    different than the type of the other arguments of STMT_INFO.
    7058              :    In such cases, the vectype that is used when transforming STMT_INFO into
    7059              :    a vector stmt is different than the vectype that is used to determine the
    7060              :    vectorization factor, because it consists of a different number of elements
    7061              :    than the actual number of elements that are being operated upon in parallel.
    7062              : 
    7063              :    For example, consider an accumulation of shorts into an int accumulator.
    7064              :    On some targets it's possible to vectorize this pattern operating on 8
    7065              :    shorts at a time (hence, the vectype for purposes of determining the
    7066              :    vectorization factor should be V8HI); on the other hand, the vectype that
    7067              :    is used to create the vector form is actually V4SI (the type of the result).
    7068              : 
    7069              :    Upon entry to this function, STMT_VINFO_VECTYPE records the vectype that
    7070              :    indicates what is the actual level of parallelism (V8HI in the example), so
    7071              :    that the right vectorization factor would be derived.  This vectype
    7072              :    corresponds to the type of arguments to the reduction stmt, and should *NOT*
    7073              :    be used to create the vectorized stmt.  The right vectype for the vectorized
    7074              :    stmt is obtained from the type of the result X:
    7075              :       get_vectype_for_scalar_type (vinfo, TREE_TYPE (X))
    7076              : 
    7077              :    This means that, contrary to "regular" reductions (or "regular" stmts in
    7078              :    general), the following equation:
    7079              :       STMT_VINFO_VECTYPE == get_vectype_for_scalar_type (vinfo, TREE_TYPE (X))
    7080              :    does *NOT* necessarily hold for reduction patterns.  */
    7081              : 
    7082              : bool
    7083       407075 : vectorizable_reduction (loop_vec_info loop_vinfo,
    7084              :                         stmt_vec_info stmt_info, slp_tree slp_node,
    7085              :                         slp_instance slp_node_instance,
    7086              :                         stmt_vector_for_cost *cost_vec)
    7087              : {
    7088       407075 :   tree vectype_in = NULL_TREE;
    7089       407075 :   enum vect_def_type cond_reduc_dt = vect_unknown_def_type;
    7090       407075 :   stmt_vec_info cond_stmt_vinfo = NULL;
    7091       407075 :   int i;
    7092       407075 :   int ncopies;
    7093       407075 :   bool single_defuse_cycle = false;
    7094       407075 :   tree cr_index_scalar_type = NULL_TREE, cr_index_vector_type = NULL_TREE;
    7095       407075 :   tree cond_reduc_val = NULL_TREE;
    7096              : 
    7097              :   /* Make sure it was already recognized as a reduction computation.  */
    7098       407075 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_reduction_def
    7099              :       && STMT_VINFO_DEF_TYPE (stmt_info) != vect_double_reduction_def
    7100       407075 :       && STMT_VINFO_DEF_TYPE (stmt_info) != vect_nested_cycle)
    7101              :     return false;
    7102              : 
    7103              :   /* The reduction meta.  */
    7104        83910 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    7105              : 
    7106        83910 :   if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle)
    7107              :     {
    7108         1402 :       gcc_assert (is_a <gphi *> (stmt_info->stmt));
    7109              :       /* We eventually need to set a vector type on invariant arguments.  */
    7110              :       unsigned j;
    7111              :       slp_tree child;
    7112         4198 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
    7113         2804 :         if (!vect_maybe_update_slp_op_vectype (child,
    7114              :                                                SLP_TREE_VECTYPE (slp_node)))
    7115              :           {
    7116            0 :             if (dump_enabled_p ())
    7117            0 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7118              :                                "incompatible vector types for "
    7119              :                                "invariants\n");
    7120              :             return false;
    7121              :           }
    7122         2804 :         else if (SLP_TREE_DEF_TYPE (child) == vect_internal_def
    7123         2804 :                  && !useless_type_conversion_p (SLP_TREE_VECTYPE (slp_node),
    7124              :                                                 SLP_TREE_VECTYPE (child)))
    7125              :           {
    7126              :             /* With bools we can have mask and non-mask precision vectors
    7127              :                or different non-mask precisions.  while pattern recog is
    7128              :                supposed to guarantee consistency here, we do not have
    7129              :                pattern stmts for PHIs (PR123316).
    7130              :                Deal with that here instead of ICEing later.  */
    7131            8 :             if (dump_enabled_p ())
    7132            8 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7133              :                                "incompatible vector type setup from "
    7134              :                                "bool pattern detection\n");
    7135              :             return false;
    7136              :           }
    7137              :       /* Analysis for double-reduction is done on the outer
    7138              :          loop PHI, nested cycles have no further restrictions.  */
    7139         1394 :       SLP_TREE_TYPE (slp_node) = cycle_phi_info_type;
    7140         1394 :       return true;
    7141              :     }
    7142              : 
    7143        82508 :   if (!is_a <gphi *> (stmt_info->stmt))
    7144              :     {
    7145         8506 :       gcc_assert (STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def);
    7146         8506 :       SLP_TREE_TYPE (slp_node) = reduc_vec_info_type;
    7147         8506 :       return true;
    7148              :     }
    7149              : 
    7150        74002 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    7151        74002 :   stmt_vec_info phi_info = stmt_info;
    7152        74002 :   bool double_reduc = false;
    7153        74002 :   if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    7154              :     {
    7155              :       /* We arrive here for both the inner loop LC PHI and the
    7156              :          outer loop PHI.  The latter is what we want to analyze the
    7157              :          reduction with.  The LC PHI is handled by vectorizable_lc_phi.  */
    7158          322 :       if (gimple_bb (stmt_info->stmt) != loop->header)
    7159            0 :         return false;
    7160              : 
    7161              :       /* Set loop and phi_info to the inner loop.  */
    7162          322 :       use_operand_p use_p;
    7163          322 :       gimple *use_stmt;
    7164          322 :       bool res = single_imm_use (gimple_phi_result (stmt_info->stmt),
    7165              :                                  &use_p, &use_stmt);
    7166          322 :       gcc_assert (res);
    7167          322 :       phi_info = loop_vinfo->lookup_stmt (use_stmt);
    7168          322 :       loop = loop->inner;
    7169          322 :       double_reduc = true;
    7170              :     }
    7171              : 
    7172        74002 :   const bool reduc_chain = reduc_info->is_reduc_chain;
    7173        74002 :   slp_node_instance->reduc_phis = slp_node;
    7174              :   /* ???  We're leaving slp_node to point to the PHIs, we only
    7175              :      need it to get at the number of vector stmts which wasn't
    7176              :      yet initialized for the instance root.  */
    7177              : 
    7178              :   /* PHIs should not participate in patterns.  */
    7179        74002 :   gcc_assert (!STMT_VINFO_RELATED_STMT (phi_info));
    7180        74002 :   gphi *reduc_def_phi = as_a <gphi *> (phi_info->stmt);
    7181              : 
    7182              :   /* Verify following REDUC_IDX from the latch def leads us back to the PHI
    7183              :      and compute the reduction chain length.  Discover the real
    7184              :      reduction operation stmt on the way (slp_for_stmt_info).  */
    7185        74002 :   unsigned reduc_chain_length = 0;
    7186        74002 :   stmt_info = NULL;
    7187        74002 :   slp_tree slp_for_stmt_info = NULL;
    7188        74002 :   slp_tree vdef_slp = slp_node_instance->root;
    7189       162136 :   while (vdef_slp != slp_node)
    7190              :     {
    7191        89226 :       int reduc_idx = SLP_TREE_REDUC_IDX (vdef_slp);
    7192        89226 :       if (reduc_idx == -1)
    7193              :         {
    7194         1084 :           if (dump_enabled_p ())
    7195            7 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7196              :                              "reduction chain broken by patterns.\n");
    7197         1092 :           return false;
    7198              :         }
    7199        88142 :       stmt_vec_info vdef = SLP_TREE_REPRESENTATIVE (vdef_slp);
    7200        88142 :       if (is_a <gphi *> (vdef->stmt))
    7201              :         {
    7202          644 :           vdef_slp = SLP_TREE_CHILDREN (vdef_slp)[reduc_idx];
    7203              :           /* Do not count PHIs towards the chain length.  */
    7204          644 :           continue;
    7205              :         }
    7206        87498 :       gimple_match_op op;
    7207        87498 :       if (!gimple_extract_op (vdef->stmt, &op))
    7208              :         {
    7209            0 :           if (dump_enabled_p ())
    7210            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7211              :                              "reduction chain includes unsupported"
    7212              :                              " statement type.\n");
    7213              :           return false;
    7214              :         }
    7215        87498 :       if (CONVERT_EXPR_CODE_P (op.code))
    7216              :         {
    7217         5392 :           if (!tree_nop_conversion_p (op.type, TREE_TYPE (op.ops[0])))
    7218              :             {
    7219            8 :               if (dump_enabled_p ())
    7220            8 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7221              :                                  "conversion in the reduction chain.\n");
    7222              :               return false;
    7223              :             }
    7224         5384 :           vdef_slp = SLP_TREE_CHILDREN (vdef_slp)[0];
    7225              :         }
    7226              :       else
    7227              :         {
    7228              :           /* First non-conversion stmt.  */
    7229        82106 :           if (!slp_for_stmt_info)
    7230        72898 :             slp_for_stmt_info = vdef_slp;
    7231              : 
    7232        82106 :           if (lane_reducing_op_p (op.code))
    7233              :             {
    7234              :               /* The last operand of lane-reducing operation is for
    7235              :                  reduction.  */
    7236          788 :               gcc_assert (reduc_idx > 0 && reduc_idx == (int) op.num_ops - 1);
    7237              : 
    7238          788 :               slp_tree op_node = SLP_TREE_CHILDREN (vdef_slp)[0];
    7239          788 :               tree vectype_op = SLP_TREE_VECTYPE (op_node);
    7240          788 :               tree type_op = TREE_TYPE (op.ops[0]);
    7241          788 :               if (!vectype_op)
    7242              :                 {
    7243           18 :                   vectype_op = get_vectype_for_scalar_type (loop_vinfo,
    7244              :                                                             type_op);
    7245           18 :                   if (!vectype_op
    7246           18 :                       || !vect_maybe_update_slp_op_vectype (op_node,
    7247              :                                                             vectype_op))
    7248              :                     return false;
    7249              :                 }
    7250              : 
    7251              :               /* To accommodate lane-reducing operations of mixed input
    7252              :                  vectypes, choose input vectype with the least lanes for the
    7253              :                  reduction PHI statement, which would result in the most
    7254              :                  ncopies for vectorized reduction results.  */
    7255          788 :               if (!vectype_in
    7256          788 :                   || (GET_MODE_SIZE (SCALAR_TYPE_MODE (TREE_TYPE (vectype_in)))
    7257          817 :                        < GET_MODE_SIZE (SCALAR_TYPE_MODE (type_op))))
    7258              :                 vectype_in = vectype_op;
    7259              :             }
    7260        81318 :           else if (!vectype_in)
    7261        72139 :             vectype_in = SLP_TREE_VECTYPE (slp_node);
    7262        82106 :           vdef_slp = SLP_TREE_CHILDREN (vdef_slp)[reduc_idx];
    7263              :         }
    7264        87490 :       reduc_chain_length++;
    7265              :     }
    7266        72910 :   if (!slp_for_stmt_info)
    7267              :     {
    7268           12 :       if (dump_enabled_p ())
    7269           12 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7270              :                          "only noop-conversions in the reduction chain.\n");
    7271              :       return false;
    7272              :     }
    7273        72898 :   stmt_info = SLP_TREE_REPRESENTATIVE (slp_for_stmt_info);
    7274              : 
    7275              :   /* PHIs should not participate in patterns.  */
    7276        72898 :   gcc_assert (!STMT_VINFO_RELATED_STMT (phi_info));
    7277              : 
    7278              :   /* 1. Is vectorizable reduction?  */
    7279              :   /* Not supportable if the reduction variable is used in the loop, unless
    7280              :      it's a reduction chain.  */
    7281        72898 :   if (STMT_VINFO_RELEVANT (stmt_info) > vect_used_in_outer
    7282            0 :       && !reduc_chain)
    7283              :     return false;
    7284              : 
    7285              :   /* Reductions that are not used even in an enclosing outer-loop,
    7286              :      are expected to be "live" (used out of the loop).  */
    7287        72898 :   if (STMT_VINFO_RELEVANT (stmt_info) == vect_unused_in_scope
    7288            0 :       && !STMT_VINFO_LIVE_P (stmt_info))
    7289              :     return false;
    7290              : 
    7291              :   /* 2. Has this been recognized as a reduction pattern?
    7292              : 
    7293              :      Check if STMT represents a pattern that has been recognized
    7294              :      in earlier analysis stages.  For stmts that represent a pattern,
    7295              :      the STMT_VINFO_RELATED_STMT field records the last stmt in
    7296              :      the original sequence that constitutes the pattern.  */
    7297              : 
    7298        72898 :   stmt_vec_info orig_stmt_info = STMT_VINFO_RELATED_STMT (stmt_info);
    7299        72898 :   if (orig_stmt_info)
    7300              :     {
    7301         5163 :       gcc_assert (STMT_VINFO_IN_PATTERN_P (orig_stmt_info));
    7302         5163 :       gcc_assert (!STMT_VINFO_IN_PATTERN_P (stmt_info));
    7303              :     }
    7304              : 
    7305              :   /* 3. Check the operands of the operation.  The first operands are defined
    7306              :         inside the loop body. The last operand is the reduction variable,
    7307              :         which is defined by the loop-header-phi.  */
    7308              : 
    7309        72898 :   tree vectype_out = SLP_TREE_VECTYPE (slp_for_stmt_info);
    7310        72898 :   VECT_REDUC_INFO_VECTYPE (reduc_info) = vectype_out;
    7311              : 
    7312        72898 :   gimple_match_op op;
    7313        72898 :   if (!gimple_extract_op (stmt_info->stmt, &op))
    7314            0 :     gcc_unreachable ();
    7315        72898 :   bool lane_reducing = lane_reducing_op_p (op.code);
    7316              : 
    7317        72898 :   if (!POINTER_TYPE_P (op.type) && !INTEGRAL_TYPE_P (op.type)
    7318        19303 :       && !SCALAR_FLOAT_TYPE_P (op.type))
    7319              :     return false;
    7320              : 
    7321              :   /* Do not try to vectorize bit-precision reductions.  */
    7322        72898 :   if (!type_has_mode_precision_p (op.type)
    7323         1815 :       && op.code != BIT_AND_EXPR
    7324         1685 :       && op.code != BIT_IOR_EXPR
    7325        73390 :       && op.code != BIT_XOR_EXPR)
    7326              :     return false;
    7327              : 
    7328              :   /* Lane-reducing ops also never can be used in a SLP reduction group
    7329              :      since we'll mix lanes belonging to different reductions.  But it's
    7330              :      OK to use them in a reduction chain or when the reduction group
    7331              :      has just one element.  */
    7332        72588 :   if (lane_reducing
    7333        72588 :       && !reduc_chain
    7334          716 :       && SLP_TREE_LANES (slp_node) > 1)
    7335              :     {
    7336            0 :       if (dump_enabled_p ())
    7337            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7338              :                          "lane-reducing reduction in reduction group.\n");
    7339              :       return false;
    7340              :     }
    7341              : 
    7342              :   /* We'll verify the reduction operation only later - avoid
    7343              :      all operations that mismatch on the number of SLP children.  */
    7344       145176 :   if (op.num_ops != SLP_TREE_CHILDREN (slp_for_stmt_info).length ())
    7345              :     {
    7346            0 :       if (dump_enabled_p ())
    7347            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7348              :                          "unsupported reduction operation.\n");
    7349              :       return false;
    7350              :     }
    7351              : 
    7352              :   /* All uses but the last are expected to be defined in the loop.
    7353              :      The last use is the reduction variable.  In case of nested cycle this
    7354              :      assumption is not true: we use reduc_index to record the index of the
    7355              :      reduction variable.  */
    7356        72588 :   slp_tree *slp_op = XALLOCAVEC (slp_tree, op.num_ops);
    7357        72588 :   tree *vectype_op = XALLOCAVEC (tree, op.num_ops);
    7358        72588 :   gcc_assert (op.code != COND_EXPR || !COMPARISON_CLASS_P (op.ops[0]));
    7359       232929 :   for (i = 0; i < (int) op.num_ops; i++)
    7360              :     {
    7361              :       /* The condition of COND_EXPR is checked in vectorizable_condition().  */
    7362       160341 :       if (i == 0 && op.code == COND_EXPR)
    7363        80236 :         continue;
    7364              : 
    7365       159452 :       stmt_vec_info def_stmt_info;
    7366       159452 :       enum vect_def_type dt;
    7367       159452 :       if (!vect_is_simple_use (loop_vinfo, slp_for_stmt_info,
    7368              :                                i, &op.ops[i], &slp_op[i], &dt,
    7369       159452 :                                &vectype_op[i], &def_stmt_info))
    7370              :         {
    7371            0 :           if (dump_enabled_p ())
    7372            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7373              :                              "use not simple.\n");
    7374            0 :           return false;
    7375              :         }
    7376              : 
    7377              :       /* Skip reduction operands, and for an IFN_COND_OP we might hit the
    7378              :          reduction operand twice (once as definition, once as else).  */
    7379       159452 :       if (SLP_TREE_CHILDREN (slp_for_stmt_info)[i]
    7380       318904 :           == SLP_TREE_CHILDREN
    7381       159452 :                (slp_for_stmt_info)[SLP_TREE_REDUC_IDX (slp_for_stmt_info)])
    7382        79347 :         continue;
    7383              : 
    7384              :       /* There should be only one cycle def in the stmt, the one
    7385              :          leading to reduc_def.  */
    7386        80105 :       if (SLP_TREE_CHILDREN (slp_for_stmt_info)[i]->cycle_info.id != -1)
    7387              :         return false;
    7388              : 
    7389        80105 :       if (!vectype_op[i])
    7390         7489 :         vectype_op[i]
    7391         7489 :           = get_vectype_for_scalar_type (loop_vinfo,
    7392         7489 :                                          TREE_TYPE (op.ops[i]), slp_op[i]);
    7393              : 
    7394              :       /* Record how the non-reduction-def value of COND_EXPR is defined.
    7395              :          ???  For a chain of multiple CONDs we'd have to match them up all.  */
    7396        80105 :       if (op.code == COND_EXPR && reduc_chain_length == 1)
    7397              :         {
    7398          866 :           if (dt == vect_constant_def)
    7399              :             {
    7400          124 :               cond_reduc_dt = dt;
    7401          124 :               cond_reduc_val = op.ops[i];
    7402              :             }
    7403          742 :           else if (dt == vect_induction_def
    7404          414 :                    && def_stmt_info
    7405         1156 :                    && is_nonwrapping_integer_induction (def_stmt_info, loop))
    7406              :             {
    7407          109 :               cond_reduc_dt = dt;
    7408          109 :               cond_stmt_vinfo = def_stmt_info;
    7409              :             }
    7410              :         }
    7411              :     }
    7412              : 
    7413        72588 :   enum vect_reduction_type reduction_type = VECT_REDUC_INFO_TYPE (reduc_info);
    7414              :   /* If we have a condition reduction, see if we can simplify it further.  */
    7415        72588 :   if (reduction_type == COND_REDUCTION)
    7416              :     {
    7417          877 :       if (SLP_TREE_LANES (slp_node) != 1)
    7418              :         return false;
    7419              : 
    7420              :       /* When the condition uses the reduction value in the condition, fail.  */
    7421          853 :       if (SLP_TREE_REDUC_IDX (slp_node) == 0)
    7422              :         {
    7423            0 :           if (dump_enabled_p ())
    7424            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7425              :                              "condition depends on previous iteration\n");
    7426              :           return false;
    7427              :         }
    7428              : 
    7429          853 :       if (reduc_chain_length == 1
    7430          853 :           && (direct_internal_fn_supported_p (IFN_FOLD_EXTRACT_LAST, vectype_in,
    7431              :                                               OPTIMIZE_FOR_SPEED)
    7432          830 :               || direct_internal_fn_supported_p (IFN_LEN_FOLD_EXTRACT_LAST,
    7433              :                                                  vectype_in,
    7434              :                                                  OPTIMIZE_FOR_SPEED)))
    7435              :         {
    7436            0 :           if (dump_enabled_p ())
    7437            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7438              :                              "optimizing condition reduction with"
    7439              :                              " FOLD_EXTRACT_LAST.\n");
    7440            0 :           VECT_REDUC_INFO_TYPE (reduc_info) = EXTRACT_LAST_REDUCTION;
    7441              :         }
    7442          853 :       else if (cond_reduc_dt == vect_induction_def)
    7443              :         {
    7444          109 :           tree base
    7445              :             = STMT_VINFO_LOOP_PHI_EVOLUTION_BASE_UNCHANGED (cond_stmt_vinfo);
    7446          109 :           tree step = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (cond_stmt_vinfo);
    7447              : 
    7448          109 :           gcc_assert (TREE_CODE (base) == INTEGER_CST
    7449              :                       && TREE_CODE (step) == INTEGER_CST);
    7450          109 :           cond_reduc_val = NULL_TREE;
    7451          109 :           enum tree_code cond_reduc_op_code = ERROR_MARK;
    7452          109 :           tree res = PHI_RESULT (STMT_VINFO_STMT (cond_stmt_vinfo));
    7453          109 :           if (!types_compatible_p (TREE_TYPE (res), TREE_TYPE (base)))
    7454              :             ;
    7455              :           /* Find a suitable value, for MAX_EXPR below base, for MIN_EXPR
    7456              :              above base; punt if base is the minimum value of the type for
    7457              :              MAX_EXPR or maximum value of the type for MIN_EXPR for now.  */
    7458           97 :           else if (tree_int_cst_sgn (step) == -1)
    7459              :             {
    7460           18 :               cond_reduc_op_code = MIN_EXPR;
    7461           18 :               if (tree_int_cst_sgn (base) == -1)
    7462            0 :                 cond_reduc_val = build_int_cst (TREE_TYPE (base), 0);
    7463           18 :               else if (tree_int_cst_lt (base,
    7464           18 :                                         TYPE_MAX_VALUE (TREE_TYPE (base))))
    7465           18 :                 cond_reduc_val
    7466           18 :                   = int_const_binop (PLUS_EXPR, base, integer_one_node);
    7467              :             }
    7468              :           else
    7469              :             {
    7470           79 :               cond_reduc_op_code = MAX_EXPR;
    7471           79 :               if (tree_int_cst_sgn (base) == 1)
    7472            0 :                 cond_reduc_val = build_int_cst (TREE_TYPE (base), 0);
    7473           79 :               else if (tree_int_cst_lt (TYPE_MIN_VALUE (TREE_TYPE (base)),
    7474              :                                         base))
    7475           79 :                 cond_reduc_val
    7476           79 :                   = int_const_binop (MINUS_EXPR, base, integer_one_node);
    7477              :             }
    7478           97 :           if (cond_reduc_val)
    7479              :             {
    7480           97 :               if (dump_enabled_p ())
    7481           61 :                 dump_printf_loc (MSG_NOTE, vect_location,
    7482              :                                  "condition expression based on "
    7483              :                                  "integer induction.\n");
    7484           97 :               VECT_REDUC_INFO_CODE (reduc_info) = cond_reduc_op_code;
    7485           97 :               VECT_REDUC_INFO_INDUC_COND_INITIAL_VAL (reduc_info)
    7486           97 :                 = cond_reduc_val;
    7487           97 :               VECT_REDUC_INFO_TYPE (reduc_info) = INTEGER_INDUC_COND_REDUCTION;
    7488              :             }
    7489              :         }
    7490          744 :       else if (cond_reduc_dt == vect_constant_def)
    7491              :         {
    7492          114 :           enum vect_def_type cond_initial_dt;
    7493          114 :           tree cond_initial_val = vect_phi_initial_value (reduc_def_phi);
    7494          114 :           vect_is_simple_use (cond_initial_val, loop_vinfo, &cond_initial_dt);
    7495          114 :           if (cond_initial_dt == vect_constant_def
    7496          145 :               && types_compatible_p (TREE_TYPE (cond_initial_val),
    7497           31 :                                      TREE_TYPE (cond_reduc_val)))
    7498              :             {
    7499           31 :               tree lt, gt;
    7500           31 :               enum tree_code cond_reduc_code = ERROR_MARK;
    7501           31 :               if ((lt = fold_binary (LT_EXPR, boolean_type_node,
    7502              :                                      cond_initial_val, cond_reduc_val))
    7503           31 :                   && integer_onep (lt))
    7504              :                 cond_reduc_code = MAX_EXPR;
    7505           13 :               else if ((gt = fold_binary (GT_EXPR, boolean_type_node,
    7506              :                                           cond_initial_val, cond_reduc_val))
    7507           13 :                        && integer_onep (gt))
    7508              :                 cond_reduc_code = MIN_EXPR;
    7509              :               if (cond_reduc_code != ERROR_MARK)
    7510              :                 {
    7511           25 :                   if (dump_enabled_p ())
    7512           16 :                     dump_printf_loc (MSG_NOTE, vect_location,
    7513              :                                      "condition expression based on "
    7514              :                                      "compile time constant.\n");
    7515              :                   /* Record reduction code at analysis stage.  */
    7516           25 :                   VECT_REDUC_INFO_CODE (reduc_info) = cond_reduc_code;
    7517           25 :                   VECT_REDUC_INFO_TYPE (reduc_info) = CONST_COND_REDUCTION;
    7518              :                 }
    7519              :             }
    7520              :         }
    7521              :     }
    7522              : 
    7523        72564 :   if (STMT_VINFO_LIVE_P (phi_info))
    7524              :     return false;
    7525              : 
    7526        72564 :   ncopies = vect_get_num_copies (loop_vinfo, slp_node);
    7527              : 
    7528        72564 :   gcc_assert (ncopies >= 1);
    7529              : 
    7530        72564 :   poly_uint64 nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
    7531              : 
    7532              :   /* 4.2. Check support for the epilog operation.
    7533              : 
    7534              :           If STMT represents a reduction pattern, then the type of the
    7535              :           reduction variable may be different than the type of the rest
    7536              :           of the arguments.  For example, consider the case of accumulation
    7537              :           of shorts into an int accumulator; The original code:
    7538              :                         S1: int_a = (int) short_a;
    7539              :           orig_stmt->   S2: int_acc = plus <int_a ,int_acc>;
    7540              : 
    7541              :           was replaced with:
    7542              :                         STMT: int_acc = widen_sum <short_a, int_acc>
    7543              : 
    7544              :           This means that:
    7545              :           1. The tree-code that is used to create the vector operation in the
    7546              :              epilog code (that reduces the partial results) is not the
    7547              :              tree-code of STMT, but is rather the tree-code of the original
    7548              :              stmt from the pattern that STMT is replacing.  I.e, in the example
    7549              :              above we want to use 'widen_sum' in the loop, but 'plus' in the
    7550              :              epilog.
    7551              :           2. The type (mode) we use to check available target support
    7552              :              for the vector operation to be created in the *epilog*, is
    7553              :              determined by the type of the reduction variable (in the example
    7554              :              above we'd check this: optab_handler (plus_optab, vect_int_mode])).
    7555              :              However the type (mode) we use to check available target support
    7556              :              for the vector operation to be created *inside the loop*, is
    7557              :              determined by the type of the other arguments to STMT (in the
    7558              :              example we'd check this: optab_handler (widen_sum_optab,
    7559              :              vect_short_mode)).
    7560              : 
    7561              :           This is contrary to "regular" reductions, in which the types of all
    7562              :           the arguments are the same as the type of the reduction variable.
    7563              :           For "regular" reductions we can therefore use the same vector type
    7564              :           (and also the same tree-code) when generating the epilog code and
    7565              :           when generating the code inside the loop.  */
    7566              : 
    7567        72564 :   code_helper orig_code = VECT_REDUC_INFO_CODE (reduc_info);
    7568              : 
    7569              :   /* If conversion might have created a conditional operation like
    7570              :      IFN_COND_ADD already.  Use the internal code for the following checks.  */
    7571        72564 :   if (orig_code.is_internal_fn ())
    7572              :     {
    7573         6835 :       tree_code new_code = conditional_internal_fn_code (internal_fn (orig_code));
    7574         6835 :       orig_code = new_code != ERROR_MARK ? new_code : orig_code;
    7575              :     }
    7576              : 
    7577        72564 :   VECT_REDUC_INFO_CODE (reduc_info) = orig_code;
    7578              : 
    7579        72564 :   reduction_type = VECT_REDUC_INFO_TYPE (reduc_info);
    7580        72564 :   if (reduction_type == TREE_CODE_REDUCTION)
    7581              :     {
    7582              :       /* Check whether it's ok to change the order of the computation.
    7583              :          Generally, when vectorizing a reduction we change the order of the
    7584              :          computation.  This may change the behavior of the program in some
    7585              :          cases, so we need to check that this is ok.  One exception is when
    7586              :          vectorizing an outer-loop: the inner-loop is executed sequentially,
    7587              :          and therefore vectorizing reductions in the inner-loop during
    7588              :          outer-loop vectorization is safe.  Likewise when we are vectorizing
    7589              :          a series of reductions using SLP and the VF is one the reductions
    7590              :          are performed in scalar order.  */
    7591        71711 :       if (!reduc_chain
    7592        71711 :           && known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), 1u))
    7593              :         ;
    7594        71535 :       else if (needs_fold_left_reduction_p (op.type, orig_code))
    7595              :         {
    7596              :           /* When vectorizing a reduction chain w/o SLP the reduction PHI
    7597              :              is not directly used in stmt.  */
    7598         5773 :           if (reduc_chain_length != 1)
    7599              :             {
    7600          105 :               if (dump_enabled_p ())
    7601           28 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7602              :                                  "in-order reduction chain without SLP.\n");
    7603              :               return false;
    7604              :             }
    7605              :           /* Code generation doesn't support function calls other
    7606              :              than .COND_*.  */
    7607         5668 :           if (!op.code.is_tree_code ()
    7608         5856 :               && !(op.code.is_internal_fn ()
    7609           94 :                    && conditional_internal_fn_code (internal_fn (op.code))
    7610              :                         != ERROR_MARK))
    7611              :             {
    7612           18 :               if (dump_enabled_p ())
    7613           16 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7614              :                                  "in-order reduction chain operation not "
    7615              :                                  "supported.\n");
    7616              :               return false;
    7617              :             }
    7618         5650 :           VECT_REDUC_INFO_TYPE (reduc_info)
    7619         5650 :             = reduction_type = FOLD_LEFT_REDUCTION;
    7620              :         }
    7621        65762 :       else if (!commutative_binary_op_p (orig_code, op.type)
    7622        65762 :                || !associative_binary_op_p (orig_code, op.type))
    7623              :         {
    7624          180 :           if (dump_enabled_p ())
    7625           28 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7626              :                             "reduction: not commutative/associative\n");
    7627              :           return false;
    7628              :         }
    7629              :     }
    7630              : 
    7631         5650 :   if ((reduction_type == COND_REDUCTION
    7632              :        || reduction_type == INTEGER_INDUC_COND_REDUCTION
    7633              :        || reduction_type == CONST_COND_REDUCTION
    7634        66611 :        || reduction_type == EXTRACT_LAST_REDUCTION)
    7635          853 :       && ncopies > 1)
    7636              :     {
    7637          276 :       if (dump_enabled_p ())
    7638           60 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7639              :                          "multiple types in condition reduction.\n");
    7640              :       return false;
    7641              :     }
    7642              : 
    7643              :   /* See if we can convert a mask vector to a corresponding bool data vector
    7644              :      to perform the epilogue reduction.  */
    7645        71985 :   tree alt_vectype_out = NULL_TREE;
    7646        71985 :   if (VECTOR_BOOLEAN_TYPE_P (vectype_out))
    7647              :     {
    7648         1195 :       alt_vectype_out
    7649         2390 :         = get_related_vectype_for_scalar_type (loop_vinfo->vector_mode,
    7650         1195 :                                                TREE_TYPE (vectype_out),
    7651              :                                                TYPE_VECTOR_SUBPARTS
    7652              :                                                  (vectype_out));
    7653         1195 :       if (!alt_vectype_out
    7654         1195 :           || maybe_ne (TYPE_VECTOR_SUBPARTS (alt_vectype_out),
    7655         2390 :                        TYPE_VECTOR_SUBPARTS (vectype_out))
    7656         2390 :           || !expand_vec_cond_expr_p (alt_vectype_out, vectype_out))
    7657              :         alt_vectype_out = NULL_TREE;
    7658              :     }
    7659              : 
    7660        71985 :   internal_fn reduc_fn = IFN_LAST;
    7661        71985 :   if (reduction_type == TREE_CODE_REDUCTION
    7662        71985 :       || reduction_type == FOLD_LEFT_REDUCTION
    7663              :       || reduction_type == INTEGER_INDUC_COND_REDUCTION
    7664          577 :       || reduction_type == CONST_COND_REDUCTION)
    7665              :     {
    7666        65872 :       if (reduction_type == FOLD_LEFT_REDUCTION
    7667        76355 :           ? fold_left_reduction_fn (orig_code, &reduc_fn)
    7668        65872 :           : reduction_fn_for_scalar_code (orig_code, &reduc_fn))
    7669              :         {
    7670        70819 :           internal_fn sbool_fn = IFN_LAST;
    7671        70819 :           if (reduc_fn == IFN_LAST)
    7672              :             ;
    7673        68663 :           else if ((!VECTOR_BOOLEAN_TYPE_P (vectype_out)
    7674         1195 :                     || (GET_MODE_CLASS (TYPE_MODE (vectype_out))
    7675              :                         == MODE_VECTOR_BOOL))
    7676       136131 :                    && direct_internal_fn_supported_p (reduc_fn, vectype_out,
    7677              :                                                       OPTIMIZE_FOR_SPEED))
    7678              :             ;
    7679        19154 :           else if (VECTOR_BOOLEAN_TYPE_P (vectype_out)
    7680         1195 :                    && sbool_reduction_fn_for_fn (reduc_fn, &sbool_fn)
    7681        20349 :                    && direct_internal_fn_supported_p (sbool_fn, vectype_out,
    7682              :                                                       OPTIMIZE_FOR_SPEED))
    7683          131 :             reduc_fn = sbool_fn;
    7684        19023 :           else if (reduction_type != FOLD_LEFT_REDUCTION
    7685        19023 :                    && alt_vectype_out
    7686        19023 :                    && direct_internal_fn_supported_p (reduc_fn, alt_vectype_out,
    7687              :                                                       OPTIMIZE_FOR_SPEED))
    7688          813 :             VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info) = alt_vectype_out;
    7689              :           else
    7690              :             {
    7691        18210 :               if (dump_enabled_p ())
    7692          969 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7693              :                                  "reduc op not supported by target.\n");
    7694              : 
    7695        18210 :               reduc_fn = IFN_LAST;
    7696              :             }
    7697              :         }
    7698              :       else
    7699              :         {
    7700          703 :           if (dump_enabled_p ())
    7701           48 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7702              :                              "no reduc code for scalar code.\n");
    7703              : 
    7704              :           return false;
    7705              :         }
    7706        70819 :       if (reduc_fn == IFN_LAST
    7707        70819 :           && VECTOR_BOOLEAN_TYPE_P (vectype_out))
    7708              :         {
    7709          251 :           if (!alt_vectype_out)
    7710              :             {
    7711           12 :               if (dump_enabled_p ())
    7712            8 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7713              :                                  "cannot turn mask into bool data vector for "
    7714              :                                  "reduction epilogue.\n");
    7715              :               return false;
    7716              :             }
    7717          239 :           VECT_REDUC_INFO_VECTYPE_FOR_MASK (reduc_info) = alt_vectype_out;
    7718              :         }
    7719              :     }
    7720          463 :   else if (reduction_type == COND_REDUCTION)
    7721              :     {
    7722          463 :       int scalar_precision
    7723          463 :         = GET_MODE_PRECISION (SCALAR_TYPE_MODE (op.type));
    7724          463 :       cr_index_scalar_type = make_unsigned_type (scalar_precision);
    7725          463 :       cr_index_vector_type = get_same_sized_vectype (cr_index_scalar_type,
    7726              :                                                 vectype_out);
    7727              : 
    7728          463 :       if (direct_internal_fn_supported_p (IFN_REDUC_MAX, cr_index_vector_type,
    7729              :                                           OPTIMIZE_FOR_SPEED))
    7730           22 :         reduc_fn = IFN_REDUC_MAX;
    7731              :     }
    7732        71270 :   VECT_REDUC_INFO_FN (reduc_info) = reduc_fn;
    7733              : 
    7734        71270 :   if (reduction_type != EXTRACT_LAST_REDUCTION
    7735              :       && reduc_fn == IFN_LAST
    7736              :       && !nunits_out.is_constant ())
    7737              :     {
    7738              :       if (dump_enabled_p ())
    7739              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7740              :                          "missing target support for reduction on"
    7741              :                          " variable-length vectors.\n");
    7742              :       return false;
    7743              :     }
    7744              : 
    7745              :   /* For SLP reductions, see if there is a neutral value we can use.  */
    7746        71270 :   tree neutral_op = NULL_TREE;
    7747        71270 :   tree initial_value = NULL_TREE;
    7748        71270 :   if (reduc_chain)
    7749          536 :     initial_value = vect_phi_initial_value (reduc_def_phi);
    7750        71270 :   neutral_op = neutral_op_for_reduction (TREE_TYPE
    7751              :                                            (gimple_phi_result (reduc_def_phi)),
    7752              :                                          orig_code, initial_value);
    7753        71270 :   VECT_REDUC_INFO_NEUTRAL_OP (reduc_info) = neutral_op;
    7754              : 
    7755        71270 :   if (double_reduc && reduction_type == FOLD_LEFT_REDUCTION)
    7756              :     {
    7757              :       /* We can't support in-order reductions of code such as this:
    7758              : 
    7759              :            for (int i = 0; i < n1; ++i)
    7760              :              for (int j = 0; j < n2; ++j)
    7761              :                l += a[j];
    7762              : 
    7763              :          since GCC effectively transforms the loop when vectorizing:
    7764              : 
    7765              :            for (int i = 0; i < n1 / VF; ++i)
    7766              :              for (int j = 0; j < n2; ++j)
    7767              :                for (int k = 0; k < VF; ++k)
    7768              :                  l += a[j];
    7769              : 
    7770              :          which is a reassociation of the original operation.  */
    7771           66 :       if (dump_enabled_p ())
    7772           20 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7773              :                          "in-order double reduction not supported.\n");
    7774              : 
    7775              :       return false;
    7776              :     }
    7777              : 
    7778        71204 :   if (reduction_type == FOLD_LEFT_REDUCTION
    7779         4881 :       && SLP_TREE_LANES (slp_node) > 1
    7780          194 :       && !reduc_chain)
    7781              :     {
    7782              :       /* We cannot use in-order reductions in this case because there is
    7783              :          an implicit reassociation of the operations involved.  */
    7784           72 :       if (dump_enabled_p ())
    7785            6 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7786              :                          "in-order unchained SLP reductions not supported.\n");
    7787              :       return false;
    7788              :     }
    7789              : 
    7790              :   /* For double reductions, and for SLP reductions with a neutral value,
    7791              :      we construct a variable-length initial vector by loading a vector
    7792              :      full of the neutral value and then shift-and-inserting the start
    7793              :      values into the low-numbered elements.  This is however not needed
    7794              :      when neutral and initial value are equal or we can handle the
    7795              :      initial value via adjustment in the epilogue.  */
    7796        71132 :   if ((double_reduc || neutral_op)
    7797              :       && !nunits_out.is_constant ()
    7798              :       && reduction_type != INTEGER_INDUC_COND_REDUCTION
    7799              :       && !((SLP_TREE_LANES (slp_node) == 1 || reduc_chain)
    7800              :            && neutral_op
    7801              :            && (!double_reduc
    7802              :                || operand_equal_p (neutral_op,
    7803              :                                    vect_phi_initial_value (reduc_def_phi))))
    7804              :       && !direct_internal_fn_supported_p (IFN_VEC_SHL_INSERT,
    7805              :                                           vectype_out, OPTIMIZE_FOR_BOTH))
    7806              :     {
    7807              :       if (dump_enabled_p ())
    7808              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7809              :                          "reduction on variable-length vectors requires"
    7810              :                          " target support for a vector-shift-and-insert"
    7811              :                          " operation.\n");
    7812              :       return false;
    7813              :     }
    7814              : 
    7815              :   /* Check extra constraints for variable-length unchained SLP reductions.  */
    7816        71132 :   if (!reduc_chain
    7817              :       && !nunits_out.is_constant ())
    7818              :     {
    7819              :       /* We checked above that we could build the initial vector when
    7820              :          there's a neutral element value.  Check here for the case in
    7821              :          which each SLP statement has its own initial value and in which
    7822              :          that value needs to be repeated for every instance of the
    7823              :          statement within the initial vector.  */
    7824              :       unsigned int group_size = SLP_TREE_LANES (slp_node);
    7825              :       if (!neutral_op
    7826              :           && !can_duplicate_and_interleave_p (loop_vinfo, group_size,
    7827              :                                               TREE_TYPE (vectype_out)))
    7828              :         {
    7829              :           if (dump_enabled_p ())
    7830              :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7831              :                              "unsupported form of SLP reduction for"
    7832              :                              " variable-length vectors: cannot build"
    7833              :                              " initial vector.\n");
    7834              :           return false;
    7835              :         }
    7836              :       /* The epilogue code relies on the number of elements being a multiple
    7837              :          of the group size.  The duplicate-and-interleave approach to setting
    7838              :          up the initial vector does too.  */
    7839              :       if (!multiple_p (nunits_out, group_size))
    7840              :         {
    7841              :           if (dump_enabled_p ())
    7842              :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7843              :                              "unsupported form of SLP reduction for"
    7844              :                              " variable-length vectors: the vector size"
    7845              :                              " is not a multiple of the number of results.\n");
    7846              :           return false;
    7847              :         }
    7848              :     }
    7849              : 
    7850        71132 :   if (reduction_type == COND_REDUCTION)
    7851              :     {
    7852          463 :       widest_int ni;
    7853              : 
    7854          463 :       if (! max_loop_iterations (loop, &ni))
    7855              :         {
    7856            8 :           if (dump_enabled_p ())
    7857            0 :             dump_printf_loc (MSG_NOTE, vect_location,
    7858              :                              "loop count not known, cannot create cond "
    7859              :                              "reduction.\n");
    7860              :           return false;
    7861              :         }
    7862              :       /* Convert backedges to iterations.  */
    7863          455 :       ni += 1;
    7864              : 
    7865              :       /* The additional index will be the same type as the condition.  Check
    7866              :          that the loop can fit into this less one (because we'll use up the
    7867              :          zero slot for when there are no matches).  */
    7868          455 :       tree max_index = TYPE_MAX_VALUE (cr_index_scalar_type);
    7869          455 :       if (wi::geu_p (ni, wi::to_widest (max_index)))
    7870              :         {
    7871           90 :           if (dump_enabled_p ())
    7872           54 :             dump_printf_loc (MSG_NOTE, vect_location,
    7873              :                              "loop size is greater than data size.\n");
    7874              :           return false;
    7875              :         }
    7876          463 :     }
    7877              : 
    7878              :   /* In case the vectorization factor (VF) is bigger than the number
    7879              :      of elements that we can fit in a vectype (nunits), we have to generate
    7880              :      more than one vector stmt - i.e - we need to "unroll" the
    7881              :      vector stmt by a factor VF/nunits.  For more details see documentation
    7882              :      in vectorizable_operation.  */
    7883              : 
    7884              :   /* If the reduction is used in an outer loop we need to generate
    7885              :      VF intermediate results, like so (e.g. for ncopies=2):
    7886              :         r0 = phi (init, r0)
    7887              :         r1 = phi (init, r1)
    7888              :         r0 = x0 + r0;
    7889              :         r1 = x1 + r1;
    7890              :     (i.e. we generate VF results in 2 registers).
    7891              :     In this case we have a separate def-use cycle for each copy, and therefore
    7892              :     for each copy we get the vector def for the reduction variable from the
    7893              :     respective phi node created for this copy.
    7894              : 
    7895              :     Otherwise (the reduction is unused in the loop nest), we can combine
    7896              :     together intermediate results, like so (e.g. for ncopies=2):
    7897              :         r = phi (init, r)
    7898              :         r = x0 + r;
    7899              :         r = x1 + r;
    7900              :    (i.e. we generate VF/2 results in a single register).
    7901              :    In this case for each copy we get the vector def for the reduction variable
    7902              :    from the vectorized reduction operation generated in the previous iteration.
    7903              : 
    7904              :    This only works when we see both the reduction PHI and its only consumer
    7905              :    in vectorizable_reduction and there are no intermediate stmts
    7906              :    participating.  When unrolling we want each unrolled iteration to have its
    7907              :    own reduction accumulator since one of the main goals of unrolling a
    7908              :    reduction is to reduce the aggregate loop-carried latency.  */
    7909        71034 :   if (ncopies > 1
    7910        71034 :       && !reduc_chain
    7911         8298 :       && SLP_TREE_LANES (slp_node) == 1
    7912         8125 :       && (STMT_VINFO_RELEVANT (stmt_info) <= vect_used_only_live)
    7913         8102 :       && reduc_chain_length == 1
    7914         7696 :       && loop_vinfo->suggested_unroll_factor == 1)
    7915        71034 :     single_defuse_cycle = true;
    7916              : 
    7917        71034 :   if (single_defuse_cycle && !lane_reducing)
    7918              :     {
    7919         6688 :       gcc_assert (op.code != COND_EXPR);
    7920              : 
    7921              :       /* 4. check support for the operation in the loop
    7922              : 
    7923              :          This isn't necessary for the lane reduction codes, since they
    7924              :          can only be produced by pattern matching, and it's up to the
    7925              :          pattern matcher to test for support.  The main reason for
    7926              :          specifically skipping this step is to avoid rechecking whether
    7927              :          mixed-sign dot-products can be implemented using signed
    7928              :          dot-products.  */
    7929         6688 :       machine_mode vec_mode = TYPE_MODE (vectype_in);
    7930         6688 :       if (!directly_supported_p (op.code, vectype_in, optab_vector))
    7931              :         {
    7932         2092 :           if (dump_enabled_p ())
    7933           36 :             dump_printf (MSG_NOTE, "op not supported by target.\n");
    7934         4184 :           if (maybe_ne (GET_MODE_SIZE (vec_mode), UNITS_PER_WORD)
    7935         2092 :               || !vect_can_vectorize_without_simd_p (op.code))
    7936              :             single_defuse_cycle = false;
    7937              :           else
    7938           10 :             if (dump_enabled_p ())
    7939            0 :               dump_printf (MSG_NOTE, "proceeding using word mode.\n");
    7940              :         }
    7941              : 
    7942         6688 :       if (vect_emulated_vector_p (vectype_in)
    7943         6688 :           && !vect_can_vectorize_without_simd_p (op.code))
    7944              :         {
    7945            0 :           if (dump_enabled_p ())
    7946            0 :             dump_printf (MSG_NOTE, "using word mode not possible.\n");
    7947              :           return false;
    7948              :         }
    7949              :     }
    7950        71034 :   if (dump_enabled_p () && single_defuse_cycle)
    7951          760 :     dump_printf_loc (MSG_NOTE, vect_location,
    7952              :                      "using single def-use cycle for reduction by reducing "
    7953              :                      "multiple vectors to one in the loop body\n");
    7954        71034 :   VECT_REDUC_INFO_FORCE_SINGLE_CYCLE (reduc_info) = single_defuse_cycle;
    7955              : 
    7956              :   /* For lane-reducing operation, the below processing related to single
    7957              :      defuse-cycle will be done in its own vectorizable function.  One more
    7958              :      thing to note is that the operation must not be involved in fold-left
    7959              :      reduction.  */
    7960        71034 :   single_defuse_cycle &= !lane_reducing;
    7961              : 
    7962        71034 :   if (single_defuse_cycle || reduction_type == FOLD_LEFT_REDUCTION)
    7963        30283 :     for (i = 0; i < (int) op.num_ops; i++)
    7964        20982 :       if (!vect_maybe_update_slp_op_vectype (slp_op[i], vectype_op[i]))
    7965              :         {
    7966            0 :           if (dump_enabled_p ())
    7967            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    7968              :                              "incompatible vector types for invariants\n");
    7969              :           return false;
    7970              :         }
    7971              : 
    7972        71034 :   vect_model_reduction_cost (loop_vinfo, slp_for_stmt_info, reduc_fn,
    7973              :                              reduction_type, ncopies, cost_vec);
    7974              :   /* Cost the reduction op inside the loop if transformed via
    7975              :      vect_transform_reduction for non-lane-reducing operation.  Otherwise
    7976              :      this is costed by the separate vectorizable_* routines.  */
    7977        71034 :   if (single_defuse_cycle)
    7978         4606 :     record_stmt_cost (cost_vec, ncopies, vector_stmt,
    7979              :                       slp_for_stmt_info, 0, vect_body);
    7980              : 
    7981        71034 :   if (dump_enabled_p ()
    7982        71034 :       && reduction_type == FOLD_LEFT_REDUCTION)
    7983          267 :     dump_printf_loc (MSG_NOTE, vect_location,
    7984              :                      "using an in-order (fold-left) reduction.\n");
    7985        71034 :   SLP_TREE_TYPE (slp_node) = cycle_phi_info_type;
    7986              : 
    7987              :   /* All but single defuse-cycle optimized and fold-left reductions go
    7988              :      through their own vectorizable_* routines.  */
    7989        71034 :   stmt_vec_info tem
    7990        71034 :     = SLP_TREE_REPRESENTATIVE (SLP_INSTANCE_TREE (slp_node_instance));
    7991        71034 :   if (!single_defuse_cycle && reduction_type != FOLD_LEFT_REDUCTION)
    7992        61733 :     STMT_VINFO_DEF_TYPE (tem) = vect_internal_def;
    7993              :   else
    7994              :     {
    7995         9301 :       STMT_VINFO_DEF_TYPE (tem) = vect_reduction_def;
    7996         9301 :       if (LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo)
    7997         9301 :           && vect_reduction_update_partial_vector_usage (loop_vinfo, reduc_info,
    7998              :                                                          op.code, op.type,
    7999              :                                                          vectype_in))
    8000              :         {
    8001         2152 :           internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    8002         2152 :           internal_fn mask_reduc_fn
    8003         2152 :             = get_masked_reduction_fn (reduc_fn, vectype_in);
    8004         2152 :           if (mask_reduc_fn == IFN_MASK_LEN_FOLD_LEFT_PLUS)
    8005            0 :             vect_record_len (loop_vinfo, ncopies, vectype_in, 1);
    8006              :           else
    8007         2152 :             vect_record_mask (loop_vinfo, ncopies, vectype_in, NULL_TREE);
    8008              :         }
    8009              :     }
    8010              :   return true;
    8011              : }
    8012              : 
    8013              : /* STMT_INFO is a dot-product reduction whose multiplication operands
    8014              :    have different signs.  Emit a sequence to emulate the operation
    8015              :    using a series of signed DOT_PROD_EXPRs and return the last
    8016              :    statement generated.  VEC_DEST is the result of the vector operation
    8017              :    and VOP lists its inputs.  */
    8018              : 
    8019              : static gassign *
    8020            4 : vect_emulate_mixed_dot_prod (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
    8021              :                              gimple_stmt_iterator *gsi, tree vec_dest,
    8022              :                              tree vop[3])
    8023              : {
    8024            4 :   tree wide_vectype = signed_type_for (TREE_TYPE (vec_dest));
    8025            4 :   tree narrow_vectype = signed_type_for (TREE_TYPE (vop[0]));
    8026            4 :   tree narrow_elttype = TREE_TYPE (narrow_vectype);
    8027            4 :   gimple *new_stmt;
    8028              : 
    8029              :   /* Make VOP[0] the unsigned operand VOP[1] the signed operand.  */
    8030            4 :   if (!TYPE_UNSIGNED (TREE_TYPE (vop[0])))
    8031            0 :     std::swap (vop[0], vop[1]);
    8032              : 
    8033              :   /* Convert all inputs to signed types.  */
    8034           12 :   for (int i = 1; i < 3; ++i)
    8035            8 :     if (TYPE_UNSIGNED (TREE_TYPE (vop[i])))
    8036              :       {
    8037            0 :         tree tmp = make_ssa_name (signed_type_for (TREE_TYPE (vop[i])));
    8038            0 :         new_stmt = gimple_build_assign (tmp, NOP_EXPR, vop[i]);
    8039            0 :         vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    8040            0 :         vop[i] = tmp;
    8041              :       }
    8042              : 
    8043              :   /* In the comments below we assume 8-bit inputs for simplicity,
    8044              :      but the approach works for any full integer type.  */
    8045              : 
    8046              :   /* Create a vector of -128.  */
    8047            4 :   tree min_narrow_elttype = TYPE_MIN_VALUE (narrow_elttype);
    8048            4 :   tree min_narrow = build_vector_from_val (TREE_TYPE (vop[0]),
    8049            4 :                                            fold_convert
    8050              :                                              (TREE_TYPE (TREE_TYPE (vop[0])),
    8051              :                                               min_narrow_elttype));
    8052              : 
    8053              :   /* Create a vector of 64.  */
    8054            4 :   auto half_wi = wi::lrshift (wi::to_wide (min_narrow_elttype), 1);
    8055            4 :   tree half_narrow = wide_int_to_tree (narrow_elttype, half_wi);
    8056            4 :   half_narrow = build_vector_from_val (narrow_vectype, half_narrow);
    8057              : 
    8058              :   /* Emit: SUB_RES = VOP[0] - 128 in an unsigned type.  */
    8059            4 :   tree sub_res = make_ssa_name (TREE_TYPE (vop[0]));
    8060            4 :   new_stmt = gimple_build_assign (sub_res, PLUS_EXPR, vop[0], min_narrow);
    8061            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    8062              : 
    8063            4 :   vop[0] = make_ssa_name (narrow_vectype);
    8064            4 :   new_stmt = gimple_build_assign (vop[0], VIEW_CONVERT_EXPR,
    8065              :                                   build1 (VIEW_CONVERT_EXPR, narrow_vectype,
    8066              :                                           sub_res));
    8067            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    8068              : 
    8069              :   /* Emit:
    8070              : 
    8071              :        STAGE1 = DOT_PROD_EXPR <VOP[1], 64, VOP[2]>;
    8072              :        STAGE2 = DOT_PROD_EXPR <VOP[1], 64, STAGE1>;
    8073              :        STAGE3 = DOT_PROD_EXPR <SUB_RES, -128, STAGE2>;
    8074              : 
    8075              :      on the basis that x * y == (x - 128) * y + 64 * y + 64 * y
    8076              :      Doing the two 64 * y steps first allows more time to compute x.  */
    8077            4 :   tree stage1 = make_ssa_name (wide_vectype);
    8078            4 :   new_stmt = gimple_build_assign (stage1, DOT_PROD_EXPR,
    8079              :                                   vop[1], half_narrow, vop[2]);
    8080            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    8081              : 
    8082            4 :   tree stage2 = make_ssa_name (wide_vectype);
    8083            4 :   new_stmt = gimple_build_assign (stage2, DOT_PROD_EXPR,
    8084              :                                   vop[1], half_narrow, stage1);
    8085            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    8086              : 
    8087            4 :   tree stage3 = make_ssa_name (wide_vectype);
    8088            4 :   new_stmt = gimple_build_assign (stage3, DOT_PROD_EXPR,
    8089              :                                   vop[0], vop[1], stage2);
    8090            4 :   vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    8091              : 
    8092              :   /* Convert STAGE3 to the reduction type.  */
    8093            4 :   return gimple_build_assign (vec_dest, CONVERT_EXPR, stage3);
    8094            4 : }
    8095              : 
    8096              : /* Transform the definition stmt STMT_INFO of a reduction PHI backedge
    8097              :    value.  */
    8098              : 
    8099              : bool
    8100         2773 : vect_transform_reduction (loop_vec_info loop_vinfo,
    8101              :                           stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
    8102              :                           slp_tree slp_node)
    8103              : {
    8104         2773 :   tree vectype_out = SLP_TREE_VECTYPE (slp_node);
    8105         2773 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    8106              : 
    8107         2773 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    8108              : 
    8109         2773 :   if (nested_in_vect_loop_p (loop, stmt_info))
    8110              :     {
    8111            0 :       loop = loop->inner;
    8112            0 :       gcc_assert (VECT_REDUC_INFO_DEF_TYPE (reduc_info)
    8113              :                   == vect_double_reduction_def);
    8114              :     }
    8115              : 
    8116         2773 :   gimple_match_op op;
    8117         2773 :   if (!gimple_extract_op (stmt_info->stmt, &op))
    8118            0 :     gcc_unreachable ();
    8119              : 
    8120              :   /* All uses but the last are expected to be defined in the loop.
    8121              :      The last use is the reduction variable.  In case of nested cycle this
    8122              :      assumption is not true: we use reduc_index to record the index of the
    8123              :      reduction variable.  */
    8124         2773 :   int reduc_index = SLP_TREE_REDUC_IDX (slp_node);
    8125         2773 :   tree vectype_in = SLP_TREE_VECTYPE (slp_node);
    8126         2773 :   if (lane_reducing_op_p (op.code))
    8127          293 :     vectype_in = SLP_TREE_VECTYPE (SLP_TREE_CHILDREN (slp_node)[0]);
    8128              : 
    8129         2773 :   code_helper code = canonicalize_code (op.code, op.type);
    8130         2773 :   internal_fn cond_fn
    8131          484 :     = ((code.is_internal_fn ()
    8132          484 :         && internal_fn_mask_index ((internal_fn)code) != -1)
    8133         2773 :        ? (internal_fn)code : get_conditional_internal_fn (code, op.type));
    8134              : 
    8135         2773 :   bool mask_by_cond_expr = use_mask_by_cond_expr_p (code, cond_fn, vectype_in);
    8136              : 
    8137              :   /* Transform.  */
    8138         2773 :   tree new_temp = NULL_TREE;
    8139        19411 :   auto_vec<tree> vec_oprnds[3];
    8140              : 
    8141         2773 :   if (dump_enabled_p ())
    8142          824 :     dump_printf_loc (MSG_NOTE, vect_location, "transform reduction.\n");
    8143              : 
    8144              :   /* A binary COND_OP reduction must have the same definition and else
    8145              :      value. */
    8146         3257 :   bool cond_fn_p = code.is_internal_fn ()
    8147          484 :     && conditional_internal_fn_code (internal_fn (code)) != ERROR_MARK;
    8148          482 :   if (cond_fn_p)
    8149              :     {
    8150          482 :       gcc_assert (code == IFN_COND_ADD || code == IFN_COND_SUB
    8151              :                   || code == IFN_COND_MUL || code == IFN_COND_AND
    8152              :                   || code == IFN_COND_IOR || code == IFN_COND_XOR
    8153              :                   || code == IFN_COND_MIN || code == IFN_COND_MAX);
    8154          482 :       gcc_assert (op.num_ops == 4
    8155              :                   && (op.ops[reduc_index]
    8156              :                       == op.ops[internal_fn_else_index ((internal_fn) code)]));
    8157              :     }
    8158              : 
    8159         2773 :   bool masked_loop_p = LOOP_VINFO_FULLY_MASKED_P (loop_vinfo);
    8160              : 
    8161         2773 :   vect_reduction_type reduction_type = VECT_REDUC_INFO_TYPE (reduc_info);
    8162         2773 :   if (reduction_type == FOLD_LEFT_REDUCTION)
    8163              :     {
    8164         1021 :       internal_fn reduc_fn = VECT_REDUC_INFO_FN (reduc_info);
    8165         1021 :       gcc_assert (code.is_tree_code () || cond_fn_p);
    8166         1021 :       return vectorize_fold_left_reduction (loop_vinfo, stmt_info, gsi,
    8167              :                                             slp_node, code, reduc_fn,
    8168         1021 :                                             op.num_ops, vectype_in,
    8169         1021 :                                             reduc_index);
    8170              :     }
    8171              : 
    8172         1752 :   bool single_defuse_cycle = VECT_REDUC_INFO_FORCE_SINGLE_CYCLE (reduc_info);
    8173         1752 :   bool lane_reducing = lane_reducing_op_p (code);
    8174         1459 :   gcc_assert (single_defuse_cycle || lane_reducing);
    8175              : 
    8176         1752 :   if (lane_reducing)
    8177              :     {
    8178              :       /* The last operand of lane-reducing op is for reduction.  */
    8179          293 :       gcc_assert (reduc_index == (int) op.num_ops - 1);
    8180              :     }
    8181              : 
    8182              :   /* Create the destination vector  */
    8183         1752 :   tree scalar_dest = gimple_get_lhs (stmt_info->stmt);
    8184         1752 :   tree vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
    8185              : 
    8186              :   /* Get NCOPIES vector definitions for all operands except the reduction
    8187              :      definition.  */
    8188         1752 :   if (!cond_fn_p)
    8189              :     {
    8190         1299 :       gcc_assert (reduc_index >= 0 && reduc_index <= 2);
    8191         1299 :       vect_get_vec_defs (loop_vinfo, slp_node,
    8192         1299 :                          single_defuse_cycle && reduc_index == 0
    8193         1299 :                          ? NULL_TREE : op.ops[0], &vec_oprnds[0],
    8194         1299 :                          single_defuse_cycle && reduc_index == 1
    8195         1299 :                          ? NULL_TREE : op.ops[1], &vec_oprnds[1],
    8196         1299 :                          op.num_ops == 3
    8197          295 :                          && !(single_defuse_cycle && reduc_index == 2)
    8198         1412 :                          ? op.ops[2] : NULL_TREE, &vec_oprnds[2]);
    8199              :     }
    8200              :   else
    8201              :     {
    8202              :       /* For a conditional operation pass the truth type as mask
    8203              :          vectype.  */
    8204          453 :       gcc_assert (single_defuse_cycle
    8205              :                   && (reduc_index == 1 || reduc_index == 2));
    8206          453 :       vect_get_vec_defs (loop_vinfo, slp_node, op.ops[0],
    8207              :                          &vec_oprnds[0],
    8208            2 :                          reduc_index == 1 ? NULL_TREE : op.ops[1],
    8209              :                          &vec_oprnds[1],
    8210          453 :                          reduc_index == 2 ? NULL_TREE : op.ops[2],
    8211              :                          &vec_oprnds[2]);
    8212              :     }
    8213              : 
    8214              :   /* For single def-use cycles get one copy of the vectorized reduction
    8215              :      definition.  */
    8216         3088 :   unsigned vec_in_num = vec_oprnds[reduc_index == 0 ? 1 : 0].length ();
    8217         1752 :   if (single_defuse_cycle)
    8218              :     {
    8219         1639 :       vect_get_vec_defs (loop_vinfo, slp_node,
    8220         1639 :                          reduc_index == 0 ? op.ops[0] : NULL_TREE,
    8221              :                          &vec_oprnds[0],
    8222         1639 :                          reduc_index == 1 ? op.ops[1] : NULL_TREE,
    8223              :                          &vec_oprnds[1],
    8224         1639 :                          reduc_index == 2 ? op.ops[2] : NULL_TREE,
    8225              :                          &vec_oprnds[2]);
    8226              :     }
    8227          113 :   else if (lane_reducing)
    8228              :     {
    8229              :       /* For normal reduction, consistency between vectorized def/use is
    8230              :          naturally ensured when mapping from scalar statement.  But if lane-
    8231              :          reducing op is involved in reduction, thing would become somewhat
    8232              :          complicated in that the op's result and operand for accumulation are
    8233              :          limited to less lanes than other operands, which certainly causes
    8234              :          def/use mismatch on adjacent statements around the op if do not have
    8235              :          any kind of specific adjustment.  One approach is to refit lane-
    8236              :          reducing op in the way of introducing new trivial pass-through copies
    8237              :          to fix possible def/use gap, so as to make it behave like a normal op.
    8238              :          And vector reduction PHIs are always generated to the full extent, no
    8239              :          matter lane-reducing op exists or not.  If some copies or PHIs are
    8240              :          actually superfluous, they would be cleaned up by passes after
    8241              :          vectorization.  An example for single-lane slp, lane-reducing ops
    8242              :          with mixed input vectypes in a reduction chain, is given as below.
    8243              :          Similarly, this handling is applicable for multiple-lane slp as well.
    8244              : 
    8245              :            int sum = 1;
    8246              :            for (i)
    8247              :              {
    8248              :                sum += d0[i] * d1[i];      // dot-prod <vector(16) char>
    8249              :                sum += w[i];               // widen-sum <vector(16) char>
    8250              :                sum += abs(s0[i] - s1[i]); // sad <vector(8) short>
    8251              :                sum += n[i];               // normal <vector(4) int>
    8252              :              }
    8253              : 
    8254              :          The vector size is 128-bit,vectorization factor is 16.  Reduction
    8255              :          statements would be transformed as:
    8256              : 
    8257              :            vector<4> int sum_v0 = { 0, 0, 0, 1 };
    8258              :            vector<4> int sum_v1 = { 0, 0, 0, 0 };
    8259              :            vector<4> int sum_v2 = { 0, 0, 0, 0 };
    8260              :            vector<4> int sum_v3 = { 0, 0, 0, 0 };
    8261              : 
    8262              :            for (i / 16)
    8263              :              {
    8264              :                sum_v0 = DOT_PROD (d0_v0[i: 0 ~ 15], d1_v0[i: 0 ~ 15], sum_v0);
    8265              :                sum_v1 = sum_v1;  // copy
    8266              :                sum_v2 = sum_v2;  // copy
    8267              :                sum_v3 = sum_v3;  // copy
    8268              : 
    8269              :                sum_v0 = sum_v0;  // copy
    8270              :                sum_v1 = WIDEN_SUM (w_v1[i: 0 ~ 15], sum_v1);
    8271              :                sum_v2 = sum_v2;  // copy
    8272              :                sum_v3 = sum_v3;  // copy
    8273              : 
    8274              :                sum_v0 = sum_v0;  // copy
    8275              :                sum_v1 = SAD (s0_v1[i: 0 ~ 7 ], s1_v1[i: 0 ~ 7 ], sum_v1);
    8276              :                sum_v2 = SAD (s0_v2[i: 8 ~ 15], s1_v2[i: 8 ~ 15], sum_v2);
    8277              :                sum_v3 = sum_v3;  // copy
    8278              : 
    8279              :                sum_v0 += n_v0[i: 0  ~ 3 ];
    8280              :                sum_v1 += n_v1[i: 4  ~ 7 ];
    8281              :                sum_v2 += n_v2[i: 8  ~ 11];
    8282              :                sum_v3 += n_v3[i: 12 ~ 15];
    8283              :              }
    8284              : 
    8285              :          Moreover, for a higher instruction parallelism in final vectorized
    8286              :          loop, it is considered to make those effective vector lane-reducing
    8287              :          ops be distributed evenly among all def-use cycles.  In the above
    8288              :          example, DOT_PROD, WIDEN_SUM and SADs are generated into disparate
    8289              :          cycles, instruction dependency among them could be eliminated.  */
    8290          113 :       unsigned effec_ncopies = vec_oprnds[0].length ();
    8291          113 :       unsigned total_ncopies = vec_oprnds[reduc_index].length ();
    8292              : 
    8293          113 :       gcc_assert (effec_ncopies <= total_ncopies);
    8294              : 
    8295          113 :       if (effec_ncopies < total_ncopies)
    8296              :         {
    8297          312 :           for (unsigned i = 0; i < op.num_ops - 1; i++)
    8298              :             {
    8299          416 :               gcc_assert (vec_oprnds[i].length () == effec_ncopies);
    8300          208 :               vec_oprnds[i].safe_grow_cleared (total_ncopies);
    8301              :             }
    8302              :         }
    8303              : 
    8304          113 :       tree reduc_vectype_in = vectype_in;
    8305          113 :       gcc_assert (reduc_vectype_in);
    8306              :     }
    8307              : 
    8308         1752 :   bool emulated_mixed_dot_prod = vect_is_emulated_mixed_dot_prod (slp_node);
    8309         1752 :   unsigned num = vec_oprnds[reduc_index == 0 ? 1 : 0].length ();
    8310         1752 :   unsigned mask_index = 0;
    8311              : 
    8312         7633 :   for (unsigned i = 0; i < num; ++i)
    8313              :     {
    8314         5881 :       gimple *new_stmt;
    8315         5881 :       tree vop[3] = { vec_oprnds[0][i], vec_oprnds[1][i],
    8316         8242 :                       op.num_ops >= 3 ? vec_oprnds[2][i] : NULL_TREE };
    8317         5881 :       if (!vop[0] || !vop[1])
    8318              :         {
    8319          527 :           tree reduc_vop = vec_oprnds[reduc_index][i];
    8320              : 
    8321              :           /* If could not generate an effective vector statement for current
    8322              :              portion of reduction operand, insert a trivial copy to simply
    8323              :              handle over the operand to other dependent statements.  */
    8324          527 :           gcc_assert (reduc_vop);
    8325              : 
    8326          527 :           if (TREE_CODE (reduc_vop) == SSA_NAME
    8327          527 :               && !SSA_NAME_IS_DEFAULT_DEF (reduc_vop))
    8328          527 :             new_stmt = SSA_NAME_DEF_STMT (reduc_vop);
    8329              :           else
    8330              :             {
    8331            0 :               new_temp = make_ssa_name (vec_dest);
    8332            0 :               new_stmt = gimple_build_assign (new_temp, reduc_vop);
    8333            0 :               vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt,
    8334              :                                            gsi);
    8335              :             }
    8336              :         }
    8337         5354 :       else if (masked_loop_p && !mask_by_cond_expr)
    8338              :         {
    8339              :           /* No conditional ifns have been defined for lane-reducing op
    8340              :              yet.  */
    8341           20 :           gcc_assert (!lane_reducing);
    8342              : 
    8343           32 :           auto_vec<tree> args (op.num_ops + (cond_fn_p ? 0 : 2));
    8344           20 :           tree mask = vect_get_mask (loop_vinfo, gsi, vec_in_num, vectype_in,
    8345           20 :                                      mask_index++);
    8346           20 :           if (cond_fn_p)
    8347              :             {
    8348            8 :               gcc_assert (internal_fn_mask_index (internal_fn (code)) == 0);
    8349            8 :               mask = prepare_vec_mask (loop_vinfo, TREE_TYPE (mask),
    8350              :                                        mask, vop[0], gsi);
    8351              :             }
    8352           20 :           gcc_assert (internal_fn_mask_index (internal_fn (cond_fn)) == 0);
    8353           20 :           args.quick_push (mask);
    8354           20 :           for (unsigned j = cond_fn_p ? 1 : 0;
    8355          104 :                j < op.num_ops - (cond_fn_p ? 1 : 0); ++j)
    8356           44 :             args.quick_push (vop[j]);
    8357           40 :           gcc_assert (internal_fn_else_index (internal_fn (cond_fn))
    8358              :                       == (int) args.length ());
    8359           20 :           args.quick_push (vop[reduc_index]);
    8360           20 :           gcall *call = gimple_build_call_internal_vec (cond_fn, args);
    8361           20 :           new_temp = make_ssa_name (vec_dest, call);
    8362           20 :           gimple_call_set_lhs (call, new_temp);
    8363           20 :           gimple_call_set_nothrow (call, true);
    8364           20 :           vect_finish_stmt_generation (loop_vinfo, stmt_info, call, gsi);
    8365           20 :           new_stmt = call;
    8366           20 :         }
    8367              :       else
    8368              :         {
    8369         5334 :           if (masked_loop_p && mask_by_cond_expr)
    8370              :             {
    8371            4 :               tree mask = vect_get_mask (loop_vinfo, gsi, vec_in_num,
    8372              :                                          vectype_in, mask_index++);
    8373            4 :               build_vect_cond_expr (code, vop, mask, gsi);
    8374              :             }
    8375              : 
    8376         5334 :           if (emulated_mixed_dot_prod)
    8377            4 :             new_stmt = vect_emulate_mixed_dot_prod (loop_vinfo, stmt_info, gsi,
    8378              :                                                     vec_dest, vop);
    8379              : 
    8380         6672 :           else if (code.is_internal_fn () && !cond_fn_p)
    8381            0 :             new_stmt = gimple_build_call_internal (internal_fn (code),
    8382              :                                                    op.num_ops,
    8383              :                                                    vop[0], vop[1], vop[2]);
    8384         6672 :           else if (code.is_internal_fn () && cond_fn_p)
    8385         1342 :             new_stmt = gimple_build_call_internal (internal_fn (code),
    8386              :                                                    op.num_ops,
    8387              :                                                    vop[0], vop[1], vop[2],
    8388              :                                                    vop[reduc_index]);
    8389              :           else
    8390         3988 :             new_stmt = gimple_build_assign (vec_dest, tree_code (op.code),
    8391              :                                             vop[0], vop[1], vop[2]);
    8392         5334 :           new_temp = make_ssa_name (vec_dest, new_stmt);
    8393         5334 :           gimple_set_lhs (new_stmt, new_temp);
    8394         5334 :           vect_finish_stmt_generation (loop_vinfo, stmt_info, new_stmt, gsi);
    8395              :         }
    8396              : 
    8397         5881 :       if (single_defuse_cycle && i < num - 1)
    8398         3425 :         vec_oprnds[reduc_index].safe_push (gimple_get_lhs (new_stmt));
    8399              :       else
    8400         2456 :         slp_node->push_vec_def (new_stmt);
    8401              :     }
    8402              : 
    8403              :   return true;
    8404        11092 : }
    8405              : 
    8406              : /* Transform phase of a cycle PHI.  */
    8407              : 
    8408              : bool
    8409        23868 : vect_transform_cycle_phi (loop_vec_info loop_vinfo,
    8410              :                           stmt_vec_info stmt_info,
    8411              :                           slp_tree slp_node, slp_instance slp_node_instance)
    8412              : {
    8413        23868 :   tree vectype_out = SLP_TREE_VECTYPE (slp_node);
    8414        23868 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    8415        23868 :   int i;
    8416        23868 :   bool nested_cycle = false;
    8417        23868 :   int vec_num;
    8418              : 
    8419        23868 :   if (nested_in_vect_loop_p (loop, stmt_info))
    8420              :     {
    8421        23868 :       loop = loop->inner;
    8422        23868 :       nested_cycle = true;
    8423              :     }
    8424              : 
    8425        23868 :   vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
    8426        23868 :   if (reduc_info
    8427        23284 :       && (VECT_REDUC_INFO_TYPE (reduc_info) == EXTRACT_LAST_REDUCTION
    8428        23284 :           || VECT_REDUC_INFO_TYPE (reduc_info) == FOLD_LEFT_REDUCTION))
    8429              :     /* Leave the scalar phi in place.  */
    8430              :     return true;
    8431              : 
    8432        22263 :   if (reduc_info && reduc_info->is_reduc_chain && dump_enabled_p ())
    8433          133 :     dump_printf_loc (MSG_NOTE, vect_location,
    8434              :                      "vectorizing a reduction chain\n");
    8435              : 
    8436        22847 :   vec_num = vect_get_num_copies (loop_vinfo, slp_node);
    8437              : 
    8438              :   /* Check whether we should use a single PHI node and accumulate
    8439              :      vectors to one before the backedge.  */
    8440        22847 :   if (reduc_info && VECT_REDUC_INFO_FORCE_SINGLE_CYCLE (reduc_info))
    8441        22847 :     vec_num = 1;
    8442              : 
    8443              :   /* Create the destination vector  */
    8444        22847 :   gphi *phi = as_a <gphi *> (stmt_info->stmt);
    8445        22847 :   tree vec_dest = vect_create_destination_var (gimple_phi_result (phi),
    8446              :                                                vectype_out);
    8447              : 
    8448              :   /* Get the loop-entry arguments.  */
    8449        22847 :   auto_vec<tree> vec_initial_defs;
    8450        22847 :   vec_initial_defs.reserve (vec_num);
    8451              :   /* Optimize: if initial_def is for REDUC_MAX smaller than the base
    8452              :      and we can't use zero for induc_val, use initial_def.  Similarly
    8453              :      for REDUC_MIN and initial_def larger than the base.  */
    8454        22847 :   if (reduc_info
    8455        22263 :       && VECT_REDUC_INFO_TYPE (reduc_info) == INTEGER_INDUC_COND_REDUCTION)
    8456              :     {
    8457           62 :       gcc_assert (SLP_TREE_LANES (slp_node) == 1);
    8458           62 :       tree initial_def = vect_phi_initial_value (phi);
    8459           62 :       VECT_REDUC_INFO_INITIAL_VALUES (reduc_info).safe_push (initial_def);
    8460           62 :       tree induc_val = VECT_REDUC_INFO_INDUC_COND_INITIAL_VAL (reduc_info);
    8461           62 :       if (TREE_CODE (initial_def) == INTEGER_CST
    8462           60 :           && !integer_zerop (induc_val)
    8463          122 :           && ((VECT_REDUC_INFO_CODE (reduc_info) == MAX_EXPR
    8464           42 :                && tree_int_cst_lt (initial_def, induc_val))
    8465           58 :               || (VECT_REDUC_INFO_CODE (reduc_info) == MIN_EXPR
    8466           18 :                   && tree_int_cst_lt (induc_val, initial_def))))
    8467              :         {
    8468            2 :           induc_val = initial_def;
    8469              :           /* Communicate we used the initial_def to epilouge
    8470              :              generation.  */
    8471            2 :           VECT_REDUC_INFO_INDUC_COND_INITIAL_VAL (reduc_info) = NULL_TREE;
    8472              :         }
    8473           62 :       vec_initial_defs.quick_push
    8474           62 :         (build_vector_from_val (vectype_out, induc_val));
    8475           62 :     }
    8476        22785 :   else if (nested_cycle)
    8477              :     {
    8478          668 :       unsigned phi_idx = loop_preheader_edge (loop)->dest_idx;
    8479          668 :       vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[phi_idx],
    8480              :                          &vec_initial_defs);
    8481              :     }
    8482              :   else
    8483              :     {
    8484        22117 :       gcc_assert (slp_node == slp_node_instance->reduc_phis);
    8485        22117 :       vec<tree> &initial_values = VECT_REDUC_INFO_INITIAL_VALUES (reduc_info);
    8486        22117 :       vec<stmt_vec_info> &stmts = SLP_TREE_SCALAR_STMTS (slp_node);
    8487              : 
    8488        22117 :       unsigned int num_phis = stmts.length ();
    8489        22117 :       if (reduc_info->is_reduc_chain)
    8490          219 :         num_phis = 1;
    8491        22117 :       initial_values.reserve (num_phis);
    8492        66829 :       for (unsigned int i = 0; i < num_phis; ++i)
    8493              :         {
    8494        22595 :           gphi *this_phi = as_a<gphi *> (stmts[i]->stmt);
    8495        22595 :           initial_values.quick_push (vect_phi_initial_value (this_phi));
    8496              :         }
    8497        22117 :       tree neutral_op = VECT_REDUC_INFO_NEUTRAL_OP (reduc_info);
    8498        22117 :       if (vec_num == 1
    8499        22117 :           && vect_find_reusable_accumulator (loop_vinfo,
    8500              :                                              reduc_info, vectype_out))
    8501              :         ;
    8502              :       /* Try to simplify the vector initialization by applying an
    8503              :          adjustment after the reduction has been performed.  This
    8504              :          can also break a critical path but on the other hand
    8505              :          requires to keep the initial value live across the loop.  */
    8506        18173 :       else if (neutral_op
    8507        17563 :                && initial_values.length () == 1
    8508        17354 :                && STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
    8509        35452 :                && !operand_equal_p (neutral_op, initial_values[0]))
    8510              :         {
    8511        12150 :           VECT_REDUC_INFO_EPILOGUE_ADJUSTMENT (reduc_info)
    8512        12150 :             = initial_values[0];
    8513        12150 :           initial_values[0] = neutral_op;
    8514              :         }
    8515        22117 :       if (!VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info)
    8516         3944 :           || loop_vinfo->main_loop_edge)
    8517        43936 :         get_initial_defs_for_reduction (loop_vinfo, reduc_info, vectype_out,
    8518              :                                         &vec_initial_defs, vec_num,
    8519              :                                         stmts.length (), neutral_op);
    8520              :     }
    8521              : 
    8522        22847 :   if (reduc_info)
    8523        22263 :   if (auto *accumulator = VECT_REDUC_INFO_REUSED_ACCUMULATOR (reduc_info))
    8524              :     {
    8525         3944 :       tree def = accumulator->reduc_input;
    8526         3944 :       if (!useless_type_conversion_p (vectype_out, TREE_TYPE (def)))
    8527              :         {
    8528         3941 :           unsigned int nreduc;
    8529         7882 :           bool res = constant_multiple_p (TYPE_VECTOR_SUBPARTS
    8530         3941 :                                             (TREE_TYPE (def)),
    8531         3941 :                                           TYPE_VECTOR_SUBPARTS (vectype_out),
    8532              :                                           &nreduc);
    8533            0 :           gcc_assert (res);
    8534         3941 :           gimple_seq stmts = NULL;
    8535              :           /* Reduce the single vector to a smaller one.  */
    8536         3941 :           if (nreduc != 1)
    8537              :             {
    8538              :               /* Perform the reduction in the appropriate type.  */
    8539         3941 :               tree rvectype = vectype_out;
    8540         3941 :               if (!useless_type_conversion_p (TREE_TYPE (vectype_out),
    8541         3941 :                                               TREE_TYPE (TREE_TYPE (def))))
    8542          235 :                 rvectype = build_vector_type (TREE_TYPE (TREE_TYPE (def)),
    8543              :                                               TYPE_VECTOR_SUBPARTS
    8544          470 :                                                 (vectype_out));
    8545         3941 :               def = vect_create_partial_epilog (def, rvectype,
    8546              :                                                 VECT_REDUC_INFO_CODE
    8547              :                                                   (reduc_info),
    8548              :                                                 &stmts);
    8549              :             }
    8550              :           /* The epilogue loop might use a different vector mode, like
    8551              :              VNx2DI vs. V2DI.  */
    8552         3941 :           if (TYPE_MODE (vectype_out) != TYPE_MODE (TREE_TYPE (def)))
    8553              :             {
    8554            0 :               tree reduc_type = build_vector_type_for_mode
    8555            0 :                 (TREE_TYPE (TREE_TYPE (def)), TYPE_MODE (vectype_out));
    8556            0 :               def = gimple_convert (&stmts, reduc_type, def);
    8557              :             }
    8558              :           /* Adjust the input so we pick up the partially reduced value
    8559              :              for the skip edge in vect_create_epilog_for_reduction.  */
    8560         3941 :           accumulator->reduc_input = def;
    8561              :           /* And the reduction could be carried out using a different sign.  */
    8562         3941 :           if (!useless_type_conversion_p (vectype_out, TREE_TYPE (def)))
    8563          235 :             def = gimple_convert (&stmts, vectype_out, def);
    8564         3941 :           edge e;
    8565         3941 :           if ((e = loop_vinfo->main_loop_edge)
    8566         3941 :               || (e = loop_vinfo->skip_this_loop_edge))
    8567              :             {
    8568              :               /* While we'd like to insert on the edge this will split
    8569              :                  blocks and disturb bookkeeping, we also will eventually
    8570              :                  need this on the skip edge.  Rely on sinking to
    8571              :                  fixup optimal placement and insert in the pred.  */
    8572         3792 :               gimple_stmt_iterator gsi = gsi_last_bb (e->src);
    8573              :               /* Insert before a cond that eventually skips the
    8574              :                  epilogue.  */
    8575         3792 :               if (!gsi_end_p (gsi) && stmt_ends_bb_p (gsi_stmt (gsi)))
    8576         3775 :                 gsi_prev (&gsi);
    8577         3792 :               gsi_insert_seq_after (&gsi, stmts, GSI_CONTINUE_LINKING);
    8578              :             }
    8579              :           else
    8580          149 :             gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop),
    8581              :                                               stmts);
    8582              :         }
    8583         3944 :       if (loop_vinfo->main_loop_edge)
    8584         3795 :         vec_initial_defs[0]
    8585         3795 :           = vect_get_main_loop_result (loop_vinfo, def,
    8586         3795 :                                        vec_initial_defs[0]);
    8587              :       else
    8588          149 :         vec_initial_defs.safe_push (def);
    8589              :     }
    8590              : 
    8591              :   /* Generate the reduction PHIs upfront.  */
    8592        47625 :   for (i = 0; i < vec_num; i++)
    8593              :     {
    8594        24778 :       tree vec_init_def = vec_initial_defs[i];
    8595              :       /* Create the reduction-phi that defines the reduction
    8596              :          operand.  */
    8597        24778 :       gphi *new_phi = create_phi_node (vec_dest, loop->header);
    8598        24778 :       add_phi_arg (new_phi, vec_init_def, loop_preheader_edge (loop),
    8599              :                    UNKNOWN_LOCATION);
    8600              : 
    8601              :       /* The loop-latch arg is set in epilogue processing.  */
    8602              : 
    8603        24778 :       slp_node->push_vec_def (new_phi);
    8604              :     }
    8605              : 
    8606        22847 :   return true;
    8607        22847 : }
    8608              : 
    8609              : /* Vectorizes LC PHIs.  */
    8610              : 
    8611              : bool
    8612       198693 : vectorizable_lc_phi (loop_vec_info loop_vinfo,
    8613              :                      stmt_vec_info stmt_info,
    8614              :                      slp_tree slp_node)
    8615              : {
    8616       198693 :   if (!loop_vinfo
    8617       198693 :       || !is_a <gphi *> (stmt_info->stmt)
    8618       237937 :       || gimple_phi_num_args (stmt_info->stmt) != 1)
    8619              :     return false;
    8620              : 
    8621          815 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
    8622            0 :       && STMT_VINFO_DEF_TYPE (stmt_info) != vect_double_reduction_def)
    8623              :     return false;
    8624              : 
    8625              :   /* Deal with copies from externs or constants that disguise as
    8626              :      loop-closed PHI nodes (PR97886).  */
    8627          815 :   if (!vect_maybe_update_slp_op_vectype (SLP_TREE_CHILDREN (slp_node)[0],
    8628              :                                          SLP_TREE_VECTYPE (slp_node)))
    8629              :     {
    8630            0 :       if (dump_enabled_p ())
    8631            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8632              :                          "incompatible vector types for invariants\n");
    8633              :       return false;
    8634              :     }
    8635              : 
    8636              :   /* ???  This can happen with data vs. mask uses of boolean.  */
    8637          815 :   if (!useless_type_conversion_p (SLP_TREE_VECTYPE (slp_node),
    8638          815 :                                   SLP_TREE_VECTYPE
    8639              :                                     (SLP_TREE_CHILDREN (slp_node)[0])))
    8640              :     {
    8641            0 :       if (dump_enabled_p ())
    8642            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8643              :                          "missed mask promotion\n");
    8644              :       return false;
    8645              :     }
    8646              : 
    8647          815 :   SLP_TREE_TYPE (slp_node) = lc_phi_info_type;
    8648          815 :   return true;
    8649              : }
    8650              : 
    8651              : bool
    8652          494 : vect_transform_lc_phi (loop_vec_info loop_vinfo,
    8653              :                        stmt_vec_info stmt_info,
    8654              :                        slp_tree slp_node)
    8655              : {
    8656              : 
    8657          494 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    8658          494 :   tree scalar_dest = gimple_phi_result (stmt_info->stmt);
    8659          494 :   basic_block bb = gimple_bb (stmt_info->stmt);
    8660          494 :   edge e = single_pred_edge (bb);
    8661          494 :   tree vec_dest = vect_create_destination_var (scalar_dest, vectype);
    8662          494 :   auto_vec<tree> vec_oprnds;
    8663          494 :   vect_get_vec_defs (loop_vinfo, slp_node, true, &vec_oprnds);
    8664         1592 :   for (unsigned i = 0; i < vec_oprnds.length (); i++)
    8665              :     {
    8666              :       /* Create the vectorized LC PHI node.  */
    8667          604 :       gphi *new_phi = create_phi_node (vec_dest, bb);
    8668          604 :       add_phi_arg (new_phi, vec_oprnds[i], e, UNKNOWN_LOCATION);
    8669          604 :       slp_node->push_vec_def (new_phi);
    8670              :     }
    8671              : 
    8672          494 :   return true;
    8673          494 : }
    8674              : 
    8675              : /* Vectorizes PHIs.  */
    8676              : 
    8677              : bool
    8678       153431 : vectorizable_phi (bb_vec_info vinfo,
    8679              :                   stmt_vec_info stmt_info,
    8680              :                   slp_tree slp_node, stmt_vector_for_cost *cost_vec)
    8681              : {
    8682       153431 :   if (!is_a <gphi *> (stmt_info->stmt) || !slp_node)
    8683              :     return false;
    8684              : 
    8685        72353 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def)
    8686              :     return false;
    8687              : 
    8688        72353 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    8689              : 
    8690        72353 :   if (cost_vec) /* transformation not required.  */
    8691              :     {
    8692              :       slp_tree child;
    8693              :       unsigned i;
    8694       202246 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), i, child)
    8695       142501 :         if (!child)
    8696              :           {
    8697            0 :             if (dump_enabled_p ())
    8698            0 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8699              :                                "PHI node with unvectorized backedge def\n");
    8700              :             return false;
    8701              :           }
    8702       142501 :         else if (!vect_maybe_update_slp_op_vectype (child, vectype))
    8703              :           {
    8704           26 :             if (dump_enabled_p ())
    8705            2 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8706              :                                "incompatible vector types for invariants\n");
    8707              :             return false;
    8708              :           }
    8709       142475 :         else if (SLP_TREE_DEF_TYPE (child) == vect_internal_def
    8710       142475 :                  && !useless_type_conversion_p (vectype,
    8711              :                                                 SLP_TREE_VECTYPE (child)))
    8712              :           {
    8713              :             /* With bools we can have mask and non-mask precision vectors
    8714              :                or different non-mask precisions.  while pattern recog is
    8715              :                supposed to guarantee consistency here bugs in it can cause
    8716              :                mismatches (PR103489 and PR103800 for example).
    8717              :                Deal with them here instead of ICEing later.  */
    8718           18 :             if (dump_enabled_p ())
    8719            8 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8720              :                                "incompatible vector type setup from "
    8721              :                                "bool pattern detection\n");
    8722              :             return false;
    8723              :           }
    8724              : 
    8725              :       /* For single-argument PHIs assume coalescing which means zero cost
    8726              :          for the scalar and the vector PHIs.  This avoids artificially
    8727              :          favoring the vector path (but may pessimize it in some cases).  */
    8728        59745 :       if (gimple_phi_num_args (as_a <gphi *> (stmt_info->stmt)) > 1)
    8729        54040 :         record_stmt_cost (cost_vec, vect_get_num_copies (vinfo, slp_node),
    8730              :                           vector_stmt, slp_node, vectype, 0, vect_body);
    8731        59745 :       SLP_TREE_TYPE (slp_node) = phi_info_type;
    8732        59745 :       return true;
    8733              :     }
    8734              : 
    8735        12564 :   tree scalar_dest = gimple_phi_result (stmt_info->stmt);
    8736        12564 :   basic_block bb = gimple_bb (stmt_info->stmt);
    8737        12564 :   tree vec_dest = vect_create_destination_var (scalar_dest, vectype);
    8738        12564 :   auto_vec<gphi *> new_phis;
    8739        44351 :   for (unsigned i = 0; i < gimple_phi_num_args (stmt_info->stmt); ++i)
    8740              :     {
    8741        31787 :       slp_tree child = SLP_TREE_CHILDREN (slp_node)[i];
    8742              : 
    8743              :       /* Skip not yet vectorized defs.  */
    8744        32385 :       if (SLP_TREE_DEF_TYPE (child) == vect_internal_def
    8745        31787 :           && SLP_TREE_VEC_DEFS (child).is_empty ())
    8746          598 :         continue;
    8747              : 
    8748        31189 :       auto_vec<tree> vec_oprnds;
    8749        31189 :       vect_get_slp_defs (SLP_TREE_CHILDREN (slp_node)[i], &vec_oprnds);
    8750        31189 :       if (!new_phis.exists ())
    8751              :         {
    8752        12564 :           new_phis.create (vec_oprnds.length ());
    8753        38944 :           for (unsigned j = 0; j < vec_oprnds.length (); j++)
    8754              :             {
    8755              :               /* Create the vectorized LC PHI node.  */
    8756        13816 :               new_phis.quick_push (create_phi_node (vec_dest, bb));
    8757        13816 :               slp_node->push_vec_def (new_phis[j]);
    8758              :             }
    8759              :         }
    8760        31189 :       edge e = gimple_phi_arg_edge (as_a <gphi *> (stmt_info->stmt), i);
    8761        66582 :       for (unsigned j = 0; j < vec_oprnds.length (); j++)
    8762        35393 :         add_phi_arg (new_phis[j], vec_oprnds[j], e, UNKNOWN_LOCATION);
    8763        31189 :     }
    8764              :   /* We should have at least one already vectorized child.  */
    8765        12564 :   gcc_assert (new_phis.exists ());
    8766              : 
    8767        12564 :   return true;
    8768        12564 : }
    8769              : 
    8770              : /* Vectorizes first order recurrences.  An overview of the transformation
    8771              :    is described below. Suppose we have the following loop.
    8772              : 
    8773              :      int t = 0;
    8774              :      for (int i = 0; i < n; ++i)
    8775              :        {
    8776              :          b[i] = a[i] - t;
    8777              :          t = a[i];
    8778              :        }
    8779              : 
    8780              :    There is a first-order recurrence on 'a'. For this loop, the scalar IR
    8781              :    looks (simplified) like:
    8782              : 
    8783              :     scalar.preheader:
    8784              :       init = 0;
    8785              : 
    8786              :     scalar.body:
    8787              :       i = PHI <0(scalar.preheader), i+1(scalar.body)>
    8788              :       _2 = PHI <(init(scalar.preheader), <_1(scalar.body)>
    8789              :       _1 = a[i]
    8790              :       b[i] = _1 - _2
    8791              :       if (i < n) goto scalar.body
    8792              : 
    8793              :    In this example, _2 is a recurrence because it's value depends on the
    8794              :    previous iteration.  We vectorize this as (VF = 4)
    8795              : 
    8796              :     vector.preheader:
    8797              :       vect_init = vect_cst(..., ..., ..., 0)
    8798              : 
    8799              :     vector.body
    8800              :       i = PHI <0(vector.preheader), i+4(vector.body)>
    8801              :       vect_1 = PHI <vect_init(vector.preheader), v2(vector.body)>
    8802              :       vect_2 = a[i, i+1, i+2, i+3];
    8803              :       vect_3 = vec_perm (vect_1, vect_2, { 3, 4, 5, 6 })
    8804              :       b[i, i+1, i+2, i+3] = vect_2 - vect_3
    8805              :       if (..) goto vector.body
    8806              : 
    8807              :    In this function, vectorizable_recurr, we code generate both the
    8808              :    vector PHI node and the permute since those together compute the
    8809              :    vectorized value of the scalar PHI.  We do not yet have the
    8810              :    backedge value to fill in there nor into the vec_perm.  Those
    8811              :    are filled in vect_schedule_scc.
    8812              : 
    8813              :    TODO:  Since the scalar loop does not have a use of the recurrence
    8814              :    outside of the loop the natural way to implement peeling via
    8815              :    vectorizing the live value doesn't work.  For now peeling of loops
    8816              :    with a recurrence is not implemented.  For SLP the supported cases
    8817              :    are restricted to those requiring a single vector recurrence PHI.  */
    8818              : 
    8819              : bool
    8820       197921 : vectorizable_recurr (loop_vec_info loop_vinfo, stmt_vec_info stmt_info,
    8821              :                      slp_tree slp_node, stmt_vector_for_cost *cost_vec)
    8822              : {
    8823       197921 :   if (!loop_vinfo || !is_a<gphi *> (stmt_info->stmt))
    8824              :     return false;
    8825              : 
    8826        38472 :   gphi *phi = as_a<gphi *> (stmt_info->stmt);
    8827              : 
    8828              :   /* So far we only support first-order recurrence auto-vectorization.  */
    8829        38472 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_first_order_recurrence)
    8830              :     return false;
    8831              : 
    8832          424 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    8833          424 :   unsigned ncopies = vect_get_num_copies (loop_vinfo, slp_node);
    8834          424 :   poly_int64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
    8835          424 :   unsigned dist = SLP_TREE_LANES (slp_node);
    8836              :   /* We need to be able to make progress with a single vector.  */
    8837          424 :   if (maybe_gt (dist * 2, nunits))
    8838              :     {
    8839            0 :       if (dump_enabled_p ())
    8840            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8841              :                          "first order recurrence exceeds half of "
    8842              :                          "a vector\n");
    8843              :       return false;
    8844              :     }
    8845              : 
    8846              :   /* We need to be able to build a { ..., a, b } init vector with
    8847              :      dist number of distinct trailing values.  Always possible
    8848              :      when dist == 1 or when nunits is constant or when the initializations
    8849              :      are uniform.  */
    8850          424 :   tree uniform_initval = NULL_TREE;
    8851          424 :   edge pe = loop_preheader_edge (LOOP_VINFO_LOOP (loop_vinfo));
    8852         1720 :   for (stmt_vec_info s : SLP_TREE_SCALAR_STMTS (slp_node))
    8853              :     {
    8854          460 :       gphi *phi = as_a <gphi *> (s->stmt);
    8855          460 :       if (! uniform_initval)
    8856          424 :         uniform_initval = PHI_ARG_DEF_FROM_EDGE (phi, pe);
    8857           36 :       else if (! operand_equal_p (uniform_initval,
    8858           36 :                                   PHI_ARG_DEF_FROM_EDGE (phi, pe)))
    8859              :         {
    8860              :           uniform_initval = NULL_TREE;
    8861              :           break;
    8862              :         }
    8863              :     }
    8864          424 :   if (!uniform_initval && !nunits.is_constant ())
    8865              :     {
    8866              :       if (dump_enabled_p ())
    8867              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8868              :                          "cannot build initialization vector for "
    8869              :                          "first order recurrence\n");
    8870              :       return false;
    8871              :     }
    8872              : 
    8873              :   /* First-order recurrence autovectorization needs to handle permutation
    8874              :      with indices = [nunits-1, nunits, nunits+1, ...].  */
    8875          424 :   vec_perm_builder sel (nunits, 1, 3);
    8876         1696 :   for (int i = 0; i < 3; ++i)
    8877         1272 :     sel.quick_push (nunits - dist + i);
    8878          424 :   vec_perm_indices indices (sel, 2, nunits);
    8879              : 
    8880          424 :   if (cost_vec) /* transformation not required.  */
    8881              :     {
    8882          381 :       if (!can_vec_perm_const_p (TYPE_MODE (vectype), TYPE_MODE (vectype),
    8883              :                                  indices))
    8884              :         return false;
    8885              : 
    8886              :       /* We eventually need to set a vector type on invariant
    8887              :          arguments.  */
    8888              :       unsigned j;
    8889              :       slp_tree child;
    8890          807 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
    8891          538 :         if (!vect_maybe_update_slp_op_vectype (child, vectype))
    8892              :           {
    8893            0 :             if (dump_enabled_p ())
    8894            0 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    8895              :                                "incompatible vector types for "
    8896              :                                "invariants\n");
    8897              :             return false;
    8898              :           }
    8899              : 
    8900              :       /* Verify we have set up compatible types.  */
    8901          269 :       edge le = loop_latch_edge (LOOP_VINFO_LOOP (loop_vinfo));
    8902          269 :       slp_tree latch_def = SLP_TREE_CHILDREN (slp_node)[le->dest_idx];
    8903          269 :       tree latch_vectype = SLP_TREE_VECTYPE (latch_def);
    8904          269 :       if (!types_compatible_p (latch_vectype, vectype))
    8905              :         return false;
    8906              : 
    8907              :       /* The recurrence costs the initialization vector and one permute
    8908              :          for each copy.  With SLP the prologue value is explicitly
    8909              :          represented and costed separately.  */
    8910          269 :       unsigned prologue_cost = 0;
    8911          269 :       unsigned inside_cost = record_stmt_cost (cost_vec, ncopies, vector_stmt,
    8912              :                                                slp_node, 0, vect_body);
    8913          269 :       if (dump_enabled_p ())
    8914           51 :         dump_printf_loc (MSG_NOTE, vect_location,
    8915              :                          "vectorizable_recurr: inside_cost = %d, "
    8916              :                          "prologue_cost = %d .\n", inside_cost,
    8917              :                          prologue_cost);
    8918              : 
    8919          269 :       SLP_TREE_TYPE (slp_node) = recurr_info_type;
    8920          269 :       return true;
    8921              :     }
    8922              : 
    8923           43 :   tree vec_init;
    8924           43 :   if (! uniform_initval)
    8925              :     {
    8926            6 :       vec<constructor_elt, va_gc> *v = NULL;
    8927            6 :       vec_alloc (v, nunits.to_constant ());
    8928           39 :       for (unsigned i = 0; i < nunits.to_constant () - dist; ++i)
    8929           27 :         CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
    8930              :                                 build_zero_cst (TREE_TYPE (vectype)));
    8931           39 :       for (stmt_vec_info s : SLP_TREE_SCALAR_STMTS (slp_node))
    8932              :         {
    8933           21 :           gphi *phi = as_a <gphi *> (s->stmt);
    8934           21 :           tree preheader = PHI_ARG_DEF_FROM_EDGE (phi, pe);
    8935           21 :           if (!useless_type_conversion_p (TREE_TYPE (vectype),
    8936           21 :                                           TREE_TYPE (preheader)))
    8937              :             {
    8938            0 :               gimple_seq stmts = NULL;
    8939            0 :               preheader = gimple_convert (&stmts,
    8940            0 :                                           TREE_TYPE (vectype), preheader);
    8941            0 :               gsi_insert_seq_on_edge_immediate (pe, stmts);
    8942              :             }
    8943           21 :           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, preheader);
    8944              :         }
    8945            6 :       vec_init = build_constructor (vectype, v);
    8946              :     }
    8947              :   else
    8948              :     vec_init = uniform_initval;
    8949           43 :   vec_init = vect_init_vector (loop_vinfo, stmt_info, vec_init, vectype, NULL);
    8950              : 
    8951              :   /* Create the vectorized first-order PHI node.  */
    8952           43 :   tree vec_dest = vect_get_new_vect_var (vectype,
    8953              :                                          vect_simple_var, "vec_recur_");
    8954           43 :   basic_block bb = gimple_bb (phi);
    8955           43 :   gphi *new_phi = create_phi_node (vec_dest, bb);
    8956           43 :   add_phi_arg (new_phi, vec_init, pe, UNKNOWN_LOCATION);
    8957              : 
    8958              :   /* Insert shuffles the first-order recurrence autovectorization.
    8959              :        result = VEC_PERM <vec_recur, vect_1, index[nunits-1, nunits, ...]>.  */
    8960           43 :   tree perm = vect_gen_perm_mask_checked (vectype, indices);
    8961              : 
    8962              :   /* Insert the required permute after the latch definition.  The
    8963              :      second and later operands are tentative and will be updated when we have
    8964              :      vectorized the latch definition.  */
    8965           43 :   edge le = loop_latch_edge (LOOP_VINFO_LOOP (loop_vinfo));
    8966           43 :   gimple *latch_def = SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, le));
    8967           43 :   gimple_stmt_iterator gsi2 = gsi_for_stmt (latch_def);
    8968           49 :   do
    8969              :     {
    8970           49 :       gsi_next (&gsi2);
    8971              :     }
    8972              :   /* Skip inserted vectorized stmts for the latch definition.  We have to
    8973              :      insert after those.  */
    8974           92 :   while (gsi_stmt (gsi2) && gimple_uid (gsi_stmt (gsi2)) == 0);
    8975              : 
    8976          123 :   for (unsigned i = 0; i < ncopies; ++i)
    8977              :     {
    8978           80 :       vec_dest = make_ssa_name (vectype);
    8979           80 :       gassign *vperm
    8980          123 :           = gimple_build_assign (vec_dest, VEC_PERM_EXPR,
    8981           43 :                                  i == 0 ? gimple_phi_result (new_phi) : NULL,
    8982              :                                  NULL, perm);
    8983           80 :       vect_finish_stmt_generation (loop_vinfo, stmt_info, vperm, &gsi2);
    8984              : 
    8985           80 :       slp_node->push_vec_def (vperm);
    8986              :     }
    8987              : 
    8988              :   return true;
    8989          424 : }
    8990              : 
    8991              : /* Return true if VECTYPE represents a vector that requires lowering
    8992              :    by the vector lowering pass.  */
    8993              : 
    8994              : bool
    8995       690924 : vect_emulated_vector_p (tree vectype)
    8996              : {
    8997      1381848 :   return (!VECTOR_MODE_P (TYPE_MODE (vectype))
    8998       695054 :           && (!VECTOR_BOOLEAN_TYPE_P (vectype)
    8999         4112 :               || TYPE_PRECISION (TREE_TYPE (vectype)) != 1));
    9000              : }
    9001              : 
    9002              : /* Return true if we can emulate CODE on an integer mode representation
    9003              :    of a vector.  */
    9004              : 
    9005              : bool
    9006        12676 : vect_can_vectorize_without_simd_p (tree_code code)
    9007              : {
    9008        12676 :   switch (code)
    9009              :     {
    9010              :     case PLUS_EXPR:
    9011              :     case MINUS_EXPR:
    9012              :     case NEGATE_EXPR:
    9013              :     case BIT_AND_EXPR:
    9014              :     case BIT_IOR_EXPR:
    9015              :     case BIT_XOR_EXPR:
    9016              :     case BIT_NOT_EXPR:
    9017              :       return true;
    9018              : 
    9019        12066 :     default:
    9020        12066 :       return false;
    9021              :     }
    9022              : }
    9023              : 
    9024              : /* Likewise, but taking a code_helper.  */
    9025              : 
    9026              : bool
    9027         1003 : vect_can_vectorize_without_simd_p (code_helper code)
    9028              : {
    9029         1003 :   return (code.is_tree_code ()
    9030         1003 :           && vect_can_vectorize_without_simd_p (tree_code (code)));
    9031              : }
    9032              : 
    9033              : /* Create vector init for vectorized iv.  */
    9034              : static tree
    9035          936 : vect_create_nonlinear_iv_init (gimple_seq* stmts, tree init_expr,
    9036              :                                tree step_expr, poly_uint64 nunits,
    9037              :                                tree vectype,
    9038              :                                enum vect_induction_op_type induction_type)
    9039              : {
    9040          936 :   unsigned HOST_WIDE_INT const_nunits;
    9041          936 :   tree vec_shift, vec_init, new_name;
    9042          936 :   unsigned i;
    9043          936 :   tree itype = TREE_TYPE (vectype);
    9044              : 
    9045              :   /* iv_loop is the loop to be vectorized. Create:
    9046              :      vec_init = [X, X+S, X+2*S, X+3*S] (S = step_expr, X = init_expr).  */
    9047          936 :   new_name = gimple_convert (stmts, itype, init_expr);
    9048          936 :   switch (induction_type)
    9049              :     {
    9050           21 :     case vect_step_op_shr:
    9051           21 :     case vect_step_op_shl:
    9052              :       /* Build the Initial value from shift_expr.  */
    9053           21 :       vec_init = gimple_build_vector_from_val (stmts,
    9054              :                                                vectype,
    9055              :                                                new_name);
    9056           21 :       vec_shift = gimple_build (stmts, VEC_SERIES_EXPR, vectype,
    9057              :                                 build_zero_cst (itype), step_expr);
    9058           21 :       vec_init = gimple_build (stmts,
    9059              :                                (induction_type == vect_step_op_shr
    9060              :                                 ? RSHIFT_EXPR : LSHIFT_EXPR),
    9061              :                                vectype, vec_init, vec_shift);
    9062           21 :       break;
    9063              : 
    9064          837 :     case vect_step_op_neg:
    9065          837 :       {
    9066          837 :         vec_init = gimple_build_vector_from_val (stmts,
    9067              :                                                  vectype,
    9068              :                                                  new_name);
    9069          837 :         tree vec_neg = gimple_build (stmts, NEGATE_EXPR,
    9070              :                                      vectype, vec_init);
    9071              :         /* The encoding has 2 interleaved stepped patterns.  */
    9072          837 :         vec_perm_builder sel (nunits, 2, 3);
    9073          837 :         sel.quick_grow (6);
    9074         4185 :         for (i = 0; i < 3; i++)
    9075              :           {
    9076         2511 :             sel[2 * i] = i;
    9077         2511 :             sel[2 * i + 1] = i + nunits;
    9078              :           }
    9079          837 :         vec_perm_indices indices (sel, 2, nunits);
    9080              :         /* Don't use vect_gen_perm_mask_checked since can_vec_perm_const_p may
    9081              :            fail when vec_init is const vector. In that situation vec_perm is not
    9082              :            really needed.  */
    9083          837 :         tree perm_mask_even
    9084          837 :           = vect_gen_perm_mask_any (vectype, indices);
    9085          837 :         vec_init = gimple_build (stmts, VEC_PERM_EXPR,
    9086              :                                  vectype,
    9087              :                                  vec_init, vec_neg,
    9088              :                                  perm_mask_even);
    9089          837 :       }
    9090          837 :       break;
    9091              : 
    9092           78 :     case vect_step_op_mul:
    9093           78 :       {
    9094              :         /* Use unsigned mult to avoid UD integer overflow.  */
    9095           78 :         gcc_assert (nunits.is_constant (&const_nunits));
    9096           78 :         tree utype = unsigned_type_for (itype);
    9097           78 :         tree uvectype = build_vector_type (utype,
    9098           78 :                                            TYPE_VECTOR_SUBPARTS (vectype));
    9099           78 :         new_name = gimple_convert (stmts, utype, new_name);
    9100           78 :         vec_init = gimple_build_vector_from_val (stmts,
    9101              :                                                  uvectype,
    9102              :                                                  new_name);
    9103           78 :         tree_vector_builder elts (uvectype, const_nunits, 1);
    9104           78 :         tree elt_step = build_one_cst (utype);
    9105              : 
    9106           78 :         elts.quick_push (elt_step);
    9107          670 :         for (i = 1; i < const_nunits; i++)
    9108              :           {
    9109              :             /* Create: new_name_i = new_name + step_expr.  */
    9110          514 :             elt_step = gimple_build (stmts, MULT_EXPR,
    9111              :                                      utype, elt_step, step_expr);
    9112          514 :             elts.quick_push (elt_step);
    9113              :           }
    9114              :         /* Create a vector from [new_name_0, new_name_1, ...,
    9115              :            new_name_nunits-1].  */
    9116           78 :         tree vec_mul = gimple_build_vector (stmts, &elts);
    9117           78 :         vec_init = gimple_build (stmts, MULT_EXPR, uvectype,
    9118              :                                  vec_init, vec_mul);
    9119           78 :         vec_init = gimple_convert (stmts, vectype, vec_init);
    9120           78 :       }
    9121           78 :       break;
    9122              : 
    9123            0 :     default:
    9124            0 :       gcc_unreachable ();
    9125              :     }
    9126              : 
    9127          936 :   return vec_init;
    9128              : }
    9129              : 
    9130              : /* Peel init_expr by skip_niter for induction_type.  */
    9131              : tree
    9132           83 : vect_peel_nonlinear_iv_init (gimple_seq* stmts, tree init_expr,
    9133              :                              tree skip_niters, tree step_expr,
    9134              :                              enum vect_induction_op_type induction_type,
    9135              :                              bool early_exit_p)
    9136              : {
    9137           83 :   gcc_assert (TREE_CODE (skip_niters) == INTEGER_CST || early_exit_p);
    9138           83 :   tree type = TREE_TYPE (init_expr);
    9139           83 :   unsigned prec = TYPE_PRECISION (type);
    9140           83 :   switch (induction_type)
    9141              :     {
    9142              :     /* neg inductions are typically not used for loop termination conditions but
    9143              :        are typically implemented as b = -b.  That is every scalar iteration b is
    9144              :        negated.  That means that for the initial value of b we will have to
    9145              :        determine whether the number of skipped iteration is a multiple of 2
    9146              :        because every 2 scalar iterations we are back at "b".  */
    9147            0 :     case vect_step_op_neg:
    9148              :       /* For early exits the neg induction will always be the same value at the
    9149              :          start of the iteration.  */
    9150            0 :       if (early_exit_p)
    9151              :         break;
    9152              : 
    9153            0 :       if (TREE_INT_CST_LOW (skip_niters) % 2)
    9154            0 :         init_expr = gimple_build (stmts, NEGATE_EXPR, type, init_expr);
    9155              :       /* else no change.  */
    9156              :       break;
    9157              : 
    9158           12 :     case vect_step_op_shr:
    9159           12 :     case vect_step_op_shl:
    9160              :       /* When shift count >= precision, need to avoid UD.
    9161              :          In the original loop, there's no UD, and according to semantic,
    9162              :          init_expr should be 0 for lshr, ashl, and >>= (prec - 1) for ashr.  */
    9163           24 :       if (!early_exit_p
    9164           24 :           && wi::mul (wi::to_widest (step_expr),
    9165           36 :                       wi::to_widest (skip_niters)) >= prec)
    9166              :         {
    9167            6 :           if (induction_type == vect_step_op_shl
    9168            6 :               || TYPE_UNSIGNED (type))
    9169            4 :             init_expr = build_zero_cst (type);
    9170              :           else
    9171            2 :             init_expr = gimple_build (stmts, RSHIFT_EXPR, type,
    9172              :                                       init_expr,
    9173            4 :                                       wide_int_to_tree (type, prec - 1));
    9174              :         }
    9175              :       else
    9176              :         {
    9177              :           /* ???  For not constant skip_niters we'd have to treat the
    9178              :              overflow case.  */
    9179            6 :           gcc_assert (!early_exit_p);
    9180            6 :           step_expr = fold_build2 (MULT_EXPR, TREE_TYPE (skip_niters),
    9181              :                                    skip_niters,
    9182              :                                    fold_convert (TREE_TYPE (skip_niters),
    9183              :                                                  step_expr));
    9184            8 :           init_expr = fold_build2 ((induction_type == vect_step_op_shr
    9185              :                                     ? RSHIFT_EXPR : LSHIFT_EXPR),
    9186              :                                     type, init_expr, step_expr);
    9187            6 :           init_expr = force_gimple_operand (init_expr, stmts, false, NULL);
    9188              :         }
    9189              :       break;
    9190              : 
    9191           71 :     case vect_step_op_mul:
    9192           71 :       {
    9193              :         /* Due to UB we can't support vect_step_op_mul with early break for now.
    9194              :            so assert and block.  */
    9195           71 :         gcc_assert (TREE_CODE (skip_niters) == INTEGER_CST);
    9196           71 :         tree utype = unsigned_type_for (type);
    9197           71 :         init_expr = gimple_convert (stmts, utype, init_expr);
    9198           71 :         wide_int skipn = wi::to_wide (skip_niters);
    9199           71 :         wide_int begin = wi::to_wide (step_expr);
    9200           71 :         auto_mpz base, exp, mod, res;
    9201           71 :         wi::to_mpz (begin, base, TYPE_SIGN (type));
    9202           71 :         wi::to_mpz (skipn, exp, UNSIGNED);
    9203           71 :         mpz_ui_pow_ui (mod, 2, TYPE_PRECISION (type));
    9204           71 :         mpz_powm (res, base, exp, mod);
    9205           71 :         begin = wi::from_mpz (utype, res, true);
    9206           71 :         tree mult_expr = wide_int_to_tree (utype, begin);
    9207           71 :         init_expr = gimple_build (stmts, MULT_EXPR, utype,
    9208              :                                   init_expr, mult_expr);
    9209           71 :         init_expr = gimple_convert (stmts, type, init_expr);
    9210           71 :       }
    9211           71 :       break;
    9212              : 
    9213            0 :     default:
    9214            0 :       gcc_unreachable ();
    9215              :     }
    9216              : 
    9217           83 :   return init_expr;
    9218              : }
    9219              : 
    9220              : /* Create vector step for vectorized iv.  */
    9221              : static tree
    9222         1225 : vect_create_nonlinear_iv_step (gimple_seq* stmts, tree step_expr,
    9223              :                                poly_uint64 vf,
    9224              :                                enum vect_induction_op_type induction_type)
    9225              : {
    9226         1225 :   tree expr = build_int_cst (TREE_TYPE (step_expr), vf);
    9227         1225 :   tree new_name = NULL;
    9228              :   /* Step should be pow (step, vf) for mult induction.  */
    9229         1225 :   if (induction_type == vect_step_op_mul)
    9230              :     {
    9231           78 :       gcc_assert (vf.is_constant ());
    9232           78 :       wide_int begin = wi::to_wide (step_expr);
    9233              : 
    9234          592 :       for (unsigned i = 0; i != vf.to_constant () - 1; i++)
    9235          514 :         begin = wi::mul (begin, wi::to_wide (step_expr));
    9236              : 
    9237           78 :       new_name = wide_int_to_tree (TREE_TYPE (step_expr), begin);
    9238           78 :     }
    9239         1147 :   else if (induction_type == vect_step_op_neg)
    9240              :     /* Do nothing.  */
    9241              :     ;
    9242              :   else
    9243           24 :     new_name = gimple_build (stmts, MULT_EXPR, TREE_TYPE (step_expr),
    9244              :                              expr, step_expr);
    9245         1225 :   return new_name;
    9246              : }
    9247              : 
    9248              : static tree
    9249         1225 : vect_create_nonlinear_iv_vec_step (loop_vec_info loop_vinfo,
    9250              :                                    stmt_vec_info stmt_info,
    9251              :                                    tree new_name, tree vectype,
    9252              :                                    enum vect_induction_op_type induction_type)
    9253              : {
    9254              :   /* No step is needed for neg induction.  */
    9255         1225 :   if (induction_type == vect_step_op_neg)
    9256              :     return NULL;
    9257              : 
    9258          102 :   tree t = unshare_expr (new_name);
    9259          102 :   gcc_assert (CONSTANT_CLASS_P (new_name)
    9260              :               || TREE_CODE (new_name) == SSA_NAME);
    9261          102 :   tree new_vec = build_vector_from_val (vectype, t);
    9262          102 :   tree vec_step = vect_init_vector (loop_vinfo, stmt_info,
    9263              :                                     new_vec, vectype, NULL);
    9264          102 :   return vec_step;
    9265              : }
    9266              : 
    9267              : /* Update vectorized iv with vect_step, induc_def is init.  */
    9268              : static tree
    9269         1431 : vect_update_nonlinear_iv (gimple_seq* stmts, tree vectype,
    9270              :                           tree induc_def, tree vec_step,
    9271              :                           enum vect_induction_op_type induction_type)
    9272              : {
    9273         1431 :   tree vec_def = induc_def;
    9274         1431 :   switch (induction_type)
    9275              :     {
    9276           78 :     case vect_step_op_mul:
    9277           78 :       {
    9278              :         /* Use unsigned mult to avoid UD integer overflow.  */
    9279           78 :         tree uvectype = unsigned_type_for (vectype);
    9280           78 :         vec_def = gimple_convert (stmts, uvectype, vec_def);
    9281           78 :         vec_step = gimple_convert (stmts, uvectype, vec_step);
    9282           78 :         vec_def = gimple_build (stmts, MULT_EXPR, uvectype,
    9283              :                                 vec_def, vec_step);
    9284           78 :         vec_def = gimple_convert (stmts, vectype, vec_def);
    9285              :       }
    9286           78 :       break;
    9287              : 
    9288           36 :     case vect_step_op_shr:
    9289           36 :       vec_def = gimple_build (stmts, RSHIFT_EXPR, vectype,
    9290              :                               vec_def, vec_step);
    9291           36 :       break;
    9292              : 
    9293            6 :     case vect_step_op_shl:
    9294            6 :       vec_def = gimple_build (stmts, LSHIFT_EXPR, vectype,
    9295              :                               vec_def, vec_step);
    9296            6 :       break;
    9297              :     case vect_step_op_neg:
    9298              :       vec_def = induc_def;
    9299              :       /* Do nothing.  */
    9300              :       break;
    9301            0 :     default:
    9302            0 :       gcc_unreachable ();
    9303              :     }
    9304              : 
    9305         1431 :   return vec_def;
    9306              : 
    9307              : }
    9308              : 
    9309              : /* Function vectorizable_nonlinear_induction
    9310              : 
    9311              :    Check if STMT_INFO performs an nonlinear induction computation that can be
    9312              :    vectorized. If VEC_STMT is also passed, vectorize the induction PHI: create
    9313              :    a vectorized phi to replace it, put it in VEC_STMT, and add it to the same
    9314              :    basic block.
    9315              :    Return true if STMT_INFO is vectorizable in this way.  */
    9316              : 
    9317              : static bool
    9318         9903 : vectorizable_nonlinear_induction (loop_vec_info loop_vinfo,
    9319              :                                   stmt_vec_info stmt_info,
    9320              :                                   slp_tree slp_node,
    9321              :                                   stmt_vector_for_cost *cost_vec)
    9322              : {
    9323         9903 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    9324         9903 :   unsigned ncopies;
    9325         9903 :   bool nested_in_vect_loop = false;
    9326         9903 :   class loop *iv_loop;
    9327         9903 :   tree vec_def;
    9328         9903 :   edge pe = loop_preheader_edge (loop);
    9329         9903 :   basic_block new_bb;
    9330         9903 :   tree vec_init, vec_step;
    9331         9903 :   tree new_name;
    9332         9903 :   gimple *new_stmt;
    9333         9903 :   gphi *induction_phi;
    9334         9903 :   tree induc_def, vec_dest;
    9335         9903 :   tree init_expr, step_expr;
    9336         9903 :   tree niters_skip;
    9337         9903 :   poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    9338         9903 :   unsigned i;
    9339         9903 :   gimple_stmt_iterator si;
    9340              : 
    9341         9903 :   gphi *phi = dyn_cast <gphi *> (stmt_info->stmt);
    9342              : 
    9343         9903 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    9344         9903 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
    9345         9903 :   enum vect_induction_op_type induction_type
    9346              :     = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info);
    9347              : 
    9348         9903 :   gcc_assert (induction_type > vect_step_op_add);
    9349              : 
    9350         9903 :   ncopies = vect_get_num_copies (loop_vinfo, slp_node);
    9351         9903 :   gcc_assert (ncopies >= 1);
    9352              : 
    9353              :   /* FORNOW. Only handle nonlinear induction in the same loop.  */
    9354         9903 :   if (nested_in_vect_loop_p (loop, stmt_info))
    9355              :     {
    9356            0 :       if (dump_enabled_p ())
    9357            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9358              :                          "nonlinear induction in nested loop.\n");
    9359              :       return false;
    9360              :     }
    9361              : 
    9362         9903 :   iv_loop = loop;
    9363         9903 :   gcc_assert (iv_loop == (gimple_bb (phi))->loop_father);
    9364              : 
    9365              :   /* TODO: Support multi-lane SLP for nonlinear iv. There should be separate
    9366              :      vector iv update for each iv and a permutation to generate wanted
    9367              :      vector iv.  */
    9368         9903 :   if (SLP_TREE_LANES (slp_node) > 1)
    9369              :     {
    9370            0 :       if (dump_enabled_p ())
    9371            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9372              :                          "SLP induction not supported for nonlinear"
    9373              :                          " induction.\n");
    9374              :       return false;
    9375              :     }
    9376              : 
    9377         9903 :   if (!INTEGRAL_TYPE_P (TREE_TYPE (vectype)))
    9378              :     {
    9379            0 :       if (dump_enabled_p ())
    9380            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9381              :                          "floating point nonlinear induction vectorization"
    9382              :                          " not supported.\n");
    9383              :       return false;
    9384              :     }
    9385              : 
    9386         9903 :   step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
    9387         9903 :   init_expr = vect_phi_initial_value (phi);
    9388         9903 :   gcc_assert (step_expr != NULL_TREE && init_expr != NULL
    9389              :               && TREE_CODE (step_expr) == INTEGER_CST);
    9390              :   /* step_expr should be aligned with init_expr,
    9391              :      .i.e. uint64 a >> 1, step is int, but vector<uint64> shift is used.  */
    9392         9903 :   step_expr = fold_convert (TREE_TYPE (vectype), step_expr);
    9393              : 
    9394         9903 :   if (TREE_CODE (init_expr) == INTEGER_CST)
    9395         4153 :     init_expr = fold_convert (TREE_TYPE (vectype), init_expr);
    9396         5750 :   else if (!tree_nop_conversion_p (TREE_TYPE (vectype), TREE_TYPE (init_expr)))
    9397              :     {
    9398              :       /* INIT_EXPR could be a bit_field, bail out for such case.  */
    9399            4 :       if (dump_enabled_p ())
    9400            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9401              :                          "nonlinear induction vectorization failed:"
    9402              :                          " component type of vectype is not a nop conversion"
    9403              :                          " from type of init_expr.\n");
    9404              :       return false;
    9405              :     }
    9406              : 
    9407         9899 :   switch (induction_type)
    9408              :     {
    9409         3731 :     case vect_step_op_neg:
    9410         3731 :       if (maybe_eq (TYPE_VECTOR_SUBPARTS (vectype), 1u))
    9411              :         return false;
    9412         3569 :       if (TREE_CODE (init_expr) != INTEGER_CST
    9413          289 :           && TREE_CODE (init_expr) != REAL_CST)
    9414              :         {
    9415              :           /* Check for backend support of NEGATE_EXPR and vec_perm.  */
    9416          289 :           if (!directly_supported_p (NEGATE_EXPR, vectype))
    9417            0 :             return false;
    9418              : 
    9419              :           /* The encoding has 2 interleaved stepped patterns.  */
    9420          289 :           vec_perm_builder sel (nunits, 2, 3);
    9421          289 :           machine_mode mode = TYPE_MODE (vectype);
    9422          289 :           sel.quick_grow (6);
    9423         1445 :           for (i = 0; i < 3; i++)
    9424              :             {
    9425          867 :               sel[i * 2] = i;
    9426          867 :               sel[i * 2 + 1] = i + nunits;
    9427              :             }
    9428          289 :           vec_perm_indices indices (sel, 2, nunits);
    9429          289 :           if (!can_vec_perm_const_p (mode, mode, indices))
    9430            0 :             return false;
    9431          289 :         }
    9432              :       break;
    9433              : 
    9434         1078 :     case vect_step_op_mul:
    9435         1078 :       {
    9436              :         /* Check for backend support of MULT_EXPR.  */
    9437         1078 :         if (!directly_supported_p (MULT_EXPR, vectype))
    9438              :           return false;
    9439              : 
    9440              :         /* ?? How to construct vector step for variable number vector.
    9441              :            [ 1, step, pow (step, 2), pow (step, 4), .. ].  */
    9442              :         if (!vf.is_constant ())
    9443              :           return false;
    9444              :       }
    9445              :       break;
    9446              : 
    9447         4688 :     case vect_step_op_shr:
    9448              :       /* Check for backend support of RSHIFT_EXPR.  */
    9449         4688 :       if (!directly_supported_p (RSHIFT_EXPR, vectype, optab_vector))
    9450              :         return false;
    9451              : 
    9452              :       /* Don't shift more than type precision to avoid UB.  */
    9453           98 :       if (!tree_fits_uhwi_p (step_expr)
    9454           98 :           || maybe_ge (vf * tree_to_uhwi (step_expr),
    9455              :                        TYPE_PRECISION (TREE_TYPE (init_expr))))
    9456              :         return false;
    9457              :       break;
    9458              : 
    9459          402 :     case vect_step_op_shl:
    9460              :       /* Check for backend support of RSHIFT_EXPR.  */
    9461          402 :       if (!directly_supported_p (LSHIFT_EXPR, vectype, optab_vector))
    9462              :         return false;
    9463              : 
    9464              :       /* Don't shift more than type precision to avoid UB.  */
    9465           42 :       if (!tree_fits_uhwi_p (step_expr)
    9466           42 :           || maybe_ge (vf * tree_to_uhwi (step_expr),
    9467              :                        TYPE_PRECISION (TREE_TYPE (init_expr))))
    9468              :         return false;
    9469              :       break;
    9470              : 
    9471            0 :     default:
    9472            0 :       gcc_unreachable ();
    9473              :     }
    9474              : 
    9475         4507 :   if (cost_vec) /* transformation not required.  */
    9476              :     {
    9477         3571 :       unsigned inside_cost = 0, prologue_cost = 0;
    9478              :       /* loop cost for vec_loop. Neg induction doesn't have any
    9479              :          inside_cost.  */
    9480         3571 :       inside_cost = record_stmt_cost (cost_vec, ncopies, vector_stmt,
    9481              :                                       slp_node, 0, vect_body);
    9482              : 
    9483              :       /* loop cost for vec_loop. Neg induction doesn't have any
    9484              :          inside_cost.  */
    9485         3571 :       if (induction_type == vect_step_op_neg)
    9486         2732 :         inside_cost = 0;
    9487              : 
    9488              :       /* prologue cost for vec_init and vec_step.  */
    9489         3571 :       prologue_cost = record_stmt_cost (cost_vec, 2, scalar_to_vec,
    9490              :                                         slp_node, 0, vect_prologue);
    9491              : 
    9492         3571 :       if (dump_enabled_p ())
    9493          133 :         dump_printf_loc (MSG_NOTE, vect_location,
    9494              :                          "vect_model_induction_cost: inside_cost = %d, "
    9495              :                          "prologue_cost = %d. \n", inside_cost,
    9496              :                          prologue_cost);
    9497              : 
    9498         3571 :       SLP_TREE_TYPE (slp_node) = induc_vec_info_type;
    9499         3571 :       DUMP_VECT_SCOPE ("vectorizable_nonlinear_induction");
    9500         3571 :       return true;
    9501              :     }
    9502              : 
    9503              :   /* Transform.  */
    9504              : 
    9505              :   /* Compute a vector variable, initialized with the first VF values of
    9506              :      the induction variable.  E.g., for an iv with IV_PHI='X' and
    9507              :      evolution S, for a vector of 4 units, we want to compute:
    9508              :      [X, X + S, X + 2*S, X + 3*S].  */
    9509              : 
    9510          936 :   if (dump_enabled_p ())
    9511           43 :     dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
    9512              : 
    9513          936 :   pe = loop_preheader_edge (iv_loop);
    9514              :   /* Find the first insertion point in the BB.  */
    9515          936 :   basic_block bb = gimple_bb (phi);
    9516          936 :   si = gsi_after_labels (bb);
    9517              : 
    9518          936 :   gimple_seq stmts = NULL;
    9519              : 
    9520          936 :   niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
    9521              :   /* If we are using the loop mask to "peel" for alignment then we need
    9522              :      to adjust the start value here.  */
    9523          936 :   if (niters_skip != NULL_TREE)
    9524            0 :     init_expr = vect_peel_nonlinear_iv_init (&stmts, init_expr, niters_skip,
    9525              :                                              step_expr, induction_type, false);
    9526              : 
    9527          936 :   vec_init = vect_create_nonlinear_iv_init (&stmts, init_expr,
    9528              :                                             step_expr, nunits, vectype,
    9529              :                                             induction_type);
    9530          936 :   if (stmts)
    9531              :     {
    9532          169 :       new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
    9533          169 :       gcc_assert (!new_bb);
    9534              :     }
    9535              : 
    9536          936 :   stmts = NULL;
    9537          936 :   new_name = vect_create_nonlinear_iv_step (&stmts, step_expr,
    9538              :                                             vf, induction_type);
    9539          936 :   if (stmts)
    9540              :     {
    9541            0 :       new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
    9542            0 :       gcc_assert (!new_bb);
    9543              :     }
    9544              : 
    9545          936 :   vec_step = vect_create_nonlinear_iv_vec_step (loop_vinfo, stmt_info,
    9546              :                                                 new_name, vectype,
    9547              :                                                 induction_type);
    9548              :   /* Create the following def-use cycle:
    9549              :      loop prolog:
    9550              :      vec_init = ...
    9551              :      vec_step = ...
    9552              :      loop:
    9553              :      vec_iv = PHI <vec_init, vec_loop>
    9554              :      ...
    9555              :      STMT
    9556              :      ...
    9557              :      vec_loop = vec_iv + vec_step;  */
    9558              : 
    9559              :   /* Create the induction-phi that defines the induction-operand.  */
    9560          936 :   vec_dest = vect_get_new_vect_var (vectype, vect_simple_var, "vec_iv_");
    9561          936 :   induction_phi = create_phi_node (vec_dest, iv_loop->header);
    9562          936 :   induc_def = PHI_RESULT (induction_phi);
    9563              : 
    9564              :   /* Create the iv update inside the loop.  */
    9565          936 :   stmts = NULL;
    9566          936 :   vec_def = vect_update_nonlinear_iv (&stmts, vectype,
    9567              :                                       induc_def, vec_step,
    9568              :                                       induction_type);
    9569              : 
    9570          936 :   gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
    9571          936 :   new_stmt = SSA_NAME_DEF_STMT (vec_def);
    9572              : 
    9573              :   /* Set the arguments of the phi node:  */
    9574          936 :   add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
    9575          936 :   add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
    9576              :                UNKNOWN_LOCATION);
    9577              : 
    9578          936 :   slp_node->push_vec_def (induction_phi);
    9579              : 
    9580              :   /* In case that vectorization factor (VF) is bigger than the number
    9581              :      of elements that we can fit in a vectype (nunits), we have to generate
    9582              :      more than one vector stmt - i.e - we need to "unroll" the
    9583              :      vector stmt by a factor VF/nunits.  For more details see documentation
    9584              :      in vectorizable_operation.  */
    9585              : 
    9586          936 :   if (ncopies > 1)
    9587              :     {
    9588          289 :       stmts = NULL;
    9589              :       /* FORNOW. This restriction should be relaxed.  */
    9590          289 :       gcc_assert (!nested_in_vect_loop);
    9591              : 
    9592          289 :       new_name = vect_create_nonlinear_iv_step (&stmts, step_expr,
    9593              :                                                 nunits, induction_type);
    9594              : 
    9595          289 :       vec_step = vect_create_nonlinear_iv_vec_step (loop_vinfo, stmt_info,
    9596              :                                                     new_name, vectype,
    9597              :                                                     induction_type);
    9598          289 :       vec_def = induc_def;
    9599         1073 :       for (i = 1; i < ncopies; i++)
    9600              :         {
    9601              :           /* vec_i = vec_prev + vec_step.  */
    9602          495 :           stmts = NULL;
    9603          495 :           vec_def = vect_update_nonlinear_iv (&stmts, vectype,
    9604              :                                               vec_def, vec_step,
    9605              :                                               induction_type);
    9606          495 :           gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
    9607          495 :           new_stmt = SSA_NAME_DEF_STMT (vec_def);
    9608          495 :           slp_node->push_vec_def (new_stmt);
    9609              :         }
    9610              :     }
    9611              : 
    9612          936 :   if (dump_enabled_p ())
    9613           86 :     dump_printf_loc (MSG_NOTE, vect_location,
    9614              :                      "transform induction: created def-use cycle: %G%G",
    9615           43 :                      (gimple *) induction_phi, SSA_NAME_DEF_STMT (vec_def));
    9616              : 
    9617              :   return true;
    9618              : }
    9619              : 
    9620              : /* Return true if the scalar initial values and steps of the SLP induction
    9621              :    lanes allow the first CANDIDATE_NIVS IVs to be reused circularly for the
    9622              :    remaining lanes.  */
    9623              : static bool
    9624           26 : vect_slp_induction_reuse_p (tree *steps, tree *inits, unsigned group_size,
    9625              :                           unsigned HOST_WIDE_INT const_nunits,
    9626              :                           unsigned candidate_nivs, unsigned nivs)
    9627              : {
    9628           26 :   gcc_assert (candidate_nivs > 0);
    9629           26 :   gcc_assert (candidate_nivs < nivs);
    9630              : 
    9631              :   /* This function compares only STEPS and INITS, so all checked lanes must
    9632              :      precede the first wrap of the SLP group.  */
    9633           26 :   gcc_assert (nivs * const_nunits <= group_size);
    9634              : 
    9635           62 :   for (unsigned ivn = candidate_nivs; ivn < nivs; ++ivn)
    9636              :     {
    9637           42 :       unsigned reuse_ivn = ivn % candidate_nivs;
    9638          172 :       for (unsigned HOST_WIDE_INT eltn = 0; eltn < const_nunits; ++eltn)
    9639              :         {
    9640          136 :           unsigned HOST_WIDE_INT elt = ivn * const_nunits + eltn;
    9641          136 :           unsigned HOST_WIDE_INT reused_elt
    9642          136 :             = reuse_ivn * const_nunits + eltn;
    9643              : 
    9644          136 :           if (!operand_equal_p (steps[elt], steps[reused_elt], 0)
    9645          136 :               || !operand_equal_p (inits[elt], inits[reused_elt], 0))
    9646              :             return false;
    9647              :         }
    9648              :     }
    9649              : 
    9650              :   return true;
    9651              : }
    9652              : 
    9653              : /* Function vectorizable_induction
    9654              : 
    9655              :    Check if STMT_INFO performs an induction computation that can be vectorized.
    9656              :    If VEC_STMT is also passed, vectorize the induction PHI: create a vectorized
    9657              :    phi to replace it, put it in VEC_STMT, and add it to the same basic block.
    9658              :    Return true if STMT_INFO is vectorizable in this way.  */
    9659              : 
    9660              : bool
    9661       344505 : vectorizable_induction (loop_vec_info loop_vinfo,
    9662              :                         stmt_vec_info stmt_info,
    9663              :                         slp_tree slp_node, stmt_vector_for_cost *cost_vec)
    9664              : {
    9665       344505 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    9666       344505 :   bool nested_in_vect_loop = false;
    9667       344505 :   class loop *iv_loop;
    9668       344505 :   tree vec_def;
    9669       344505 :   edge pe = loop_preheader_edge (loop);
    9670       344505 :   basic_block new_bb;
    9671       344505 :   tree vec_init = NULL_TREE, vec_step, t;
    9672       344505 :   tree new_name;
    9673       344505 :   gphi *induction_phi;
    9674       344505 :   tree induc_def, vec_dest;
    9675       344505 :   unsigned i;
    9676       344505 :   tree index_vectype = NULL_TREE;
    9677       344505 :   gimple_stmt_iterator si;
    9678       344505 :   enum vect_induction_op_type induction_type
    9679              :     = STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (stmt_info);
    9680              : 
    9681       344505 :   gphi *phi = dyn_cast <gphi *> (stmt_info->stmt);
    9682       185056 :   if (!phi)
    9683              :     return false;
    9684              : 
    9685       185056 :   if (!STMT_VINFO_RELEVANT_P (stmt_info))
    9686              :     return false;
    9687              : 
    9688              :   /* Make sure it was recognized as induction computation.  */
    9689       185056 :   if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_induction_def)
    9690              :     return false;
    9691              : 
    9692       728514 :   for (auto phi_info : SLP_TREE_SCALAR_STMTS (slp_node))
    9693       185865 :     if (phi_info)
    9694              :       {
    9695       185865 :         gcc_assert (STMT_VINFO_DEF_TYPE (phi_info) == vect_induction_def);
    9696       185865 :         if (STMT_VINFO_LOOP_PHI_EVOLUTION_TYPE (phi_info) != induction_type)
    9697              :           return false;
    9698              :       }
    9699              : 
    9700              :   /* Handle nonlinear induction in a separate place.  */
    9701       180881 :   if (induction_type != vect_step_op_add)
    9702         9903 :     return vectorizable_nonlinear_induction (loop_vinfo, stmt_info,
    9703         9903 :                                              slp_node, cost_vec);
    9704              : 
    9705       170978 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
    9706       170978 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
    9707              : 
    9708              :   /* FORNOW. These restrictions should be relaxed.  */
    9709       170978 :   if (nested_in_vect_loop_p (loop, stmt_info))
    9710              :     {
    9711          789 :       imm_use_iterator imm_iter;
    9712          789 :       use_operand_p use_p;
    9713          789 :       gimple *exit_phi;
    9714          789 :       edge latch_e;
    9715          789 :       tree loop_arg;
    9716              : 
    9717          789 :       exit_phi = NULL;
    9718          789 :       latch_e = loop_latch_edge (loop->inner);
    9719          789 :       loop_arg = PHI_ARG_DEF_FROM_EDGE (phi, latch_e);
    9720         1615 :       FOR_EACH_IMM_USE_FAST (use_p, imm_iter, loop_arg)
    9721              :         {
    9722          852 :           gimple *use_stmt = USE_STMT (use_p);
    9723          852 :           if (is_gimple_debug (use_stmt))
    9724           36 :             continue;
    9725              : 
    9726          816 :           if (!flow_bb_inside_loop_p (loop->inner, gimple_bb (use_stmt)))
    9727              :             {
    9728              :               exit_phi = use_stmt;
    9729              :               break;
    9730              :             }
    9731          789 :         }
    9732          789 :       if (exit_phi)
    9733              :         {
    9734           26 :           stmt_vec_info exit_phi_vinfo = loop_vinfo->lookup_stmt (exit_phi);
    9735           26 :           if (!(STMT_VINFO_RELEVANT_P (exit_phi_vinfo)
    9736           10 :                 && !STMT_VINFO_LIVE_P (exit_phi_vinfo)))
    9737              :             {
    9738           16 :               if (dump_enabled_p ())
    9739           16 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9740              :                                  "inner-loop induction only used outside "
    9741              :                                  "of the outer vectorized loop.\n");
    9742           16 :               return false;
    9743              :             }
    9744              :         }
    9745              : 
    9746          773 :       nested_in_vect_loop = true;
    9747          773 :       iv_loop = loop->inner;
    9748              :     }
    9749              :   else
    9750              :     iv_loop = loop;
    9751       170962 :   gcc_assert (iv_loop == (gimple_bb (phi))->loop_father);
    9752              : 
    9753       170962 :   if (!nunits.is_constant () && SLP_TREE_LANES (slp_node) != 1)
    9754              :     {
    9755              :       /* The current SLP code creates the step value element-by-element.  */
    9756              :       if (dump_enabled_p ())
    9757              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9758              :                          "SLP induction not supported for variable-length"
    9759              :                          " vectors.\n");
    9760              :       return false;
    9761              :     }
    9762              : 
    9763       170962 :   if (FLOAT_TYPE_P (vectype) && !param_vect_induction_float)
    9764              :     {
    9765           12 :       if (dump_enabled_p ())
    9766           12 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9767              :                          "floating point induction vectorization disabled\n");
    9768              :       return false;
    9769              :     }
    9770              : 
    9771       170950 :   tree step_expr = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (stmt_info);
    9772       170950 :   gcc_assert (step_expr != NULL_TREE);
    9773       341876 :   if (INTEGRAL_TYPE_P (TREE_TYPE (step_expr))
    9774       341775 :       && !type_has_mode_precision_p (TREE_TYPE (step_expr)))
    9775              :     {
    9776           12 :       if (dump_enabled_p ())
    9777           12 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9778              :                          "bit-precision induction vectorization not "
    9779              :                          "supported.\n");
    9780              :       return false;
    9781              :     }
    9782       170938 :   tree stept = TREE_TYPE (step_expr);
    9783       170938 :   tree step_vectype
    9784       170938 :     = (!INTEGRAL_TYPE_P (stept) ? vectype
    9785       170837 :        : signed_or_unsigned_type_for (TYPE_UNSIGNED (stept), vectype));
    9786       170938 :   stept = TREE_TYPE (step_vectype);
    9787              : 
    9788              :   /* Check for target support of the vectorized arithmetic used here.  */
    9789       170938 :   if (!target_supports_op_p (step_vectype, PLUS_EXPR, optab_default)
    9790       170938 :       || !target_supports_op_p (step_vectype, MINUS_EXPR, optab_default))
    9791              :       return false;
    9792       141305 :   if (!nunits.is_constant ()
    9793       141305 :       || !LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9794              :     {
    9795            0 :       if (!target_supports_op_p (step_vectype, MULT_EXPR, optab_default))
    9796              :         return false;
    9797              :       /* FLOAT_EXPR when computing VEC_INIT for float inductions.  */
    9798            0 :       if (SCALAR_FLOAT_TYPE_P (stept))
    9799              :         {
    9800            0 :           tree index_type = build_nonstandard_integer_type
    9801            0 :                 (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (stept)), 1);
    9802              : 
    9803            0 :           index_vectype = build_vector_type (index_type, nunits);
    9804            0 :           if (!can_float_p (TYPE_MODE (step_vectype),
    9805            0 :                             TYPE_MODE (index_vectype), 1))
    9806              :             return false;
    9807              :         }
    9808              :     }
    9809              : 
    9810       141305 :   unsigned nvects = vect_get_num_copies (loop_vinfo, slp_node);
    9811       141305 :   if (cost_vec) /* transformation not required.  */
    9812              :     {
    9813       371631 :       unsigned inside_cost = 0, prologue_cost = 0;
    9814              :       /* We eventually need to set a vector type on invariant
    9815              :          arguments.  */
    9816              :       unsigned j;
    9817              :       slp_tree child;
    9818       371631 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (slp_node), j, child)
    9819       247754 :         if (!vect_maybe_update_slp_op_vectype
    9820       247754 :             (child, SLP_TREE_VECTYPE (slp_node)))
    9821              :           {
    9822            0 :             if (dump_enabled_p ())
    9823            0 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9824              :                                "incompatible vector types for "
    9825              :                                "invariants\n");
    9826              :             return false;
    9827              :           }
    9828              :       /* loop cost for vec_loop.  */
    9829       123877 :       inside_cost = record_stmt_cost (cost_vec, nvects,
    9830              :                                       vector_stmt, slp_node, 0, vect_body);
    9831              :       /* prologue cost for vec_init (if not nested) and step.  */
    9832       123877 :       prologue_cost = record_stmt_cost (cost_vec, 1 + !nested_in_vect_loop,
    9833              :                                         scalar_to_vec,
    9834              :                                         slp_node, 0, vect_prologue);
    9835       123877 :       if (dump_enabled_p ())
    9836         4622 :         dump_printf_loc (MSG_NOTE, vect_location,
    9837              :                          "vect_model_induction_cost: inside_cost = %d, "
    9838              :                          "prologue_cost = %d .\n", inside_cost,
    9839              :                          prologue_cost);
    9840              : 
    9841       123877 :       SLP_TREE_TYPE (slp_node) = induc_vec_info_type;
    9842       123877 :       DUMP_VECT_SCOPE ("vectorizable_induction");
    9843       123877 :       return true;
    9844              :     }
    9845              : 
    9846              :   /* Transform.  */
    9847              : 
    9848              :   /* Compute a vector variable, initialized with the first VF values of
    9849              :      the induction variable.  E.g., for an iv with IV_PHI='X' and
    9850              :      evolution S, for a vector of 4 units, we want to compute:
    9851              :      [X, X + S, X + 2*S, X + 3*S].  */
    9852              : 
    9853        17428 :   if (dump_enabled_p ())
    9854         3093 :     dump_printf_loc (MSG_NOTE, vect_location, "transform induction phi.\n");
    9855              : 
    9856        17428 :   pe = loop_preheader_edge (iv_loop);
    9857              :   /* Find the first insertion point in the BB.  */
    9858        17428 :   basic_block bb = gimple_bb (phi);
    9859        17428 :   si = gsi_after_labels (bb);
    9860              : 
    9861              :   /* For SLP induction we have to generate several IVs as for example
    9862              :      with group size 3 we need
    9863              :        [i0, i1, i2, i0 + S0] [i1 + S1, i2 + S2, i0 + 2*S0, i1 + 2*S1]
    9864              :        [i2 + 2*S2, i0 + 3*S0, i1 + 3*S1, i2 + 3*S2].  */
    9865        17428 :   gimple_stmt_iterator incr_si;
    9866        17428 :   bool insert_after;
    9867        17428 :   standard_iv_increment_position (iv_loop, &incr_si, &insert_after);
    9868              : 
    9869              :   /* The initial values are vectorized, but any lanes > group_size
    9870              :      need adjustment.  */
    9871        17428 :   slp_tree init_node
    9872        17428 :       = SLP_TREE_CHILDREN (slp_node)[pe->dest_idx];
    9873              : 
    9874              :   /* Gather steps.  Since we do not vectorize inductions as
    9875              :      cycles we have to reconstruct the step from SCEV data.  */
    9876        17428 :   unsigned group_size = SLP_TREE_LANES (slp_node);
    9877        17428 :   tree *steps = XALLOCAVEC (tree, group_size);
    9878        17428 :   tree *inits = XALLOCAVEC (tree, group_size);
    9879        17428 :   stmt_vec_info phi_info;
    9880        53733 :   FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (slp_node), i, phi_info)
    9881              :     {
    9882        18877 :       steps[i] = STMT_VINFO_LOOP_PHI_EVOLUTION_PART (phi_info);
    9883        18877 :       if (!init_node)
    9884        18646 :         inits[i] = gimple_phi_arg_def (as_a<gphi *> (phi_info->stmt),
    9885              :                                        pe->dest_idx);
    9886              :     }
    9887              : 
    9888              :   /* Now generate the IVs.  */
    9889        34856 :   gcc_assert (multiple_p (nunits * nvects, group_size));
    9890        17428 :   unsigned nivs;
    9891        17428 :   unsigned HOST_WIDE_INT const_nunits;
    9892        17428 :   if (nested_in_vect_loop)
    9893              :     nivs = nvects;
    9894        17218 :   else if (nunits.is_constant (&const_nunits)
    9895        17218 :            && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9896              :     {
    9897        17218 :       gcc_assert (!init_node);
    9898              :       /* Compute the number of distinct IVs we need.  We can reduce the
    9899              :          number when later vector chunks are equal to earlier chunks.  */
    9900        17218 :       nivs = least_common_multiple (group_size, const_nunits) / const_nunits;
    9901        17218 :       unsigned group_sizep = group_size;
    9902        17218 :       if (group_sizep % const_nunits == 0)
    9903              :         {
    9904          128 :           group_sizep = group_sizep / const_nunits;
    9905          128 :           unsigned candidate_nivs
    9906          128 :             = least_common_multiple (group_sizep, const_nunits) / const_nunits;
    9907          128 :           if (candidate_nivs < nivs
    9908          128 :               && vect_slp_induction_reuse_p (steps, inits, group_size,
    9909              :                                            const_nunits, candidate_nivs, nivs))
    9910              :             {
    9911           20 :               if (dump_enabled_p ())
    9912           16 :                 dump_printf_loc (MSG_NOTE, vect_location,
    9913              :                                  "reusing %u SLP induction IVs for %u "
    9914              :                                  "vector chunks\n",
    9915              :                                  candidate_nivs, nivs);
    9916              :               nivs = candidate_nivs;
    9917              :             }
    9918              :         }
    9919              :     }
    9920              :   else
    9921              :     {
    9922            0 :       gcc_assert (SLP_TREE_LANES (slp_node) == 1);
    9923              :       nivs = 1;
    9924              :     }
    9925        17428 :   gimple_seq init_stmts = NULL;
    9926        17428 :   gimple_seq lupdate_mul_stmts = NULL;
    9927        17428 :   tree lupdate_mul = NULL_TREE;
    9928        17428 :   if (!nested_in_vect_loop)
    9929              :     {
    9930        17218 :       if (nunits.is_constant (&const_nunits)
    9931        17218 :           && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9932              :         {
    9933              :           /* The number of iterations covered in one vector iteration.  */
    9934        17218 :           unsigned lup_mul = (nvects * const_nunits) / group_size;
    9935        17218 :           lupdate_mul
    9936        17218 :             = build_vector_from_val (step_vectype,
    9937        17218 :                                      SCALAR_FLOAT_TYPE_P (stept)
    9938           28 :                                      ? build_real_from_wide (stept, lup_mul,
    9939              :                                                              UNSIGNED)
    9940        34408 :                                      : build_int_cstu (stept, lup_mul));
    9941              :         }
    9942              :       else
    9943              :         {
    9944            0 :           gimple_seq *update_stmts
    9945              :             = LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo)
    9946              :                 ? &init_stmts
    9947              :                 : &lupdate_mul_stmts;
    9948            0 :           if (SCALAR_FLOAT_TYPE_P (stept))
    9949              :             {
    9950            0 :               tree increment
    9951            0 :                 = gimple_convert (update_stmts, integer_type_node,
    9952              :                                   LOOP_VINFO_IV_INCREMENT (loop_vinfo));
    9953            0 :               lupdate_mul = gimple_build (update_stmts, FLOAT_EXPR, stept,
    9954              :                                           increment);
    9955              :             }
    9956              :           else
    9957            0 :             lupdate_mul = gimple_convert (update_stmts, stept,
    9958              :                                          LOOP_VINFO_IV_INCREMENT (loop_vinfo));
    9959            0 :           lupdate_mul = gimple_build_vector_from_val (update_stmts,
    9960              :                                                       step_vectype,
    9961              :                                                       lupdate_mul);
    9962              :         }
    9963              :     }
    9964        17428 :   tree peel_mul = NULL_TREE;
    9965        17428 :   if (LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo))
    9966              :     {
    9967            0 :       if (SCALAR_FLOAT_TYPE_P (stept))
    9968            0 :         peel_mul = gimple_build (&init_stmts, FLOAT_EXPR, stept,
    9969              :                                  LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo));
    9970              :       else
    9971            0 :         peel_mul = gimple_convert (&init_stmts, stept,
    9972              :                                    LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo));
    9973            0 :       peel_mul = gimple_build_vector_from_val (&init_stmts,
    9974              :                                                step_vectype, peel_mul);
    9975              :     }
    9976        17428 :   tree step_mul = NULL_TREE;
    9977        17428 :   unsigned ivn;
    9978        17428 :   auto_vec<tree> vec_steps;
    9979        35452 :   for (ivn = 0; ivn < nivs; ++ivn)
    9980              :     {
    9981        18024 :       gimple_seq stmts = NULL;
    9982        18024 :       bool invariant = true;
    9983        18024 :       if (nunits.is_constant (&const_nunits)
    9984        18024 :           && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
    9985              :         {
    9986        18024 :           tree_vector_builder step_elts (step_vectype, const_nunits, 1);
    9987        18024 :           tree_vector_builder init_elts (vectype, const_nunits, 1);
    9988        18024 :           tree_vector_builder mul_elts (step_vectype, const_nunits, 1);
    9989       130596 :           for (unsigned eltn = 0; eltn < const_nunits; ++eltn)
    9990              :             {
    9991              :               /* The scalar steps of the IVs.  */
    9992        94548 :               tree elt = steps[(ivn*const_nunits + eltn) % group_size];
    9993        94548 :               elt = gimple_convert (&init_stmts, TREE_TYPE (step_vectype), elt);
    9994        94548 :               step_elts.quick_push (elt);
    9995        94548 :               if (!init_node)
    9996              :                 {
    9997              :                   /* The scalar inits of the IVs if not vectorized.  */
    9998        93330 :                   elt = inits[(ivn*const_nunits + eltn) % group_size];
    9999        93330 :                   if (!useless_type_conversion_p (TREE_TYPE (vectype),
   10000        93330 :                                                   TREE_TYPE (elt)))
   10001          282 :                     elt = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
   10002          282 :                                         TREE_TYPE (vectype), elt);
   10003        93330 :                   init_elts.quick_push (elt);
   10004              :                 }
   10005              :               /* The number of steps to add to the initial values.  */
   10006        94548 :               unsigned mul_elt = (ivn*const_nunits + eltn) / group_size;
   10007       189096 :               mul_elts.quick_push (SCALAR_FLOAT_TYPE_P (stept)
   10008       188994 :                                    ? build_real_from_wide (stept, mul_elt,
   10009              :                                                            UNSIGNED)
   10010       188994 :                                    : build_int_cstu (stept, mul_elt));
   10011              :             }
   10012        18024 :           vec_step = gimple_build_vector (&init_stmts, &step_elts);
   10013        18024 :           step_mul = gimple_build_vector (&init_stmts, &mul_elts);
   10014        18024 :           if (!init_node)
   10015        17780 :             vec_init = gimple_build_vector (&init_stmts, &init_elts);
   10016        18024 :         }
   10017              :       else
   10018              :         {
   10019            0 :           tree step = gimple_convert (&init_stmts, stept, steps[0]);
   10020            0 :           if (init_node)
   10021              :             ;
   10022            0 :           else if (INTEGRAL_TYPE_P (stept))
   10023              :             {
   10024            0 :               new_name = gimple_convert (&init_stmts, stept, inits[0]);
   10025              :               /* Build the initial value directly as a VEC_SERIES_EXPR.  */
   10026            0 :               vec_init = gimple_build (&init_stmts, VEC_SERIES_EXPR,
   10027              :                                        step_vectype, new_name, step);
   10028            0 :               if (!useless_type_conversion_p (vectype, step_vectype))
   10029            0 :                 vec_init = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
   10030              :                                          vectype, vec_init);
   10031              :             }
   10032              :           else
   10033              :             {
   10034              :               /* Build:
   10035              :                  [base, base, base, ...]
   10036              :                  + (vectype) [0, 1, 2, ...] * [step, step, step, ...].  */
   10037            0 :               gcc_assert (SCALAR_FLOAT_TYPE_P (stept));
   10038            0 :               gcc_assert (flag_associative_math);
   10039            0 :               gcc_assert (index_vectype != NULL_TREE);
   10040              : 
   10041            0 :               tree index = build_index_vector (index_vectype, 0, 1);
   10042            0 :               new_name = gimple_convert (&init_stmts, stept, inits[0]);
   10043            0 :               tree base_vec = gimple_build_vector_from_val (&init_stmts,
   10044              :                                                             step_vectype,
   10045              :                                                             new_name);
   10046            0 :               tree step_vec = gimple_build_vector_from_val (&init_stmts,
   10047              :                                                             step_vectype,
   10048              :                                                             step);
   10049            0 :               vec_init = gimple_build (&init_stmts, FLOAT_EXPR,
   10050              :                                        step_vectype, index);
   10051            0 :               vec_init = gimple_build (&init_stmts, MULT_EXPR,
   10052              :                                        step_vectype, vec_init, step_vec);
   10053            0 :               vec_init = gimple_build (&init_stmts, PLUS_EXPR,
   10054              :                                        step_vectype, vec_init, base_vec);
   10055            0 :               if (!useless_type_conversion_p (vectype, step_vectype))
   10056            0 :                 vec_init = gimple_build (&init_stmts, VIEW_CONVERT_EXPR,
   10057              :                                          vectype, vec_init);
   10058              :             }
   10059              :           /* iv_loop is nested in the loop to be vectorized. Generate:
   10060              :              vec_step = [S, S, S, S]  */
   10061            0 :           t = unshare_expr (step);
   10062            0 :           gcc_assert (CONSTANT_CLASS_P (t)
   10063              :                       || TREE_CODE (t) == SSA_NAME);
   10064            0 :           vec_step = gimple_build_vector_from_val (&init_stmts,
   10065              :                                                    step_vectype, t);
   10066              :         }
   10067        18024 :       vec_steps.safe_push (vec_step);
   10068        18024 :       if (peel_mul)
   10069              :         {
   10070            0 :           if (!step_mul)
   10071              :             {
   10072            0 :               gcc_assert (!nunits.is_constant ());
   10073              :               step_mul = gimple_build (&init_stmts,
   10074              :                                        MINUS_EXPR, step_vectype,
   10075              :                                        build_zero_cst (step_vectype), peel_mul);
   10076              :             }
   10077              :           else
   10078            0 :             step_mul = gimple_build (&init_stmts,
   10079              :                                      MINUS_EXPR, step_vectype,
   10080              :                                      step_mul, peel_mul);
   10081              :         }
   10082              : 
   10083              :       /* Create the induction-phi that defines the induction-operand.  */
   10084        18024 :       vec_dest = vect_get_new_vect_var (vectype, vect_simple_var,
   10085              :                                         "vec_iv_");
   10086        18024 :       induction_phi = create_phi_node (vec_dest, iv_loop->header);
   10087        18024 :       induc_def = PHI_RESULT (induction_phi);
   10088              : 
   10089              :       /* Create the iv update inside the loop  */
   10090        18024 :       tree up = vec_step;
   10091        18024 :       if (lupdate_mul)
   10092              :          {
   10093        17780 :            if (lupdate_mul_stmts)
   10094            0 :              gimple_seq_add_seq (&stmts, lupdate_mul_stmts);
   10095        17780 :            up = gimple_build (&stmts, MULT_EXPR, step_vectype, vec_step,
   10096              :                               lupdate_mul);
   10097              :          }
   10098        18024 :       vec_def = gimple_convert (&stmts, step_vectype, induc_def);
   10099        18024 :       vec_def = gimple_build (&stmts, PLUS_EXPR, step_vectype, vec_def, up);
   10100        18024 :       vec_def = gimple_convert (&stmts, vectype, vec_def);
   10101        18024 :       insert_iv_increment (&incr_si, insert_after, stmts);
   10102        18024 :       add_phi_arg (induction_phi, vec_def, loop_latch_edge (iv_loop),
   10103              :                    UNKNOWN_LOCATION);
   10104              : 
   10105        18024 :       if (init_node)
   10106          244 :         vec_init = vect_get_slp_vect_def (init_node, ivn);
   10107        18024 :       if (!nested_in_vect_loop
   10108        18024 :           && step_mul
   10109        18024 :           && !integer_zerop (step_mul))
   10110              :         {
   10111        17302 :           gcc_assert (invariant);
   10112        17302 :           vec_def = gimple_convert (&init_stmts, step_vectype, vec_init);
   10113        17302 :           up = gimple_build (&init_stmts, MULT_EXPR, step_vectype,
   10114              :                              vec_step, step_mul);
   10115        17302 :           vec_def = gimple_build (&init_stmts, PLUS_EXPR, step_vectype,
   10116              :                                   vec_def, up);
   10117        17302 :           vec_init = gimple_convert (&init_stmts, vectype, vec_def);
   10118              :         }
   10119              : 
   10120              :       /* Set the arguments of the phi node:  */
   10121        18024 :       add_phi_arg (induction_phi, vec_init, pe, UNKNOWN_LOCATION);
   10122              : 
   10123        18024 :       slp_node->push_vec_def (induction_phi);
   10124              :     }
   10125        17428 :   if (!nested_in_vect_loop)
   10126              :     {
   10127              :       /* Fill up to the number of vectors we need for the whole group.  */
   10128        17218 :       if (nunits.is_constant (&const_nunits)
   10129        17218 :           && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
   10130        17218 :         nivs = least_common_multiple (group_size, const_nunits) / const_nunits;
   10131              :       else
   10132              :         nivs = 1;
   10133        17218 :       vec_steps.reserve (nivs-ivn);
   10134        17218 :       unsigned generated_nivs = ivn;
   10135        17218 :       gcc_assert (generated_nivs > 0);
   10136        17254 :       for (; ivn < nivs; ++ivn)
   10137              :         {
   10138           36 :           unsigned reuse_ivn = ivn % generated_nivs;
   10139           36 :           slp_node->push_vec_def (SLP_TREE_VEC_DEFS (slp_node)[reuse_ivn]);
   10140           36 :           vec_steps.quick_push (vec_steps[reuse_ivn]);
   10141              :         }
   10142              :     }
   10143              : 
   10144              :   /* Re-use IVs when we can.  We are generating further vector
   10145              :      stmts by adding VF' * stride to the IVs generated above.  */
   10146        17428 :   if (ivn < nvects)
   10147              :     {
   10148         3605 :       if (nunits.is_constant (&const_nunits)
   10149         3605 :           && LOOP_VINFO_IV_INCREMENT_INVARIANT_P (loop_vinfo))
   10150              :         {
   10151         3605 :           unsigned vfp = (least_common_multiple (group_size, const_nunits)
   10152         3605 :                           / group_size);
   10153         3605 :           lupdate_mul
   10154         3605 :               = build_vector_from_val (step_vectype,
   10155         3605 :                                        SCALAR_FLOAT_TYPE_P (stept)
   10156            8 :                                        ? build_real_from_wide (stept,
   10157            8 :                                                                vfp, UNSIGNED)
   10158         7202 :                                        : build_int_cstu (stept, vfp));
   10159              :         }
   10160              :       else
   10161              :         {
   10162            0 :           if (SCALAR_FLOAT_TYPE_P (stept))
   10163              :             {
   10164            0 :               tree tem = build_int_cst (integer_type_node, nunits);
   10165            0 :               lupdate_mul = gimple_build (&init_stmts, FLOAT_EXPR, stept, tem);
   10166              :             }
   10167              :           else
   10168            0 :             lupdate_mul = build_int_cst (stept, nunits);
   10169            0 :           lupdate_mul = gimple_build_vector_from_val (&init_stmts, step_vectype,
   10170              :                                                       lupdate_mul);
   10171              :         }
   10172        11700 :       for (; ivn < nvects; ++ivn)
   10173              :         {
   10174         8095 :           gimple *iv
   10175         8095 :             = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (slp_node)[ivn - nivs]);
   10176         8095 :           tree def = gimple_get_lhs (iv);
   10177         8095 :           if (ivn < 2*nivs)
   10178         3703 :             vec_steps[ivn - nivs]
   10179         3703 :               = gimple_build (&init_stmts, MULT_EXPR, step_vectype,
   10180         3703 :                               vec_steps[ivn - nivs], lupdate_mul);
   10181         8095 :           gimple_seq stmts = NULL;
   10182         8095 :           def = gimple_convert (&stmts, step_vectype, def);
   10183        24285 :           def = gimple_build (&stmts, PLUS_EXPR, step_vectype,
   10184         8095 :                               def, vec_steps[ivn % nivs]);
   10185         8095 :           def = gimple_convert (&stmts, vectype, def);
   10186         8095 :           if (gimple_code (iv) == GIMPLE_PHI)
   10187         3703 :             gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
   10188              :           else
   10189              :             {
   10190         4392 :               gimple_stmt_iterator tgsi = gsi_for_stmt (iv);
   10191         4392 :               gsi_insert_seq_after (&tgsi, stmts, GSI_CONTINUE_LINKING);
   10192              :             }
   10193         8095 :           slp_node->push_vec_def (def);
   10194              :         }
   10195              :     }
   10196              : 
   10197        17428 :   new_bb = gsi_insert_seq_on_edge_immediate (pe, init_stmts);
   10198        17428 :   gcc_assert (!new_bb);
   10199              : 
   10200        17428 :   return true;
   10201        17428 : }
   10202              : 
   10203              : /* Function vectorizable_live_operation_1.
   10204              : 
   10205              :    helper function for vectorizable_live_operation.  */
   10206              : 
   10207              : static tree
   10208         3143 : vectorizable_live_operation_1 (loop_vec_info loop_vinfo, basic_block exit_bb,
   10209              :                                tree vectype, slp_tree slp_node,
   10210              :                                tree bitsize, tree bitstart, tree vec_lhs,
   10211              :                                tree lhs_type, gimple_stmt_iterator *exit_gsi)
   10212              : {
   10213         3143 :   gcc_assert (single_pred_p (exit_bb) || LOOP_VINFO_EARLY_BREAKS (loop_vinfo));
   10214              : 
   10215         3143 :   tree vec_lhs_phi = copy_ssa_name (vec_lhs);
   10216         3143 :   gimple *phi = create_phi_node (vec_lhs_phi, exit_bb);
   10217         9431 :   for (unsigned i = 0; i < gimple_phi_num_args (phi); i++)
   10218         3145 :     SET_PHI_ARG_DEF (phi, i, vec_lhs);
   10219              : 
   10220         3143 :   gimple_seq stmts = NULL;
   10221         3143 :   tree new_tree;
   10222              : 
   10223              :   /* If bitstart is 0 then we can use a BIT_FIELD_REF  */
   10224         3143 :   if (integer_zerop (bitstart))
   10225              :     {
   10226          243 :       tree scalar_res = gimple_build (&stmts, BIT_FIELD_REF, TREE_TYPE (vectype),
   10227              :                                       vec_lhs_phi, bitsize, bitstart);
   10228              : 
   10229              :       /* Convert the extracted vector element to the scalar type.  */
   10230          243 :       new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
   10231              :     }
   10232         2900 :   else if (LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
   10233              :     {
   10234              :       /* Emit:
   10235              : 
   10236              :          SCALAR_RES = VEC_EXTRACT <VEC_LHS, LEN - 1>
   10237              : 
   10238              :          where VEC_LHS is the vectorized live-out result, LEN is the length of
   10239              :          the vector, BIAS is the load-store bias.  The bias should not be used
   10240              :          at all since we are not using load/store operations, but LEN will be
   10241              :          REALLEN + BIAS, so subtract it to get to the correct position.  */
   10242            0 :       gcc_assert (SLP_TREE_LANES (slp_node) == 1);
   10243            0 :       gimple_seq tem = NULL;
   10244            0 :       gimple_stmt_iterator gsi = gsi_last (tem);
   10245            0 :       tree len = vect_get_len (loop_vinfo, &gsi, 1, vectype, 0, 1, false);
   10246            0 :       gimple_seq_add_seq (&stmts, tem);
   10247              : 
   10248              :       /* LAST_INDEX = LEN - 1.  */
   10249            0 :       tree last_index = gimple_build (&stmts, MINUS_EXPR, TREE_TYPE (len),
   10250            0 :                                      len, build_one_cst (TREE_TYPE (len)));
   10251              : 
   10252              :       /* SCALAR_RES = VEC_EXTRACT <VEC_LHS, LEN - 1>.  */
   10253            0 :       tree scalar_res
   10254            0 :         = gimple_build (&stmts, CFN_VEC_EXTRACT, TREE_TYPE (vectype),
   10255              :                         vec_lhs_phi, last_index);
   10256              : 
   10257              :       /* Convert the extracted vector element to the scalar type.  */
   10258            0 :       new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
   10259              :     }
   10260         2900 :   else if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
   10261              :     {
   10262              :       /* Emit:
   10263              : 
   10264              :          SCALAR_RES = EXTRACT_LAST_ACTIVE <VEC_LHS, MASK>
   10265              : 
   10266              :          where VEC_LHS is the vectorized live-out result and MASK is
   10267              :          the loop mask for the final iteration.  */
   10268            0 :       gcc_assert (SLP_TREE_LANES (slp_node) == 1);
   10269            0 :       tree scalar_type = TREE_TYPE (vectype);
   10270            0 :       gimple_seq tem = NULL;
   10271            0 :       gimple_stmt_iterator gsi = gsi_last (tem);
   10272            0 :       tree mask = vect_get_mask (loop_vinfo, &gsi, 1, vectype, 0);
   10273            0 :       tree scalar_res;
   10274            0 :       gimple_seq_add_seq (&stmts, tem);
   10275              : 
   10276            0 :       scalar_res = gimple_build (&stmts, CFN_EXTRACT_LAST_ACTIVE, scalar_type,
   10277              :                                  mask, vec_lhs_phi);
   10278              : 
   10279              :       /* Convert the extracted vector element to the scalar type.  */
   10280            0 :       new_tree = gimple_convert (&stmts, lhs_type, scalar_res);
   10281              :     }
   10282              :   else
   10283              :     {
   10284         2900 :       tree bftype = TREE_TYPE (vectype);
   10285         2900 :       if (VECTOR_BOOLEAN_TYPE_P (vectype))
   10286           87 :         bftype = build_nonstandard_integer_type (tree_to_uhwi (bitsize), 1);
   10287         2900 :       new_tree = build3 (BIT_FIELD_REF, bftype, vec_lhs_phi, bitsize, bitstart);
   10288         2900 :       new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree),
   10289              :                                        &stmts, true, NULL_TREE);
   10290              :     }
   10291              : 
   10292         3143 :   *exit_gsi = gsi_after_labels (exit_bb);
   10293         3143 :   if (stmts)
   10294         3143 :     gsi_insert_seq_before (exit_gsi, stmts, GSI_SAME_STMT);
   10295              : 
   10296         3143 :   return new_tree;
   10297              : }
   10298              : 
   10299              : /* Function vectorizable_live_operation.
   10300              : 
   10301              :    STMT_INFO computes a value that is used outside the loop.  Check if
   10302              :    it can be supported.  */
   10303              : 
   10304              : bool
   10305       286937 : vectorizable_live_operation (vec_info *vinfo, stmt_vec_info stmt_info,
   10306              :                              slp_tree slp_node, slp_instance slp_node_instance,
   10307              :                              int slp_index, bool vec_stmt_p,
   10308              :                              stmt_vector_for_cost *cost_vec)
   10309              : {
   10310       286937 :   loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
   10311       286937 :   imm_use_iterator imm_iter;
   10312       286937 :   tree lhs, lhs_type, bitsize;
   10313       286937 :   tree vectype = SLP_TREE_VECTYPE (slp_node);
   10314       286937 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
   10315       286937 :   gimple *use_stmt;
   10316       286937 :   use_operand_p use_p;
   10317       286937 :   auto_vec<tree> vec_oprnds;
   10318       286937 :   int vec_entry = 0;
   10319       286937 :   poly_uint64 vec_index = 0;
   10320              : 
   10321       286937 :   gcc_assert (STMT_VINFO_LIVE_P (stmt_info)
   10322              :               || LOOP_VINFO_EARLY_BREAKS (loop_vinfo));
   10323              : 
   10324              :   /* If a stmt of a reduction is live, vectorize it via
   10325              :      vect_create_epilog_for_reduction.  vectorizable_reduction assessed
   10326              :      validity so just trigger the transform here.  */
   10327       286937 :   if (vect_is_reduction (slp_node))
   10328              :     {
   10329        85723 :       if (!vec_stmt_p)
   10330              :         {
   10331        62003 :           SLP_TREE_LIVE_LANES (slp_node).safe_push (slp_index);
   10332        62003 :           return true;
   10333              :         }
   10334              :       /* For SLP reductions we vectorize the epilogue for all involved stmts
   10335              :          together.  For SLP reduction chains we only get here once.  */
   10336        23720 :       if (SLP_INSTANCE_KIND (slp_node_instance) == slp_inst_kind_reduc_group
   10337        23417 :           && slp_index != 0)
   10338              :         return true;
   10339        23239 :       vect_reduc_info reduc_info = info_for_reduction (loop_vinfo, slp_node);
   10340        23239 :       if (VECT_REDUC_INFO_TYPE (reduc_info) == FOLD_LEFT_REDUCTION
   10341        23239 :           || VECT_REDUC_INFO_TYPE (reduc_info) == EXTRACT_LAST_REDUCTION)
   10342              :         return true;
   10343              : 
   10344        22218 :       if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
   10345        22218 :           || !LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
   10346        22206 :         vect_create_epilog_for_reduction (loop_vinfo, stmt_info, slp_node,
   10347              :                                           slp_node_instance,
   10348              :                                           LOOP_VINFO_MAIN_EXIT (loop_vinfo));
   10349              : 
   10350              :       /* If early break we only have to materialize the reduction on the merge
   10351              :          block, but we have to find an alternate exit first.  */
   10352        22218 :       if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   10353              :         {
   10354           31 :           slp_tree phis_node = slp_node_instance->reduc_phis;
   10355           31 :           stmt_info = SLP_TREE_REPRESENTATIVE (phis_node);
   10356           98 :           for (auto exit : get_loop_exit_edges (LOOP_VINFO_LOOP (loop_vinfo)))
   10357           31 :             if (exit != LOOP_VINFO_MAIN_EXIT (loop_vinfo))
   10358              :               {
   10359           26 :                 vect_create_epilog_for_reduction (loop_vinfo, stmt_info,
   10360              :                                                   phis_node, slp_node_instance,
   10361              :                                                   exit);
   10362           26 :                 break;
   10363           31 :               }
   10364           31 :           if (LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo))
   10365           12 :             vect_create_epilog_for_reduction (loop_vinfo, stmt_info,
   10366              :                                               phis_node, slp_node_instance,
   10367              :                                               LOOP_VINFO_MAIN_EXIT
   10368              :                                               (loop_vinfo));
   10369              :         }
   10370              : 
   10371              :       return true;
   10372              :     }
   10373              : 
   10374              :   /* If STMT is not relevant and it is a simple assignment and its inputs are
   10375              :      invariant then it can remain in place, unvectorized.  The original last
   10376              :      scalar value that it computes will be used.  */
   10377       201214 :   if (!STMT_VINFO_RELEVANT_P (stmt_info))
   10378              :     {
   10379            0 :       gcc_assert (is_simple_and_all_uses_invariant (stmt_info, loop_vinfo));
   10380            0 :       if (dump_enabled_p ())
   10381            0 :         dump_printf_loc (MSG_NOTE, vect_location,
   10382              :                          "statement is simple and uses invariant.  Leaving in "
   10383              :                          "place.\n");
   10384              :       return true;
   10385              :     }
   10386              : 
   10387       201214 :   gcc_assert (slp_index >= 0);
   10388              : 
   10389       201214 :   int num_vec = vect_get_num_copies (vinfo, slp_node);
   10390       201214 :   poly_uint64 pos = slp_index;
   10391       201214 :   if (loop_vinfo)
   10392              :     {
   10393              :       /* Get the last occurrence of the scalar index from the concatenation of
   10394              :          all the slp vectors. Calculate which slp vector it is and the index
   10395              :          within.  */
   10396        76956 :       int num_scalar = SLP_TREE_LANES (slp_node);
   10397        76956 :       pos += (num_vec * nunits) - num_scalar;
   10398              :     }
   10399              : 
   10400              :   /* Calculate which vector contains the result, and which lane of
   10401              :      that vector we need.  */
   10402       201214 :   if (!can_div_trunc_p (pos, nunits, &vec_entry, &vec_index))
   10403              :     {
   10404              :       if (dump_enabled_p ())
   10405              :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10406              :                          "Cannot determine which vector holds the"
   10407              :                          " final result.\n");
   10408              :       return false;
   10409              :     }
   10410              : 
   10411       201214 :   if (!vec_stmt_p)
   10412              :     {
   10413              :       /* No transformation required.  */
   10414       183688 :       if (loop_vinfo && LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo))
   10415              :         {
   10416        29544 :           if (SLP_TREE_LANES (slp_node) != 1)
   10417              :             {
   10418           19 :               if (dump_enabled_p ())
   10419           19 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10420              :                                  "can't operate on partial vectors "
   10421              :                                  "because an SLP statement is live after "
   10422              :                                  "the loop.\n");
   10423           19 :               LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
   10424              :             }
   10425        29525 :           else if (num_vec > 1)
   10426              :             {
   10427        16705 :               if (dump_enabled_p ())
   10428           61 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10429              :                                  "can't operate on partial vectors "
   10430              :                                  "because ncopies is greater than 1.\n");
   10431        16705 :               LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
   10432              :             }
   10433              :           else
   10434              :             {
   10435        12820 :               if (direct_internal_fn_supported_p (IFN_EXTRACT_LAST_ACTIVE, vectype,
   10436              :                                                   OPTIMIZE_FOR_SPEED))
   10437            0 :                 vect_record_mask (loop_vinfo, 1, vectype, NULL_TREE);
   10438        12820 :               else if (can_vec_extract_var_idx_p (
   10439        12820 :                          TYPE_MODE (vectype), TYPE_MODE (TREE_TYPE (vectype))))
   10440            0 :                 vect_record_len (loop_vinfo, 1, vectype, 1);
   10441              :               else
   10442              :                 {
   10443        12820 :                   if (dump_enabled_p ())
   10444          755 :                     dump_printf_loc (
   10445          755 :                       MSG_MISSED_OPTIMIZATION, vect_location,
   10446              :                       "can't operate on partial vectors "
   10447              :                       "because the target doesn't support extract "
   10448              :                       "last reduction.\n");
   10449        12820 :                   LOOP_VINFO_CAN_USE_PARTIAL_VECTORS_P (loop_vinfo) = false;
   10450              :                 }
   10451              :             }
   10452              :         }
   10453        29544 :       record_stmt_cost (cost_vec, 1, vec_to_scalar, slp_node,
   10454              :                         0, loop_vinfo ? vect_epilogue : vect_body);
   10455       183688 :       SLP_TREE_LIVE_LANES (slp_node).safe_push (slp_index);
   10456       183688 :       return true;
   10457              :     }
   10458              : 
   10459              :   /* Use the lhs of the original scalar statement.  */
   10460        17526 :   gimple *stmt = vect_orig_stmt (stmt_info)->stmt;
   10461        17526 :   if (dump_enabled_p ())
   10462         1096 :     dump_printf_loc (MSG_NOTE, vect_location, "extracting lane for live "
   10463              :                      "stmt %G", stmt);
   10464              : 
   10465        17526 :   lhs = gimple_get_lhs (stmt);
   10466        17526 :   lhs_type = TREE_TYPE (lhs);
   10467              : 
   10468        17526 :   bitsize = vector_element_bits_tree (vectype);
   10469              : 
   10470              :   /* Get the vectorized lhs of STMT and the lane to use (counted in bits).  */
   10471        17526 :   gcc_assert (!loop_vinfo
   10472              :               || ((!LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
   10473              :                    && !LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
   10474              :                   || SLP_TREE_LANES (slp_node) == 1));
   10475              : 
   10476              :   /* Get the correct slp vectorized stmt.  */
   10477        17526 :   tree vec_lhs = SLP_TREE_VEC_DEFS (slp_node)[vec_entry];
   10478              : 
   10479              :   /* In case we need to early break vectorize also get the first stmt.  */
   10480        17526 :   tree vec_lhs0 = SLP_TREE_VEC_DEFS (slp_node)[0];
   10481              : 
   10482              :   /* Get entry to use.  */
   10483        17526 :   tree bitstart = bitsize_int (vec_index);
   10484        17526 :   bitstart = int_const_binop (MULT_EXPR, bitsize, bitstart);
   10485              : 
   10486        17526 :   if (loop_vinfo)
   10487              :     {
   10488              :       /* Ensure the VEC_LHS for lane extraction stmts satisfy loop-closed PHI
   10489              :          requirement, insert one phi node for it.  It looks like:
   10490              :            loop;
   10491              :          BB:
   10492              :            # lhs' = PHI <lhs>
   10493              :          ==>
   10494              :            loop;
   10495              :          BB:
   10496              :            # vec_lhs' = PHI <vec_lhs>
   10497              :            new_tree = lane_extract <vec_lhs', ...>;
   10498              :            lhs' = new_tree;  */
   10499              : 
   10500         3233 :       class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   10501              :       /* Check if we have a loop where the chosen exit is not the main exit,
   10502              :          in these cases for an early break we restart the iteration the vector code
   10503              :          did.  For the live values we want the value at the start of the iteration
   10504              :          rather than at the end.  */
   10505         3233 :       edge main_e = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
   10506         3233 :       bool all_exits_as_early_p = LOOP_VINFO_EARLY_BREAKS_VECT_PEELED (loop_vinfo);
   10507        13533 :       FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
   10508        10300 :         if (!is_gimple_debug (use_stmt)
   10509        10300 :             && !flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)))
   10510         3143 :           FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
   10511              :             {
   10512         3143 :               edge e = gimple_phi_arg_edge (as_a <gphi *> (use_stmt),
   10513         3143 :                                            phi_arg_index_from_use (use_p));
   10514         3143 :               gcc_assert (loop_exit_edge_p (loop, e));
   10515         3143 :               bool main_exit_edge = e == main_e;
   10516         3143 :               tree tmp_vec_lhs = vec_lhs;
   10517         3143 :               tree tmp_bitstart = bitstart;
   10518              : 
   10519              :               /* For early exit where the exit is not in the BB that leads
   10520              :                  to the latch then we're restarting the iteration in the
   10521              :                  scalar loop.  So get the first live value.  */
   10522         3143 :               bool early_break_first_element_p
   10523         3143 :                 = all_exits_as_early_p || !main_exit_edge;
   10524         3143 :               if (early_break_first_element_p)
   10525              :                 {
   10526          225 :                   tmp_vec_lhs = vec_lhs0;
   10527          225 :                   tmp_bitstart = build_zero_cst (TREE_TYPE (bitstart));
   10528              :                 }
   10529              : 
   10530         3143 :               gimple_stmt_iterator exit_gsi;
   10531         3143 :               tree new_tree
   10532         3143 :                   = vectorizable_live_operation_1 (loop_vinfo,
   10533              :                                                    e->dest, vectype,
   10534              :                                                    slp_node, bitsize,
   10535              :                                                    tmp_bitstart, tmp_vec_lhs,
   10536              :                                                    lhs_type, &exit_gsi);
   10537              : 
   10538         3143 :               auto gsi = gsi_for_stmt (use_stmt);
   10539         3143 :               tree lhs_phi = gimple_phi_result (use_stmt);
   10540         3143 :               remove_phi_node (&gsi, false);
   10541         3143 :               gimple *copy = gimple_build_assign (lhs_phi, new_tree);
   10542         3143 :               gsi_insert_before (&exit_gsi, copy, GSI_SAME_STMT);
   10543         3143 :               break;
   10544         3233 :             }
   10545              : 
   10546              :       /* There a no further out-of-loop uses of lhs by LC-SSA construction.  */
   10547        10390 :       FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
   10548         7157 :         gcc_assert (is_gimple_debug (use_stmt)
   10549         3233 :                     || flow_bb_inside_loop_p (loop, gimple_bb (use_stmt)));
   10550              :     }
   10551              :   else
   10552              :     {
   10553              :       /* For basic-block vectorization simply insert the lane-extraction.  */
   10554        14293 :       tree bftype = TREE_TYPE (vectype);
   10555        14293 :       if (VECTOR_BOOLEAN_TYPE_P (vectype))
   10556           36 :         bftype = build_nonstandard_integer_type (tree_to_uhwi (bitsize), 1);
   10557        14293 :       tree new_tree = build3 (BIT_FIELD_REF, bftype,
   10558              :                               vec_lhs, bitsize, bitstart);
   10559        14293 :       gimple_seq stmts = NULL;
   10560        14293 :       new_tree = force_gimple_operand (fold_convert (lhs_type, new_tree),
   10561              :                                        &stmts, true, NULL_TREE);
   10562        14293 :       if (TREE_CODE (new_tree) == SSA_NAME
   10563        28586 :           && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
   10564            0 :         SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_tree) = 1;
   10565        14293 :       gimple *vec_stmt = SSA_NAME_DEF_STMT (vec_lhs);
   10566        14293 :       if (TREE_CODE (vec_lhs) != SSA_NAME
   10567        14293 :           || SSA_NAME_IS_DEFAULT_DEF (vec_lhs)
   10568        14293 :           || (vinfo->bbs[0] != gimple_bb (vec_stmt)
   10569         9897 :               && dominated_by_p (CDI_DOMINATORS, vinfo->bbs[0],
   10570         9897 :                                  gimple_bb (vec_stmt))))
   10571            2 :         vinfo->insert_seq_on_entry (stmt_info, stmts);
   10572        14291 :       else if (is_a <gphi *> (vec_stmt))
   10573              :         {
   10574         1392 :           gimple_stmt_iterator si = gsi_after_labels (gimple_bb (vec_stmt));
   10575         1392 :           gsi_insert_seq_before (&si, stmts, GSI_SAME_STMT);
   10576              :         }
   10577              :       else
   10578              :         {
   10579        12899 :           gimple_stmt_iterator si = gsi_for_stmt (vec_stmt);
   10580        12899 :           gsi_insert_seq_after (&si, stmts, GSI_SAME_STMT);
   10581              :         }
   10582              : 
   10583              :       /* Replace use of lhs with newly computed result.  If the use stmt is a
   10584              :          single arg PHI, just replace all uses of PHI result.  It's necessary
   10585              :          because lcssa PHI defining lhs may be before newly inserted stmt.  */
   10586        14293 :       use_operand_p use_p;
   10587        14293 :       stmt_vec_info use_stmt_info;
   10588        77898 :       FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
   10589        63605 :         if (!is_gimple_debug (use_stmt)
   10590        63605 :             && (!(use_stmt_info = vinfo->lookup_stmt (use_stmt))
   10591        47490 :                 || !PURE_SLP_STMT (use_stmt_info)))
   10592              :           {
   10593              :             /* ???  This can happen when the live lane ends up being
   10594              :                rooted in a vector construction code-generated by an
   10595              :                external SLP node (and code-generation for that already
   10596              :                happened).
   10597              :                Doing this is what would happen if that vector CTOR
   10598              :                were not code-generated yet so it is not too bad.
   10599              :                ???  In fact we'd likely want to avoid this situation
   10600              :                in the first place.  */
   10601        26233 :             if (TREE_CODE (new_tree) == SSA_NAME
   10602        26233 :                 && !SSA_NAME_IS_DEFAULT_DEF (new_tree)
   10603        26233 :                 && gimple_code (use_stmt) != GIMPLE_PHI
   10604        49268 :                 && !vect_stmt_dominates_stmt_p (SSA_NAME_DEF_STMT (new_tree),
   10605              :                                                 use_stmt))
   10606              :               {
   10607            0 :                 if (dump_enabled_p ())
   10608            0 :                   dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10609              :                                    "Using original scalar computation for "
   10610              :                                    "live lane because use precedes vector "
   10611              :                                    "def\n");
   10612            0 :                 continue;
   10613              :               }
   10614        54896 :             FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
   10615              :               {
   10616              :                 /* ???  It can also happen that we end up pulling a def into
   10617              :                    a loop where replacing out-of-loop uses would require
   10618              :                    a new LC SSA PHI node.  Retain the original scalar in
   10619              :                    those cases as well.  PR98064.  */
   10620        27448 :                 edge e;
   10621        27448 :                 if (TREE_CODE (new_tree) == SSA_NAME
   10622        27448 :                     && !SSA_NAME_IS_DEFAULT_DEF (new_tree)
   10623        27448 :                     && TREE_CODE (vec_lhs) == SSA_NAME
   10624        27448 :                     && !SSA_NAME_IS_DEFAULT_DEF (vec_lhs)
   10625        27448 :                     && (gimple_bb (use_stmt)->loop_father
   10626        27448 :                         != gimple_bb (vec_stmt)->loop_father)
   10627              :                     /* But a replacement in a LC PHI is OK.  This happens
   10628              :                        in gcc.dg/vect/bb-slp-57.c for example.  */
   10629         3151 :                     && (gimple_code (use_stmt) != GIMPLE_PHI
   10630         1270 :                         || (((e = phi_arg_edge_from_use (use_p)), true)
   10631         1270 :                             && !loop_exit_edge_p
   10632         1270 :                                   (gimple_bb (vec_stmt)->loop_father, e)))
   10633        30043 :                     && !flow_loop_nested_p (gimple_bb (vec_stmt)->loop_father,
   10634         2595 :                                             gimple_bb (use_stmt)->loop_father))
   10635              :                   {
   10636            0 :                     if (dump_enabled_p ())
   10637            0 :                       dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10638              :                                        "Using original scalar computation for "
   10639              :                                        "live lane because there is an "
   10640              :                                        "out-of-loop definition for it\n");
   10641            0 :                     continue;
   10642              :                   }
   10643        27448 :                 SET_USE (use_p, new_tree);
   10644              :               }
   10645        26233 :             update_stmt (use_stmt);
   10646        14293 :           }
   10647              :     }
   10648              : 
   10649              :   return true;
   10650       286937 : }
   10651              : 
   10652              : /* Given loop represented by LOOP_VINFO, return true if computation of
   10653              :    LOOP_VINFO_NITERS (= LOOP_VINFO_NITERSM1 + 1) doesn't overflow, false
   10654              :    otherwise.  */
   10655              : 
   10656              : static bool
   10657        66457 : loop_niters_no_overflow (loop_vec_info loop_vinfo)
   10658              : {
   10659        66457 :   gcc_assert (!LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo));
   10660              : 
   10661              :   /* Constant case.  */
   10662        66457 :   if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo))
   10663              :     {
   10664        38799 :       tree cst_niters = LOOP_VINFO_NITERS (loop_vinfo);
   10665        38799 :       tree cst_nitersm1 = LOOP_VINFO_NITERSM1 (loop_vinfo);
   10666              : 
   10667        38799 :       gcc_assert (TREE_CODE (cst_niters) == INTEGER_CST);
   10668        38799 :       gcc_assert (TREE_CODE (cst_nitersm1) == INTEGER_CST);
   10669        38799 :       if (wi::to_widest (cst_nitersm1) < wi::to_widest (cst_niters))
   10670              :         return true;
   10671              :     }
   10672              : 
   10673        27658 :   widest_int max;
   10674        27658 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   10675              :   /* Check the upper bound of loop niters.  */
   10676        27658 :   if (get_max_loop_iterations (loop, &max))
   10677              :     {
   10678        27658 :       tree type = TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo));
   10679        27658 :       signop sgn = TYPE_SIGN (type);
   10680        27658 :       widest_int type_max = widest_int::from (wi::max_value (type), sgn);
   10681        27658 :       if (max < type_max)
   10682        27446 :         return true;
   10683        27658 :     }
   10684              :   return false;
   10685        66457 : }
   10686              : 
   10687              : /* Return a mask type with half the number of elements as OLD_TYPE,
   10688              :    given that it should have mode NEW_MODE.  */
   10689              : 
   10690              : tree
   10691         4719 : vect_halve_mask_nunits (tree old_type, machine_mode new_mode)
   10692              : {
   10693         4719 :   poly_uint64 nunits = exact_div (TYPE_VECTOR_SUBPARTS (old_type), 2);
   10694         4719 :   return build_truth_vector_type_for_mode (nunits, new_mode);
   10695              : }
   10696              : 
   10697              : /* Return a mask type with twice as many elements as OLD_TYPE,
   10698              :    given that it should have mode NEW_MODE.  */
   10699              : 
   10700              : tree
   10701         7050 : vect_double_mask_nunits (tree old_type, machine_mode new_mode)
   10702              : {
   10703         7050 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (old_type) * 2;
   10704         7050 :   return build_truth_vector_type_for_mode (nunits, new_mode);
   10705              : }
   10706              : 
   10707              : /* Record that a fully-masked version of the loop or SLP region represented by
   10708              :    VINFO would need a sequence of NVECTORS masks that each control a
   10709              :    vector of type VECTYPE.  If SCALAR_MASK is nonnull and VINFO represents a
   10710              :    loop, the fully-masked loop would AND these vector masks with the vector
   10711              :    version of SCALAR_MASK.  If VINFO represents an SLP region then GROUP_SIZE
   10712              :    gives the total number of active lanes across the sequence.  */
   10713              : 
   10714              : void
   10715       108211 : vect_record_mask (vec_info *vinfo, unsigned int nvectors, tree vectype,
   10716              :                   tree scalar_mask, unsigned int group_size)
   10717              : {
   10718       108211 :   gcc_assert (!is_a <bb_vec_info> (vinfo) || group_size != 0);
   10719       108211 :   gcc_assert (nvectors != 0);
   10720       108211 :   vec_masks *masks = &vinfo->masks;
   10721       108211 :   loop_vec_info loop_vinfo = dyn_cast<loop_vec_info> (vinfo);
   10722              : 
   10723       108211 :   if (loop_vinfo && scalar_mask)
   10724              :     {
   10725         5079 :       scalar_cond_masked_key cond (scalar_mask, nvectors);
   10726         5079 :       loop_vinfo->scalar_cond_masked_set.add (cond);
   10727              :     }
   10728              : 
   10729       108211 :   masks->mask_set.add (std::make_pair (vectype, nvectors));
   10730       108211 : }
   10731              : 
   10732              : /* Given a complete set of masks for the loop or SLP region represented by
   10733              :    VINFO, extract mask number INDEX for an rgroup that operates on NVECTORS
   10734              :    vectors of type VECTYPE, where 0 <= INDEX < NVECTORS.  Insert any set-up
   10735              :    statements before GSI.  If VINFO represents an SLP region then GROUP_SIZE
   10736              :    gives the total number of active lanes across the sequence.
   10737              : 
   10738              :    See the comment above vec_masks for more details about the mask
   10739              :    arrangement.  */
   10740              : 
   10741              : tree
   10742          232 : vect_get_mask (vec_info *vinfo, gimple_stmt_iterator *gsi,
   10743              :                unsigned int nvectors, tree vectype, unsigned int index,
   10744              :                unsigned int group_size)
   10745              : {
   10746          232 :   gcc_assert (!is_a <bb_vec_info> (vinfo) || group_size != 0);
   10747          232 :   vec_masks *masks = &LOOP_VINFO_MASKS (vinfo);
   10748              : 
   10749          232 :   if (vinfo->partial_vector_style == vect_partial_vectors_while_ult)
   10750              :     {
   10751            0 :       rgroup_controls *rgm = &(masks->rgc_vec)[nvectors - 1];
   10752            0 :       tree mask_type = rgm->type;
   10753              : 
   10754              :       /* Populate the rgroup's mask array, if this is the first time we've
   10755              :          used it.  */
   10756            0 :       if (rgm->controls.is_empty ())
   10757              :         {
   10758            0 :           rgm->controls.safe_grow_cleared (nvectors, true);
   10759            0 :           for (unsigned int i = 0; i < nvectors; ++i)
   10760              :             {
   10761            0 :               tree mask = make_temp_ssa_name (mask_type, NULL, "loop_mask");
   10762              :               /* Provide a dummy definition until the real one is available.  */
   10763            0 :               SSA_NAME_DEF_STMT (mask) = gimple_build_nop ();
   10764            0 :               rgm->controls[i] = mask;
   10765              :             }
   10766              :         }
   10767              : 
   10768            0 :       tree mask = rgm->controls[index];
   10769            0 :       if (maybe_ne (TYPE_VECTOR_SUBPARTS (mask_type),
   10770            0 :                     TYPE_VECTOR_SUBPARTS (vectype)))
   10771              :         {
   10772              :           /* A loop mask for data type X can be reused for data type Y
   10773              :              if X has N times more elements than Y and if Y's elements
   10774              :              are N times bigger than X's.  In this case each sequence
   10775              :              of N elements in the loop mask will be all-zero or all-one.
   10776              :              We can then view-convert the mask so that each sequence of
   10777              :              N elements is replaced by a single element.  */
   10778            0 :           gcc_assert (multiple_p (TYPE_VECTOR_SUBPARTS (mask_type),
   10779              :                                   TYPE_VECTOR_SUBPARTS (vectype)));
   10780            0 :           gimple_seq seq = NULL;
   10781            0 :           mask_type = truth_type_for (vectype);
   10782            0 :           mask = gimple_build (&seq, VIEW_CONVERT_EXPR, mask_type, mask);
   10783            0 :           if (seq)
   10784            0 :             gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10785              :         }
   10786              :       return mask;
   10787              :     }
   10788          232 :   else if (vinfo->partial_vector_style == vect_partial_vectors_avx512)
   10789              :     {
   10790              :       /* The number of scalars per iteration and the number of vectors are
   10791              :          both compile-time constants.  */
   10792          232 :       unsigned int nscalars_per_iter
   10793          232 :         = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
   10794              :                      vinfo->vectorization_factor)
   10795          232 :             .to_constant ();
   10796              : 
   10797          232 :       rgroup_controls *rgm = &masks->rgc_vec[nscalars_per_iter - 1];
   10798              : 
   10799              :       /* The stored nV is dependent on the mask type produced.  */
   10800          232 :       gcc_assert (exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
   10801              :                              TYPE_VECTOR_SUBPARTS (rgm->type)).to_constant ()
   10802              :                   == rgm->factor);
   10803          232 :       nvectors = rgm->factor;
   10804              : 
   10805              :       /* Populate the rgroup's mask array, if this is the first time we've
   10806              :          used it.  */
   10807          232 :       if (rgm->controls.is_empty ())
   10808              :         {
   10809           26 :           rgm->controls.safe_grow_cleared (nvectors, true);
   10810          144 :           for (unsigned int i = 0; i < nvectors; ++i)
   10811              :             {
   10812           92 :               tree mask = make_temp_ssa_name (rgm->type, NULL, "loop_mask");
   10813              :               /* Provide a dummy definition until the real one is available.  */
   10814           92 :               SSA_NAME_DEF_STMT (mask) = gimple_build_nop ();
   10815           92 :               rgm->controls[i] = mask;
   10816              :             }
   10817              :         }
   10818          232 :       if (known_eq (TYPE_VECTOR_SUBPARTS (rgm->type),
   10819              :                     TYPE_VECTOR_SUBPARTS (vectype)))
   10820          170 :         return rgm->controls[index];
   10821              : 
   10822              :       /* Split the vector if needed.  Since we are dealing with integer mode
   10823              :          masks with AVX512 we can operate on the integer representation
   10824              :          performing the whole vector shifting.  */
   10825           62 :       unsigned HOST_WIDE_INT factor;
   10826           62 :       bool ok = constant_multiple_p (TYPE_VECTOR_SUBPARTS (rgm->type),
   10827           62 :                                      TYPE_VECTOR_SUBPARTS (vectype), &factor);
   10828            0 :       gcc_assert (ok);
   10829           62 :       gcc_assert (GET_MODE_CLASS (TYPE_MODE (rgm->type)) == MODE_INT);
   10830           62 :       tree mask_type = truth_type_for (vectype);
   10831           62 :       gcc_assert (GET_MODE_CLASS (TYPE_MODE (mask_type)) == MODE_INT);
   10832           62 :       unsigned vi = index / factor;
   10833           62 :       unsigned vpart = index % factor;
   10834           62 :       tree vec = rgm->controls[vi];
   10835           62 :       gimple_seq seq = NULL;
   10836           62 :       vec = gimple_build (&seq, VIEW_CONVERT_EXPR,
   10837           62 :                           lang_hooks.types.type_for_mode
   10838           62 :                                 (TYPE_MODE (rgm->type), 1), vec);
   10839              :       /* For integer mode masks simply shift the right bits into position.  */
   10840           62 :       if (vpart != 0)
   10841           47 :         vec = gimple_build (&seq, RSHIFT_EXPR, TREE_TYPE (vec), vec,
   10842              :                             build_int_cst (integer_type_node,
   10843           94 :                                            (TYPE_VECTOR_SUBPARTS (vectype)
   10844           47 :                                             * vpart)));
   10845           62 :       vec = gimple_convert (&seq, lang_hooks.types.type_for_mode
   10846           62 :                                     (TYPE_MODE (mask_type), 1), vec);
   10847           62 :       vec = gimple_build (&seq, VIEW_CONVERT_EXPR, mask_type, vec);
   10848           62 :       if (seq)
   10849           62 :         gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10850              :       return vec;
   10851              :     }
   10852              :   else
   10853            0 :     gcc_unreachable ();
   10854              : }
   10855              : 
   10856              : /* Record that the loop or SLP region represented by VINFO would need a sequence
   10857              :    of NVECTORS lengths for controlling an operation on VECTYPE.  The operation
   10858              :    splits each element of VECTYPE into FACTOR separate subelements, measuring
   10859              :    the length as a number of these subelements.  If VINFO represents an SLP
   10860              :    region then GROUP_SIZE gives the total number of active lanes across the
   10861              :    sequence.  */
   10862              : 
   10863              : void
   10864            0 : vect_record_len (vec_info *vinfo, unsigned int nvectors, tree vectype,
   10865              :                  unsigned int factor, unsigned int group_size)
   10866              : {
   10867            0 :   gcc_assert (!is_a <bb_vec_info> (vinfo) || group_size != 0);
   10868            0 :   gcc_assert (nvectors != 0);
   10869            0 :   vec_lens *lens = &vinfo->lens;
   10870            0 :   if (lens->length () < nvectors)
   10871            0 :     lens->safe_grow_cleared (nvectors, true);
   10872            0 :   rgroup_controls *rgl = &(*lens)[nvectors - 1];
   10873              : 
   10874              :   /* The number of scalars per iteration, scalar occupied bytes and
   10875              :      the number of vectors are both compile-time constants.  */
   10876            0 :   unsigned int nscalars_per_iter
   10877            0 :     = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
   10878              :                  vinfo->vectorization_factor)
   10879            0 :         .to_constant ();
   10880              : 
   10881            0 :   if (rgl->max_nscalars_per_iter < nscalars_per_iter)
   10882              :     {
   10883              :       /* For now, we only support cases in which all loads and stores fall back
   10884              :          to VnQI or none do.  */
   10885            0 :       gcc_assert (!rgl->max_nscalars_per_iter
   10886              :                   || (rgl->factor == 1 && factor == 1)
   10887              :                   || (rgl->max_nscalars_per_iter * rgl->factor
   10888              :                       == nscalars_per_iter * factor));
   10889            0 :       rgl->max_nscalars_per_iter = nscalars_per_iter;
   10890            0 :       rgl->type = vectype;
   10891            0 :       rgl->factor = factor;
   10892              :     }
   10893            0 : }
   10894              : 
   10895              : /* Given a complete set of lengths for the loop or SLP region represented by
   10896              :    VINFO, extract length number INDEX for an rgroup that operates on NVECTORS
   10897              :    vectors of type VECTYPE, where 0 <= INDEX < NVECTORS.  Return a value that
   10898              :    contains FACTOR multiplied by the number of elements that should be
   10899              :    processed.  Insert any set-up statements before GSI.  If VINFO represents an
   10900              :    SLP region then GROUP_SIZE gives the total number of active lanes across the
   10901              :    sequence.  */
   10902              : 
   10903              : tree
   10904            0 : vect_get_len (vec_info *vinfo, gimple_stmt_iterator *gsi, unsigned int nvectors,
   10905              :               tree vectype, unsigned int index, unsigned int factor,
   10906              :               bool adjusted, unsigned int group_size)
   10907              : {
   10908            0 :   gcc_assert (!is_a <bb_vec_info> (vinfo) || group_size != 0);
   10909            0 :   vec_lens *lens = &vinfo->lens;
   10910            0 :   rgroup_controls *rgl = &(*lens)[nvectors - 1];
   10911            0 :   bool use_bias_adjusted_len =
   10912            0 :     vinfo->partial_load_store_bias != 0;
   10913              : 
   10914              :   /* Populate the rgroup's len array, if this is the first time we've
   10915              :      used it.  */
   10916            0 :   if (rgl->controls.is_empty ())
   10917              :     {
   10918            0 :       rgl->controls.safe_grow_cleared (nvectors, true);
   10919            0 :       for (unsigned int i = 0; i < nvectors; ++i)
   10920              :         {
   10921            0 :           tree len_type = vinfo->rgroup_compare_type;
   10922            0 :           gcc_assert (len_type != NULL_TREE);
   10923              : 
   10924            0 :           tree len = make_temp_ssa_name (len_type, NULL, "loop_len");
   10925              : 
   10926              :           /* Provide a dummy definition until the real one is available.  */
   10927            0 :           SSA_NAME_DEF_STMT (len) = gimple_build_nop ();
   10928            0 :           rgl->controls[i] = len;
   10929              : 
   10930            0 :           if (use_bias_adjusted_len)
   10931              :             {
   10932            0 :               gcc_assert (i == 0);
   10933            0 :               tree adjusted_len =
   10934            0 :                 make_temp_ssa_name (len_type, NULL, "adjusted_loop_len");
   10935            0 :               SSA_NAME_DEF_STMT (adjusted_len) = gimple_build_nop ();
   10936            0 :               rgl->bias_adjusted_ctrl = adjusted_len;
   10937              :             }
   10938              :         }
   10939              :     }
   10940              : 
   10941            0 :   if (use_bias_adjusted_len && adjusted)
   10942            0 :     return rgl->bias_adjusted_ctrl;
   10943              : 
   10944            0 :   tree loop_len = rgl->controls[index];
   10945            0 :   if (rgl->factor == 1 && factor == 1)
   10946              :     {
   10947            0 :       poly_int64 nunits1 = TYPE_VECTOR_SUBPARTS (rgl->type);
   10948            0 :       poly_int64 nunits2 = TYPE_VECTOR_SUBPARTS (vectype);
   10949            0 :       if (maybe_ne (nunits1, nunits2))
   10950              :         {
   10951              :           /* A loop len for data type X can be reused for data type Y
   10952              :              if X has N times more elements than Y and if Y's elements
   10953              :              are N times bigger than X's.  */
   10954            0 :           gcc_assert (multiple_p (nunits1, nunits2));
   10955            0 :           factor = exact_div (nunits1, nunits2).to_constant ();
   10956            0 :           tree iv_type = vinfo->rgroup_iv_type;
   10957            0 :           gimple_seq seq = NULL;
   10958            0 :           loop_len = gimple_build (&seq, EXACT_DIV_EXPR, iv_type, loop_len,
   10959            0 :                                    build_int_cst (iv_type, factor));
   10960            0 :           if (seq)
   10961            0 :             gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10962              :         }
   10963            0 :     }
   10964            0 :   else if (factor && rgl->factor != factor)
   10965              :     {
   10966              :       /* The number of scalars per iteration, scalar occupied bytes and
   10967              :          the number of vectors are both compile-time constants.  */
   10968            0 :       unsigned int nscalars_per_iter
   10969            0 :         = exact_div (nvectors * TYPE_VECTOR_SUBPARTS (vectype),
   10970            0 :                      vinfo->vectorization_factor).to_constant ();
   10971            0 :       unsigned int rglvecsize = rgl->factor * rgl->max_nscalars_per_iter;
   10972            0 :       unsigned int vecsize = nscalars_per_iter * factor;
   10973            0 :       if (rglvecsize > vecsize)
   10974              :         {
   10975            0 :           unsigned int fac = rglvecsize / vecsize;
   10976            0 :           tree iv_type = vinfo->rgroup_iv_type;
   10977            0 :           gimple_seq seq = NULL;
   10978            0 :           loop_len = gimple_build (&seq, EXACT_DIV_EXPR, iv_type, loop_len,
   10979            0 :                                    build_int_cst (iv_type, fac));
   10980            0 :           if (seq)
   10981            0 :             gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10982              :         }
   10983            0 :       else if (rglvecsize < vecsize)
   10984              :         {
   10985            0 :           unsigned int fac = vecsize / rglvecsize;
   10986            0 :           tree iv_type = vinfo->rgroup_iv_type;
   10987            0 :           gimple_seq seq = NULL;
   10988            0 :           loop_len = gimple_build (&seq, MULT_EXPR, iv_type, loop_len,
   10989            0 :                                    build_int_cst (iv_type, fac));
   10990            0 :           if (seq)
   10991            0 :             gsi_insert_seq_before (gsi, seq, GSI_SAME_STMT);
   10992              :         }
   10993              :     }
   10994              :   return loop_len;
   10995              : }
   10996              : 
   10997              : /* Generate the tree for the loop len mask and return it.  Given the lens,
   10998              :    nvectors, vectype, index and factor to gen the len mask as below.
   10999              : 
   11000              :    tree len_mask = VCOND_MASK_LEN (compare_mask, ones, zero, len, bias)
   11001              : */
   11002              : tree
   11003            0 : vect_gen_loop_len_mask (loop_vec_info loop_vinfo, gimple_stmt_iterator *gsi,
   11004              :                         gimple_stmt_iterator *cond_gsi, unsigned int nvectors,
   11005              :                         tree vectype, tree stmt, unsigned int index,
   11006              :                         unsigned int factor)
   11007              : {
   11008            0 :   tree all_one_mask = build_all_ones_cst (vectype);
   11009            0 :   tree all_zero_mask = build_zero_cst (vectype);
   11010            0 :   tree len
   11011            0 :     = vect_get_len (loop_vinfo, gsi, nvectors, vectype, index, factor, true);
   11012            0 :   tree bias = build_int_cst (intQI_type_node,
   11013            0 :                              LOOP_VINFO_PARTIAL_LOAD_STORE_BIAS (loop_vinfo));
   11014            0 :   tree len_mask = make_temp_ssa_name (TREE_TYPE (stmt), NULL, "vec_len_mask");
   11015            0 :   gcall *call = gimple_build_call_internal (IFN_VCOND_MASK_LEN, 5, stmt,
   11016              :                                             all_one_mask, all_zero_mask, len,
   11017              :                                             bias);
   11018            0 :   gimple_call_set_lhs (call, len_mask);
   11019            0 :   gsi_insert_before (cond_gsi, call, GSI_SAME_STMT);
   11020              : 
   11021            0 :   return len_mask;
   11022              : }
   11023              : 
   11024              : /* Update the exit profile counts scaling them from scalar to vector counts.
   11025              : 
   11026              :    The calculations are as follows.
   11027              : 
   11028              :    let P be the scalar probability that one iteration takes an early exit edge.
   11029              :    1 - P is then the probabiliy that the exit is not taken.
   11030              : 
   11031              :    Since every vector iteration handles VF scalar iterations, the early exit
   11032              :    branch can be taken when any of the lanes are true.
   11033              : 
   11034              :    We invert this and first calculate the probablity that you reach the latch,
   11035              :    i.e. the probability that the vector code does not exit is the probability
   11036              :    Q that none of the lanes are true.
   11037              : 
   11038              :    Q = (1 - P) * (1 - P) * ... * (1 - P)
   11039              :      = (1 - P) ^ VF
   11040              : 
   11041              :    and so the probability that at least one lane breaks is 1 - Q,
   11042              :    or rather 1 - (i - P) ^ VF.
   11043              : 
   11044              :    For example, if the scalar break probability is 10% and VF is 4:
   11045              : 
   11046              :    P = 0.1
   11047              :    1 - P = 0.9
   11048              :    (1 - P) ^ VF = 0.9 ^ 4 = 0.6561
   11049              :    1 - (1 - p) ^ VF = 1 - 0.6561 = 0.3439
   11050              : 
   11051              :    So a scalar early-exit edge that is taken 10% of the time becomes a vector
   11052              :    early-exit edge that is taken about 34.4% of the time, because each vector
   11053              :    iteration gives the break condition four chances to trigger.  */
   11054              : 
   11055              : static void
   11056        66514 : vect_update_early_break_profiles (loop_vec_info loop_vinfo)
   11057              : {
   11058        66514 :   if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   11059        65003 :     return;
   11060              : 
   11061         1511 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   11062         1511 :   unsigned int vf = vect_vf_for_cost (loop_vinfo);
   11063              : 
   11064         1511 :   auto_vec<std::pair<edge, profile_probability>, 8> updates;
   11065         7669 :   for (edge e : get_loop_exit_edges (loop))
   11066              :     {
   11067         4526 :       if ((e == LOOP_VINFO_MAIN_EXIT (loop_vinfo)
   11068         1447 :            && !LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
   11069         3193 :           || !e->probability.initialized_p ())
   11070         1390 :         continue;
   11071              : 
   11072              :       /* For any early break exits, the probablity of exiting are based on if
   11073              :          any lane is true, and so are tied to VF since you have VF chances.
   11074              :          As such scale the scalar profile by VF to the the probability for the
   11075              :          vector edges using 1 - (1 - p) ^ VF.  */
   11076         1746 :       profile_probability probability
   11077         1746 :         = profile_probability::always () - e->probability.invert ().pow (vf);
   11078         1746 :       updates.safe_push ({e, probability});
   11079         1511 :     }
   11080              : 
   11081              :   /* First update the edge counts.  */
   11082         6279 :   for (auto update : updates)
   11083         1746 :     set_edge_probability_and_rescale_others (update.first, update.second);
   11084              : 
   11085              :   /* And then only update the in loop BBs, i.e. the fall through block for
   11086              :      the early exits.  */
   11087         6279 :   for (auto update : updates)
   11088         8730 :     for (edge e : update.first->src->succs)
   11089         5238 :       if (!loop_exit_edge_p (loop, e) && single_pred_p (e->dest))
   11090         1746 :         e->dest->count = e->count ();
   11091         1511 : }
   11092              : 
   11093              : /* Scale profiling counters by estimation for LOOP which is vectorized
   11094              :    by factor VF.
   11095              :    If FLAT is true, the loop we started with had unrealistically flat
   11096              :    profile.  */
   11097              : 
   11098              : static void
   11099        66514 : scale_profile_for_vect_loop (loop_vec_info loop_vinfo,
   11100              :                              class loop *loop, edge exit_e, unsigned vf,
   11101              :                              bool flat)
   11102              : {
   11103              :   /* First scale any early exits.  */
   11104        66514 :   vect_update_early_break_profiles (loop_vinfo);
   11105              : 
   11106              :   /* For flat profiles do not scale down proportionally by VF and only
   11107              :      cap by known iteration count bounds.  */
   11108        66514 :   if (flat)
   11109              :     {
   11110        37664 :       if (dump_file && (dump_flags & TDF_DETAILS))
   11111         5768 :         fprintf (dump_file,
   11112              :                  "Vectorized loop profile seems flat; not scaling iteration "
   11113              :                  "count down by the vectorization factor %i\n", vf);
   11114        37664 :       scale_loop_profile (loop, profile_probability::always (),
   11115              :                           get_likely_max_loop_iterations_int (loop));
   11116        37664 :       return;
   11117              :     }
   11118              :   /* Loop body executes VF fewer times and exit increases VF times.  */
   11119        28850 :   profile_count entry_count = loop_preheader_edge (loop)->count ();
   11120              : 
   11121              :   /* If we have unreliable loop profile avoid dropping entry
   11122              :      count below header count.  This can happen since loops
   11123              :      has unrealistically low trip counts.  */
   11124        28850 :   while (vf > 1
   11125        30026 :          && loop->header->count > entry_count
   11126        61160 :          && loop->header->count < entry_count * vf)
   11127              :     {
   11128         2284 :       if (dump_file && (dump_flags & TDF_DETAILS))
   11129          161 :         fprintf (dump_file,
   11130              :                  "Vectorization factor %i seems too large for profile "
   11131              :                  "previously believed to be consistent; reducing.\n", vf);
   11132         2284 :       vf /= 2;
   11133              :     }
   11134              : 
   11135        28850 :   if (!LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo))
   11136              :     {
   11137        28850 :       if (entry_count.nonzero_p ())
   11138        28850 :         set_edge_probability_and_rescale_others
   11139        28850 :             (exit_e,
   11140        28850 :              entry_count.probability_in (loop->header->count / vf));
   11141              :       /* Avoid producing very large exit probability when we do not have
   11142              :          sensible profile.  */
   11143            0 :       else if (exit_e->probability < profile_probability::always () / (vf * 2))
   11144            0 :         set_edge_probability_and_rescale_others (exit_e,
   11145              :                                                  exit_e->probability * vf);
   11146              :     }
   11147              : 
   11148        28850 :   loop->latch->count = single_pred_edge (loop->latch)->count ();
   11149              : 
   11150        28850 :   scale_loop_profile (loop, profile_probability::always () / vf,
   11151              :                       get_likely_max_loop_iterations_int (loop));
   11152              : }
   11153              : 
   11154              : /* Update EPILOGUE's loop_vec_info.  EPILOGUE was constructed as a copy of the
   11155              :    original loop that has now been vectorized.
   11156              : 
   11157              :    The inits of the data_references need to be advanced with the number of
   11158              :    iterations of the main loop.  This has been computed in vect_do_peeling and
   11159              :    is stored in parameter ADVANCE.
   11160              : 
   11161              :    Since the loop_vec_info of this EPILOGUE was constructed for the original
   11162              :    loop, its stmt_vec_infos all point to the original statements.  These need
   11163              :    to be updated to point to their corresponding copies.
   11164              : 
   11165              :    The data_reference's connections also need to be updated.  Their
   11166              :    corresponding dr_vec_info need to be reconnected to the EPILOGUE's
   11167              :    stmt_vec_infos, their statements need to point to their corresponding
   11168              :    copy.  */
   11169              : 
   11170              : static void
   11171         7377 : update_epilogue_loop_vinfo (class loop *epilogue, tree advance)
   11172              : {
   11173         7377 :   loop_vec_info epilogue_vinfo = loop_vec_info_for_loop (epilogue);
   11174         7377 :   hash_map<tree,tree> mapping;
   11175         7377 :   gimple *orig_stmt, *new_stmt;
   11176         7377 :   gimple_stmt_iterator epilogue_gsi;
   11177         7377 :   gphi_iterator epilogue_phi_gsi;
   11178         7377 :   stmt_vec_info stmt_vinfo = NULL, related_vinfo;
   11179         7377 :   basic_block *epilogue_bbs = get_loop_body (epilogue);
   11180         7377 :   unsigned i;
   11181              : 
   11182         7377 :   free (LOOP_VINFO_BBS (epilogue_vinfo));
   11183         7377 :   LOOP_VINFO_BBS (epilogue_vinfo) = epilogue_bbs;
   11184         7377 :   LOOP_VINFO_NBBS (epilogue_vinfo) = epilogue->num_nodes;
   11185              : 
   11186              :   /* The EPILOGUE loop is a copy of the original loop so they share the same
   11187              :      gimple UIDs.  In this loop we update the loop_vec_info of the EPILOGUE to
   11188              :      point to the copied statements.  */
   11189        22131 :   for (unsigned i = 0; i < epilogue->num_nodes; ++i)
   11190              :     {
   11191        14754 :       for (epilogue_phi_gsi = gsi_start_phis (epilogue_bbs[i]);
   11192        37731 :            !gsi_end_p (epilogue_phi_gsi); gsi_next (&epilogue_phi_gsi))
   11193              :         {
   11194        22977 :           new_stmt = epilogue_phi_gsi.phi ();
   11195              : 
   11196        22977 :           gcc_assert (gimple_uid (new_stmt) > 0);
   11197        22977 :           stmt_vinfo
   11198        22977 :             = epilogue_vinfo->stmt_vec_infos[gimple_uid (new_stmt) - 1];
   11199              : 
   11200        22977 :           STMT_VINFO_STMT (stmt_vinfo) = new_stmt;
   11201              :         }
   11202              : 
   11203        29508 :       for (epilogue_gsi = gsi_start_bb (epilogue_bbs[i]);
   11204       144298 :            !gsi_end_p (epilogue_gsi); gsi_next (&epilogue_gsi))
   11205              :         {
   11206       129544 :           new_stmt = gsi_stmt (epilogue_gsi);
   11207       129544 :           if (is_gimple_debug (new_stmt))
   11208        20142 :             continue;
   11209              : 
   11210       109402 :           gcc_assert (gimple_uid (new_stmt) > 0);
   11211       109402 :           stmt_vinfo
   11212       109402 :             = epilogue_vinfo->stmt_vec_infos[gimple_uid (new_stmt) - 1];
   11213              : 
   11214       109402 :           STMT_VINFO_STMT (stmt_vinfo) = new_stmt;
   11215              : 
   11216       109402 :           related_vinfo = STMT_VINFO_RELATED_STMT (stmt_vinfo);
   11217       109402 :           if (related_vinfo != NULL && related_vinfo != stmt_vinfo)
   11218              :             {
   11219         2492 :               gimple *stmt = STMT_VINFO_STMT (related_vinfo);
   11220              :               /* Set BB such that the assert in
   11221              :                 'get_initial_defs_for_reduction' is able to determine that
   11222              :                 the BB of the related stmt is inside this loop.  */
   11223         2492 :               gimple_set_bb (stmt,
   11224              :                              gimple_bb (new_stmt));
   11225         2492 :               related_vinfo = STMT_VINFO_RELATED_STMT (related_vinfo);
   11226         2492 :               gcc_assert (related_vinfo == NULL
   11227              :                           || related_vinfo == stmt_vinfo);
   11228              :             }
   11229              :         }
   11230              :     }
   11231              : 
   11232         7377 :   struct data_reference *dr;
   11233         7377 :   vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (epilogue_vinfo);
   11234        33226 :   FOR_EACH_VEC_ELT (datarefs, i, dr)
   11235              :     {
   11236        25849 :       orig_stmt = DR_STMT (dr);
   11237        25849 :       gcc_assert (gimple_uid (orig_stmt) > 0);
   11238        25849 :       stmt_vinfo = epilogue_vinfo->stmt_vec_infos[gimple_uid (orig_stmt) - 1];
   11239        25849 :       DR_STMT (dr) = STMT_VINFO_STMT (stmt_vinfo);
   11240              :     }
   11241              : 
   11242              :   /* Advance data_reference's with the number of iterations of the previous
   11243              :      loop and its prologue.  */
   11244         7377 :   vect_update_inits_of_drs (epilogue_vinfo, advance, PLUS_EXPR);
   11245              : 
   11246              :   /* Remember the advancement made.  */
   11247         7377 :   LOOP_VINFO_DRS_ADVANCED_BY (epilogue_vinfo) = advance;
   11248         7377 : }
   11249              : 
   11250              : /*  When vectorizing early break statements instructions that happen before
   11251              :     the early break in the current BB need to be moved to after the early
   11252              :     break.  This function deals with that and assumes that any validity
   11253              :     checks has already been performed.
   11254              : 
   11255              :     While moving the instructions if it encounters a VUSE or VDEF it then
   11256              :     corrects the VUSES as it moves the statements along.  GDEST is the location
   11257              :     in which to insert the new statements.  */
   11258              : 
   11259              : static void
   11260         1511 : move_early_exit_stmts (loop_vec_info loop_vinfo)
   11261              : {
   11262         1511 :   DUMP_VECT_SCOPE ("move_early_exit_stmts");
   11263              : 
   11264         1511 :   if (LOOP_VINFO_EARLY_BRK_STORES (loop_vinfo).is_empty ())
   11265         1261 :     return;
   11266              : 
   11267              :   /* Move all stmts that need moving.  */
   11268          250 :   basic_block dest_bb = LOOP_VINFO_EARLY_BRK_DEST_BB (loop_vinfo);
   11269          250 :   gimple_stmt_iterator dest_gsi = gsi_after_labels (dest_bb);
   11270              : 
   11271          250 :   tree last_seen_vuse = NULL_TREE;
   11272          599 :   for (gimple *stmt : LOOP_VINFO_EARLY_BRK_STORES (loop_vinfo))
   11273              :     {
   11274              :       /* We have to update crossed degenerate virtual PHIs.  Simply
   11275              :          elide them.  */
   11276          349 :       if (gphi *vphi = dyn_cast <gphi *> (stmt))
   11277              :         {
   11278            7 :           tree vdef = gimple_phi_result (vphi);
   11279            7 :           tree vuse = gimple_phi_arg_def (vphi, 0);
   11280            7 :           imm_use_iterator iter;
   11281            7 :           use_operand_p use_p;
   11282            7 :           gimple *use_stmt;
   11283           23 :           FOR_EACH_IMM_USE_STMT (use_stmt, iter, vdef)
   11284              :             {
   11285           32 :               FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
   11286           16 :                 SET_USE (use_p, vuse);
   11287            7 :             }
   11288            7 :           auto gsi = gsi_for_stmt (stmt);
   11289            7 :           remove_phi_node (&gsi, true);
   11290            7 :           last_seen_vuse = vuse;
   11291            7 :           continue;
   11292            7 :         }
   11293              : 
   11294              :       /* Check to see if statement is still required for vect or has been
   11295              :          elided.  */
   11296          342 :       auto stmt_info = loop_vinfo->lookup_stmt (stmt);
   11297          342 :       if (!stmt_info)
   11298            0 :         continue;
   11299              : 
   11300          342 :       if (dump_enabled_p ())
   11301          177 :         dump_printf_loc (MSG_NOTE, vect_location, "moving stmt %G", stmt);
   11302              : 
   11303          342 :       gimple_stmt_iterator stmt_gsi = gsi_for_stmt (stmt);
   11304          342 :       gsi_move_before (&stmt_gsi, &dest_gsi, GSI_NEW_STMT);
   11305          684 :       last_seen_vuse = gimple_vuse (stmt);
   11306              :     }
   11307              : 
   11308              :   /* Update all the stmts with their new reaching VUSES.  */
   11309          865 :   for (auto p : LOOP_VINFO_EARLY_BRK_VUSES (loop_vinfo))
   11310              :     {
   11311          281 :       if (dump_enabled_p ())
   11312          203 :           dump_printf_loc (MSG_NOTE, vect_location,
   11313              :                            "updating vuse to %T for load %G",
   11314              :                            last_seen_vuse, p);
   11315          281 :       gimple_set_vuse (p, last_seen_vuse);
   11316          281 :       update_stmt (p);
   11317              :     }
   11318              : 
   11319              :   /* And update the LC PHIs on exits.  */
   11320         1263 :   for (edge e : get_loop_exit_edges (LOOP_VINFO_LOOP  (loop_vinfo)))
   11321          513 :     if (!dominated_by_p (CDI_DOMINATORS, e->src, dest_bb))
   11322          293 :       if (gphi *phi = get_virtual_phi (e->dest))
   11323          543 :         SET_PHI_ARG_DEF_ON_EDGE (phi, e, last_seen_vuse);
   11324              : }
   11325              : 
   11326              : /* Generate adjustment code for early break scalar IVs filling in the value
   11327              :    we created earlier on for LOOP_VINFO_EARLY_BRK_NITERS_VAR.  */
   11328              : 
   11329              : static void
   11330         1511 : vect_update_ivs_after_vectorizer_for_early_breaks (loop_vec_info loop_vinfo)
   11331              : {
   11332         1511 :   DUMP_VECT_SCOPE ("vect_update_ivs_after_vectorizer_for_early_breaks");
   11333              : 
   11334         1511 :   if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo)
   11335              :       /* If no peeling was done then we have no IV to update.  */
   11336         1511 :       || !LOOP_VINFO_EARLY_BRK_NITERS_VAR (loop_vinfo))
   11337          598 :     return;
   11338              : 
   11339          913 :   tree phi_var = LOOP_VINFO_EARLY_BRK_NITERS_VAR (loop_vinfo);
   11340          913 :   tree niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
   11341          913 :   tree ty_var = TREE_TYPE (phi_var);
   11342          913 :   auto loop = LOOP_VINFO_LOOP (loop_vinfo);
   11343          913 :   tree induc_var = niters_skip ? copy_ssa_name (phi_var) : phi_var;
   11344              : 
   11345              :   /* Remove the existing dummy GIMPLE statement and just keep the def.  */
   11346          913 :   gimple *def = SSA_NAME_DEF_STMT (phi_var);
   11347          913 :   auto def_gsi = gsi_for_stmt (def);
   11348          913 :   gsi_remove (&def_gsi, true);
   11349              : 
   11350          913 :   auto induction_phi = create_phi_node (induc_var, loop->header);
   11351          913 :   tree induc_def = PHI_RESULT (induction_phi);
   11352              : 
   11353              :   /* Create the iv update inside the loop.  */
   11354          913 :   gimple_seq init_stmts = NULL;
   11355          913 :   gimple_seq stmts = NULL;
   11356          913 :   gimple_seq iv_stmts = NULL;
   11357          913 :   tree tree_iv_incr = LOOP_VINFO_IV_INCREMENT (loop_vinfo);
   11358              : 
   11359          913 :   tree iter_var;
   11360          913 :   if (POINTER_TYPE_P (ty_var))
   11361            0 :     iter_var = gimple_build (&stmts, POINTER_PLUS_EXPR, ty_var, induc_def,
   11362              :                              tree_iv_incr);
   11363              :   else
   11364              :     {
   11365          913 :       tree offset = gimple_convert (&stmts, ty_var, tree_iv_incr);
   11366          913 :       iter_var = gimple_build (&stmts, PLUS_EXPR, ty_var, induc_def, offset);
   11367              :     }
   11368              : 
   11369          913 :   tree init_var = build_zero_cst (ty_var);
   11370          913 :   if (niters_skip)
   11371            0 :     init_var = gimple_build (&init_stmts, MINUS_EXPR, ty_var, init_var,
   11372              :                              gimple_convert (&init_stmts, ty_var, niters_skip));
   11373              : 
   11374          913 :   add_phi_arg (induction_phi, iter_var,
   11375              :                loop_latch_edge (loop), UNKNOWN_LOCATION);
   11376          913 :   add_phi_arg (induction_phi, init_var,
   11377              :                loop_preheader_edge (loop), UNKNOWN_LOCATION);
   11378              : 
   11379              :   /* Find the first insertion point in the BB.  */
   11380          913 :   auto pe = loop_preheader_edge (loop);
   11381              : 
   11382              :   /* If we've done any peeling, calculate the peeling adjustment needed to the
   11383              :      final IV.  */
   11384          913 :   if (niters_skip)
   11385              :     {
   11386            0 :       tree induc_type = TREE_TYPE (induc_def);
   11387            0 :       tree s_induc_type = signed_type_for (induc_type);
   11388            0 :       induc_def = gimple_build (&iv_stmts, MAX_EXPR, s_induc_type,
   11389              :                                 gimple_convert (&iv_stmts, s_induc_type,
   11390              :                                                 induc_def),
   11391              :                                 build_zero_cst (s_induc_type));
   11392            0 :       auto stmt = gimple_build_assign (phi_var,
   11393              :                                        gimple_convert (&iv_stmts, induc_type,
   11394              :                                                        induc_def));
   11395            0 :       gimple_seq_add_stmt_without_update (&iv_stmts, stmt);
   11396            0 :       basic_block exit_bb = NULL;
   11397              :       /* Identify the early exit merge block.  I wish we had stored this.  */
   11398            0 :       for (auto e : get_loop_exit_edges (loop))
   11399            0 :         if (e != LOOP_VINFO_MAIN_EXIT (loop_vinfo))
   11400              :           {
   11401            0 :             exit_bb = e->dest;
   11402            0 :             break;
   11403            0 :           }
   11404              : 
   11405            0 :       gcc_assert (exit_bb);
   11406            0 :       auto exit_gsi = gsi_after_labels (exit_bb);
   11407            0 :       gsi_insert_seq_before (&exit_gsi, iv_stmts, GSI_SAME_STMT);
   11408              :     }
   11409              :   /* Write the init_stmts in the loop-preheader block.  */
   11410          913 :   auto psi = gsi_last_nondebug_bb (pe->src);
   11411          913 :   gsi_insert_seq_after (&psi, init_stmts, GSI_LAST_NEW_STMT);
   11412              : 
   11413              :   /* Write the adjustments at the end of the iv increment.  */
   11414          913 :   bool insert_after;
   11415          913 :   gimple_stmt_iterator incr_gsi;
   11416          913 :   standard_iv_increment_position (loop, &incr_gsi, &insert_after);
   11417              : 
   11418          913 :   if (insert_after)
   11419            0 :     gsi_insert_seq_after (&incr_gsi, stmts, GSI_NEW_STMT);
   11420              :   else
   11421          913 :     gsi_insert_seq_before (&incr_gsi, stmts, GSI_NEW_STMT);
   11422              : }
   11423              : 
   11424              : /* Function vect_transform_loop.
   11425              : 
   11426              :    The analysis phase has determined that the loop is vectorizable.
   11427              :    Vectorize the loop - created vectorized stmts to replace the scalar
   11428              :    stmts in the loop, and update the loop exit condition.
   11429              :    Returns scalar epilogue loop if any.  */
   11430              : 
   11431              : class loop *
   11432        66514 : vect_transform_loop (loop_vec_info loop_vinfo, gimple *loop_vectorized_call)
   11433              : {
   11434        66514 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   11435        66514 :   class loop *epilogue = NULL;
   11436        66514 :   basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
   11437        66514 :   int nbbs = loop->num_nodes;
   11438        66514 :   int i;
   11439        66514 :   tree niters_vector = NULL_TREE;
   11440        66514 :   tree step_vector = NULL_TREE;
   11441        66514 :   tree niters_vector_mult_vf = NULL_TREE;
   11442        66514 :   poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
   11443        66514 :   unsigned int lowest_vf = constant_lower_bound (vf);
   11444        66514 :   gimple *stmt;
   11445        66514 :   bool check_profitability = false;
   11446        66514 :   unsigned int th;
   11447        66514 :   bool flat = maybe_flat_loop_profile (loop);
   11448        66514 :   bool uncounted_p = LOOP_VINFO_NITERS_UNCOUNTED_P (loop_vinfo);
   11449              : 
   11450        66514 :   DUMP_VECT_SCOPE ("vec_transform_loop");
   11451              : 
   11452        66514 :   if (! LOOP_VINFO_EPILOGUE_P (loop_vinfo))
   11453        59137 :     loop_vinfo->shared->check_datarefs ();
   11454              : 
   11455              :   /* Use the more conservative vectorization threshold.  If the number
   11456              :      of iterations is constant assume the cost check has been performed
   11457              :      by our caller.  If the threshold makes all loops profitable that
   11458              :      run at least the (estimated) vectorization factor number of times
   11459              :      checking is pointless, too.  */
   11460        66514 :   th = LOOP_VINFO_COST_MODEL_THRESHOLD (loop_vinfo);
   11461        66514 :   if (vect_apply_runtime_profitability_check_p (loop_vinfo))
   11462              :     {
   11463        19280 :       if (dump_enabled_p ())
   11464          213 :         dump_printf_loc (MSG_NOTE, vect_location,
   11465              :                          "Profitability threshold is %d loop iterations.\n",
   11466              :                          th);
   11467              :       check_profitability = true;
   11468              :     }
   11469              : 
   11470              :   /* Make sure there exists a single-predecessor exit bb.  Do this before
   11471              :      versioning.   */
   11472        66514 :   edge e = LOOP_VINFO_MAIN_EXIT (loop_vinfo);
   11473        66514 :   if (! single_pred_p (e->dest) && !LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   11474              :     {
   11475        20137 :       split_loop_exit_edge (e, true);
   11476        20137 :       if (dump_enabled_p ())
   11477         2494 :         dump_printf (MSG_NOTE, "split exit edge\n");
   11478              :     }
   11479              : 
   11480              :   /* Version the loop first, if required, so the profitability check
   11481              :      comes first.  */
   11482              : 
   11483        66514 :   if (LOOP_REQUIRES_VERSIONING (loop_vinfo))
   11484              :     {
   11485         3965 :       class loop *sloop
   11486         3965 :         = vect_loop_versioning (loop_vinfo, loop_vectorized_call);
   11487         3965 :       sloop->force_vectorize = false;
   11488         3965 :       check_profitability = false;
   11489              :     }
   11490              : 
   11491              :   /* Make sure there exists a single-predecessor exit bb also on the
   11492              :      scalar loop copy.  Do this after versioning but before peeling
   11493              :      so CFG structure is fine for both scalar and if-converted loop
   11494              :      to make slpeel_duplicate_current_defs_from_edges face matched
   11495              :      loop closed PHI nodes on the exit.  */
   11496        66514 :   if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))
   11497              :     {
   11498         7441 :       e = LOOP_VINFO_SCALAR_MAIN_EXIT (loop_vinfo);
   11499         7441 :       if (! single_pred_p (e->dest))
   11500              :         {
   11501         7139 :           split_loop_exit_edge (e, true);
   11502         7139 :           if (dump_enabled_p ())
   11503         1230 :             dump_printf (MSG_NOTE, "split exit edge of scalar loop\n");
   11504              :         }
   11505              :     }
   11506              : 
   11507        66514 :   tree niters = vect_build_loop_niters (loop_vinfo);
   11508        66514 :   LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo) = niters;
   11509        66514 :   tree nitersm1 = unshare_expr (LOOP_VINFO_NITERSM1 (loop_vinfo));
   11510        66514 :   tree advance;
   11511        66514 :   drs_init_vec orig_drs_init;
   11512        66514 :   bool niters_no_overflow = uncounted_p ? false /* Not known.  */
   11513        66457 :                                         : loop_niters_no_overflow (loop_vinfo);
   11514              : 
   11515        66514 :   epilogue = vect_do_peeling (loop_vinfo, niters, nitersm1, &niters_vector,
   11516              :                               &step_vector, &niters_vector_mult_vf, th,
   11517              :                               check_profitability, niters_no_overflow,
   11518              :                               &advance);
   11519              : 
   11520        66514 :   LOOP_VINFO_IV_INCREMENT (loop_vinfo)
   11521        66514 :     = vect_get_loop_iv_increment (loop_vinfo);
   11522              : 
   11523              :   /* Assign hierarchical discriminators to the vectorized loop.  */
   11524        66514 :   poly_uint64 vf_val = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
   11525        66514 :   unsigned int vf_int = constant_lower_bound (vf_val);
   11526        66514 :   if (vf_int > DISCR_MULTIPLICITY_MAX)
   11527              :     vf_int = DISCR_MULTIPLICITY_MAX;
   11528              : 
   11529              :   /* Assign unique copy_id dynamically instead of using hardcoded constants.
   11530              :      Epilogue and main vectorized loops get different copy_ids.  */
   11531        66514 :   gimple *loop_last = last_nondebug_stmt (loop->header);
   11532        66514 :   location_t loop_loc
   11533        66514 :     = loop_last ? gimple_location (loop_last) : UNKNOWN_LOCATION;
   11534        66240 :   if (loop_loc != UNKNOWN_LOCATION)
   11535              :     {
   11536        54479 :       unsigned int copyid = allocate_copyid_base (loop_loc, 1);
   11537        54479 :       assign_discriminators_to_loop (loop, vf_int, copyid);
   11538              :     }
   11539        66514 :   if (LOOP_VINFO_SCALAR_LOOP (loop_vinfo)
   11540        66514 :       && LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo).initialized_p ())
   11541              :     {
   11542              :       /* Ifcvt duplicates loop preheader, loop body and produces an basic
   11543              :          block after loop exit.  We need to scale all that.  */
   11544           98 :       basic_block preheader
   11545           98 :         = loop_preheader_edge (LOOP_VINFO_SCALAR_LOOP (loop_vinfo))->src;
   11546           98 :       preheader->count
   11547              :         = preheader->count.apply_probability
   11548           98 :               (LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo));
   11549           98 :       scale_loop_frequencies (LOOP_VINFO_SCALAR_LOOP (loop_vinfo),
   11550              :                               LOOP_VINFO_SCALAR_LOOP_SCALING (loop_vinfo));
   11551           98 :       LOOP_VINFO_SCALAR_MAIN_EXIT (loop_vinfo)->dest->count = preheader->count;
   11552              :     }
   11553              : 
   11554        66514 :   if (niters_vector == NULL_TREE && !uncounted_p)
   11555              :     {
   11556        29797 :       if (LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
   11557        29797 :           && !LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
   11558        60406 :           && known_eq (lowest_vf, vf))
   11559              :         {
   11560        29792 :           niters_vector
   11561        29792 :             = build_int_cst (TREE_TYPE (LOOP_VINFO_NITERS (loop_vinfo)),
   11562        29792 :                              LOOP_VINFO_INT_NITERS (loop_vinfo) / lowest_vf);
   11563        29792 :           step_vector = build_one_cst (TREE_TYPE (niters));
   11564              :         }
   11565          822 :       else if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
   11566            2 :         vect_gen_vector_loop_niters (loop_vinfo, niters, &niters_vector,
   11567              :                                      &step_vector, niters_no_overflow);
   11568              :       else
   11569              :         /* vect_do_peeling subtracted the number of peeled prologue
   11570              :            iterations from LOOP_VINFO_NITERS.  */
   11571          820 :         vect_gen_vector_loop_niters (loop_vinfo, LOOP_VINFO_NITERS (loop_vinfo),
   11572              :                                      &niters_vector, &step_vector,
   11573              :                                      niters_no_overflow);
   11574              :     }
   11575              : 
   11576              :   /* 1) Make sure the loop header has exactly two entries
   11577              :      2) Make sure we have a preheader basic block.  */
   11578              : 
   11579        66514 :   gcc_assert (EDGE_COUNT (loop->header->preds) == 2);
   11580              : 
   11581        66514 :   split_edge (loop_preheader_edge (loop));
   11582              : 
   11583        66514 :   if (vect_use_loop_mask_for_alignment_p (loop_vinfo))
   11584              :     /* This will deal with any possible peeling.  */
   11585            2 :     vect_prepare_for_masked_peels (loop_vinfo);
   11586              : 
   11587              :   /* Handle any code motion that we need to for early-break vectorization after
   11588              :      we've done peeling but just before we start vectorizing.  */
   11589        66514 :   if (LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   11590              :     {
   11591         1511 :       vect_update_ivs_after_vectorizer_for_early_breaks (loop_vinfo);
   11592         1511 :       move_early_exit_stmts (loop_vinfo);
   11593              :     }
   11594              : 
   11595              :   /* Remove existing clobber stmts and prefetches.  */
   11596       202873 :   for (i = 0; i < nbbs; i++)
   11597              :     {
   11598       136359 :       basic_block bb = bbs[i];
   11599      1169633 :       for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);)
   11600              :         {
   11601       896915 :           stmt = gsi_stmt (si);
   11602       896915 :           if (gimple_clobber_p (stmt)
   11603       896915 :               || gimple_call_builtin_p (stmt, BUILT_IN_PREFETCH))
   11604              :             {
   11605          108 :               unlink_stmt_vdef (stmt);
   11606          108 :               gsi_remove (&si, true);
   11607          108 :               release_defs (stmt);
   11608              :             }
   11609              :           else
   11610       896807 :             gsi_next (&si);
   11611              :         }
   11612              :     }
   11613              : 
   11614              :   /* Schedule the SLP instances.  */
   11615        66514 :   if (!loop_vinfo->slp_instances.is_empty ())
   11616              :     {
   11617        66514 :       DUMP_VECT_SCOPE ("scheduling SLP instances");
   11618        66514 :       vect_schedule_slp (loop_vinfo, LOOP_VINFO_SLP_INSTANCES (loop_vinfo),
   11619              :                          false);
   11620              :     }
   11621              : 
   11622              :   /* Generate the loop invariant statements.  */
   11623        66514 :   if (!gimple_seq_empty_p (LOOP_VINFO_INV_PATTERN_DEF_SEQ (loop_vinfo)))
   11624              :     {
   11625           91 :       if (dump_enabled_p ())
   11626           26 :         dump_printf_loc (MSG_NOTE, vect_location,
   11627              :                          "------>generating loop invariant statements\n");
   11628           91 :       gimple_stmt_iterator gsi;
   11629           91 :       gsi = gsi_after_labels (loop_preheader_edge (loop)->src);
   11630           91 :       gsi_insert_seq_before (&gsi, LOOP_VINFO_INV_PATTERN_DEF_SEQ (loop_vinfo),
   11631              :                              GSI_CONTINUE_LINKING);
   11632              :     }
   11633              : 
   11634              :   /* Stub out scalar statements that must not survive vectorization and
   11635              :      were not picked as relevant in any SLP instance.
   11636              :      Doing this here helps with grouped statements, or statements that
   11637              :      are involved in patterns.  */
   11638       202873 :   for (i = 0; i < nbbs; i++)
   11639              :     {
   11640       136359 :       basic_block bb = bbs[i];
   11641       136359 :       stmt_vec_info stmt_info;
   11642       272718 :       for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
   11643      1777639 :            !gsi_end_p (gsi); gsi_next (&gsi))
   11644              :         {
   11645      1641280 :           gcall *call = dyn_cast <gcall *> (gsi_stmt (gsi));
   11646         7009 :           if (!call || !gimple_call_internal_p (call))
   11647      1635623 :             continue;
   11648         5657 :           internal_fn ifn = gimple_call_internal_fn (call);
   11649         5657 :           if (ifn == IFN_MASK_LOAD)
   11650              :             {
   11651          733 :               tree lhs = gimple_get_lhs (call);
   11652          733 :               if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
   11653              :                 {
   11654            0 :                   tree zero = build_zero_cst (TREE_TYPE (lhs));
   11655            0 :                   gimple *new_stmt = gimple_build_assign (lhs, zero);
   11656            0 :                   gsi_replace (&gsi, new_stmt, true);
   11657              :                 }
   11658              :             }
   11659         4924 :           else if (conditional_internal_fn_code (ifn) != ERROR_MARK)
   11660              :             {
   11661         2403 :               tree lhs = gimple_get_lhs (call);
   11662         2403 :               if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
   11663              :                 {
   11664            0 :                   tree else_arg
   11665            0 :                     = gimple_call_arg (call, gimple_call_num_args (call) - 1);
   11666            0 :                   gimple *new_stmt = gimple_build_assign (lhs, else_arg);
   11667            0 :                   gsi_replace (&gsi, new_stmt, true);
   11668              :                 }
   11669              :             }
   11670         2521 :           else if (ifn == IFN_MASK_CALL
   11671           14 :                    && (stmt_info = loop_vinfo->lookup_stmt (call))
   11672           14 :                    && !STMT_VINFO_RELEVANT_P (stmt_info)
   11673         2535 :                    && !STMT_VINFO_LIVE_P (stmt_info))
   11674              :             {
   11675              :               /* With -fno-tree-{dce,dse} we can end up with dead
   11676              :                  .MASK_CALL without side-effects and thus with a (dead)
   11677              :                  LHS.  So we cannot assert there is no LHS.  */
   11678           14 :               loop_vinfo->remove_stmt (stmt_info);
   11679              :             }
   11680              :         }
   11681              :     }
   11682              : 
   11683        66514 :   if (!uncounted_p)
   11684              :     {
   11685              :       /* The vectorization factor is always > 1, so if we use an IV increment of
   11686              :          1.  A zero NITERS becomes a nonzero NITERS_VECTOR.  */
   11687        66457 :       if (integer_onep (step_vector))
   11688        66433 :         niters_no_overflow = true;
   11689              : 
   11690        66457 :       vect_set_loop_condition (loop, LOOP_VINFO_MAIN_EXIT (loop_vinfo),
   11691              :                                loop_vinfo, niters_vector, step_vector,
   11692              :                                niters_vector_mult_vf, !niters_no_overflow);
   11693              :     }
   11694              : 
   11695        66514 :   unsigned int assumed_vf = vect_vf_for_cost (loop_vinfo);
   11696              : 
   11697              :   /* True if the final iteration might not handle a full vector's
   11698              :      worth of scalar iterations.  */
   11699       133028 :   bool final_iter_may_be_partial
   11700        66514 :     = LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo)
   11701        66514 :       || LOOP_VINFO_EARLY_BREAKS (loop_vinfo);
   11702              : 
   11703              :   /* +1 to convert latch counts to loop iteration counts.  */
   11704        66514 :   int bias_for_lowest = 1;
   11705              : 
   11706              :   /* When we are peeling for gaps then we take away one scalar iteration
   11707              :      from the vector loop.  Thus we can adjust the upper bound by one
   11708              :      scalar iteration.  But only when we know the bound applies to the
   11709              :      IV exit test which might not be true when we have multiple exits.  */
   11710        66514 :   if (!LOOP_VINFO_EARLY_BREAKS (loop_vinfo))
   11711       129603 :     bias_for_lowest -= LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) ? 1 : 0;
   11712              : 
   11713        66514 :   int bias_for_assumed = bias_for_lowest;
   11714        66514 :   int alignment_npeels = LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo);
   11715        66514 :   if (alignment_npeels && LOOP_VINFO_USING_PARTIAL_VECTORS_P (loop_vinfo))
   11716              :     {
   11717              :       /* When the amount of peeling is known at compile time, the first
   11718              :          iteration will have exactly alignment_npeels active elements.
   11719              :          In the worst case it will have at least one.  */
   11720            2 :       int min_first_active = (alignment_npeels > 0 ? alignment_npeels : 1);
   11721            2 :       bias_for_lowest += lowest_vf - min_first_active;
   11722            2 :       bias_for_assumed += assumed_vf - min_first_active;
   11723              :     }
   11724              :   /* In these calculations the "- 1" converts loop iteration counts
   11725              :      back to latch counts.  */
   11726        66514 :   if (loop->any_upper_bound)
   11727              :     {
   11728        66490 :       loop_vec_info main_vinfo = LOOP_VINFO_ORIG_LOOP_INFO (loop_vinfo);
   11729        66490 :       loop->nb_iterations_upper_bound
   11730        66490 :         = (final_iter_may_be_partial
   11731        67999 :            ? wi::udiv_ceil (loop->nb_iterations_upper_bound + bias_for_lowest,
   11732         3018 :                             lowest_vf) - 1
   11733        64981 :            : wi::udiv_floor (loop->nb_iterations_upper_bound + bias_for_lowest,
   11734       129962 :                              lowest_vf) - 1);
   11735        66490 :       if (main_vinfo
   11736              :           /* Both peeling for alignment and peeling for gaps can end up
   11737              :              with the scalar epilogue running for more than VF-1 iterations.  */
   11738         7377 :           && !main_vinfo->peeling_for_alignment
   11739         7315 :           && !main_vinfo->peeling_for_gaps)
   11740              :         {
   11741         7138 :           unsigned int bound;
   11742         7138 :           poly_uint64 main_iters
   11743         7138 :             = upper_bound (LOOP_VINFO_VECT_FACTOR (main_vinfo),
   11744              :                            LOOP_VINFO_COST_MODEL_THRESHOLD (main_vinfo));
   11745         7138 :           main_iters
   11746         7138 :             = upper_bound (main_iters,
   11747         7138 :                            LOOP_VINFO_VERSIONING_THRESHOLD (main_vinfo));
   11748         7138 :           if (can_div_away_from_zero_p (main_iters,
   11749         7138 :                                         LOOP_VINFO_VECT_FACTOR (loop_vinfo),
   11750              :                                         &bound))
   11751         7138 :             loop->nb_iterations_upper_bound
   11752         7138 :               = wi::umin ((bound_wide_int) (bound - 1),
   11753         7138 :                           loop->nb_iterations_upper_bound);
   11754              :       }
   11755              :   }
   11756        66514 :   if (loop->any_likely_upper_bound)
   11757        66496 :     loop->nb_iterations_likely_upper_bound
   11758        66496 :       = (final_iter_may_be_partial
   11759        68011 :          ? wi::udiv_ceil (loop->nb_iterations_likely_upper_bound
   11760         1515 :                           + bias_for_lowest, lowest_vf) - 1
   11761        64981 :          : wi::udiv_floor (loop->nb_iterations_likely_upper_bound
   11762        66496 :                            + bias_for_lowest, lowest_vf) - 1);
   11763        66514 :   if (loop->any_estimate)
   11764        38395 :     loop->nb_iterations_estimate
   11765        38395 :       = (final_iter_may_be_partial
   11766        39101 :          ? wi::udiv_ceil (loop->nb_iterations_estimate + bias_for_assumed,
   11767         1412 :                           assumed_vf) - 1
   11768        37689 :          : wi::udiv_floor (loop->nb_iterations_estimate + bias_for_assumed,
   11769        76084 :                            assumed_vf) - 1);
   11770        66514 :   scale_profile_for_vect_loop (loop_vinfo, loop,
   11771              :                                LOOP_VINFO_MAIN_EXIT (loop_vinfo), assumed_vf,
   11772              :                                flat);
   11773              : 
   11774        66514 :   if (dump_enabled_p ())
   11775              :     {
   11776        11710 :       if (!LOOP_VINFO_EPILOGUE_P (loop_vinfo))
   11777              :         {
   11778        10089 :           dump_printf_loc (MSG_NOTE, vect_location,
   11779              :                            "LOOP VECTORIZED\n");
   11780        10089 :           if (loop->inner)
   11781          346 :             dump_printf_loc (MSG_NOTE, vect_location,
   11782              :                              "OUTER LOOP VECTORIZED\n");
   11783        10089 :           dump_printf (MSG_NOTE, "\n");
   11784              :         }
   11785              :       else
   11786         1621 :         dump_printf_loc (MSG_NOTE, vect_location,
   11787              :                          "LOOP EPILOGUE VECTORIZED (MODE=%s)\n",
   11788         1621 :                          GET_MODE_NAME (loop_vinfo->vector_mode));
   11789              :     }
   11790              : 
   11791              :   /* Loops vectorized with a variable factor won't benefit from
   11792              :      unrolling/peeling.  */
   11793        66514 :   if (!vf.is_constant ())
   11794              :     {
   11795              :       loop->unroll = 1;
   11796              :       if (dump_enabled_p ())
   11797              :         dump_printf_loc (MSG_NOTE, vect_location, "Disabling unrolling due to"
   11798              :                          " variable-length vectorization factor\n");
   11799              :     }
   11800              : 
   11801              :   /* When we have unrolled the loop due to a user requested value we should
   11802              :      leave it up to the RTL unroll heuristics to determine if it's still worth
   11803              :      while to unroll more.  */
   11804        66514 :   if (LOOP_VINFO_USER_UNROLL (loop_vinfo))
   11805           44 :     loop->unroll = 0;
   11806              : 
   11807              :   /* Free SLP instances here because otherwise stmt reference counting
   11808              :      won't work.  */
   11809        66514 :   slp_instance instance;
   11810       162485 :   FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (loop_vinfo), i, instance)
   11811        95971 :     vect_free_slp_instance (instance);
   11812        66514 :   LOOP_VINFO_SLP_INSTANCES (loop_vinfo).release ();
   11813              :   /* Clear-up safelen field since its value is invalid after vectorization
   11814              :      since vectorized loop can have loop-carried dependencies.  */
   11815        66514 :   loop->safelen = 0;
   11816              : 
   11817        66514 :   if (epilogue)
   11818              :     {
   11819              :       /* Accumulate past advancements made.  */
   11820         7377 :       if (LOOP_VINFO_DRS_ADVANCED_BY (loop_vinfo))
   11821           91 :         advance = fold_build2 (PLUS_EXPR, TREE_TYPE (advance),
   11822              :                                LOOP_VINFO_DRS_ADVANCED_BY (loop_vinfo),
   11823              :                                advance);
   11824         7377 :       update_epilogue_loop_vinfo (epilogue, advance);
   11825              : 
   11826         7377 :       epilogue->simduid = loop->simduid;
   11827         7377 :       epilogue->force_vectorize = loop->force_vectorize;
   11828         7377 :       epilogue->dont_vectorize = false;
   11829              :     }
   11830              : 
   11831        66514 :   return epilogue;
   11832        66514 : }
   11833              : 
   11834              : /* The code below is trying to perform simple optimization - revert
   11835              :    if-conversion for masked stores, i.e. if the mask of a store is zero
   11836              :    do not perform it and all stored value producers also if possible.
   11837              :    For example,
   11838              :      for (i=0; i<n; i++)
   11839              :        if (c[i])
   11840              :         {
   11841              :           p1[i] += 1;
   11842              :           p2[i] = p3[i] +2;
   11843              :         }
   11844              :    this transformation will produce the following semi-hammock:
   11845              : 
   11846              :    if (!mask__ifc__42.18_165 == { 0, 0, 0, 0, 0, 0, 0, 0 })
   11847              :      {
   11848              :        vect__11.19_170 = MASK_LOAD (vectp_p1.20_168, 0B, mask__ifc__42.18_165);
   11849              :        vect__12.22_172 = vect__11.19_170 + vect_cst__171;
   11850              :        MASK_STORE (vectp_p1.23_175, 0B, mask__ifc__42.18_165, vect__12.22_172);
   11851              :        vect__18.25_182 = MASK_LOAD (vectp_p3.26_180, 0B, mask__ifc__42.18_165);
   11852              :        vect__19.28_184 = vect__18.25_182 + vect_cst__183;
   11853              :        MASK_STORE (vectp_p2.29_187, 0B, mask__ifc__42.18_165, vect__19.28_184);
   11854              :      }
   11855              : */
   11856              : 
   11857              : void
   11858          509 : optimize_mask_stores (class loop *loop)
   11859              : {
   11860          509 :   basic_block *bbs = get_loop_body (loop);
   11861          509 :   unsigned nbbs = loop->num_nodes;
   11862          509 :   unsigned i;
   11863          509 :   basic_block bb;
   11864          509 :   class loop *bb_loop;
   11865          509 :   gimple_stmt_iterator gsi;
   11866          509 :   gimple *stmt;
   11867          509 :   auto_vec<gimple *> worklist;
   11868          509 :   auto_purge_vect_location sentinel;
   11869              : 
   11870          509 :   vect_location = find_loop_location (loop);
   11871              :   /* Pick up all masked stores in loop if any.  */
   11872         2036 :   for (i = 0; i < nbbs; i++)
   11873              :     {
   11874         1018 :       bb = bbs[i];
   11875        18106 :       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
   11876        16070 :            gsi_next (&gsi))
   11877              :         {
   11878        16070 :           stmt = gsi_stmt (gsi);
   11879        16070 :           if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
   11880          707 :             worklist.safe_push (stmt);
   11881              :         }
   11882              :     }
   11883              : 
   11884          509 :   free (bbs);
   11885          509 :   if (worklist.is_empty ())
   11886           68 :     return;
   11887              : 
   11888              :   /* Loop has masked stores.  */
   11889         1131 :   while (!worklist.is_empty ())
   11890              :     {
   11891          690 :       gimple *last, *last_store;
   11892          690 :       edge e, efalse;
   11893          690 :       tree mask;
   11894          690 :       basic_block store_bb, join_bb;
   11895          690 :       gimple_stmt_iterator gsi_to;
   11896          690 :       tree vdef, new_vdef;
   11897          690 :       gphi *phi;
   11898          690 :       tree vectype;
   11899          690 :       tree zero;
   11900              : 
   11901          690 :       last = worklist.pop ();
   11902          690 :       mask = gimple_call_arg (last, 2);
   11903          690 :       bb = gimple_bb (last);
   11904              :       /* Create then_bb and if-then structure in CFG, then_bb belongs to
   11905              :          the same loop as if_bb.  It could be different to LOOP when two
   11906              :          level loop-nest is vectorized and mask_store belongs to the inner
   11907              :          one.  */
   11908          690 :       e = split_block (bb, last);
   11909          690 :       bb_loop = bb->loop_father;
   11910          690 :       gcc_assert (loop == bb_loop || flow_loop_nested_p (loop, bb_loop));
   11911          690 :       join_bb = e->dest;
   11912          690 :       store_bb = create_empty_bb (bb);
   11913          690 :       add_bb_to_loop (store_bb, bb_loop);
   11914          690 :       e->flags = EDGE_TRUE_VALUE;
   11915          690 :       efalse = make_edge (bb, store_bb, EDGE_FALSE_VALUE);
   11916              :       /* Put STORE_BB to likely part.  */
   11917          690 :       efalse->probability = profile_probability::likely ();
   11918          690 :       e->probability = efalse->probability.invert ();
   11919          690 :       store_bb->count = efalse->count ();
   11920          690 :       make_single_succ_edge (store_bb, join_bb, EDGE_FALLTHRU);
   11921          690 :       if (dom_info_available_p (CDI_DOMINATORS))
   11922          690 :         set_immediate_dominator (CDI_DOMINATORS, store_bb, bb);
   11923          690 :       if (dump_enabled_p ())
   11924          362 :         dump_printf_loc (MSG_NOTE, vect_location,
   11925              :                          "Create new block %d to sink mask stores.",
   11926              :                          store_bb->index);
   11927              :       /* Create vector comparison with boolean result.  */
   11928          690 :       vectype = TREE_TYPE (mask);
   11929          690 :       zero = build_zero_cst (vectype);
   11930          690 :       stmt = gimple_build_cond (EQ_EXPR, mask, zero, NULL_TREE, NULL_TREE);
   11931          690 :       gsi = gsi_last_bb (bb);
   11932          690 :       gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
   11933              :       /* Create new PHI node for vdef of the last masked store:
   11934              :          .MEM_2 = VDEF <.MEM_1>
   11935              :          will be converted to
   11936              :          .MEM.3 = VDEF <.MEM_1>
   11937              :          and new PHI node will be created in join bb
   11938              :          .MEM_2 = PHI <.MEM_1, .MEM_3>
   11939              :       */
   11940          690 :       vdef = gimple_vdef (last);
   11941          690 :       new_vdef = make_ssa_name (gimple_vop (cfun), last);
   11942          690 :       gimple_set_vdef (last, new_vdef);
   11943          690 :       phi = create_phi_node (vdef, join_bb);
   11944          690 :       add_phi_arg (phi, new_vdef, EDGE_SUCC (store_bb, 0), UNKNOWN_LOCATION);
   11945              : 
   11946              :       /* Put all masked stores with the same mask to STORE_BB if possible.  */
   11947          724 :       while (true)
   11948              :         {
   11949          707 :           gimple_stmt_iterator gsi_from;
   11950          707 :           gimple *stmt1 = NULL;
   11951              : 
   11952              :           /* Move masked store to STORE_BB.  */
   11953          707 :           last_store = last;
   11954          707 :           gsi = gsi_for_stmt (last);
   11955          707 :           gsi_from = gsi;
   11956              :           /* Shift GSI to the previous stmt for further traversal.  */
   11957          707 :           gsi_prev (&gsi);
   11958          707 :           gsi_to = gsi_start_bb (store_bb);
   11959          707 :           gsi_move_before (&gsi_from, &gsi_to);
   11960              :           /* Setup GSI_TO to the non-empty block start.  */
   11961          707 :           gsi_to = gsi_start_bb (store_bb);
   11962          707 :           if (dump_enabled_p ())
   11963          378 :             dump_printf_loc (MSG_NOTE, vect_location,
   11964              :                              "Move stmt to created bb\n%G", last);
   11965              :           /* Move all stored value producers if possible.  */
   11966         5504 :           while (!gsi_end_p (gsi))
   11967              :             {
   11968         5503 :               tree lhs;
   11969         5503 :               imm_use_iterator imm_iter;
   11970         5503 :               use_operand_p use_p;
   11971         5503 :               bool res;
   11972              : 
   11973              :               /* Skip debug statements.  */
   11974         5503 :               if (is_gimple_debug (gsi_stmt (gsi)))
   11975              :                 {
   11976            7 :                   gsi_prev (&gsi);
   11977         3512 :                   continue;
   11978              :                 }
   11979         5496 :               stmt1 = gsi_stmt (gsi);
   11980              :               /* Do not consider statements writing to memory or having
   11981              :                  volatile operand.  */
   11982        10795 :               if (gimple_vdef (stmt1)
   11983        10795 :                   || gimple_has_volatile_ops (stmt1))
   11984              :                 break;
   11985         5299 :               gsi_from = gsi;
   11986         5299 :               gsi_prev (&gsi);
   11987         5299 :               lhs = gimple_get_lhs (stmt1);
   11988         5299 :               if (!lhs)
   11989              :                 break;
   11990              : 
   11991              :               /* LHS of vectorized stmt must be SSA_NAME.  */
   11992         5299 :               if (TREE_CODE (lhs) != SSA_NAME)
   11993              :                 break;
   11994              : 
   11995         5299 :               if (!VECTOR_TYPE_P (TREE_TYPE (lhs)))
   11996              :                 {
   11997              :                   /* Remove dead scalar statement.  */
   11998         3842 :                   if (has_zero_uses (lhs))
   11999              :                     {
   12000         3505 :                       gsi_remove (&gsi_from, true);
   12001         3505 :                       release_defs (stmt1);
   12002         3505 :                       continue;
   12003              :                     }
   12004              :                 }
   12005              : 
   12006              :               /* Check that LHS does not have uses outside of STORE_BB.  */
   12007         1794 :               res = true;
   12008         3103 :               FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
   12009              :                 {
   12010         1818 :                   gimple *use_stmt;
   12011         1818 :                   use_stmt = USE_STMT (use_p);
   12012         1818 :                   if (is_gimple_debug (use_stmt))
   12013            0 :                     continue;
   12014         1818 :                   if (gimple_bb (use_stmt) != store_bb)
   12015              :                     {
   12016              :                       res = false;
   12017              :                       break;
   12018              :                     }
   12019         1794 :                 }
   12020         1794 :               if (!res)
   12021              :                 break;
   12022              : 
   12023         1285 :               if (gimple_vuse (stmt1)
   12024         1757 :                   && gimple_vuse (stmt1) != gimple_vuse (last_store))
   12025              :                 break;
   12026              : 
   12027              :               /* Can move STMT1 to STORE_BB.  */
   12028         1285 :               if (dump_enabled_p ())
   12029          685 :                 dump_printf_loc (MSG_NOTE, vect_location,
   12030              :                                  "Move stmt to created bb\n%G", stmt1);
   12031         1285 :               gsi_move_before (&gsi_from, &gsi_to);
   12032              :               /* Shift GSI_TO for further insertion.  */
   12033         1285 :               gsi_prev (&gsi_to);
   12034              :             }
   12035              :           /* Put other masked stores with the same mask to STORE_BB.  */
   12036          707 :           if (worklist.is_empty ()
   12037          266 :               || gimple_call_arg (worklist.last (), 2) != mask
   12038           17 :               || worklist.last () != stmt1)
   12039              :             break;
   12040           17 :           last = worklist.pop ();
   12041           17 :         }
   12042         1380 :       add_phi_arg (phi, gimple_vuse (last_store), e, UNKNOWN_LOCATION);
   12043              :     }
   12044          509 : }
   12045              : 
   12046              : /* Decide whether it is possible to use a zero-based induction variable
   12047              :    when vectorizing LOOP_VINFO with partial vectors.  If it is, return
   12048              :    the value that the induction variable must be able to hold in order
   12049              :    to ensure that the rgroups eventually have no active vector elements.
   12050              :    Return -1 otherwise.  */
   12051              : 
   12052              : widest_int
   12053        48574 : vect_iv_limit_for_partial_vectors (loop_vec_info loop_vinfo)
   12054              : {
   12055        48574 :   tree niters_skip = LOOP_VINFO_MASK_SKIP_NITERS (loop_vinfo);
   12056        48574 :   class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
   12057        48574 :   unsigned HOST_WIDE_INT max_vf = vect_max_vf (loop_vinfo);
   12058              : 
   12059              :   /* Calculate the value that the induction variable must be able
   12060              :      to hit in order to ensure that we end the loop with an all-false mask.
   12061              :      This involves adding the maximum number of inactive trailing scalar
   12062              :      iterations.  */
   12063        48574 :   widest_int iv_limit = -1;
   12064        48574 :   if (max_loop_iterations (loop, &iv_limit))
   12065              :     {
   12066        48574 :       if (niters_skip)
   12067              :         {
   12068              :           /* Add the maximum number of skipped iterations to the
   12069              :              maximum iteration count.  */
   12070            0 :           if (TREE_CODE (niters_skip) == INTEGER_CST)
   12071            0 :             iv_limit += wi::to_widest (niters_skip);
   12072              :           else
   12073            0 :             iv_limit += max_vf - 1;
   12074              :         }
   12075        48574 :       else if (LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo))
   12076              :         /* Make a conservatively-correct assumption.  */
   12077          326 :         iv_limit += max_vf - 1;
   12078              : 
   12079              :       /* IV_LIMIT is the maximum number of latch iterations, which is also
   12080              :          the maximum in-range IV value.  Round this value down to the previous
   12081              :          vector alignment boundary and then add an extra full iteration.  */
   12082        48574 :       poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
   12083        48574 :       iv_limit = (iv_limit & -(int) known_alignment (vf)) + max_vf;
   12084              :     }
   12085        48574 :   return iv_limit;
   12086              : }
   12087              : 
   12088              : /* For the given rgroup_controls RGC, check whether an induction variable
   12089              :    would ever hit a value that produces a set of all-false masks or zero
   12090              :    lengths before wrapping around.  Return true if it's possible to wrap
   12091              :    around before hitting the desirable value, otherwise return false.  */
   12092              : 
   12093              : bool
   12094            0 : vect_rgroup_iv_might_wrap_p (loop_vec_info loop_vinfo, rgroup_controls *rgc)
   12095              : {
   12096            0 :   widest_int iv_limit = vect_iv_limit_for_partial_vectors (loop_vinfo);
   12097              : 
   12098            0 :   if (iv_limit == -1)
   12099              :     return true;
   12100              : 
   12101            0 :   tree compare_type = LOOP_VINFO_RGROUP_COMPARE_TYPE (loop_vinfo);
   12102            0 :   unsigned int compare_precision = TYPE_PRECISION (compare_type);
   12103            0 :   unsigned nitems = rgc->max_nscalars_per_iter * rgc->factor;
   12104              : 
   12105            0 :   if (wi::min_precision (iv_limit * nitems, UNSIGNED) > compare_precision)
   12106            0 :     return true;
   12107              : 
   12108              :   return false;
   12109            0 : }
        

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.