LCOV - code coverage report
Current view: top level - gcc - tree-vect-slp.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 93.1 % 6186 5760
Test Date: 2026-09-19 16:22:48 Functions: 95.2 % 186 177
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* SLP - Basic Block Vectorization
       2              :    Copyright (C) 2007-2026 Free Software Foundation, Inc.
       3              :    Contributed by Dorit Naishlos <dorit@il.ibm.com>
       4              :    and 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              : #include "config.h"
      23              : #define INCLUDE_ALGORITHM
      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 "tree-pass.h"
      32              : #include "ssa.h"
      33              : #include "optabs-tree.h"
      34              : #include "insn-config.h"
      35              : #include "recog.h"            /* FIXME: for insn_data */
      36              : #include "fold-const.h"
      37              : #include "stor-layout.h"
      38              : #include "gimple-iterator.h"
      39              : #include "cfgloop.h"
      40              : #include "tree-vectorizer.h"
      41              : #include "langhooks.h"
      42              : #include "gimple-walk.h"
      43              : #include "dbgcnt.h"
      44              : #include "tree-vector-builder.h"
      45              : #include "vec-perm-indices.h"
      46              : #include "gimple-fold.h"
      47              : #include "internal-fn.h"
      48              : #include "dump-context.h"
      49              : #include "cfganal.h"
      50              : #include "tree-eh.h"
      51              : #include "tree-cfg.h"
      52              : #include "alloc-pool.h"
      53              : #include "sreal.h"
      54              : #include "predict.h"
      55              : 
      56              : #define REDUC_GROUP_FIRST_ELEMENT(S) \
      57              :   (gcc_checking_assert (!(S)->dr_aux.dr), (S)->first_element)
      58              : 
      59              : static bool vect_transform_slp_perm_load_1 (vec_info *, slp_tree,
      60              :                                             load_permutation_t &,
      61              :                                             const vec<tree> &,
      62              :                                             gimple_stmt_iterator *,
      63              :                                             poly_uint64, bool, bool,
      64              :                                             unsigned *,
      65              :                                             unsigned * = nullptr,
      66              :                                             bool = false);
      67              : static int vectorizable_slp_permutation_1 (vec_info *, gimple_stmt_iterator *,
      68              :                                            slp_tree, lane_permutation_t &,
      69              :                                            vec<slp_tree> &, bool);
      70              : static void vect_print_slp_tree (dump_flags_t, dump_location_t, slp_tree);
      71              : static bool vect_slp_can_convert_to_external (const vec<stmt_vec_info> &);
      72              : 
      73              : static object_allocator<_slp_tree> *slp_tree_pool;
      74              : static slp_tree slp_first_node;
      75              : 
      76              : void
      77      1138792 : vect_slp_init (void)
      78              : {
      79      1138792 :   slp_tree_pool = new object_allocator<_slp_tree> ("SLP nodes");
      80      1138792 : }
      81              : 
      82              : void
      83      1138792 : vect_slp_fini (void)
      84              : {
      85      1830668 :   while (slp_first_node)
      86       691876 :     delete slp_first_node;
      87      2277584 :   delete slp_tree_pool;
      88      1138792 :   slp_tree_pool = NULL;
      89      1138792 : }
      90              : 
      91              : void *
      92      8194569 : _slp_tree::operator new (size_t n)
      93              : {
      94      8194569 :   gcc_assert (n == sizeof (_slp_tree));
      95      8194569 :   return slp_tree_pool->allocate_raw ();
      96              : }
      97              : 
      98              : void
      99      8194569 : _slp_tree::operator delete (void *node, size_t n)
     100              : {
     101      8194569 :   gcc_assert (n == sizeof (_slp_tree));
     102      8194569 :   slp_tree_pool->remove_raw (node);
     103      8194569 : }
     104              : 
     105              : 
     106              : /* Initialize a SLP node.  */
     107              : 
     108      8194569 : _slp_tree::_slp_tree ()
     109              : {
     110      8194569 :   this->prev_node = NULL;
     111      8194569 :   if (slp_first_node)
     112      7168112 :     slp_first_node->prev_node = this;
     113      8194569 :   this->next_node = slp_first_node;
     114      8194569 :   slp_first_node = this;
     115      8194569 :   SLP_TREE_SCALAR_STMTS (this) = vNULL;
     116      8194569 :   SLP_TREE_SCALAR_OPS (this) = vNULL;
     117      8194569 :   SLP_TREE_LIVE_LANES (this) = vNULL;
     118      8194569 :   SLP_TREE_VEC_DEFS (this) = vNULL;
     119      8194569 :   SLP_TREE_CHILDREN (this) = vNULL;
     120      8194569 :   SLP_TREE_LOAD_PERMUTATION (this) = vNULL;
     121      8194569 :   SLP_TREE_LANE_PERMUTATION (this) = vNULL;
     122      8194569 :   SLP_TREE_DEF_TYPE (this) = vect_uninitialized_def;
     123      8194569 :   SLP_TREE_CODE (this) = ERROR_MARK;
     124      8194569 :   SLP_TREE_GS_SCALE (this) = 0;
     125      8194569 :   SLP_TREE_GS_BASE (this) = NULL_TREE;
     126      8194569 :   this->ldst_lanes = false;
     127      8194569 :   this->avoid_stlf_fail = false;
     128      8194569 :   SLP_TREE_VECTYPE (this) = NULL_TREE;
     129      8194569 :   SLP_TREE_REPRESENTATIVE (this) = NULL;
     130      8194569 :   this->cycle_info.id = -1;
     131      8194569 :   this->cycle_info.reduc_idx = -1;
     132      8194569 :   SLP_TREE_REF_COUNT (this) = 1;
     133      8194569 :   this->failed = NULL;
     134      8194569 :   this->lanes = 0;
     135      8194569 :   SLP_TREE_TYPE (this) = undef_vec_info_type;
     136      8194569 :   this->data = NULL;
     137      8194569 :   this->si = NULL;
     138      8194569 : }
     139              : 
     140              : /* Tear down a SLP node.  */
     141              : 
     142      8194569 : _slp_tree::~_slp_tree ()
     143              : {
     144      8194569 :   if (this->prev_node)
     145      4995305 :     this->prev_node->next_node = this->next_node;
     146              :   else
     147      3199264 :     slp_first_node = this->next_node;
     148      8194569 :   if (this->next_node)
     149      6190445 :     this->next_node->prev_node = this->prev_node;
     150      8194569 :   SLP_TREE_CHILDREN (this).release ();
     151      8194569 :   SLP_TREE_SCALAR_STMTS (this).release ();
     152      8194569 :   SLP_TREE_SCALAR_OPS (this).release ();
     153      8194569 :   SLP_TREE_LIVE_LANES (this).release ();
     154      8194569 :   SLP_TREE_VEC_DEFS (this).release ();
     155      8194569 :   SLP_TREE_LOAD_PERMUTATION (this).release ();
     156      8194569 :   SLP_TREE_LANE_PERMUTATION (this).release ();
     157      8194569 :   if (this->failed)
     158      2135485 :     free (failed);
     159      8194569 :   if (this->data)
     160      1280343 :     delete this->data;
     161      8194569 : }
     162              : 
     163              : /* Push the single SSA definition in DEF to the vector of vector defs.  */
     164              : 
     165              : void
     166       537040 : _slp_tree::push_vec_def (gimple *def)
     167              : {
     168       537040 :   if (gphi *phi = dyn_cast <gphi *> (def))
     169        60077 :     vec_defs.quick_push (gimple_phi_result (phi));
     170              :   else
     171              :     {
     172       476963 :       def_operand_p defop = single_ssa_def_operand (def, SSA_OP_ALL_DEFS);
     173       476963 :       vec_defs.quick_push (get_def_from_ptr (defop));
     174              :     }
     175       537040 : }
     176              : 
     177              : /* Recursively free the memory allocated for the SLP tree rooted at NODE.  */
     178              : 
     179              : void
     180     15525630 : vect_free_slp_tree (slp_tree node)
     181              : {
     182     15525630 :   int i;
     183     15525630 :   slp_tree child;
     184              : 
     185     15525630 :   if (--SLP_TREE_REF_COUNT (node) != 0)
     186     15525630 :     return;
     187              : 
     188     11674966 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
     189      4172273 :     if (child)
     190      3790644 :       vect_free_slp_tree (child);
     191              : 
     192      7502693 :   delete node;
     193              : }
     194              : 
     195              : /* Return a location suitable for dumpings related to the SLP instance.  */
     196              : 
     197              : dump_user_location_t
     198      3556319 : _slp_instance::location () const
     199              : {
     200      3556319 :   if (!root_stmts.is_empty ())
     201       416435 :     return root_stmts[0]->stmt;
     202              :   else
     203      3139884 :     return SLP_TREE_SCALAR_STMTS (root)[0]->stmt;
     204              : }
     205              : 
     206              : 
     207              : /* Free the memory allocated for the SLP instance.  */
     208              : 
     209              : void
     210      1631226 : vect_free_slp_instance (slp_instance instance)
     211              : {
     212      1631226 :   vect_free_slp_tree (SLP_INSTANCE_TREE (instance));
     213      1631226 :   SLP_INSTANCE_LOADS (instance).release ();
     214      1631226 :   SLP_INSTANCE_ROOT_STMTS (instance).release ();
     215      1631226 :   SLP_INSTANCE_REMAIN_DEFS (instance).release ();
     216      1631226 :   instance->subgraph_entries.release ();
     217      1631226 :   instance->cost_vec.release ();
     218      1631226 :   free (instance);
     219      1631226 : }
     220              : 
     221              : 
     222              : /* Create a SLP node with NOPS children with CODE, either VEC_PERM_EXPR
     223              :    for a permute node or else ERROR_MARK.  */
     224              : 
     225              : slp_tree
     226        97864 : vect_create_new_slp_node (unsigned nops, tree_code code)
     227              : {
     228        97864 :   gcc_assert (code == ERROR_MARK || code == VEC_PERM_EXPR);
     229        97864 :   slp_tree node = new _slp_tree;
     230        97864 :   SLP_TREE_SCALAR_STMTS (node) = vNULL;
     231        97864 :   SLP_TREE_CHILDREN (node).create (nops);
     232        97864 :   SLP_TREE_DEF_TYPE (node) = vect_internal_def;
     233        97864 :   SLP_TREE_CODE (node) = code;
     234        97864 :   return node;
     235              : }
     236              : 
     237              : /* Create a SLP node inplace at NODE for SCALAR_STMTS and NOPS children.  */
     238              : 
     239              : static slp_tree
     240      3981291 : vect_create_new_slp_node (slp_tree node,
     241              :                           vec<stmt_vec_info> scalar_stmts, unsigned nops)
     242              : {
     243      3981291 :   SLP_TREE_SCALAR_STMTS (node) = scalar_stmts;
     244      3981291 :   SLP_TREE_CHILDREN (node).create (nops);
     245      3981291 :   SLP_TREE_DEF_TYPE (node) = vect_internal_def;
     246      3981291 :   SLP_TREE_REPRESENTATIVE (node) = scalar_stmts[0];
     247      3981291 :   SLP_TREE_LANES (node) = scalar_stmts.length ();
     248      3981291 :   return node;
     249              : }
     250              : 
     251              : /* Create an SLP node for SCALAR_STMTS and NOPS children.  */
     252              : 
     253              : static slp_tree
     254         8398 : vect_create_new_slp_node (vec<stmt_vec_info> scalar_stmts, unsigned nops)
     255              : {
     256         8398 :   return vect_create_new_slp_node (new _slp_tree, scalar_stmts, nops);
     257              : }
     258              : 
     259              : /* Create a vect_external_def SLP node inplace at NODE for scalar
     260              :    operands OPS.  */
     261              : 
     262              : static slp_tree
     263      1967666 : vect_create_new_slp_node (slp_tree node, vec<tree> ops)
     264              : {
     265      1967666 :   SLP_TREE_SCALAR_OPS (node) = ops;
     266      1967666 :   SLP_TREE_DEF_TYPE (node) = vect_external_def;
     267            0 :   SLP_TREE_LANES (node) = ops.length ();
     268      1967666 :   return node;
     269              : }
     270              : 
     271              : /* Create a vect_external_def SLP node for scalar operands OPS.  */
     272              : 
     273              : static slp_tree
     274      1967666 : vect_create_new_slp_node (vec<tree> ops)
     275              : {
     276      1967666 :   return vect_create_new_slp_node (new _slp_tree, ops);
     277              : }
     278              : 
     279              : 
     280              : /* This structure is used in creation of an SLP tree.  Each instance
     281              :    corresponds to the same operand in a group of scalar stmts in an SLP
     282              :    node.  */
     283              : typedef struct _slp_oprnd_info
     284              : {
     285              :   /* Def-stmts for the operands.  */
     286              :   vec<stmt_vec_info> def_stmts;
     287              :   /* Operands.  */
     288              :   vec<tree> ops;
     289              :   /* Information about the first statement, its vector def-type, type, the
     290              :      operand itself in case it's constant, and an indication if it's a pattern
     291              :      stmt and gather/scatter info.  */
     292              :   tree first_op_type;
     293              :   enum vect_def_type first_dt;
     294              :   bool any_pattern;
     295              :   bool first_gs_p;
     296              :   gather_scatter_info first_gs_info;
     297              : } *slp_oprnd_info;
     298              : 
     299              : 
     300              : /* Allocate operands info for NOPS operands, and GROUP_SIZE def-stmts for each
     301              :    operand.  */
     302              : static vec<slp_oprnd_info>
     303      3665743 : vect_create_oprnd_info (int nops, int group_size)
     304              : {
     305      3665743 :   int i;
     306      3665743 :   slp_oprnd_info oprnd_info;
     307      3665743 :   vec<slp_oprnd_info> oprnds_info;
     308              : 
     309      3665743 :   oprnds_info.create (nops);
     310     13118391 :   for (i = 0; i < nops; i++)
     311              :     {
     312      5786905 :       oprnd_info = XNEW (struct _slp_oprnd_info);
     313      5786905 :       oprnd_info->def_stmts.create (group_size);
     314      5786905 :       oprnd_info->ops.create (group_size);
     315      5786905 :       oprnd_info->first_dt = vect_uninitialized_def;
     316      5786905 :       oprnd_info->first_op_type = NULL_TREE;
     317      5786905 :       oprnd_info->any_pattern = false;
     318      5786905 :       oprnd_info->first_gs_p = false;
     319      5786905 :       oprnds_info.quick_push (oprnd_info);
     320              :     }
     321              : 
     322      3665743 :   return oprnds_info;
     323              : }
     324              : 
     325              : 
     326              : /* Free operands info.  */
     327              : 
     328              : static void
     329      3543126 : vect_free_oprnd_info (vec<slp_oprnd_info> &oprnds_info)
     330              : {
     331      3543126 :   int i;
     332      3543126 :   slp_oprnd_info oprnd_info;
     333              : 
     334      9198340 :   FOR_EACH_VEC_ELT (oprnds_info, i, oprnd_info)
     335              :     {
     336      5655214 :       oprnd_info->def_stmts.release ();
     337      5655214 :       oprnd_info->ops.release ();
     338      5655214 :       XDELETE (oprnd_info);
     339              :     }
     340              : 
     341      3543126 :   oprnds_info.release ();
     342      3543126 : }
     343              : 
     344              : /* Return the execution frequency of NODE (so that a higher value indicates
     345              :    a "more important" node when optimizing for speed).  */
     346              : 
     347              : static sreal
     348      3672517 : vect_slp_node_weight (vec_info *vinfo, slp_tree node)
     349              : {
     350      3672517 :   stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (node);
     351      3672517 :   basic_block bb;
     352              :   /* ???  This is imprecise, VEC_PERM nodes do not have a representative
     353              :      but are laid out close to their children.  */
     354      3672517 :   if (!stmt_info)
     355       142973 :     bb = vinfo->bbs[0];
     356              :   else
     357      4000459 :     bb = gimple_bb (vect_orig_stmt (stmt_info)->stmt);
     358      3672517 :   return bb->count.to_sreal_scale (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count);
     359              : }
     360              : 
     361              : /* Return true if STMTS contains a pattern statement.  */
     362              : 
     363              : static bool
     364        29778 : vect_contains_pattern_stmt_p (vec<stmt_vec_info> stmts)
     365              : {
     366        29778 :   stmt_vec_info stmt_info;
     367        29778 :   unsigned int i;
     368        85430 :   FOR_EACH_VEC_ELT (stmts, i, stmt_info)
     369        63085 :     if (stmt_info && is_pattern_stmt_p (stmt_info))
     370              :       return true;
     371              :   return false;
     372              : }
     373              : 
     374              : /* Return true when all lanes in the external or constant NODE have
     375              :    the same value.  */
     376              : 
     377              : static bool
     378       645414 : vect_slp_tree_uniform_p (slp_tree node)
     379              : {
     380       645414 :   gcc_assert (SLP_TREE_DEF_TYPE (node) == vect_constant_def
     381              :               || SLP_TREE_DEF_TYPE (node) == vect_external_def);
     382              : 
     383              :   /* Pre-existing vectors.  */
     384       645414 :   if (SLP_TREE_SCALAR_OPS (node).is_empty ())
     385              :     return false;
     386              : 
     387              :   unsigned i;
     388              :   tree op, first = NULL_TREE;
     389      1480857 :   FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_OPS (node), i, op)
     390      1322441 :     if (!first)
     391              :       first = op;
     392       677027 :     else if (!operand_equal_p (first, op, 0))
     393              :       return false;
     394              : 
     395              :   return true;
     396              : }
     397              : 
     398              : /* Find the place of the data-ref in STMT_INFO in the interleaving chain
     399              :    that starts from FIRST_STMT_INFO.  Return -1 if the data-ref is not a part
     400              :    of the chain.  */
     401              : 
     402              : int
     403       750963 : vect_get_place_in_interleaving_chain (stmt_vec_info stmt_info,
     404              :                                       stmt_vec_info first_stmt_info)
     405              : {
     406       750963 :   stmt_vec_info next_stmt_info = first_stmt_info;
     407       750963 :   int result = 0;
     408              : 
     409       750963 :   if (first_stmt_info != DR_GROUP_FIRST_ELEMENT (stmt_info))
     410              :     return -1;
     411              : 
     412      2125562 :   do
     413              :     {
     414      2125562 :       if (next_stmt_info == stmt_info)
     415              :         return result;
     416      1374599 :       next_stmt_info = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
     417      1374599 :       if (next_stmt_info)
     418      1374599 :         result += DR_GROUP_GAP (next_stmt_info);
     419              :     }
     420      1374599 :   while (next_stmt_info);
     421              : 
     422              :   return -1;
     423              : }
     424              : 
     425              : /* Check whether it is possible to load COUNT elements of type ELT_TYPE
     426              :    using the method implemented by duplicate_and_interleave.  Return true
     427              :    if so, returning the number of intermediate vectors in *NVECTORS_OUT
     428              :    (if nonnull) and the type of each intermediate vector in *VECTOR_TYPE_OUT
     429              :    (if nonnull).  */
     430              : 
     431              : bool
     432            0 : can_duplicate_and_interleave_p (vec_info *vinfo, unsigned int count,
     433              :                                 tree elt_type, unsigned int *nvectors_out,
     434              :                                 tree *vector_type_out,
     435              :                                 tree *permutes)
     436              : {
     437            0 :   tree base_vector_type = get_vectype_for_scalar_type (vinfo, elt_type, count);
     438            0 :   if (!base_vector_type || !VECTOR_MODE_P (TYPE_MODE (base_vector_type)))
     439              :     return false;
     440              : 
     441            0 :   machine_mode base_vector_mode = TYPE_MODE (base_vector_type);
     442            0 :   poly_int64 elt_bytes = count * GET_MODE_UNIT_SIZE (base_vector_mode);
     443            0 :   unsigned int nvectors = 1;
     444            0 :   for (;;)
     445              :     {
     446            0 :       scalar_int_mode int_mode;
     447            0 :       poly_int64 elt_bits = elt_bytes * BITS_PER_UNIT;
     448            0 :       if (int_mode_for_size (elt_bits, 1).exists (&int_mode))
     449              :         {
     450              :           /* Get the natural vector type for this SLP group size.  */
     451            0 :           tree int_type = build_nonstandard_integer_type
     452            0 :             (GET_MODE_BITSIZE (int_mode), 1);
     453            0 :           tree vector_type
     454            0 :             = get_vectype_for_scalar_type (vinfo, int_type, count);
     455            0 :           poly_int64 half_nelts;
     456            0 :           if (vector_type
     457            0 :               && VECTOR_MODE_P (TYPE_MODE (vector_type))
     458            0 :               && known_eq (GET_MODE_SIZE (TYPE_MODE (vector_type)),
     459              :                            GET_MODE_SIZE (base_vector_mode))
     460            0 :               && multiple_p (GET_MODE_NUNITS (TYPE_MODE (vector_type)),
     461              :                              2, &half_nelts))
     462              :             {
     463              :               /* Try fusing consecutive sequences of COUNT / NVECTORS elements
     464              :                  together into elements of type INT_TYPE and using the result
     465              :                  to build NVECTORS vectors.  */
     466            0 :               poly_uint64 nelts = GET_MODE_NUNITS (TYPE_MODE (vector_type));
     467            0 :               vec_perm_builder sel1 (nelts, 2, 3);
     468            0 :               vec_perm_builder sel2 (nelts, 2, 3);
     469              : 
     470            0 :               for (unsigned int i = 0; i < 3; ++i)
     471              :                 {
     472            0 :                   sel1.quick_push (i);
     473            0 :                   sel1.quick_push (i + nelts);
     474            0 :                   sel2.quick_push (half_nelts + i);
     475            0 :                   sel2.quick_push (half_nelts + i + nelts);
     476              :                 }
     477            0 :               vec_perm_indices indices1 (sel1, 2, nelts);
     478            0 :               vec_perm_indices indices2 (sel2, 2, nelts);
     479            0 :               machine_mode vmode = TYPE_MODE (vector_type);
     480            0 :               if (can_vec_perm_const_p (vmode, vmode, indices1)
     481            0 :                   && can_vec_perm_const_p (vmode, vmode, indices2))
     482              :                 {
     483            0 :                   if (nvectors_out)
     484            0 :                     *nvectors_out = nvectors;
     485            0 :                   if (vector_type_out)
     486            0 :                     *vector_type_out = vector_type;
     487            0 :                   if (permutes)
     488              :                     {
     489            0 :                       permutes[0] = vect_gen_perm_mask_checked (vector_type,
     490              :                                                                 indices1);
     491            0 :                       permutes[1] = vect_gen_perm_mask_checked (vector_type,
     492              :                                                                 indices2);
     493              :                     }
     494            0 :                   return true;
     495              :                 }
     496            0 :             }
     497              :         }
     498            0 :       if (!multiple_p (elt_bytes, 2, &elt_bytes))
     499              :         return false;
     500            0 :       nvectors *= 2;
     501              :       /* We need to be able to fuse COUNT / NVECTORS elements together.  */
     502            0 :       if (!multiple_p (count, nvectors))
     503              :         return false;
     504              :     }
     505              : }
     506              : 
     507              : /* Return true if DTA and DTB match.  */
     508              : 
     509              : static bool
     510     17747838 : vect_def_types_match (enum vect_def_type dta, enum vect_def_type dtb)
     511              : {
     512     17747838 :   return (dta == dtb
     513       416861 :           || ((dta == vect_external_def || dta == vect_constant_def)
     514       266790 :               && (dtb == vect_external_def || dtb == vect_constant_def)));
     515              : }
     516              : 
     517              : #define GATHER_SCATTER_OFFSET (-3)
     518              : 
     519              : /* For most SLP statements, there is a one-to-one mapping between
     520              :    gimple arguments and child nodes.  If that is not true for STMT,
     521              :    return an array that contains:
     522              : 
     523              :    - the number of child nodes, followed by
     524              :    - for each child node, the index of the argument associated with that node.
     525              :      The special index -1 is the first operand of an embedded comparison and
     526              :      the special index -2 is the second operand of an embedded comparison.
     527              :      The special index -3 is the offset of a gather as analyzed by
     528              :      vect_check_gather_scatter.
     529              : 
     530              :    SWAP is as for vect_get_and_check_slp_defs.  */
     531              : 
     532              : static const int *
     533     25857378 : vect_get_operand_map (const gimple *stmt, bool gather_scatter_p,
     534              :                       unsigned char swap)
     535              : {
     536     25857378 :   static const int no_arg_map[] = { 0 };
     537     25857378 :   static const int arg0_map[] = { 1, 0 };
     538     25857378 :   static const int arg2_map[] = { 1, 2 };
     539     25857378 :   static const int arg2_arg3_map[] = { 2, 2, 3 };
     540     25857378 :   static const int arg2_arg4_map[] = { 2, 2, 4 };
     541     25857378 :   static const int arg2_arg5_arg6_map[] = { 3, 2, 5, 6 };
     542     25857378 :   static const int arg2_arg4_arg5_map[] = { 3, 2, 4, 5 };
     543     25857378 :   static const int arg3_arg2_map[] = { 2, 3, 2 };
     544     25857378 :   static const int op00_map[] = { 1, -1 };
     545     25857378 :   static const int op1_op0_map[] = { 2, 1, 0 };
     546     25857378 :   static const int off_map[] = { 1, GATHER_SCATTER_OFFSET };
     547     25857378 :   static const int off_op0_map[] = { 2, GATHER_SCATTER_OFFSET, 0 };
     548     25857378 :   static const int off_arg2_arg3_map[] = { 3, GATHER_SCATTER_OFFSET, 2, 3 };
     549     25857378 :   static const int off_arg3_arg2_map[] = { 3, GATHER_SCATTER_OFFSET, 3, 2 };
     550     25857378 :   static const int mask_call_maps[6][7] = {
     551              :         { 1, 1, },
     552              :         { 2, 1, 2, },
     553              :         { 3, 1, 2, 3, },
     554              :         { 4, 1, 2, 3, 4, },
     555              :         { 5, 1, 2, 3, 4, 5, },
     556              :         { 6, 1, 2, 3, 4, 5, 6 },
     557              :   };
     558              : 
     559     25857378 :   gcc_checking_assert (!swap
     560              :                        || !is_gimple_assign (stmt)
     561              :                        || TREE_CODE_CLASS
     562              :                             (gimple_assign_rhs_code (stmt)) == tcc_comparison
     563              :                        || commutative_tree_code
     564              :                             (gimple_assign_rhs_code (stmt)));
     565              : 
     566     25857378 :   if (auto assign = dyn_cast<const gassign *> (stmt))
     567              :     {
     568     24307908 :       tree_code code = gimple_assign_rhs_code (assign);
     569     24307908 :       if (code == COND_EXPR
     570     24307908 :           && COMPARISON_CLASS_P (gimple_assign_rhs1 (assign)))
     571            0 :         gcc_unreachable ();
     572     24307908 :       else if ((TREE_CODE_CLASS (code) == tcc_comparison
     573     22752838 :                 || commutative_tree_code (code))
     574     33404136 :                && swap)
     575              :         return op1_op0_map;
     576     24264035 :       else if (code == VIEW_CONVERT_EXPR)
     577              :         return op00_map;
     578     24254748 :       else if (gather_scatter_p)
     579        46824 :         return (TREE_CODE (gimple_assign_lhs (assign)) != SSA_NAME
     580        46824 :                 ? off_op0_map : off_map);
     581              :     }
     582      1549470 :   else if (auto call = dyn_cast<const gcall *> (stmt))
     583              :     {
     584       168120 :       if (gimple_call_internal_p (call))
     585        92195 :         switch (gimple_call_internal_fn (call))
     586              :           {
     587        13928 :           case IFN_MASK_LOAD:
     588        13928 :             return gather_scatter_p ? off_arg2_arg3_map : arg2_arg3_map;
     589              : 
     590            0 :           case IFN_GATHER_LOAD:
     591            0 :             return arg2_map;
     592              : 
     593            0 :           case IFN_MASK_GATHER_LOAD:
     594            0 :           case IFN_MASK_LEN_GATHER_LOAD:
     595            0 :             return arg2_arg5_arg6_map;
     596              : 
     597            0 :           case IFN_SCATTER_STORE:
     598            0 :             return arg2_arg4_map;
     599              : 
     600            0 :           case IFN_MASK_SCATTER_STORE:
     601            0 :           case IFN_MASK_LEN_SCATTER_STORE:
     602            0 :             return arg2_arg4_arg5_map;
     603              : 
     604         9200 :           case IFN_MASK_STORE:
     605         9200 :             return gather_scatter_p ? off_arg3_arg2_map : arg3_arg2_map;
     606              : 
     607          996 :           case IFN_MASK_CALL:
     608          996 :             {
     609          996 :               unsigned nargs = gimple_call_num_args (call);
     610          996 :               if (nargs >= 2 && nargs <= 7)
     611          996 :                 return mask_call_maps[nargs-2];
     612              :               else
     613              :                 return nullptr;
     614              :             }
     615              : 
     616          278 :           case IFN_CLZ:
     617          278 :           case IFN_CTZ:
     618          278 :             return arg0_map;
     619              : 
     620         7302 :           case IFN_GOMP_SIMD_LANE:
     621         7302 :             return no_arg_map;
     622              : 
     623              :           default:
     624              :             break;
     625              :           }
     626              :     }
     627              :   return nullptr;
     628              : }
     629              : 
     630              : static const int *
     631     25838814 : vect_get_operand_map (const stmt_vec_info stmt, unsigned char swap = 0)
     632              : {
     633            0 :   return vect_get_operand_map (stmt->stmt, STMT_VINFO_GATHER_SCATTER_P (stmt),
     634            0 :                                swap);
     635              : }
     636              : 
     637              : /* Return the SLP node child index for operand OP of STMT.  */
     638              : 
     639              : int
     640      1398704 : vect_slp_child_index_for_operand (const stmt_vec_info stmt, int op)
     641              : {
     642      1398704 :   const int *opmap = vect_get_operand_map (stmt);
     643      1398704 :   if (!opmap)
     644              :     return op;
     645        20313 :   for (int i = 1; i < 1 + opmap[0]; ++i)
     646        20313 :     if (opmap[i] == op)
     647        11556 :       return i - 1;
     648            0 :   gcc_unreachable ();
     649              : }
     650              : 
     651              : /* Helper class for mapping of GIMPLE operands to SLP children.  */
     652              : /* ???  Add vect_slp_child_index_for_operand here and amend opmaps
     653              :    with the full reverse mapping and indicating the position of the
     654              :    first commutative operand index, eliding the swap_p argument from
     655              :    vect_get_operand_map.  Adjust all consumers.  */
     656              : 
     657              : struct slp_oprnds {
     658              :   slp_oprnds (stmt_vec_info);
     659              :   tree get_op_for_slp_child (stmt_vec_info, unsigned);
     660              :   const int *opmap;
     661              :   const unsigned int num_slp_children;
     662              : };
     663              : 
     664      4622469 : slp_oprnds::slp_oprnds (stmt_vec_info stmt_info)
     665      4622469 :   : opmap (vect_get_operand_map (stmt_info)),
     666      4622469 :     num_slp_children (opmap ? opmap[0] : gimple_num_args (stmt_info->stmt))
     667              : {
     668      4622469 : }
     669              : 
     670              : /* For SLP child number N get the corresponding tree operand from GIMPLE
     671              :    statement described by STMT_INFO.  */
     672              : 
     673              : tree
     674      5158092 : slp_oprnds::get_op_for_slp_child (stmt_vec_info stmt_info, unsigned n)
     675              : {
     676      5158092 :   gcc_assert (n < num_slp_children);
     677      5158092 :   int opno = opmap ? opmap[n + 1] : (int) n;
     678      5158092 :   if (opno == GATHER_SCATTER_OFFSET)
     679            0 :     gcc_unreachable (); // TODO
     680      5158092 :   else if (opno < 0)
     681         2530 :     return TREE_OPERAND (gimple_arg (stmt_info->stmt, 0), -1 - opno);
     682              :   else
     683      5155562 :     return gimple_arg (stmt_info->stmt, opno);
     684              : }
     685              : 
     686              : /* Get the defs for the rhs of STMT (collect them in OPRNDS_INFO), check that
     687              :    they are of a valid type and that they match the defs of the first stmt of
     688              :    the SLP group (stored in OPRNDS_INFO).  This function tries to match stmts
     689              :    by swapping operands of STMTS[STMT_NUM] when possible.  Non-zero SWAP
     690              :    indicates swap is required for cond_expr stmts.  Specifically, SWAP
     691              :    is 1 if STMT is cond and operands of comparison need to be swapped;
     692              :    SWAP is 2 if STMT is cond and code of comparison needs to be inverted.
     693              : 
     694              :    If there was a fatal error return -1; if the error could be corrected by
     695              :    swapping operands of father node of this one, return 1; if everything is
     696              :    ok return 0.  */
     697              : static int
     698     13712770 : vect_get_and_check_slp_defs (vec_info *vinfo, tree vectype, unsigned char swap,
     699              :                              bool *skip_args,
     700              :                              vec<stmt_vec_info> stmts, unsigned stmt_num,
     701              :                              vec<slp_oprnd_info> *oprnds_info,
     702              :                              bool soft_fail)
     703              : {
     704     13712770 :   stmt_vec_info stmt_info = stmts[stmt_num];
     705     13712770 :   tree oprnd;
     706     13712770 :   unsigned int i, number_of_oprnds;
     707     13712770 :   enum vect_def_type dt = vect_uninitialized_def;
     708     13712770 :   slp_oprnd_info oprnd_info;
     709     13712770 :   gather_scatter_info gs_info;
     710     13712770 :   unsigned int gs_op = -1u;
     711     13712770 :   unsigned int commutative_op = -1U;
     712     13712770 :   bool first = stmt_num == 0;
     713              : 
     714     13712770 :   if (!stmt_info)
     715              :     {
     716            0 :       for (auto oi : *oprnds_info)
     717              :         {
     718            0 :           oi->def_stmts.quick_push (NULL);
     719            0 :           oi->ops.quick_push (NULL_TREE);
     720              :         }
     721              :       return 0;
     722              :     }
     723              : 
     724     13712770 :   if (!is_a<gcall *> (stmt_info->stmt)
     725              :       && !is_a<gassign *> (stmt_info->stmt)
     726              :       && !is_a<gphi *> (stmt_info->stmt))
     727              :     return -1;
     728              : 
     729     13712770 :   number_of_oprnds = gimple_num_args (stmt_info->stmt);
     730     13712770 :   const int *map = vect_get_operand_map (stmt_info, swap);
     731     13712770 :   if (map)
     732        80855 :     number_of_oprnds = *map++;
     733     13712770 :   if (gcall *stmt = dyn_cast <gcall *> (stmt_info->stmt))
     734              :     {
     735        53327 :       if (gimple_call_internal_p (stmt))
     736              :         {
     737        32950 :           internal_fn ifn = gimple_call_internal_fn (stmt);
     738        32950 :           commutative_op = first_commutative_argument (ifn);
     739        32950 :           if (internal_gather_scatter_fn_p (ifn))
     740              :             {
     741            0 :               vect_describe_gather_scatter_call
     742            0 :                 (stmt_info,
     743            0 :                  first ? &(*oprnds_info)[0]->first_gs_info : &gs_info);
     744            0 :               if (first)
     745            0 :                 (*oprnds_info)[0]->first_gs_p = true;
     746              :               gs_op = 0;
     747              :             }
     748              :         }
     749              :     }
     750     13659443 :   else if (gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt))
     751              :     {
     752     16401313 :       if (commutative_tree_code (gimple_assign_rhs_code (stmt)))
     753      8527409 :         commutative_op = 0;
     754              :     }
     755              : 
     756     13712770 :   bool swapped = (swap != 0);
     757     13712770 :   bool backedge = false;
     758     13712770 :   enum vect_def_type *dts = XALLOCAVEC (enum vect_def_type, number_of_oprnds);
     759     37451963 :   for (i = 0; i < number_of_oprnds; i++)
     760              :     {
     761     23740507 :       oprnd_info = (*oprnds_info)[i];
     762     23740507 :       int opno = map ? map[i] : int (i);
     763     23740507 :       if (opno == GATHER_SCATTER_OFFSET)
     764              :         {
     765        23847 :           gcc_assert (STMT_VINFO_GATHER_SCATTER_P (stmt_info));
     766        23847 :           if (!is_a <loop_vec_info> (vinfo)
     767        23847 :               || !vect_check_gather_scatter (stmt_info, vectype,
     768              :                                              as_a <loop_vec_info> (vinfo),
     769              :                                              first ? &oprnd_info->first_gs_info
     770              :                                              : &gs_info))
     771         1314 :             return -1;
     772              : 
     773        23847 :           if (first)
     774              :             {
     775        23573 :               oprnd_info->first_gs_p = true;
     776        23573 :               oprnd = oprnd_info->first_gs_info.offset;
     777              :             }
     778              :           else
     779              :             {
     780          274 :               gs_op = i;
     781          274 :               oprnd = gs_info.offset;
     782              :             }
     783              :         }
     784     23716660 :       else if (opno < 0)
     785         3167 :         oprnd = TREE_OPERAND (gimple_arg (stmt_info->stmt, 0), -1 - opno);
     786              :       else
     787              :         {
     788     23713493 :           oprnd = gimple_arg (stmt_info->stmt, opno);
     789     23713493 :           if (gphi *stmt = dyn_cast <gphi *> (stmt_info->stmt))
     790              :             {
     791      1271593 :               edge e = gimple_phi_arg_edge (stmt, opno);
     792      2543186 :               backedge = (is_a <bb_vec_info> (vinfo)
     793      1967594 :                           ? e->flags & EDGE_DFS_BACK
     794       696001 :                           : dominated_by_p (CDI_DOMINATORS, e->src,
     795       696001 :                                             gimple_bb (stmt_info->stmt)));
     796              :             }
     797              :         }
     798              : 
     799     23740507 :       stmt_vec_info def_stmt_info;
     800     23740507 :       if (!vect_is_simple_use (oprnd, vinfo, &dts[i], &def_stmt_info))
     801              :         {
     802         1038 :           if (dump_enabled_p ())
     803            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     804              :                              "Build SLP failed: can't analyze def for %T\n",
     805              :                              oprnd);
     806              : 
     807              :           return -1;
     808              :         }
     809              : 
     810     23739469 :       if (skip_args[i])
     811              :         {
     812       559077 :           oprnd_info->def_stmts.quick_push (NULL);
     813       559077 :           oprnd_info->ops.quick_push (NULL_TREE);
     814       559077 :           oprnd_info->first_dt = vect_uninitialized_def;
     815       559077 :           continue;
     816              :         }
     817              : 
     818     23180392 :       oprnd_info->def_stmts.quick_push (def_stmt_info);
     819     23180392 :       oprnd_info->ops.quick_push (oprnd);
     820              : 
     821     23180392 :       if (def_stmt_info
     822     23180392 :           && is_pattern_stmt_p (def_stmt_info))
     823              :         {
     824       450593 :           if (STMT_VINFO_RELATED_STMT (vect_orig_stmt (def_stmt_info))
     825              :               != def_stmt_info)
     826       320191 :             oprnd_info->any_pattern = true;
     827              :           else
     828              :             /* If we promote this to external use the original stmt def.  */
     829       130402 :             oprnd_info->ops.last ()
     830       260804 :               = gimple_get_lhs (vect_orig_stmt (def_stmt_info)->stmt);
     831              :         }
     832              : 
     833              :       /* If there's a extern def on a backedge make sure we can
     834              :          code-generate at the region start.
     835              :          ???  This is another case that could be fixed by adjusting
     836              :          how we split the function but at the moment we'd have conflicting
     837              :          goals there.  */
     838     23180392 :       if (backedge
     839       174424 :           && dts[i] == vect_external_def
     840          297 :           && is_a <bb_vec_info> (vinfo)
     841          297 :           && TREE_CODE (oprnd) == SSA_NAME
     842          276 :           && !SSA_NAME_IS_DEFAULT_DEF (oprnd)
     843     23180668 :           && !dominated_by_p (CDI_DOMINATORS, vinfo->bbs[0],
     844          276 :                               gimple_bb (SSA_NAME_DEF_STMT (oprnd))))
     845              :         {
     846          276 :           if (dump_enabled_p ())
     847            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     848              :                              "Build SLP failed: extern def %T only defined "
     849              :                              "on backedge\n", oprnd);
     850              :           return -1;
     851              :         }
     852              : 
     853     23180116 :       if (first)
     854              :         {
     855      5267020 :           tree type = TREE_TYPE (oprnd);
     856      5267020 :           dt = dts[i];
     857              : 
     858              :           /* For the swapping logic below force vect_reduction_def
     859              :              for the reduction op in a SLP reduction group.  */
     860      5267020 :           if (!STMT_VINFO_DATA_REF (stmt_info)
     861      3955130 :               && REDUC_GROUP_FIRST_ELEMENT (stmt_info)
     862         5312 :               && (int)i == STMT_VINFO_REDUC_IDX (stmt_info)
     863      5269633 :               && def_stmt_info)
     864         2613 :             dts[i] = dt = vect_reduction_def;
     865              : 
     866              :           /* Check the types of the definition.  */
     867      5267020 :           switch (dt)
     868              :             {
     869      5267020 :             case vect_external_def:
     870      5267020 :             case vect_constant_def:
     871      5267020 :             case vect_internal_def:
     872      5267020 :             case vect_reduction_def:
     873      5267020 :             case vect_double_reduction_def:
     874      5267020 :             case vect_induction_def:
     875      5267020 :             case vect_nested_cycle:
     876      5267020 :             case vect_first_order_recurrence:
     877      5267020 :               break;
     878              : 
     879            0 :             default:
     880              :               /* FORNOW: Not supported.  */
     881            0 :               if (dump_enabled_p ())
     882            0 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     883              :                                  "Build SLP failed: illegal type of def %T\n",
     884              :                                  oprnd);
     885              :               return -1;
     886              :             }
     887              : 
     888      5267020 :           oprnd_info->first_dt = dt;
     889      5267020 :           oprnd_info->first_op_type = type;
     890              :         }
     891              :     }
     892     13711456 :   if (first)
     893              :     return 0;
     894              : 
     895              :   /* Now match the operand definition types to that of the first stmt.  */
     896     27615836 :   for (i = 0; i < number_of_oprnds;)
     897              :     {
     898     17904061 :       if (skip_args[i])
     899              :         {
     900        44940 :           ++i;
     901        44940 :           continue;
     902              :         }
     903              : 
     904     17859121 :       oprnd_info = (*oprnds_info)[i];
     905     17859121 :       dt = dts[i];
     906     17859121 :       stmt_vec_info def_stmt_info = oprnd_info->def_stmts[stmt_num];
     907     17859121 :       oprnd = oprnd_info->ops[stmt_num];
     908     17859121 :       tree type = TREE_TYPE (oprnd);
     909              : 
     910     17859121 :       if (!types_compatible_p (oprnd_info->first_op_type, type))
     911              :         {
     912       118533 :           if (dump_enabled_p ())
     913           93 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     914              :                              "Build SLP failed: different operand types\n");
     915              :           return 1;
     916              :         }
     917              : 
     918     17740588 :       if ((gs_op == i) != oprnd_info->first_gs_p)
     919              :         {
     920            0 :           if (dump_enabled_p ())
     921            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     922              :                              "Build SLP failed: mixed gather and non-gather\n");
     923              :           return 1;
     924              :         }
     925     17740588 :       else if (gs_op == i)
     926              :         {
     927          242 :           if (!operand_equal_p (oprnd_info->first_gs_info.base,
     928          242 :                                 gs_info.base))
     929              :             {
     930           16 :               if (dump_enabled_p ())
     931            6 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     932              :                                  "Build SLP failed: different gather base\n");
     933              :               return 1;
     934              :             }
     935          226 :           if (oprnd_info->first_gs_info.scale != gs_info.scale)
     936              :             {
     937            8 :               if (dump_enabled_p ())
     938            2 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
     939              :                                  "Build SLP failed: different gather scale\n");
     940              :               return 1;
     941              :             }
     942              :         }
     943              : 
     944              :       /* Not first stmt of the group, check that the def-stmt/s match
     945              :          the def-stmt/s of the first stmt.  Allow different definition
     946              :          types for reduction chains: the first stmt must be a
     947              :          vect_reduction_def (a phi node), and the rest
     948              :          end in the reduction chain.  */
     949     17740564 :       if ((!vect_def_types_match (oprnd_info->first_dt, dt)
     950       334406 :            && !(oprnd_info->first_dt == vect_reduction_def
     951         5019 :                 && !STMT_VINFO_DATA_REF (stmt_info)
     952         5019 :                 && REDUC_GROUP_FIRST_ELEMENT (stmt_info)
     953         4993 :                 && def_stmt_info
     954         4991 :                 && !STMT_VINFO_DATA_REF (def_stmt_info)
     955         4991 :                 && (REDUC_GROUP_FIRST_ELEMENT (def_stmt_info)
     956              :                     == REDUC_GROUP_FIRST_ELEMENT (stmt_info))))
     957     17411149 :           || (!STMT_VINFO_DATA_REF (stmt_info)
     958     15629617 :               && REDUC_GROUP_FIRST_ELEMENT (stmt_info)
     959        10429 :               && ((!def_stmt_info
     960        10193 :                    || STMT_VINFO_DATA_REF (def_stmt_info)
     961        18668 :                    || (REDUC_GROUP_FIRST_ELEMENT (def_stmt_info)
     962              :                        != REDUC_GROUP_FIRST_ELEMENT (stmt_info)))
     963        10429 :                   != (oprnd_info->first_dt != vect_reduction_def))))
     964              :         {
     965              :           /* Try swapping operands if we got a mismatch.  For BB
     966              :              vectorization only in case it will clearly improve things.  */
     967       332034 :           if (i == commutative_op && !swapped
     968       329415 :               && (!is_a <bb_vec_info> (vinfo)
     969         5623 :                   || (!vect_def_types_match ((*oprnds_info)[i+1]->first_dt,
     970         5623 :                                              dts[i+1])
     971         1418 :                       && (vect_def_types_match (oprnd_info->first_dt, dts[i+1])
     972              :                           || vect_def_types_match
     973          233 :                                ((*oprnds_info)[i+1]->first_dt, dts[i])))))
     974              :             {
     975         2619 :               if (dump_enabled_p ())
     976          198 :                 dump_printf_loc (MSG_NOTE, vect_location,
     977              :                                  "trying swapped operands\n");
     978         2619 :               std::swap (dts[i], dts[i+1]);
     979         2619 :               std::swap ((*oprnds_info)[i]->def_stmts[stmt_num],
     980         2619 :                          (*oprnds_info)[i+1]->def_stmts[stmt_num]);
     981         2619 :               std::swap ((*oprnds_info)[i]->ops[stmt_num],
     982         2619 :                          (*oprnds_info)[i+1]->ops[stmt_num]);
     983              :               /* After swapping some operands we lost track whether an
     984              :                  operand has any pattern defs so be conservative here.  */
     985         2619 :               if ((*oprnds_info)[i]->any_pattern
     986         2619 :                   || (*oprnds_info)[i+1]->any_pattern)
     987           36 :                 (*oprnds_info)[i]->any_pattern
     988           18 :                   = (*oprnds_info)[i+1]->any_pattern = true;
     989         2619 :               swapped = true;
     990         2619 :               continue;
     991              :             }
     992              : 
     993       326796 :           if (is_a <bb_vec_info> (vinfo)
     994       309447 :               && !oprnd_info->any_pattern
     995       309179 :               && number_of_oprnds > 1
     996       635975 :               && !soft_fail)
     997              :             {
     998              :               /* Now for commutative ops we should see whether we can
     999              :                  make the other operand matching.  */
    1000       106098 :               if (dump_enabled_p ())
    1001          338 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1002              :                                  "treating operand as external\n");
    1003              :               oprnd_info->first_dt = dt = vect_external_def;
    1004              :             }
    1005              :           else
    1006              :             {
    1007       220698 :               if (dump_enabled_p ())
    1008          410 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1009              :                                  "Build SLP failed: different types\n");
    1010              :               return 1;
    1011              :             }
    1012              :         }
    1013              : 
    1014              :       /* Make sure to demote the overall operand to external.  */
    1015     17411149 :       if (dt == vect_external_def)
    1016       422807 :         oprnd_info->first_dt = vect_external_def;
    1017              :       /* For a SLP reduction chain we want to duplicate the reduction to
    1018              :          each of the chain members.  That gets us a sane SLP graph (still
    1019              :          the stmts are not 100% correct wrt the initial values).  */
    1020     17094440 :       else if ((dt == vect_internal_def
    1021     17094440 :                 || dt == vect_reduction_def)
    1022     15833770 :                && oprnd_info->first_dt == vect_reduction_def
    1023       101523 :                && !STMT_VINFO_DATA_REF (stmt_info)
    1024       101523 :                && REDUC_GROUP_FIRST_ELEMENT (stmt_info)
    1025         4991 :                && !STMT_VINFO_DATA_REF (def_stmt_info)
    1026     17099431 :                && (REDUC_GROUP_FIRST_ELEMENT (def_stmt_info)
    1027              :                    == REDUC_GROUP_FIRST_ELEMENT (stmt_info)))
    1028              :         {
    1029         4991 :           oprnd_info->def_stmts[stmt_num] = oprnd_info->def_stmts[0];
    1030         4991 :           oprnd_info->ops[stmt_num] = oprnd_info->ops[0];
    1031              :         }
    1032              : 
    1033     17517247 :       ++i;
    1034              :     }
    1035              : 
    1036              :   /* Swap operands.  */
    1037      9711775 :   if (swapped)
    1038              :     {
    1039        43610 :       if (dump_enabled_p ())
    1040          502 :         dump_printf_loc (MSG_NOTE, vect_location,
    1041              :                          "swapped operands to match def types in %G",
    1042              :                          stmt_info->stmt);
    1043              :     }
    1044              : 
    1045              :   return 0;
    1046              : }
    1047              : 
    1048              : /* Return true if call statements CALL1 and CALL2 are similar enough
    1049              :    to be combined into the same SLP group.  */
    1050              : 
    1051              : bool
    1052        65083 : compatible_calls_p (gcall *call1, gcall *call2, bool allow_two_operators)
    1053              : {
    1054        65083 :   unsigned int nargs = gimple_call_num_args (call1);
    1055        65083 :   if (nargs != gimple_call_num_args (call2))
    1056              :     return false;
    1057              : 
    1058        47996 :   auto cfn1 = gimple_call_combined_fn (call1);
    1059        47996 :   auto cfn2 = gimple_call_combined_fn (call2);
    1060        47996 :   if (cfn1 != cfn2
    1061           39 :       && (!allow_two_operators
    1062           39 :           || !((cfn1 == CFN_FMA || cfn1 == CFN_FMS)
    1063            2 :                && (cfn2 == CFN_FMA || cfn2 == CFN_FMS))))
    1064              :     return false;
    1065              : 
    1066        47959 :   if (gimple_call_internal_p (call1))
    1067              :     {
    1068         7286 :       if (!types_compatible_p (TREE_TYPE (gimple_call_lhs (call1)),
    1069         7286 :                                TREE_TYPE (gimple_call_lhs (call2))))
    1070              :         return false;
    1071        15010 :       for (unsigned int i = 0; i < nargs; ++i)
    1072         7724 :         if (!types_compatible_p (TREE_TYPE (gimple_call_arg (call1, i)),
    1073         7724 :                                  TREE_TYPE (gimple_call_arg (call2, i))))
    1074              :           return false;
    1075              :     }
    1076              :   else
    1077              :     {
    1078        40673 :       if (!operand_equal_p (gimple_call_fn (call1),
    1079        40673 :                             gimple_call_fn (call2), 0))
    1080              :         return false;
    1081              : 
    1082        33834 :       if (gimple_call_fntype (call1) != gimple_call_fntype (call2))
    1083              :         return false;
    1084              :     }
    1085              : 
    1086              :   /* Check that any unvectorized arguments are equal.  */
    1087        18564 :   if (const int *map = vect_get_operand_map (call1, false, false))
    1088              :     {
    1089           15 :       unsigned int nkept = *map++;
    1090           15 :       unsigned int mapi = 0;
    1091           57 :       for (unsigned int i = 0; i < nargs; ++i)
    1092           42 :         if (mapi < nkept && map[mapi] == int (i))
    1093           27 :           mapi += 1;
    1094           15 :         else if (!operand_equal_p (gimple_call_arg (call1, i),
    1095           15 :                                    gimple_call_arg (call2, i)))
    1096              :           return false;
    1097              :     }
    1098              : 
    1099              :   return true;
    1100              : }
    1101              : 
    1102              : /* Verify if the scalar stmts STMTS are isomorphic, require data
    1103              :    permutation or are of unsupported types of operation.
    1104              :    Return false if at least one (or all in case of BB vectorization)
    1105              :    stmt is unvectorizable or the comparison could not be carried out.
    1106              :    Return true if they all (or at least one in case of BB vectorization)
    1107              :    are and indicate in MATCHES[] which stmts are not isomorphic to the
    1108              :    stmt at *START_I.
    1109              : 
    1110              :    This function is designed to be invoked repeatedly on the same
    1111              :    set of STMTS with increasing *START_I.
    1112              : 
    1113              :    When *START_I is zero and the function returns true MATCHES[] will be
    1114              :    initialized with, in case of BB vectorization, unvectorizable stmts
    1115              :    marked with -2, stmts isomorphic to *START_I as *START_I and
    1116              :    other vectorizable stmts with -1 (not isomorphic to *START_I).
    1117              :    *START_I, when initially zero, is updated to the first vectorizable
    1118              :    statement, so MATCHES[] can have a prefix with entries valued -2.
    1119              : 
    1120              :    When *START_I is not zero MATCHES[] is expected to be pre-initialized
    1121              :    by a former call with *START_I zero and MATCHES[*START_I] should be -1.
    1122              :    The function will return true and have the stmts isomorphic to
    1123              :    MATCHES[*START_I] marked with *START_I.
    1124              : 
    1125              :    *TWO_OPERATORS indicates whether the group of isomorphic statements
    1126              :    uses two related operations like PLUS_EXPR and MINUS_EXPR.  If
    1127              :    TWO_OPERATORS is NULL such case is not considered isomorphic.
    1128              : 
    1129              :    SWAP[] indicates whether for a stmt to be isomorphic to its group
    1130              :    leader, has to have its operands swapped (1) or its predicate inverted (2).
    1131              :    COND_EXPR is possibly isomorphic to another one after swapping its
    1132              :    operands.  Set SWAP[i] to 1 if stmt I is COND_EXPR and isomorphic to
    1133              :    the first stmt by swapping the two operands of comparison; set SWAP[i]
    1134              :    to 2 if stmt I is isormorphic to the first stmt by inverting the code
    1135              :    of comparison.  Take A1 >= B1 ? X1 : Y1 as an example, it can be swapped
    1136              :    to (B1 <= A1 ? X1 : Y1); or be inverted to (A1 < B1) ? Y1 : X1.  */
    1137              : 
    1138              : static bool
    1139      6271538 : vect_build_slp_tree_3 (vec_info *vinfo, vec<stmt_vec_info> stmts,
    1140              :                        match_elt_t *matches, unsigned char *swap,
    1141              :                        bool *two_operators, tree vectype, unsigned *start_i)
    1142              : {
    1143      6271538 :   stmt_vec_info first_stmt_info = NULL;
    1144      6271538 :   code_helper first_stmt_code = ERROR_MARK;
    1145      6271538 :   code_helper alt_stmt_code = ERROR_MARK;
    1146      6271538 :   code_helper first_cond_code = ERROR_MARK;
    1147      6271538 :   bool need_same_oprnds = false;
    1148      6271538 :   tree first_lhs = NULL_TREE;
    1149      6271538 :   tree first_op1 = NULL_TREE;
    1150      6271538 :   stmt_vec_info first_load = NULL, prev_first_load = NULL;
    1151      6271538 :   bool first_stmt_ldst_p = false, first_stmt_ldst_masklen_p = false;
    1152      6271538 :   bool first_stmt_phi_p = false;
    1153      6271538 :   int first_reduc_idx = -1;
    1154              : 
    1155      6271538 :   basic_block common_bb = NULL;
    1156      6271538 :   gimple *trapping_stmt = NULL;
    1157      6271538 :   int first_match = -1;
    1158              : 
    1159     26370927 :   for (unsigned i = *start_i; i < stmts.length (); ++i)
    1160              :     {
    1161     20099624 :       stmt_vec_info stmt_info = stmts[i];
    1162     20099624 :       bool ldst_p = false;
    1163     20099624 :       bool ldst_masklen_p = false;
    1164     20099624 :       bool phi_p = false;
    1165     20099624 :       code_helper rhs_code = ERROR_MARK;
    1166              : 
    1167     20099624 :       if (*start_i == 0)
    1168              :         {
    1169     18057542 :           swap[i] = 0;
    1170     18057542 :           matches[i] = -1;
    1171              :         }
    1172      2042082 :       else if (matches[i] != -1)
    1173     20099389 :         continue;
    1174              : 
    1175     20009511 :       if (!stmt_info)
    1176              :         {
    1177              :           /* ???  We shouldn't run into this.  */
    1178        40928 :           gcc_assert (first_match != -1);
    1179        40928 :           matches[i] = first_match;
    1180        40928 :           continue;
    1181              :         }
    1182              : 
    1183     19968583 :       gimple *stmt = stmt_info->stmt;
    1184     19968583 :       if (dump_enabled_p ())
    1185       236230 :         dump_printf_loc (MSG_NOTE, vect_location, "Build SLP for %G", stmt);
    1186              : 
    1187              :       /* Fail to vectorize statements marked as unvectorizable, throw
    1188              :          or are volatile.  */
    1189     19968583 :       if (!STMT_VINFO_VECTORIZABLE (stmt_info)
    1190     19576022 :           || stmt_can_throw_internal (cfun, stmt)
    1191     38518603 :           || gimple_has_volatile_ops (stmt))
    1192              :         {
    1193       409468 :           if (dump_enabled_p ())
    1194          466 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1195              :                              "Build SLP failed: unvectorizable statement %G",
    1196              :                              stmt);
    1197       409468 :           if (is_a <bb_vec_info> (vinfo))
    1198              :             {
    1199       409468 :               matches[i] = -2;
    1200       409468 :               continue;
    1201              :             }
    1202      6271538 :           return false;
    1203              :         }
    1204              : 
    1205     19559115 :       gcall *call_stmt = dyn_cast <gcall *> (stmt);
    1206     19559115 :       tree lhs = gimple_get_lhs (stmt);
    1207     19559115 :       if (lhs == NULL_TREE && !call_stmt)
    1208              :         {
    1209           34 :           if (dump_enabled_p ())
    1210            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1211              :                              "Build SLP failed: not GIMPLE_ASSIGN nor "
    1212              :                              "GIMPLE_CALL %G", stmt);
    1213           34 :           if (is_a <bb_vec_info> (vinfo))
    1214              :             {
    1215           34 :               matches[i] = -2;
    1216           34 :               continue;
    1217              :             }
    1218              :           return false;
    1219              :         }
    1220              : 
    1221     19559081 :       if (call_stmt)
    1222              :         {
    1223       204078 :           combined_fn cfn = gimple_call_combined_fn (call_stmt);
    1224       204078 :           if (cfn != CFN_LAST && cfn != CFN_MASK_CALL)
    1225        62511 :             rhs_code = cfn;
    1226              :           else
    1227              :             rhs_code = CALL_EXPR;
    1228              : 
    1229       204078 :           if (cfn == CFN_GATHER_LOAD
    1230       204078 :               || cfn == CFN_SCATTER_STORE)
    1231              :             ldst_p = true;
    1232              :           else if (cfn == CFN_MASK_LOAD
    1233              :                    || cfn == CFN_MASK_GATHER_LOAD
    1234              :                    || cfn == CFN_MASK_LEN_GATHER_LOAD
    1235              :                    || cfn == CFN_MASK_SCATTER_STORE
    1236              :                    || cfn == CFN_MASK_LEN_SCATTER_STORE)
    1237              :             {
    1238              :               ldst_p = true;
    1239              :               ldst_masklen_p = true;
    1240              :             }
    1241              :           else if (cfn == CFN_MASK_STORE)
    1242              :             {
    1243              :               ldst_p = true;
    1244              :               ldst_masklen_p = true;
    1245              :               rhs_code = CFN_MASK_STORE;
    1246              :             }
    1247              :           else if (cfn == CFN_GOMP_SIMD_LANE)
    1248              :             ;
    1249       192977 :           else if ((cfn != CFN_LAST
    1250              :                     && cfn != CFN_MASK_CALL
    1251        51410 :                     && internal_fn_p (cfn)
    1252        38787 :                     && !vectorizable_internal_fn_p (as_internal_fn (cfn)))
    1253       192858 :                    || gimple_call_tail_p (call_stmt)
    1254       192858 :                    || gimple_call_noreturn_p (call_stmt)
    1255       385835 :                    || gimple_call_chain (call_stmt))
    1256              :             {
    1257         1402 :               if (dump_enabled_p ())
    1258            8 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1259              :                                  "Build SLP failed: unsupported call type %G",
    1260              :                                  (gimple *) call_stmt);
    1261         1402 :               if (is_a <bb_vec_info> (vinfo))
    1262              :                 {
    1263         1402 :                   matches[i] = -2;
    1264         1402 :                   continue;
    1265              :                 }
    1266              :               return false;
    1267              :             }
    1268              :         }
    1269     19355003 :       else if (gimple_code (stmt) == GIMPLE_PHI)
    1270              :         {
    1271     19509638 :           rhs_code = ERROR_MARK;
    1272              :           phi_p = true;
    1273              :         }
    1274              :       else
    1275              :         {
    1276     18329001 :           rhs_code = gimple_assign_rhs_code (stmt);
    1277     18329001 :           ldst_p = STMT_VINFO_DATA_REF (stmt_info) != nullptr;
    1278              :         }
    1279              : 
    1280     18329001 :       if (!ldst_p
    1281              :           && !phi_p
    1282     13244094 :           && rhs_code.is_tree_code ()
    1283     13189152 :           && TREE_CODE_CLASS (tree_code (rhs_code)) != tcc_binary
    1284              :           && TREE_CODE_CLASS (tree_code (rhs_code)) != tcc_unary
    1285              :           && TREE_CODE_CLASS (tree_code (rhs_code)) != tcc_expression
    1286              :           && TREE_CODE_CLASS (tree_code (rhs_code)) != tcc_comparison
    1287       239926 :           && rhs_code != VIEW_CONVERT_EXPR
    1288              :           && rhs_code != CALL_EXPR
    1289              :           && rhs_code != BIT_FIELD_REF
    1290     18329001 :           && rhs_code != SSA_NAME)
    1291              :         {
    1292        48041 :           if (dump_enabled_p ())
    1293           98 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1294              :                              "Build SLP failed: operation unsupported %G",
    1295              :                              stmt);
    1296        48041 :           if (is_a <bb_vec_info> (vinfo))
    1297              :             {
    1298        47932 :               matches[i] = -2;
    1299        47932 :               continue;
    1300              :             }
    1301              :           return false;
    1302              :         }
    1303              : 
    1304              :       /* Non-grouped store or load.  */
    1305     19509638 :       if (ldst_p
    1306      5287583 :           && !STMT_VINFO_GROUPED_ACCESS (stmt_info)
    1307      1128752 :           && DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info))
    1308       851914 :           && rhs_code != CFN_GATHER_LOAD
    1309       851914 :           && rhs_code != CFN_MASK_GATHER_LOAD
    1310       851914 :           && rhs_code != CFN_MASK_LEN_GATHER_LOAD
    1311       851914 :           && rhs_code != CFN_SCATTER_STORE
    1312       851914 :           && rhs_code != CFN_MASK_SCATTER_STORE
    1313       851914 :           && rhs_code != CFN_MASK_LEN_SCATTER_STORE
    1314       851914 :           && !STMT_VINFO_GATHER_SCATTER_P (stmt_info)
    1315              :           /* Not grouped loads are handled as externals for BB
    1316              :              vectorization.  Treat them as not vectorizable.  */
    1317     20341892 :           && is_a <bb_vec_info> (vinfo))
    1318              :         {
    1319              :           /* Not grouped load.  */
    1320            0 :           if (dump_enabled_p ())
    1321            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1322              :                              "Build SLP failed: not grouped load %G", stmt);
    1323            0 :           matches[i] = -2;
    1324            0 :           continue;
    1325              :         }
    1326              : 
    1327     19509638 :       if (!ldst_p && rhs_code == BIT_FIELD_REF)
    1328              :         {
    1329        45031 :           tree vec = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
    1330        45031 :           if (!is_a <bb_vec_info> (vinfo)
    1331        44905 :               || TREE_CODE (vec) != SSA_NAME
    1332              :               /* When the element types are not compatible we pun the
    1333              :                  source to the target vectype which requires equal size.  */
    1334        89912 :               || ((!VECTOR_TYPE_P (TREE_TYPE (vec))
    1335        42153 :                    || !types_compatible_p (TREE_TYPE (vectype),
    1336        42153 :                                            TREE_TYPE (TREE_TYPE (vec))))
    1337         3997 :                   && !operand_equal_p (TYPE_SIZE (vectype),
    1338         3997 :                                        TYPE_SIZE (TREE_TYPE (vec)))))
    1339              :             {
    1340         2282 :               if (dump_enabled_p ())
    1341            0 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1342              :                                  "Build SLP failed: "
    1343              :                                  "BIT_FIELD_REF not supported\n");
    1344         2282 :               if (is_a <bb_vec_info> (vinfo))
    1345              :                 {
    1346         2156 :                   matches[i] = -2;
    1347         2156 :                   continue;
    1348              :                 }
    1349              :               return false;
    1350              :             }
    1351              :         }
    1352              : 
    1353              :       /* Check the operation.  */
    1354     19507356 :       if (first_match == -1)
    1355              :         {
    1356      6170795 :           first_match = i;
    1357      6170795 :           first_stmt_info = stmt_info;
    1358      6170795 :           common_bb = gimple_bb (stmt_info->stmt);
    1359      6170795 :           first_lhs = lhs;
    1360      6170795 :           first_stmt_code = rhs_code;
    1361      6170795 :           first_stmt_ldst_p = ldst_p;
    1362      6170795 :           first_stmt_ldst_masklen_p = ldst_masklen_p;
    1363      6170795 :           first_stmt_phi_p = phi_p;
    1364      6170795 :           first_reduc_idx = STMT_VINFO_REDUC_IDX (stmt_info);
    1365              : 
    1366              :           /* Shift arguments should be equal in all the packed stmts for a
    1367              :              vector shift with scalar shift operand.  */
    1368      6170795 :           if (rhs_code == LSHIFT_EXPR
    1369      6078221 :               || rhs_code == RSHIFT_EXPR
    1370      5986824 :               || rhs_code == LROTATE_EXPR
    1371     12157505 :               || rhs_code == RROTATE_EXPR)
    1372              :             {
    1373              :               /* First see if we have a vector/vector shift.  */
    1374       184570 :               if (!directly_supported_p (rhs_code, vectype, optab_vector))
    1375              :                 {
    1376              :                   /* No vector/vector shift, arrange for a vector/scalar
    1377              :                      SLP layout.  */
    1378       171187 :                   need_same_oprnds = true;
    1379       171187 :                   first_op1 = gimple_assign_rhs2 (stmt);
    1380              :                 }
    1381              :             }
    1382      5986225 :           else if (rhs_code == WIDEN_LSHIFT_EXPR)
    1383              :             {
    1384            0 :               need_same_oprnds = true;
    1385            0 :               first_op1 = gimple_assign_rhs2 (stmt);
    1386              :             }
    1387      5986225 :           else if (rhs_code == CFN_DIV_POW2)
    1388              :             {
    1389            0 :               need_same_oprnds = true;
    1390            0 :               first_op1 = gimple_call_arg (call_stmt, 1);
    1391              :             }
    1392      5986225 :           else if (rhs_code == CFN_GOMP_SIMD_LANE)
    1393              :             {
    1394         3651 :               need_same_oprnds = true;
    1395         3651 :               first_op1 = gimple_call_arg (call_stmt, 1);
    1396              :             }
    1397              :         }
    1398              :       else
    1399              :         {
    1400     13336561 :           int comm_arg;
    1401     13337000 :           if (first_reduc_idx != STMT_VINFO_REDUC_IDX (stmt_info)
    1402              :               /* For SLP reduction groups the index isn't necessarily
    1403              :                  uniform but only that of the first stmt matters.  */
    1404         2525 :               && !(first_reduc_idx != -1
    1405         2525 :                    && STMT_VINFO_REDUC_IDX (stmt_info) != -1
    1406         2525 :                    && REDUC_GROUP_FIRST_ELEMENT (stmt_info))
    1407     13336561 :               && !(first_reduc_idx != -1
    1408         1187 :                    && STMT_VINFO_REDUC_IDX (stmt_info) != -1
    1409         1187 :                    && (comm_arg = first_commutative_argument
    1410         1187 :                                     (rhs_code, TREE_TYPE (lhs))) >= 0
    1411              :                    && (first_reduc_idx
    1412          932 :                        == 2 * comm_arg + 1 - STMT_VINFO_REDUC_IDX (stmt_info))))
    1413              :             {
    1414          439 :               if (dump_enabled_p ())
    1415              :                 {
    1416           12 :                   dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1417              :                                    "Build SLP failed: different reduc_idx "
    1418              :                                    "%d instead of %d in %G",
    1419              :                                    STMT_VINFO_REDUC_IDX (stmt_info),
    1420              :                                    first_reduc_idx, stmt);
    1421              :                 }
    1422              :               /* Mismatch.  */
    1423          439 :               continue;
    1424              :             }
    1425     13336122 :           if (!ldst_p
    1426     13336122 :               && two_operators
    1427     10496394 :               && first_stmt_code != rhs_code
    1428     14849032 :               && alt_stmt_code == ERROR_MARK)
    1429              :             alt_stmt_code = rhs_code;
    1430     14828021 :           if ((!ldst_p
    1431     10496394 :                && first_stmt_code != rhs_code
    1432      1512910 :                && (first_stmt_code != IMAGPART_EXPR
    1433          203 :                    || rhs_code != REALPART_EXPR)
    1434      1512910 :                && (first_stmt_code != REALPART_EXPR
    1435          738 :                    || rhs_code != IMAGPART_EXPR)
    1436              :                /* Handle mismatches in plus/minus by computing both
    1437              :                   and merging the results.  */
    1438      1512910 :                && !((((first_stmt_code == PLUS_EXPR
    1439      1402599 :                        || first_stmt_code == MINUS_EXPR)
    1440       135401 :                       && (alt_stmt_code == PLUS_EXPR
    1441       125459 :                           || alt_stmt_code == MINUS_EXPR))
    1442      1480975 :                      || ((first_stmt_code == CFN_FMA
    1443      1480973 :                           || first_stmt_code == CFN_FMS)
    1444            2 :                          && (alt_stmt_code == CFN_FMA
    1445            2 :                              || alt_stmt_code == CFN_FMS)))
    1446        31937 :                     && rhs_code == alt_stmt_code)
    1447      1524580 :                && !(first_stmt_code.is_tree_code ()
    1448      1382048 :                     && rhs_code.is_tree_code ()
    1449      1264503 :                     && (TREE_CODE_CLASS (tree_code (first_stmt_code))
    1450              :                         == tcc_comparison)
    1451       140262 :                     && (swap_tree_comparison (tree_code (first_stmt_code))
    1452       140262 :                         == tree_code (rhs_code))
    1453              :                     && (first_reduc_idx == -1
    1454            0 :                         || REDUC_GROUP_FIRST_ELEMENT (stmt_info))))
    1455              :               || (ldst_p
    1456      5679456 :                   && (STMT_VINFO_GROUPED_ACCESS (stmt_info)
    1457      2839728 :                       != STMT_VINFO_GROUPED_ACCESS (first_stmt_info)))
    1458              :               || (ldst_p
    1459      2786422 :                   && (STMT_VINFO_GATHER_SCATTER_P (stmt_info)
    1460      2786422 :                       != STMT_VINFO_GATHER_SCATTER_P (first_stmt_info)))
    1461     11844361 :               || first_stmt_ldst_p != ldst_p
    1462     11844231 :               || (ldst_p && first_stmt_ldst_masklen_p != ldst_masklen_p)
    1463     25180345 :               || first_stmt_phi_p != phi_p)
    1464              :             {
    1465      1491899 :               if (dump_enabled_p ())
    1466              :                 {
    1467         3609 :                   dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1468              :                                    "Build SLP failed: different operation "
    1469              :                                    "in stmt %G", stmt);
    1470         3609 :                   dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1471              :                                    "original stmt %G", first_stmt_info->stmt);
    1472              :                 }
    1473              :               /* Mismatch.  */
    1474      1491899 :               continue;
    1475              :             }
    1476              : 
    1477     11863632 :           if (!ldst_p
    1478      9057954 :               && first_stmt_code == BIT_FIELD_REF
    1479     11874139 :               && (TREE_OPERAND (gimple_assign_rhs1 (first_stmt_info->stmt), 0)
    1480        29916 :                   != TREE_OPERAND (gimple_assign_rhs1 (stmt_info->stmt), 0)))
    1481              :             {
    1482        19409 :               if (dump_enabled_p ())
    1483          116 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1484              :                                  "Build SLP failed: different BIT_FIELD_REF "
    1485              :                                  "arguments in %G", stmt);
    1486              :               /* Mismatch.  */
    1487        19409 :               continue;
    1488              :             }
    1489              : 
    1490     11824814 :           if (call_stmt
    1491        88439 :               && first_stmt_code != CFN_MASK_LOAD
    1492     11912851 :               && first_stmt_code != CFN_MASK_STORE)
    1493              :             {
    1494        87726 :               if (!is_a <gcall *> (stmts[0]->stmt)
    1495        87726 :                   || !compatible_calls_p (as_a <gcall *> (stmts[0]->stmt),
    1496              :                                           call_stmt, true))
    1497              :                 {
    1498        69162 :                   if (dump_enabled_p ())
    1499           13 :                     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1500              :                                      "Build SLP failed: different calls in %G",
    1501              :                                      stmt);
    1502              :                   /* Mismatch.  */
    1503        69162 :                   continue;
    1504              :                 }
    1505              :             }
    1506              : 
    1507     11798288 :           if (phi_p
    1508     11755652 :               && (gimple_bb (first_stmt_info->stmt)
    1509       213259 :                   != gimple_bb (stmt_info->stmt)))
    1510              :             {
    1511        42636 :               if (dump_enabled_p ())
    1512            8 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1513              :                                  "Build SLP failed: different BB for PHI %G",
    1514              :                                  stmt);
    1515              :               /* Mismatch.  */
    1516        42636 :               continue;
    1517              :             }
    1518              : 
    1519     11713016 :           if (need_same_oprnds)
    1520              :             {
    1521        62452 :               tree other_op1 = gimple_arg (stmt, 1);
    1522        62452 :               if (!operand_equal_p (first_op1, other_op1, 0))
    1523              :                 {
    1524        11032 :                   if (dump_enabled_p ())
    1525          195 :                     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1526              :                                      "Build SLP failed: different shift "
    1527              :                                      "arguments in %G", stmt);
    1528              :                   /* Mismatch.  */
    1529        11032 :                   continue;
    1530              :                 }
    1531              :             }
    1532              : 
    1533     11702825 :           if (first_lhs
    1534     11701984 :               && lhs
    1535     11701984 :               && !types_compatible_p (TREE_TYPE (lhs), TREE_TYPE (first_lhs)))
    1536              :             {
    1537          841 :               if (dump_enabled_p ())
    1538            6 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1539              :                                  "Build SLP failed: different vector type "
    1540              :                                  "in %G", stmt);
    1541              :               /* Mismatch.  */
    1542          841 :               continue;
    1543              :             }
    1544              : 
    1545              :           /* We need to ensure all stmts are in the same BB when one stmt could
    1546              :              trap.  */
    1547     11701143 :           if (trapping_stmt || gimple_could_trap_p (stmt))
    1548              :             {
    1549      1171457 :               gcc_assert (!trapping_stmt || common_bb);
    1550      1171457 :               if (gimple_bb (stmt) != common_bb)
    1551              :                 {
    1552         6066 :                   if (dump_enabled_p ())
    1553           13 :                     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1554              :                                      "Build SLP failed: not all stmts in same "
    1555              :                                      "BB but possibly trapping operation in %G",
    1556              :                                      trapping_stmt ? trapping_stmt : stmt);
    1557         6066 :                   continue;
    1558              :                 }
    1559              :             }
    1560              :         }
    1561              : 
    1562              :       /* Grouped store or load.  */
    1563     17865872 :       if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
    1564              :         {
    1565      4100101 :           gcc_assert (ldst_p);
    1566      4100101 :           if (DR_IS_WRITE (STMT_VINFO_DATA_REF (stmt_info)))
    1567              :             {
    1568              :               /* Store.  */
    1569      3022043 :               gcc_assert (rhs_code == CFN_MASK_STORE
    1570              :                           || REFERENCE_CLASS_P (lhs)
    1571              :                           || DECL_P (lhs));
    1572              :             }
    1573              :           else
    1574              :             {
    1575              :               /* Load.  */
    1576      1078058 :               first_load = DR_GROUP_FIRST_ELEMENT (stmt_info);
    1577      1078058 :               if (prev_first_load)
    1578              :                 {
    1579              :                   /* Check that there are no loads from different interleaving
    1580              :                      chains in the same node.  */
    1581       505623 :                   if (prev_first_load != first_load)
    1582              :                     {
    1583       106286 :                       if (dump_enabled_p ())
    1584         2296 :                         dump_printf_loc (MSG_MISSED_OPTIMIZATION,
    1585              :                                          vect_location,
    1586              :                                          "Build SLP failed: different "
    1587              :                                          "interleaving chains in one node %G",
    1588              :                                          stmt);
    1589              :                       /* Mismatch.  */
    1590       106286 :                       continue;
    1591              :                     }
    1592              :                 }
    1593              :               else
    1594              :                 prev_first_load = first_load;
    1595              :            }
    1596              :         }
    1597              :       /* Non-grouped store or load.  */
    1598     13765771 :       else if (ldst_p)
    1599              :         {
    1600      1128441 :           if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info))
    1601       851603 :               && rhs_code != CFN_GATHER_LOAD
    1602              :               && rhs_code != CFN_MASK_GATHER_LOAD
    1603              :               && rhs_code != CFN_MASK_LEN_GATHER_LOAD
    1604              :               && rhs_code != CFN_SCATTER_STORE
    1605              :               && rhs_code != CFN_MASK_SCATTER_STORE
    1606              :               && rhs_code != CFN_MASK_LEN_SCATTER_STORE
    1607      1980044 :               && !STMT_VINFO_GATHER_SCATTER_P (stmt_info))
    1608              :             {
    1609       831962 :               gcc_assert (!is_a <bb_vec_info> (vinfo));
    1610              :               /* For loop vectorization we can handle splats the same we
    1611              :                  handle single element interleaving.  Likewise we can handle
    1612              :                  a collection of invariant refs.  */
    1613      1036161 :               if (stmt_info != first_stmt_info
    1614       832224 :                   && !(integer_zerop (DR_STEP (STMT_VINFO_DATA_REF (stmt_info)))
    1615          262 :                        && integer_zerop (DR_STEP (STMT_VINFO_DATA_REF
    1616              :                                                         (first_stmt_info)))))
    1617              :                 {
    1618              :                   /* Not grouped load.  */
    1619       204199 :                   if (dump_enabled_p ())
    1620          179 :                     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1621              :                                      "Build SLP failed: not grouped load %G",
    1622              :                                      stmt);
    1623       204199 :                   continue;
    1624              :                 }
    1625              :             }
    1626              :         }
    1627              :       /* Not memory operation.  */
    1628              :       else
    1629              :         {
    1630     12637330 :           if (rhs_code == COND_EXPR)
    1631              :             {
    1632        71368 :               tree cond_expr = gimple_assign_rhs1 (stmt);
    1633        71368 :               enum tree_code cond_code = TREE_CODE (cond_expr);
    1634        71368 :               enum tree_code swap_code = ERROR_MARK;
    1635        71368 :               enum tree_code invert_code = ERROR_MARK;
    1636              : 
    1637        71368 :               if (i == (unsigned)first_match)
    1638        59186 :                 first_cond_code = TREE_CODE (cond_expr);
    1639        12182 :               else if (TREE_CODE_CLASS (cond_code) == tcc_comparison)
    1640              :                 {
    1641            0 :                   bool honor_nans = HONOR_NANS (TREE_OPERAND (cond_expr, 0));
    1642            0 :                   swap_code = swap_tree_comparison (cond_code);
    1643            0 :                   invert_code = invert_tree_comparison (cond_code, honor_nans);
    1644              :                 }
    1645              : 
    1646        71368 :               if (first_cond_code == cond_code)
    1647              :                 ;
    1648              :               /* Isomorphic can be achieved by swapping.  */
    1649            0 :               else if (first_cond_code == swap_code)
    1650            0 :                 swap[i] = 1;
    1651              :               /* Isomorphic can be achieved by inverting.  */
    1652            0 :               else if (first_cond_code == invert_code)
    1653            0 :                 swap[i] = 2;
    1654              :               else
    1655              :                 {
    1656            0 :                   if (dump_enabled_p ())
    1657            0 :                     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1658              :                                      "Build SLP failed: different"
    1659              :                                      " operation %G", stmt);
    1660              :                   /* Mismatch.  */
    1661            0 :                   continue;
    1662              :                 }
    1663              :             }
    1664              : 
    1665     12637330 :           if (i != (unsigned) first_match
    1666      8914390 :               && first_stmt_code != rhs_code
    1667        74468 :               && first_stmt_code.is_tree_code ()
    1668        74466 :               && rhs_code.is_tree_code ()
    1669        74466 :               && TREE_CODE_CLASS ((tree_code)first_stmt_code) == tcc_comparison
    1670     12680402 :               && (swap_tree_comparison ((tree_code)first_stmt_code)
    1671        43072 :                   == (tree_code)rhs_code))
    1672        43072 :             swap[i] = 1;
    1673              : 
    1674     12637330 :           if (i != (unsigned) first_match
    1675      8914390 :               && first_reduc_idx != STMT_VINFO_REDUC_IDX (stmt_info)
    1676         1786 :               && first_reduc_idx != -1
    1677         1786 :               && STMT_VINFO_REDUC_IDX (stmt_info) != -1
    1678         1786 :               && rhs_code.is_tree_code ()
    1679         1778 :               && commutative_tree_code (tree_code (rhs_code))
    1680     12639106 :               && first_reduc_idx == 1 - STMT_VINFO_REDUC_IDX (stmt_info))
    1681         1776 :             swap[i] = 1;
    1682              :         }
    1683              : 
    1684              :       /* We need to ensure all stmts are in the same BB when one stmt could
    1685              :          trap.  Not matching stmts are not relevant, so exclude those.  */
    1686     17555387 :       if (!trapping_stmt && gimple_could_trap_p (stmt))
    1687              :         trapping_stmt = stmt;
    1688     17555387 :       if (common_bb != gimple_bb (stmt))
    1689              :         {
    1690        63244 :           common_bb = NULL;
    1691        63244 :           gcc_assert (!trapping_stmt);
    1692              :         }
    1693              : 
    1694     17555387 :       matches[i] = first_match;
    1695              :     }
    1696              : 
    1697              :   /* Record if we allowed two distinct operations for the SLP node.  */
    1698      6271303 :   if (((first_stmt_code == PLUS_EXPR
    1699      5749453 :         || first_stmt_code == MINUS_EXPR)
    1700       632321 :        && (alt_stmt_code == PLUS_EXPR
    1701       625022 :            || alt_stmt_code == MINUS_EXPR))
    1702     12525561 :       || ((first_stmt_code == CFN_FMA
    1703      6254209 :            || first_stmt_code == CFN_FMS)
    1704           49 :           && (alt_stmt_code == CFN_FMA
    1705           49 :               || alt_stmt_code == CFN_FMS)))
    1706        17047 :     *two_operators = true;
    1707              : 
    1708      6271303 :   if (first_match == -1)
    1709              :     {
    1710              :       /* If there was no useful stmt, fail.  Can only happen during
    1711              :          the first sweep.  */
    1712       100508 :       gcc_assert (*start_i == 0);
    1713       100508 :       *start_i = stmts.length () - 1;
    1714       100508 :       return false;
    1715              :     }
    1716              : 
    1717      6170795 :   *start_i = first_match;
    1718      6170795 :   return true;
    1719              : }
    1720              : 
    1721              : /* Verify if the scalar stmts STMTS are isomorphic, require data
    1722              :    permutation or are of unsupported types of operation.  Return
    1723              :    true if they are, otherwise return false and indicate in *MATCHES
    1724              :    the groups of isomorphic stmts.  See vect_build_slp_tree_3 for
    1725              :    details.  *TWO_OPERATORS is for the first isomorphic group,
    1726              :    knowledge whether following isomorphic groups have one or two operators
    1727              :    is not retained.  */
    1728              : 
    1729              : static bool
    1730      6100601 : vect_build_slp_tree_1 (vec_info *vinfo, unsigned char *swap,
    1731              :                        vec<stmt_vec_info> stmts, match_elt_t *matches,
    1732              :                        bool *two_operators, tree *node_vectype)
    1733              : {
    1734      6100601 :   stmt_vec_info first_stmt_info = stmts[0];
    1735      6100601 :   unsigned int group_size = stmts.length ();
    1736      6100601 :   tree vectype;
    1737      6100601 :   if (!vect_get_vector_types_for_stmt (vinfo, first_stmt_info, &vectype,
    1738              :                                        group_size))
    1739              :     {
    1740              :       /* Fatal mismatch.  */
    1741       229172 :       matches[0] = -1;
    1742       229172 :       return false;
    1743              :     }
    1744      5871429 :   if (is_a <bb_vec_info> (vinfo)
    1745      5871429 :       && known_le (TYPE_VECTOR_SUBPARTS (vectype), 1U))
    1746              :     {
    1747       348731 :       if (dump_enabled_p ())
    1748          301 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1749              :                          "Build SLP failed: not using single lane "
    1750              :                          "vector type %T\n", vectype);
    1751       348731 :       matches[0] = -1;
    1752       348731 :       return false;
    1753              :     }
    1754              :   /* Check nunits required but continue analysis, producing matches[]
    1755              :      as if nunits was not an issue.  This allows splitting of groups
    1756              :      to happen.  */
    1757      5522698 :   unsigned HOST_WIDE_INT const_nunits = 0;
    1758      5522698 :   if (vectype
    1759      5522678 :       && is_a <bb_vec_info> (vinfo)
    1760     11045376 :       && !multiple_p (group_size, TYPE_VECTOR_SUBPARTS (vectype)))
    1761              :     {
    1762       209716 :       if (!TYPE_VECTOR_SUBPARTS (vectype).is_constant (&const_nunits)
    1763       209716 :           || const_nunits > group_size)
    1764              :         {
    1765            0 :           if (dump_enabled_p ())
    1766            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    1767              :                              "Build SLP failed: unrolling required "
    1768              :                              "in basic block SLP\n");
    1769              :           /* Fatal mismatch.  */
    1770            0 :           matches[0] = -1;
    1771            0 :           return false;
    1772              :         }
    1773              :     }
    1774              : 
    1775      5522698 :   gcc_assert (vectype || !gimple_get_lhs (first_stmt_info->stmt));
    1776      5522698 :   *node_vectype = vectype;
    1777              : 
    1778      5522698 :   unsigned start_i = 0;
    1779      5522698 :   if (!vect_build_slp_tree_3 (vinfo, stmts, matches, swap, two_operators,
    1780              :                               vectype, &start_i))
    1781              :     {
    1782              :       /* Fatal mismatch.  */
    1783       100743 :       matches[0] = -1;
    1784       100743 :       return false;
    1785              :     }
    1786      5421955 :   gcc_assert (matches[start_i] == (int)start_i);
    1787              :   /* Discover further isomorphic groups.  */
    1788     17708496 :   for (start_i = start_i + 1; start_i < group_size; ++start_i)
    1789     12286541 :     if (matches[start_i] == -1)
    1790              :       {
    1791       748840 :         unsigned prev_start_i = start_i;
    1792       748840 :         bool tem_two_operators;
    1793       748840 :         bool res = vect_build_slp_tree_3 (vinfo, stmts, matches, swap,
    1794              :                                           &tem_two_operators,
    1795              :                                           vectype, &start_i);
    1796       748840 :         gcc_assert (res && matches[start_i] == (int)prev_start_i);
    1797              :       }
    1798              : 
    1799              :   bool res = true;
    1800     23208210 :   for (unsigned i = 0; i < group_size; ++i)
    1801     17786255 :     if (matches[i] != 0)
    1802      1890510 :       res = false;
    1803              :   if (!res)
    1804              :     return false;
    1805              : 
    1806              :   return true;
    1807              : }
    1808              : 
    1809              : /* Traits for the hash_set to record failed SLP builds for a stmt set.
    1810              :    Note we never remove apart from at destruction time so we do not
    1811              :    need a special value for deleted that differs from empty.  */
    1812              : struct bst_traits
    1813              : {
    1814              :   typedef vec <stmt_vec_info> value_type;
    1815              :   typedef vec <stmt_vec_info> compare_type;
    1816              :   static inline hashval_t hash (value_type);
    1817              :   static inline bool equal (value_type existing, value_type candidate);
    1818    506535097 :   static inline bool is_empty (value_type x) { return !x.exists (); }
    1819    113595722 :   static inline bool is_deleted (value_type x) { return !x.exists (); }
    1820              :   static const bool empty_zero_p = true;
    1821            0 :   static inline void mark_empty (value_type &x) { x.release (); }
    1822              :   static inline void mark_deleted (value_type &x) { x.release (); }
    1823      9744003 :   static inline void remove (value_type &x) { x.release (); }
    1824              : };
    1825              : inline hashval_t
    1826     98879219 : bst_traits::hash (value_type x)
    1827              : {
    1828     98879219 :   inchash::hash h;
    1829    438705729 :   for (unsigned i = 0; i < x.length (); ++i)
    1830    339826510 :     h.add_int (x[i] ? gimple_uid (x[i]->stmt) : -1);
    1831     98879219 :   return h.end ();
    1832              : }
    1833              : inline bool
    1834     86602193 : bst_traits::equal (value_type existing, value_type candidate)
    1835              : {
    1836    259806579 :   if (existing.length () != candidate.length ())
    1837              :     return false;
    1838     87197819 :   for (unsigned i = 0; i < existing.length (); ++i)
    1839     82639957 :     if (existing[i] != candidate[i])
    1840              :       return false;
    1841              :   return true;
    1842              : }
    1843              : 
    1844              : typedef hash_map <vec <stmt_vec_info>, slp_tree,
    1845              :                   simple_hashmap_traits <bst_traits, slp_tree> >
    1846              :   scalar_stmts_to_slp_tree_map_t;
    1847              : 
    1848              : /* Release BST_MAP.  */
    1849              : 
    1850              : static void
    1851      1897140 : release_scalar_stmts_to_slp_tree_map (scalar_stmts_to_slp_tree_map_t *bst_map)
    1852              : {
    1853              :   /* The map keeps a reference on SLP nodes built, release that.  */
    1854     11641143 :   for (scalar_stmts_to_slp_tree_map_t::iterator it = bst_map->begin ();
    1855     11641143 :        it != bst_map->end (); ++it)
    1856      9744003 :     if ((*it).second)
    1857      9744003 :       vect_free_slp_tree ((*it).second);
    1858      3794280 :   delete bst_map;
    1859      1897140 : }
    1860              : 
    1861              : /* ???  This was std::pair<std::pair<tree_code, vect_def_type>, tree>
    1862              :    but then vec::insert does memmove and that's not compatible with
    1863              :    std::pair.  */
    1864              : struct chain_op_t
    1865              : {
    1866      4226552 :   chain_op_t (tree_code code_, vect_def_type dt_, tree op_)
    1867      4226552 :       : code (code_), dt (dt_), op (op_) {}
    1868              :   tree_code code;
    1869              :   vect_def_type dt;
    1870              :   tree op;
    1871              : };
    1872              : 
    1873              : /* Comparator for sorting associatable chains.  */
    1874              : 
    1875              : static int
    1876     12395998 : dt_sort_cmp (const void *op1_, const void *op2_, void *)
    1877              : {
    1878     12395998 :   auto *op1 = (const chain_op_t *) op1_;
    1879     12395998 :   auto *op2 = (const chain_op_t *) op2_;
    1880     12395998 :   if (op1->dt != op2->dt)
    1881      1828057 :     return (int)op1->dt - (int)op2->dt;
    1882     10567941 :   return (int)op1->code - (int)op2->code;
    1883              : }
    1884              : 
    1885              : /* Linearize the associatable expression chain at START with the
    1886              :    associatable operation CODE (where PLUS_EXPR also allows MINUS_EXPR),
    1887              :    filling CHAIN with the result and using WORKLIST as intermediate storage.
    1888              :    CODE_STMT and ALT_CODE_STMT are filled with the first stmt using CODE
    1889              :    or MINUS_EXPR.  *CHAIN_STMTS if not NULL is filled with all computation
    1890              :    stmts, starting with START.  When ALLOW_ALT_CODE is false, do not
    1891              :    follow into MINUS_EXPR when building a PLUS chain (treat MINUS as leaf).  */
    1892              : 
    1893              : static void
    1894      1822716 : vect_slp_linearize_chain (vec_info *vinfo,
    1895              :                           vec<std::pair<tree_code, gimple *> > &worklist,
    1896              :                           vec<chain_op_t> &chain,
    1897              :                           enum tree_code code, gimple *start,
    1898              :                           gimple *&code_stmt, gimple *&alt_code_stmt,
    1899              :                           vec<gimple *> *chain_stmts,
    1900              :                           bool allow_alt_code = true)
    1901              : {
    1902              :   /* For each lane linearize the addition/subtraction (or other
    1903              :      uniform associatable operation) expression tree.  */
    1904      1822716 :   worklist.safe_push (std::make_pair (code, start));
    1905      4226552 :   while (!worklist.is_empty ())
    1906              :     {
    1907      2403836 :       auto entry = worklist.pop ();
    1908      2403836 :       gassign *stmt = as_a <gassign *> (entry.second);
    1909      2403836 :       enum tree_code in_code = entry.first;
    1910      4807672 :       enum tree_code this_code = gimple_assign_rhs_code (stmt);
    1911              :       /* Pick some stmts suitable for SLP_TREE_REPRESENTATIVE.  */
    1912      2403836 :       if (!code_stmt
    1913      2403836 :           && gimple_assign_rhs_code (stmt) == code)
    1914      1515991 :         code_stmt = stmt;
    1915       887845 :       else if (!alt_code_stmt
    1916       887845 :                && gimple_assign_rhs_code (stmt) == MINUS_EXPR)
    1917       361728 :         alt_code_stmt = stmt;
    1918      2403836 :       if (chain_stmts)
    1919      2322768 :         chain_stmts->safe_push (stmt);
    1920      7211508 :       for (unsigned opnum = 1; opnum <= 2; ++opnum)
    1921              :         {
    1922      4807672 :           tree op = gimple_op (stmt, opnum);
    1923      4807672 :           vect_def_type dt;
    1924      4807672 :           stmt_vec_info def_stmt_info;
    1925      4807672 :           bool res = vect_is_simple_use (op, vinfo, &dt, &def_stmt_info);
    1926      4807672 :           gcc_assert (res);
    1927      4807672 :           if (dt == vect_internal_def
    1928      4807672 :               && is_pattern_stmt_p (def_stmt_info))
    1929         9249 :             op = gimple_get_lhs (def_stmt_info->stmt);
    1930      4807672 :           gimple *use_stmt;
    1931      4807672 :           use_operand_p use_p;
    1932      4807672 :           if (dt == vect_internal_def
    1933      4376677 :               && single_imm_use (op, &use_p, &use_stmt)
    1934      2824532 :               && is_gimple_assign (def_stmt_info->stmt)
    1935      7437839 :               && (gimple_assign_rhs_code (def_stmt_info->stmt) == code
    1936      2049364 :                   || (allow_alt_code
    1937        57371 :                       && code == PLUS_EXPR
    1938        36328 :                       && (gimple_assign_rhs_code (def_stmt_info->stmt)
    1939              :                           == MINUS_EXPR))))
    1940              :             {
    1941       581120 :               tree_code op_def_code = this_code;
    1942       581120 :               if (op_def_code == MINUS_EXPR && opnum == 1)
    1943        53246 :                 op_def_code = PLUS_EXPR;
    1944       581120 :               if (in_code == MINUS_EXPR)
    1945          222 :                 op_def_code = op_def_code == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR;
    1946       581120 :               worklist.safe_push (std::make_pair (op_def_code,
    1947       581120 :                                                   def_stmt_info->stmt));
    1948              :             }
    1949              :           else
    1950              :             {
    1951      4226552 :               tree_code op_def_code = this_code;
    1952      4226552 :               if (op_def_code == MINUS_EXPR && opnum == 1)
    1953       308601 :                 op_def_code = PLUS_EXPR;
    1954      4226552 :               if (in_code == MINUS_EXPR)
    1955         4218 :                 op_def_code = op_def_code == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR;
    1956      4226552 :               chain.safe_push (chain_op_t (op_def_code, dt, op));
    1957              :             }
    1958              :         }
    1959              :     }
    1960      1822716 : }
    1961              : 
    1962              : /* Distance from the node currently being discovered to the closest upthread
    1963              :    commutative operation whose operand-zero discovery may still be fixed by
    1964              :    retrying with swapped operands, or -1U if there is none.  */
    1965              : 
    1966              : static unsigned least_upthread_swappable_op_distance = -1U;
    1967              : 
    1968              : static slp_tree
    1969              : vect_build_slp_tree_2 (vec_info *vinfo, slp_tree node,
    1970              :                        vec<stmt_vec_info> stmts,
    1971              :                        match_elt_t *matches, unsigned *limit,
    1972              :                        unsigned *tree_size,
    1973              :                        scalar_stmts_to_slp_tree_map_t *bst_map);
    1974              : 
    1975              : static slp_tree
    1976      6602700 : vect_build_slp_tree (vec_info *vinfo,
    1977              :                      vec<stmt_vec_info> stmts,
    1978              :                      match_elt_t *matches, unsigned *limit, unsigned *tree_size,
    1979              :                      scalar_stmts_to_slp_tree_map_t *bst_map)
    1980              : {
    1981      6602700 :   unsigned int group_size = stmts.length ();
    1982      6602700 :   if (slp_tree *leader = bst_map->get (stmts))
    1983              :     {
    1984       496314 :       if (dump_enabled_p ())
    1985        17816 :         dump_printf_loc (MSG_NOTE, vect_location, "re-using %sSLP tree %p\n",
    1986        17816 :                          !(*leader)->failed ? "" : "failed ",
    1987              :                          (void *) *leader);
    1988       496314 :       if (!(*leader)->failed)
    1989              :         {
    1990       451834 :           SLP_TREE_REF_COUNT (*leader)++;
    1991       451834 :           stmts.release ();
    1992       451834 :           return *leader;
    1993              :         }
    1994        44480 :       memcpy (matches, (*leader)->failed, sizeof (match_elt_t) * group_size);
    1995        44480 :       return NULL;
    1996              :     }
    1997              : 
    1998              :   /* Single-lane SLP doesn't have the chance of run-away, do not account
    1999              :      it to the limit.  */
    2000      6106386 :   if (stmts.length () > 1)
    2001              :     {
    2002      3398561 :       if (*limit == 0)
    2003              :         {
    2004         1345 :           if (dump_enabled_p ())
    2005           15 :             dump_printf_loc (MSG_NOTE, vect_location,
    2006              :                              "SLP discovery limit exceeded\n");
    2007         1345 :           memset (matches, -1, sizeof (match_elt_t) * group_size);
    2008         1345 :           return NULL;
    2009              :         }
    2010      3397216 :       --*limit;
    2011              :     }
    2012              : 
    2013              :   /* Seed the bst_map with a stub node to be filled by vect_build_slp_tree_2
    2014              :      so we can pick up backedge destinations during discovery.  */
    2015      6105041 :   slp_tree res = new _slp_tree;
    2016      6105041 :   SLP_TREE_DEF_TYPE (res) = vect_internal_def;
    2017      6105041 :   SLP_TREE_SCALAR_STMTS (res) = stmts;
    2018      6105041 :   bst_map->put (stmts.copy (), res);
    2019              : 
    2020      6105041 :   if (dump_enabled_p ())
    2021       152241 :     dump_printf_loc (MSG_NOTE, vect_location,
    2022              :                      "starting SLP discovery for node %p\n", (void *) res);
    2023              : 
    2024      6105041 :   slp_tree res_ = vect_build_slp_tree_2 (vinfo, res, stmts,
    2025              :                                         matches, limit, tree_size, bst_map);
    2026      6105041 :   if (!res_)
    2027              :     {
    2028      2135485 :       if (dump_enabled_p ())
    2029         8175 :         dump_printf_loc (MSG_NOTE, vect_location,
    2030              :                          "SLP discovery for node %p failed\n", (void *) res);
    2031              :       /* Mark the node invalid so we can detect those when still in use
    2032              :          as backedge destinations.  */
    2033      2135485 :       SLP_TREE_SCALAR_STMTS (res) = vNULL;
    2034      2135485 :       SLP_TREE_DEF_TYPE (res) = vect_uninitialized_def;
    2035      2135485 :       res->failed = XNEWVEC (match_elt_t, group_size);
    2036      2135485 :       if (flag_checking)
    2037              :         {
    2038              :           unsigned i;
    2039      3805460 :           for (i = 0; i < group_size; ++i)
    2040      3805460 :             if (matches[i] != 0)
    2041              :               break;
    2042      2135485 :           gcc_assert (i < group_size);
    2043              :         }
    2044      2135485 :       memcpy (res->failed, matches, sizeof (match_elt_t) * group_size);
    2045              :     }
    2046              :   else
    2047              :     {
    2048      3969556 :       if (dump_enabled_p ())
    2049       144066 :         dump_printf_loc (MSG_NOTE, vect_location,
    2050              :                          "SLP discovery for node %p succeeded\n",
    2051              :                          (void *) res);
    2052      3969556 :       gcc_assert (res_ == res);
    2053              :       /* Keep a reference for the bst_map use.  */
    2054      3969556 :       SLP_TREE_REF_COUNT (res)++;
    2055              :       /* For BB vectorization nodes that need splitting should be failed.  */
    2056      3969556 :       gcc_assert (!is_a <bb_vec_info> (vinfo)
    2057              :                   || multiple_p (group_size,
    2058              :                                  TYPE_VECTOR_SUBPARTS (res->vectype)));
    2059              :     }
    2060              :   return res_;
    2061              : }
    2062              : 
    2063              : /* Helper for building an associated SLP node chain.  */
    2064              : 
    2065              : static void
    2066          162 : vect_slp_build_two_operator_nodes (slp_tree perm, tree vectype,
    2067              :                                    slp_tree op0, slp_tree op1,
    2068              :                                    stmt_vec_info oper1, stmt_vec_info oper2,
    2069              :                                    vec<std::pair<unsigned, unsigned> > lperm)
    2070              : {
    2071          162 :   unsigned group_size = SLP_TREE_LANES (op1);
    2072              : 
    2073          162 :   slp_tree child1 = new _slp_tree;
    2074          162 :   SLP_TREE_DEF_TYPE (child1) = vect_internal_def;
    2075          162 :   SLP_TREE_VECTYPE (child1) = vectype;
    2076          162 :   SLP_TREE_LANES (child1) = group_size;
    2077          162 :   SLP_TREE_CHILDREN (child1).create (2);
    2078          162 :   SLP_TREE_CHILDREN (child1).quick_push (op0);
    2079          162 :   SLP_TREE_CHILDREN (child1).quick_push (op1);
    2080          162 :   SLP_TREE_REPRESENTATIVE (child1) = oper1;
    2081              : 
    2082          162 :   slp_tree child2 = new _slp_tree;
    2083          162 :   SLP_TREE_DEF_TYPE (child2) = vect_internal_def;
    2084          162 :   SLP_TREE_VECTYPE (child2) = vectype;
    2085          162 :   SLP_TREE_LANES (child2) = group_size;
    2086          162 :   SLP_TREE_CHILDREN (child2).create (2);
    2087          162 :   SLP_TREE_CHILDREN (child2).quick_push (op0);
    2088          162 :   SLP_TREE_REF_COUNT (op0)++;
    2089          162 :   SLP_TREE_CHILDREN (child2).quick_push (op1);
    2090          162 :   SLP_TREE_REF_COUNT (op1)++;
    2091          162 :   SLP_TREE_REPRESENTATIVE (child2) = oper2;
    2092              : 
    2093          162 :   SLP_TREE_DEF_TYPE (perm) = vect_internal_def;
    2094          162 :   SLP_TREE_CODE (perm) = VEC_PERM_EXPR;
    2095          162 :   SLP_TREE_VECTYPE (perm) = vectype;
    2096          162 :   SLP_TREE_LANES (perm) = group_size;
    2097          162 :   SLP_TREE_REPRESENTATIVE (perm) = NULL;
    2098          162 :   SLP_TREE_LANE_PERMUTATION (perm) = lperm;
    2099          162 :   SLP_TREE_CHILDREN (perm).quick_push (child1);
    2100          162 :   SLP_TREE_CHILDREN (perm).quick_push (child2);
    2101          162 : }
    2102              : 
    2103              : /* For isomorphic matches[], indicate a splitting point according to
    2104              :    CONST_NUNITS.  */
    2105              : 
    2106              : static void
    2107       123577 : force_split_matches (match_elt_t *matches, unsigned group_size,
    2108              :                      unsigned const_nunits)
    2109              : {
    2110       123577 :   if (dump_enabled_p ())
    2111           53 :     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2112              :                      "Build SLP failed: unrolling required "
    2113              :                      "in basic block SLP\n");
    2114              : 
    2115              :   /* With constant vector elements simulate a mismatch at the
    2116              :      point we need to split.  But indicate the tail is isomorphic.  */
    2117       123577 :   unsigned tail = group_size & (const_nunits - 1);
    2118       272241 :   for (unsigned i = group_size - tail; i < group_size; ++i)
    2119       148664 :     matches[i] = (int)(group_size - tail);
    2120       123577 : }
    2121              : 
    2122              : /* Recursively build an SLP tree starting from NODE.
    2123              :    Fail (and return a value not equal to zero) if def-stmts are not
    2124              :    isomorphic, require data permutation or are of unsupported types of
    2125              :    operation.  Otherwise, return 0.
    2126              :    The value returned is the depth in the SLP tree where a mismatch
    2127              :    was found.  */
    2128              : 
    2129              : static slp_tree
    2130      6105041 : vect_build_slp_tree_2 (vec_info *vinfo, slp_tree node,
    2131              :                        vec<stmt_vec_info> stmts,
    2132              :                        match_elt_t *matches, unsigned *limit,
    2133              :                        unsigned *tree_size,
    2134              :                        scalar_stmts_to_slp_tree_map_t *bst_map)
    2135              : {
    2136      6105041 :   unsigned int group_size = stmts.length ();
    2137      6105041 :   unsigned nops, i, this_tree_size = 0;
    2138              : 
    2139      6105041 :   matches[0] = -1;
    2140              : 
    2141      6105041 :   stmt_vec_info stmt_info = stmts[0];
    2142      6105041 :   if (!is_a<gcall *> (stmt_info->stmt)
    2143              :       && !is_a<gassign *> (stmt_info->stmt)
    2144              :       && !is_a<gphi *> (stmt_info->stmt))
    2145              :     return NULL;
    2146              : 
    2147      6104871 :   nops = gimple_num_args (stmt_info->stmt);
    2148      6104871 :   if (const int *map = vect_get_operand_map (stmt_info))
    2149        36716 :     nops = map[0];
    2150              : 
    2151              :   /* If the SLP node is a PHI (induction or reduction), terminate
    2152              :      the recursion.  */
    2153      6104871 :   bool *skip_args = XALLOCAVEC (bool, nops);
    2154      6104871 :   memset (skip_args, 0, sizeof (bool) * nops);
    2155      6104871 :   if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
    2156      2906985 :     if (gphi *stmt = dyn_cast <gphi *> (stmt_info->stmt))
    2157              :       {
    2158       316989 :         tree scalar_type = TREE_TYPE (PHI_RESULT (stmt));
    2159       316989 :         tree vectype = get_vectype_for_scalar_type (vinfo, scalar_type,
    2160              :                                                     group_size);
    2161       316989 :         if (!vectype)
    2162              :           {
    2163         4264 :             if (dump_enabled_p ())
    2164            7 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    2165              :                                "Build SLP failed: unsupported data-type in %G\n",
    2166              :                                stmt_info->stmt);
    2167              :             return NULL;
    2168              :           }
    2169              : 
    2170       312725 :         vect_def_type def_type = STMT_VINFO_DEF_TYPE (stmt_info);
    2171       312725 :         if (def_type == vect_induction_def)
    2172              :           {
    2173              :             /* Induction PHIs are not cycles but walk the initial
    2174              :                value.  Only for inner loops through, for outer loops
    2175              :                we need to pick up the value from the actual PHIs
    2176              :                to more easily support peeling and epilogue vectorization.  */
    2177       204288 :             class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    2178       204288 :             if (!nested_in_vect_loop_p (loop, stmt_info))
    2179       203459 :               skip_args[loop_preheader_edge (loop)->dest_idx] = true;
    2180              :             else
    2181              :               loop = loop->inner;
    2182       204288 :             skip_args[loop_latch_edge (loop)->dest_idx] = true;
    2183              :           }
    2184       108437 :         else if (def_type == vect_reduction_def
    2185              :                  || def_type == vect_double_reduction_def
    2186              :                  || def_type == vect_nested_cycle
    2187       108437 :                  || def_type == vect_first_order_recurrence)
    2188              :           {
    2189              :             /* Else def types have to match.  */
    2190              :             stmt_vec_info other_info;
    2191              :             bool all_same = true;
    2192       245433 :             FOR_EACH_VEC_ELT (stmts, i, other_info)
    2193              :               {
    2194       138281 :                 if (STMT_VINFO_DEF_TYPE (other_info) != def_type)
    2195      6105041 :                   return NULL;
    2196       138275 :                 if (other_info != stmt_info)
    2197        26269 :                   all_same = false;
    2198              :               }
    2199       107152 :             class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
    2200              :             /* Reduction initial values are not explicitly represented.  */
    2201       107152 :             if (def_type != vect_first_order_recurrence
    2202       107152 :                 && gimple_bb (stmt_info->stmt) == loop->header)
    2203       103974 :               skip_args[loop_preheader_edge (loop)->dest_idx] = true;
    2204              :             /* Reduction chain backedge defs are filled manually.
    2205              :                ???  Need a better way to identify a SLP reduction chain PHI.
    2206              :                Or a better overall way to SLP match those.  */
    2207       107152 :             if (stmts.length () > 1
    2208       107152 :                 && all_same && def_type == vect_reduction_def)
    2209         2416 :               skip_args[loop_latch_edge (loop)->dest_idx] = true;
    2210              :           }
    2211         1279 :         else if (def_type != vect_internal_def)
    2212              :           return NULL;
    2213              :       }
    2214              : 
    2215              : 
    2216      6100601 :   bool two_operators = false;
    2217      6100601 :   unsigned char *swap = XALLOCAVEC (unsigned char, group_size);
    2218      6100601 :   tree vectype = NULL_TREE;
    2219      6100601 :   if (!vect_build_slp_tree_1 (vinfo, swap, stmts, matches, &two_operators,
    2220              :                               &vectype))
    2221              :     return NULL;
    2222              : 
    2223      4594854 :   bool soft_fail
    2224      4594854 :     = (is_a <bb_vec_info> (vinfo)
    2225      4594854 :        && !multiple_p (group_size, TYPE_VECTOR_SUBPARTS (vectype)));
    2226              : 
    2227              :   /* If the SLP node is a load, terminate the recursion unless masked.  */
    2228      4594854 :   if (STMT_VINFO_DATA_REF (stmt_info)
    2229      2229943 :       && DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
    2230              :     {
    2231       952171 :       if (soft_fail)
    2232              :         {
    2233          944 :           force_split_matches (matches, group_size,
    2234          944 :                                TYPE_VECTOR_SUBPARTS (vectype).to_constant ());
    2235          944 :           return NULL;
    2236              :         }
    2237       951227 :       if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
    2238              :         gcc_assert (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)));
    2239              :       else
    2240              :         {
    2241       931879 :           (*tree_size)++;
    2242       931879 :           node = vect_create_new_slp_node (node, stmts, 0);
    2243       931879 :           SLP_TREE_VECTYPE (node) = vectype;
    2244              :           /* And compute the load permutation.  Whether it is actually
    2245              :              a permutation depends on the unrolling factor which is
    2246              :              decided later.  */
    2247       931879 :           vec<unsigned> load_permutation;
    2248       931879 :           int j;
    2249       931879 :           stmt_vec_info load_info;
    2250       931879 :           load_permutation.create (group_size);
    2251       931879 :           stmt_vec_info first_stmt_info
    2252       931879 :             = STMT_VINFO_GROUPED_ACCESS (stmt_info)
    2253       931879 :               ? DR_GROUP_FIRST_ELEMENT (stmt_info) : stmt_info;
    2254       931879 :           bool any_permute = false;
    2255      2255230 :           FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), j, load_info)
    2256              :             {
    2257      1323351 :               int load_place;
    2258      1323351 :               if (! load_info)
    2259              :                 {
    2260        40688 :                   if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
    2261              :                     load_place = j;
    2262              :                   else
    2263              :                     load_place = 0;
    2264              :                 }
    2265      1282663 :               else if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
    2266       750963 :                 load_place = vect_get_place_in_interleaving_chain
    2267       750963 :                     (load_info, first_stmt_info);
    2268              :               else
    2269              :                 /* Recognize the splat case as { 0, 0, ... } but make
    2270              :                    sure to use the appropriate refs for collections
    2271              :                    of invariant refs.  */
    2272       531700 :                 load_place = (load_info == stmt_info) ? 0 : j;
    2273       791904 :               gcc_assert (load_place != -1);
    2274      1323351 :               any_permute |= load_place != j;
    2275      1323351 :               load_permutation.quick_push (load_place);
    2276              :             }
    2277              : 
    2278       931879 :           if (gcall *stmt = dyn_cast <gcall *> (stmt_info->stmt))
    2279              :             {
    2280         3353 :               gcc_assert (gimple_call_internal_p (stmt, IFN_MASK_LOAD));
    2281         3353 :               bool has_gaps = false;
    2282         3353 :               if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
    2283          189 :                 for (stmt_vec_info si = DR_GROUP_NEXT_ELEMENT (first_stmt_info);
    2284          846 :                      si; si = DR_GROUP_NEXT_ELEMENT (si))
    2285          657 :                   if (DR_GROUP_GAP (si) != 1)
    2286           80 :                     has_gaps = true;
    2287              :               /* We cannot handle permuted masked loads directly, see
    2288              :                  PR114375.  We cannot handle strided masked loads or masked
    2289              :                  loads with gaps unless the mask is uniform.  */
    2290         3353 :               if ((STMT_VINFO_GROUPED_ACCESS (stmt_info)
    2291          189 :                    && (DR_GROUP_GAP (first_stmt_info) != 0
    2292          129 :                        || (has_gaps
    2293           35 :                            && STMT_VINFO_SLP_VECT_ONLY (first_stmt_info))))
    2294         6626 :                   || STMT_VINFO_STRIDED_P (stmt_info))
    2295              :                 {
    2296          108 :                   load_permutation.release ();
    2297          108 :                   matches[0] = -1;
    2298       928673 :                   return NULL;
    2299              :                 }
    2300              : 
    2301              :               /* For permuted masked loads do an unpermuted masked load of
    2302              :                  the whole group followed by a SLP permute node.  */
    2303         3245 :               if (any_permute
    2304         3245 :                   || (STMT_VINFO_GROUPED_ACCESS (stmt_info)
    2305           83 :                       && DR_GROUP_SIZE (first_stmt_info) != group_size))
    2306              :                 {
    2307              :                   /* Discover the whole unpermuted load.  */
    2308           39 :                   vec<stmt_vec_info> stmts2;
    2309           39 :                   unsigned dr_group_size = STMT_VINFO_GROUPED_ACCESS (stmt_info)
    2310           68 :                       ? DR_GROUP_SIZE (first_stmt_info) : 1;
    2311           39 :                   stmts2.create (dr_group_size);
    2312           39 :                   stmts2.quick_grow_cleared (dr_group_size);
    2313           39 :                   unsigned i = 0;
    2314           39 :                   for (stmt_vec_info si = first_stmt_info;
    2315          464 :                        si; si = DR_GROUP_NEXT_ELEMENT (si))
    2316              :                     {
    2317          425 :                       if (si != first_stmt_info)
    2318         1586 :                         for (unsigned k = 1; k < DR_GROUP_GAP (si); ++k)
    2319         1200 :                           stmts2[i++] = NULL;
    2320          425 :                       stmts2[i++] = si;
    2321              :                     }
    2322           39 :                   match_elt_t *matches2
    2323           39 :                     = XALLOCAVEC (match_elt_t, dr_group_size);
    2324           39 :                   slp_tree unperm_load
    2325           39 :                     = vect_build_slp_tree (vinfo, stmts2, matches2, limit,
    2326           39 :                                            &this_tree_size, bst_map);
    2327              :                   /* When we are able to do the full masked load emit that
    2328              :                      followed by 'node' being the desired final permutation.  */
    2329           39 :                   if (unperm_load)
    2330              :                     {
    2331           16 :                       gcc_assert
    2332              :                         (!SLP_TREE_LOAD_PERMUTATION (unperm_load).exists ());
    2333           16 :                       lane_permutation_t lperm;
    2334           16 :                       lperm.create (group_size);
    2335           72 :                       for (unsigned j = 0; j < load_permutation.length (); ++j)
    2336           40 :                         lperm.quick_push
    2337           40 :                           (std::make_pair (0, load_permutation[j]));
    2338           16 :                       SLP_TREE_CODE (node) = VEC_PERM_EXPR;
    2339           16 :                       SLP_TREE_CHILDREN (node).safe_push (unperm_load);
    2340           16 :                       SLP_TREE_LANE_PERMUTATION (node) = lperm;
    2341           16 :                       SLP_TREE_REPRESENTATIVE (node) = NULL;
    2342           16 :                       load_permutation.release ();
    2343           16 :                       return node;
    2344              :                     }
    2345           23 :                   stmts2.release ();
    2346           23 :                   load_permutation.release ();
    2347           23 :                   matches[0] = -1;
    2348           23 :                   return NULL;
    2349              :                 }
    2350         3206 :               load_permutation.release ();
    2351              :             }
    2352              :           else
    2353              :             {
    2354       928526 :               if (!any_permute
    2355       798604 :                   && STMT_VINFO_GROUPED_ACCESS (stmt_info)
    2356      1221631 :                   && group_size == DR_GROUP_SIZE (first_stmt_info))
    2357       128893 :                 load_permutation.release ();
    2358       928526 :               SLP_TREE_LOAD_PERMUTATION (node) = load_permutation;
    2359       928526 :               return node;
    2360              :             }
    2361              :         }
    2362              :     }
    2363      3642683 :   else if (gimple_assign_single_p (stmt_info->stmt)
    2364      2562094 :            && !gimple_vuse (stmt_info->stmt)
    2365      3651469 :            && gimple_assign_rhs_code (stmt_info->stmt) == BIT_FIELD_REF)
    2366              :     {
    2367         3184 :       if (soft_fail)
    2368              :         {
    2369           16 :           force_split_matches (matches, group_size,
    2370           16 :                                TYPE_VECTOR_SUBPARTS (vectype).to_constant ());
    2371           16 :           return NULL;
    2372              :         }
    2373              :       /* vect_build_slp_tree_2 determined all BIT_FIELD_REFs reference
    2374              :          the same SSA name vector of a compatible type to vectype.  */
    2375         3168 :       vec<std::pair<unsigned, unsigned> > lperm = vNULL;
    2376         3168 :       tree vec = TREE_OPERAND (gimple_assign_rhs1 (stmt_info->stmt), 0);
    2377         3168 :       stmt_vec_info estmt_info;
    2378        11072 :       FOR_EACH_VEC_ELT (stmts, i, estmt_info)
    2379              :         {
    2380         8051 :           gassign *estmt = as_a <gassign *> (estmt_info->stmt);
    2381         8051 :           tree bfref = gimple_assign_rhs1 (estmt);
    2382         8051 :           HOST_WIDE_INT lane;
    2383         8051 :           if (!known_eq (bit_field_size (bfref),
    2384              :                          tree_to_poly_uint64 (TYPE_SIZE (TREE_TYPE (vectype))))
    2385        15955 :               || !constant_multiple_p (bit_field_offset (bfref),
    2386         8051 :                                        bit_field_size (bfref), &lane))
    2387              :             {
    2388          147 :               lperm.release ();
    2389          147 :               matches[0] = -1;
    2390          147 :               return NULL;
    2391              :             }
    2392         7904 :           lperm.safe_push (std::make_pair (0, (unsigned)lane));
    2393              :         }
    2394         3021 :       slp_tree vnode = vect_create_new_slp_node (vNULL);
    2395         3021 :       if (operand_equal_p (TYPE_SIZE (vectype), TYPE_SIZE (TREE_TYPE (vec))))
    2396              :         /* ???  We record vectype here but we hide eventually necessary
    2397              :            punning and instead rely on code generation to materialize
    2398              :            VIEW_CONVERT_EXPRs as necessary.  We instead should make
    2399              :            this explicit somehow.  */
    2400         1325 :         SLP_TREE_VECTYPE (vnode) = vectype;
    2401              :       else
    2402              :         {
    2403              :           /* For different size but compatible elements we can still
    2404              :              use VEC_PERM_EXPR without punning.  */
    2405         1696 :           gcc_assert (VECTOR_TYPE_P (TREE_TYPE (vec))
    2406              :                       && types_compatible_p (TREE_TYPE (vectype),
    2407              :                                              TREE_TYPE (TREE_TYPE (vec))));
    2408         1696 :           SLP_TREE_VECTYPE (vnode) = TREE_TYPE (vec);
    2409              :         }
    2410         3021 :       auto nunits = TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (vnode));
    2411         3021 :       unsigned HOST_WIDE_INT const_nunits;
    2412         3021 :       if (nunits.is_constant (&const_nunits))
    2413         3021 :         SLP_TREE_LANES (vnode) = const_nunits;
    2414         3021 :       SLP_TREE_VEC_DEFS (vnode).safe_push (vec);
    2415              :       /* We are always building a permutation node even if it is an identity
    2416              :          permute to shield the rest of the vectorizer from the odd node
    2417              :          representing an actual vector without any scalar ops.
    2418              :          ???  We could hide it completely with making the permute node
    2419              :          external?  */
    2420         3021 :       node = vect_create_new_slp_node (node, stmts, 1);
    2421         3021 :       SLP_TREE_CODE (node) = VEC_PERM_EXPR;
    2422         3021 :       SLP_TREE_LANE_PERMUTATION (node) = lperm;
    2423         3021 :       SLP_TREE_VECTYPE (node) = vectype;
    2424         3021 :       SLP_TREE_CHILDREN (node).quick_push (vnode);
    2425         3021 :       SLP_TREE_REPRESENTATIVE (node) = NULL;
    2426         3021 :       return node;
    2427              :     }
    2428              :   /* When discovery reaches an associatable operation see whether we can
    2429              :      improve that to match up lanes in a way superior to the operand
    2430              :      swapping code which at most looks at two defs.
    2431              :      ???  For BB vectorization we cannot do the brute-force search
    2432              :      for matching as we can succeed by means of builds from scalars
    2433              :      and have no good way to "cost" one build against another.  */
    2434      3639499 :   else if (is_a <loop_vec_info> (vinfo)
    2435              :            /* Do not bother for single-lane SLP.  */
    2436      2064970 :            && group_size > 1
    2437              :            /* ???  We don't handle !vect_internal_def defs below.  */
    2438       114225 :            && STMT_VINFO_DEF_TYPE (stmt_info) == vect_internal_def
    2439              :            /* ???  Do not associate a reduction, this will wreck REDUC_IDX
    2440              :               mapping as long as that exists on the stmt_info level.  */
    2441        88545 :            && STMT_VINFO_REDUC_IDX (stmt_info) == -1
    2442        79918 :            && is_gimple_assign (stmt_info->stmt)
    2443        79593 :            && (associative_tree_code (gimple_assign_rhs_code (stmt_info->stmt))
    2444        52647 :                || gimple_assign_rhs_code (stmt_info->stmt) == MINUS_EXPR)
    2445      3668390 :            && ((FLOAT_TYPE_P (vectype) && flag_associative_math)
    2446        16624 :                || (INTEGRAL_TYPE_P (TREE_TYPE (vectype))
    2447        14085 :                    && TYPE_OVERFLOW_WRAPS (TREE_TYPE (vectype)))))
    2448              :     {
    2449              :       /* See if we have a chain of (mixed) adds or subtracts or other
    2450              :          associatable ops.  */
    2451        21756 :       enum tree_code code = gimple_assign_rhs_code (stmt_info->stmt);
    2452        21756 :       if (code == MINUS_EXPR)
    2453          842 :         code = PLUS_EXPR;
    2454        21756 :       stmt_vec_info other_op_stmt_info = NULL;
    2455        21756 :       stmt_vec_info op_stmt_info = NULL;
    2456        21756 :       unsigned chain_len = 0;
    2457        21756 :       auto_vec<chain_op_t> chain;
    2458        21756 :       auto_vec<std::pair<tree_code, gimple *> > worklist;
    2459        21756 :       auto_vec<vec<chain_op_t> > chains (group_size);
    2460        21756 :       auto_vec<slp_tree, 4> children;
    2461        21756 :       bool hard_fail = true;
    2462        22739 :       for (unsigned lane = 0; lane < group_size; ++lane)
    2463              :         {
    2464        22413 :           if (!stmts[lane])
    2465              :             {
    2466              :               /* ???  Below we require lane zero is present.  */
    2467            0 :               if (lane == 0)
    2468              :                 {
    2469              :                   hard_fail = false;
    2470        21430 :                   break;
    2471              :                 }
    2472            0 :               chains.quick_push (vNULL);
    2473            0 :               continue;
    2474              :             }
    2475              :           /* For each lane linearize the addition/subtraction (or other
    2476              :              uniform associatable operation) expression tree.  */
    2477        22413 :           gimple *op_stmt = NULL, *other_op_stmt = NULL;
    2478        22413 :           vect_slp_linearize_chain (vinfo, worklist, chain, code,
    2479        22413 :                                     stmts[lane]->stmt, op_stmt, other_op_stmt,
    2480              :                                     NULL);
    2481        22413 :           if (!op_stmt_info && op_stmt)
    2482        21105 :             op_stmt_info = vinfo->lookup_stmt (op_stmt);
    2483        22413 :           if (!other_op_stmt_info && other_op_stmt)
    2484          878 :             other_op_stmt_info = vinfo->lookup_stmt (other_op_stmt);
    2485        22413 :           if (chain.length () == 2)
    2486              :             {
    2487              :               /* In a chain of just two elements resort to the regular
    2488              :                  operand swapping scheme.  Likewise if we run into a
    2489              :                  length mismatch process regularly as well as we did not
    2490              :                  process the other lanes we cannot report a good hint what
    2491              :                  lanes to try swapping in the parent.  */
    2492              :               hard_fail = false;
    2493              :               break;
    2494              :             }
    2495          986 :           else if (chain_len == 0)
    2496          366 :             chain_len = chain.length ();
    2497         1240 :           else if (chain.length () != chain_len)
    2498              :             {
    2499              :               /* ???  Here we could slip in magic to compensate with
    2500              :                  neutral operands.  */
    2501            3 :               matches[lane] = -1;
    2502            3 :               if (lane != group_size - 1)
    2503            3 :                 matches[0] = -1;
    2504              :               break;
    2505              :             }
    2506          983 :           chains.quick_push (chain.copy ());
    2507          983 :           chain.truncate (0);
    2508              :         }
    2509        43512 :       if (chains.length () == group_size)
    2510              :         {
    2511              :           /* We cannot yet use SLP_TREE_CODE to communicate the operation.  */
    2512          326 :           if (!op_stmt_info)
    2513              :             {
    2514            3 :               hard_fail = false;
    2515            3 :               goto out;
    2516              :             }
    2517              :           /* Now we have a set of chains with the same length.  */
    2518              :           /* 1. pre-sort according to def_type and operation.  */
    2519         1194 :           for (unsigned lane = 0; lane < group_size; ++lane)
    2520         1742 :             chains[lane].stablesort (dt_sort_cmp, vinfo);
    2521          323 :           if (dump_enabled_p ())
    2522              :             {
    2523          155 :               dump_printf_loc (MSG_NOTE, vect_location,
    2524              :                                "pre-sorted chains of %s\n",
    2525              :                                get_tree_code_name (code));
    2526          655 :               for (unsigned lane = 0; lane < group_size; ++lane)
    2527              :                 {
    2528          500 :                   if (!stmts[lane])
    2529            0 :                     dump_printf (MSG_NOTE, "--");
    2530              :                   else
    2531         2250 :                     for (unsigned opnum = 0; opnum < chain_len; ++opnum)
    2532         3500 :                       dump_printf (MSG_NOTE, "%s %T ",
    2533         1750 :                                    get_tree_code_name (chains[lane][opnum].code),
    2534         1750 :                                    chains[lane][opnum].op);
    2535          500 :                   dump_printf (MSG_NOTE, "\n");
    2536              :                 }
    2537              :             }
    2538              :           /* 2. try to build children nodes, associating as necessary.  */
    2539              :           /* 2a. prepare and perform early checks to avoid eating into
    2540              :              discovery limit unnecessarily.  */
    2541          323 :           vect_def_type *dts = XALLOCAVEC (vect_def_type, chain_len);
    2542         1361 :           for (unsigned n = 0; n < chain_len; ++n)
    2543              :             {
    2544         1038 :               vect_def_type dt = chains[0][n].dt;
    2545         1038 :               unsigned lane;
    2546         3949 :               for (lane = 0; lane < group_size; ++lane)
    2547         5822 :                 if (stmts[lane] && chains[lane][n].dt != dt)
    2548              :                   {
    2549            0 :                     if (dt == vect_constant_def
    2550            0 :                         && chains[lane][n].dt == vect_external_def)
    2551              :                       dt = vect_external_def;
    2552            0 :                     else if (dt == vect_external_def
    2553            0 :                              && chains[lane][n].dt == vect_constant_def)
    2554              :                       ;
    2555              :                     else
    2556              :                       break;
    2557              :                   }
    2558         1038 :               if (lane != group_size)
    2559              :                 {
    2560            0 :                   if (dump_enabled_p ())
    2561            0 :                     dump_printf_loc (MSG_NOTE, vect_location,
    2562              :                                      "giving up on chain due to mismatched "
    2563              :                                      "def types\n");
    2564            0 :                   matches[lane] = -1;
    2565            0 :                   if (lane != group_size - 1)
    2566            0 :                     matches[0] = -1;
    2567            0 :                   goto out;
    2568              :                 }
    2569         1038 :               dts[n] = dt;
    2570         1038 :               if (dt == vect_constant_def
    2571         1038 :                   || dt == vect_external_def)
    2572              :                 {
    2573              :                   /* Check whether we can build the invariant.  If we can't
    2574              :                      we never will be able to.  */
    2575           77 :                   tree type = TREE_TYPE (chains[0][n].op);
    2576         1038 :                   if (!GET_MODE_SIZE (vinfo->vector_mode).is_constant ()
    2577              :                       && (TREE_CODE (type) == BOOLEAN_TYPE
    2578              :                           || !can_duplicate_and_interleave_p (vinfo, group_size,
    2579              :                                                               type)))
    2580              :                     {
    2581              :                       matches[0] = -1;
    2582              :                       goto out;
    2583              :                     }
    2584              :                 }
    2585          961 :               else if (dt != vect_internal_def)
    2586              :                 {
    2587              :                   /* Not sure, we might need sth special.
    2588              :                      gcc.dg/vect/pr96854.c,
    2589              :                      gfortran.dg/vect/fast-math-pr37021.f90
    2590              :                      and gfortran.dg/vect/pr61171.f trigger.  */
    2591              :                   /* Soft-fail for now.  */
    2592            0 :                   hard_fail = false;
    2593            0 :                   goto out;
    2594              :                 }
    2595              :             }
    2596              :           /* 2b. do the actual build.  */
    2597         1307 :           for (unsigned n = 0; n < chain_len; ++n)
    2598              :             {
    2599         1003 :               vect_def_type dt = dts[n];
    2600         1003 :               unsigned lane;
    2601         1003 :               if (dt == vect_constant_def
    2602         1003 :                   || dt == vect_external_def)
    2603              :                 {
    2604           77 :                   vec<tree> ops;
    2605           77 :                   ops.create (group_size);
    2606          397 :                   for (lane = 0; lane < group_size; ++lane)
    2607          243 :                     if (stmts[lane])
    2608          243 :                       ops.quick_push (chains[lane][n].op);
    2609              :                     else
    2610            0 :                       ops.quick_push (NULL_TREE);
    2611           77 :                   slp_tree child = vect_create_new_slp_node (ops);
    2612           77 :                   SLP_TREE_DEF_TYPE (child) = dt;
    2613           77 :                   children.safe_push (child);
    2614              :                 }
    2615              :               else
    2616              :                 {
    2617          926 :                   vec<stmt_vec_info> op_stmts;
    2618          926 :                   op_stmts.create (group_size);
    2619          926 :                   slp_tree child = NULL;
    2620              :                   /* Brute-force our way.  We have to consider a lane
    2621              :                      failing after fixing an earlier fail up in the
    2622              :                      SLP discovery recursion.  So track the current
    2623              :                      permute per lane.  */
    2624          926 :                   unsigned *perms = XALLOCAVEC (unsigned, group_size);
    2625          926 :                   memset (perms, 0, sizeof (unsigned) * group_size);
    2626         1022 :                   do
    2627              :                     {
    2628         1022 :                       op_stmts.truncate (0);
    2629         4900 :                       for (lane = 0; lane < group_size; ++lane)
    2630         2856 :                         if (stmts[lane])
    2631         2856 :                           op_stmts.quick_push
    2632         2856 :                             (vinfo->lookup_def (chains[lane][n].op));
    2633              :                         else
    2634            0 :                           op_stmts.quick_push (NULL);
    2635         1022 :                       child = vect_build_slp_tree (vinfo, op_stmts,
    2636              :                                                    matches, limit,
    2637              :                                                    &this_tree_size, bst_map);
    2638              :                       /* ???  We're likely getting too many fatal mismatches
    2639              :                          here so maybe we want to ignore them (but then we
    2640              :                          have no idea which lanes fatally mismatched).  */
    2641              :                       /* ???  Revisit this with matches[] improvements.  */
    2642         1022 :                       if (child || matches[0] != 0)
    2643              :                         break;
    2644              :                       /* Swap another lane we have not yet matched up into
    2645              :                          lanes that did not match.  If we run out of
    2646              :                          permute possibilities for a lane terminate the
    2647              :                          search.  */
    2648          291 :                       bool term = false;
    2649          291 :                       for (lane = 1; lane < group_size; ++lane)
    2650          195 :                         if (matches[lane] != 0)
    2651              :                           {
    2652          167 :                             if (n + perms[lane] + 1 == chain_len)
    2653              :                               {
    2654              :                                 term = true;
    2655              :                                 break;
    2656              :                               }
    2657          148 :                             if (dump_enabled_p ())
    2658          115 :                               dump_printf_loc (MSG_NOTE, vect_location,
    2659              :                                                "swapping operand %d and %d "
    2660              :                                                "of lane %d\n",
    2661              :                                                n, n + perms[lane] + 1, lane);
    2662          296 :                             std::swap (chains[lane][n],
    2663          148 :                                        chains[lane][n + perms[lane] + 1]);
    2664          148 :                             perms[lane]++;
    2665              :                           }
    2666          115 :                       if (term)
    2667              :                         break;
    2668              :                     }
    2669              :                   while (1);
    2670          926 :                   if (!child)
    2671              :                     {
    2672           19 :                       if (dump_enabled_p ())
    2673           18 :                         dump_printf_loc (MSG_NOTE, vect_location,
    2674              :                                          "failed to match up op %d\n", n);
    2675           19 :                       op_stmts.release ();
    2676           19 :                       if (lane != group_size - 1)
    2677            9 :                         matches[0] = -1;
    2678              :                       else
    2679           10 :                         matches[lane] = -1;
    2680           19 :                       goto out;
    2681              :                     }
    2682          907 :                   if (dump_enabled_p ())
    2683              :                     {
    2684          409 :                       dump_printf_loc (MSG_NOTE, vect_location,
    2685              :                                        "matched up op %d to\n", n);
    2686          409 :                       vect_print_slp_tree (MSG_NOTE, vect_location, child);
    2687              :                     }
    2688          907 :                   children.safe_push (child);
    2689              :                 }
    2690              :             }
    2691              :           /* 3. build SLP nodes to combine the chain.  */
    2692         1102 :           for (unsigned lane = 0; lane < group_size; ++lane)
    2693         1608 :             if (stmts[lane] && chains[lane][0].code != code)
    2694              :               {
    2695              :                 /* See if there's any alternate all-PLUS entry.  */
    2696              :                 unsigned n;
    2697            6 :                 for (n = 1; n < chain_len; ++n)
    2698              :                   {
    2699           30 :                     for (lane = 0; lane < group_size; ++lane)
    2700           48 :                       if (stmts[lane] && chains[lane][n].code != code)
    2701              :                         break;
    2702            6 :                     if (lane == group_size)
    2703              :                       break;
    2704              :                   }
    2705            6 :                 if (n != chain_len)
    2706              :                   {
    2707              :                     /* Swap that in at first position.  */
    2708            6 :                     std::swap (children[0], children[n]);
    2709           30 :                     for (lane = 0; lane < group_size; ++lane)
    2710           24 :                       if (stmts[lane])
    2711           24 :                         std::swap (chains[lane][0], chains[lane][n]);
    2712              :                   }
    2713              :                 else
    2714              :                   {
    2715              :                     /* ???  When this triggers and we end up with two
    2716              :                        vect_constant/external_def up-front things break (ICE)
    2717              :                        spectacularly finding an insertion place for the
    2718              :                        all-constant op.  We should have a fully
    2719              :                        vect_internal_def operand though(?) so we can swap
    2720              :                        that into first place and then prepend the all-zero
    2721              :                        constant.  */
    2722            0 :                     if (dump_enabled_p ())
    2723            0 :                       dump_printf_loc (MSG_NOTE, vect_location,
    2724              :                                        "inserting constant zero to compensate "
    2725              :                                        "for (partially) negated first "
    2726              :                                        "operand\n");
    2727            0 :                     chain_len++;
    2728            0 :                     for (lane = 0; lane < group_size; ++lane)
    2729            0 :                       if (stmts[lane])
    2730            0 :                         chains[lane].safe_insert
    2731            0 :                           (0, chain_op_t (code, vect_constant_def, NULL_TREE));
    2732            0 :                     vec<tree> zero_ops;
    2733            0 :                     zero_ops.create (group_size);
    2734            0 :                     zero_ops.quick_push (build_zero_cst (TREE_TYPE (vectype)));
    2735            0 :                     for (lane = 1; lane < group_size; ++lane)
    2736            0 :                       if (stmts[lane])
    2737            0 :                         zero_ops.quick_push (zero_ops[0]);
    2738              :                       else
    2739            0 :                         zero_ops.quick_push (NULL_TREE);
    2740            0 :                     slp_tree zero = vect_create_new_slp_node (zero_ops);
    2741            0 :                     SLP_TREE_DEF_TYPE (zero) = vect_constant_def;
    2742            0 :                     children.safe_insert (0, zero);
    2743              :                   }
    2744              :                 break;
    2745              :               }
    2746          979 :           for (unsigned i = 1; i < children.length (); ++i)
    2747              :             {
    2748          675 :               slp_tree op0 = children[i - 1];
    2749          675 :               slp_tree op1 = children[i];
    2750          675 :               bool this_two_op = false;
    2751         2391 :               for (unsigned lane = 0; lane < group_size; ++lane)
    2752         3756 :                 if (stmts[lane] && chains[lane][i].code != chains[0][i].code)
    2753              :                   {
    2754              :                     this_two_op = true;
    2755              :                     break;
    2756              :                   }
    2757          675 :               slp_tree child;
    2758          675 :               if (i == children.length () - 1)
    2759          304 :                 child = vect_create_new_slp_node (node, stmts, 2);
    2760              :               else
    2761          371 :                 child = vect_create_new_slp_node (2, ERROR_MARK);
    2762          675 :               if (this_two_op)
    2763              :                 {
    2764          162 :                   vec<std::pair<unsigned, unsigned> > lperm;
    2765          162 :                   lperm.create (group_size);
    2766          744 :                   for (unsigned lane = 0; lane < group_size; ++lane)
    2767          840 :                     lperm.quick_push (std::make_pair
    2768          420 :                       (chains[lane][i].code != chains[0][i].code, lane));
    2769          324 :                   vect_slp_build_two_operator_nodes (child, vectype, op0, op1,
    2770          162 :                                                      (chains[0][i].code == code
    2771              :                                                       ? op_stmt_info
    2772              :                                                       : other_op_stmt_info),
    2773          162 :                                                      (chains[0][i].code == code
    2774              :                                                       ? other_op_stmt_info
    2775              :                                                       : op_stmt_info),
    2776              :                                                      lperm);
    2777              :                 }
    2778              :               else
    2779              :                 {
    2780          513 :                   SLP_TREE_DEF_TYPE (child) = vect_internal_def;
    2781          513 :                   SLP_TREE_VECTYPE (child) = vectype;
    2782          513 :                   SLP_TREE_LANES (child) = group_size;
    2783          513 :                   SLP_TREE_CHILDREN (child).quick_push (op0);
    2784          513 :                   SLP_TREE_CHILDREN (child).quick_push (op1);
    2785          513 :                   SLP_TREE_REPRESENTATIVE (child)
    2786         1026 :                     = (chains[0][i].code == code
    2787          513 :                        ? op_stmt_info : other_op_stmt_info);
    2788              :                 }
    2789          675 :               children[i] = child;
    2790              :             }
    2791          304 :           *tree_size += this_tree_size + 1;
    2792         1452 :           while (!chains.is_empty ())
    2793          822 :             chains.pop ().release ();
    2794              :           return node;
    2795              :         }
    2796        21430 : out:
    2797        21452 :       if (dump_enabled_p ())
    2798         2825 :         dump_printf_loc (MSG_NOTE, vect_location,
    2799              :                          "failed to line up SLP graph by re-associating "
    2800              :                          "operations in lanes%s\n",
    2801              :                          !hard_fail ? " trying regular discovery" : "");
    2802        21457 :       while (!children.is_empty ())
    2803            5 :         vect_free_slp_tree (children.pop ());
    2804        21613 :       while (!chains.is_empty ())
    2805          161 :         chains.pop ().release ();
    2806              :       /* Hard-fail, otherwise we might run into quadratic processing of the
    2807              :          chains starting one stmt into the chain again.  */
    2808        21452 :       if (hard_fail)
    2809              :         return NULL;
    2810              :       /* Fall thru to normal processing.  */
    2811        21756 :     }
    2812              : 
    2813              :   /* Get at the operands, verifying they are compatible.  */
    2814      3661727 :   vec<slp_oprnd_info> oprnds_info = vect_create_oprnd_info (nops, group_size);
    2815      3661727 :   slp_oprnd_info oprnd_info;
    2816     21034910 :   FOR_EACH_VEC_ELT (stmts, i, stmt_info)
    2817              :     {
    2818     27425540 :       int res = vect_get_and_check_slp_defs (vinfo, vectype,
    2819     13712770 :                                              swap[i], skip_args,
    2820              :                                              stmts, i, &oprnds_info,
    2821              :                                              soft_fail);
    2822     13712770 :       if (res != 0)
    2823              :         /* ???  This puts -1 back into matches[] and the cache.  */
    2824       340569 :         matches[(res == -1) ? 0 : i] = -1;
    2825     13712770 :       if (matches[0] == -1)
    2826              :         break;
    2827              :     }
    2828     16980417 :   for (i = 0; i < group_size; ++i)
    2829     13568847 :     if (matches[i] != 0)
    2830              :       {
    2831       250157 :         vect_free_oprnd_info (oprnds_info);
    2832       250157 :         return NULL;
    2833              :       }
    2834      3411570 :   swap = NULL;
    2835              : 
    2836              :   /* Perform delayed soft-failing only here so we can factor in mismatches
    2837              :      determined by vect_get_and_check_slp_defs.  */
    2838      3411570 :   if (soft_fail)
    2839              :     {
    2840       122617 :       force_split_matches (matches, group_size,
    2841       122617 :                            TYPE_VECTOR_SUBPARTS (vectype).to_constant ());
    2842       122617 :       return NULL;
    2843              :     }
    2844              : 
    2845      3288953 :   bool has_two_operators_perm = false;
    2846     16444765 :   auto_vec<unsigned> two_op_perm_indices[2];
    2847      3288953 :   vec<stmt_vec_info> two_op_scalar_stmts[2] = {vNULL, vNULL};
    2848              : 
    2849      3305185 :   if (two_operators && oprnds_info.length () == 2 && group_size > 2)
    2850              :     {
    2851         4016 :       unsigned idx = 0;
    2852         4016 :       hash_map<gimple *, unsigned> seen;
    2853         4016 :       vec<slp_oprnd_info> new_oprnds_info
    2854         4016 :         = vect_create_oprnd_info (1, group_size);
    2855         4016 :       bool success = true;
    2856              : 
    2857         4016 :       enum tree_code code = ERROR_MARK;
    2858         4016 :       if (oprnds_info[0]->def_stmts[0]
    2859         4016 :           && is_a<gassign *> (oprnds_info[0]->def_stmts[0]->stmt))
    2860         3956 :         code = gimple_assign_rhs_code (oprnds_info[0]->def_stmts[0]->stmt);
    2861         4016 :       basic_block bb = nullptr;
    2862              : 
    2863         7718 :       for (unsigned j = 0; j < group_size; ++j)
    2864              :         {
    2865        18000 :           FOR_EACH_VEC_ELT (oprnds_info, i, oprnd_info)
    2866              :             {
    2867        14298 :               stmt_vec_info stmt_info = oprnd_info->def_stmts[j];
    2868        14298 :               if (!stmt_info
    2869        14131 :                   || !is_a<gassign *> (stmt_info->stmt)
    2870        14131 :                   || gimple_assign_rhs_code (stmt_info->stmt) != code
    2871        25063 :                   || skip_args[i])
    2872              :                 {
    2873              :                   success = false;
    2874         3537 :                   break;
    2875              :                 }
    2876              :               /* Avoid mixing lanes with defs in different basic-blocks.  */
    2877        10765 :               if (!bb)
    2878         4152 :                 bb = gimple_bb (vect_orig_stmt (stmt_info)->stmt);
    2879         8547 :               else if (gimple_bb (vect_orig_stmt (stmt_info)->stmt) != bb)
    2880              :                 {
    2881              :                   success = false;
    2882              :                   break;
    2883              :                 }
    2884              : 
    2885        10761 :               bool exists;
    2886        10761 :               unsigned &stmt_idx
    2887        10761 :                 = seen.get_or_insert (stmt_info->stmt, &exists);
    2888              : 
    2889        10761 :               if (!exists)
    2890              :                 {
    2891         9380 :                   new_oprnds_info[0]->def_stmts.safe_push (stmt_info);
    2892         9380 :                   new_oprnds_info[0]->ops.safe_push (oprnd_info->ops[j]);
    2893         9380 :                   stmt_idx = idx;
    2894         9380 :                   idx++;
    2895              :                 }
    2896              : 
    2897        10761 :               two_op_perm_indices[i].safe_push (stmt_idx);
    2898              :             }
    2899              : 
    2900         7239 :           if (!success)
    2901              :             break;
    2902              :         }
    2903              : 
    2904         4016 :       if (success && idx == group_size)
    2905              :         {
    2906           98 :           if (dump_enabled_p ())
    2907              :             {
    2908            0 :               dump_printf_loc (MSG_NOTE, vect_location,
    2909              :                                "Replace two_operators operands:\n");
    2910              : 
    2911            0 :               FOR_EACH_VEC_ELT (oprnds_info, i, oprnd_info)
    2912              :                 {
    2913            0 :                   dump_printf_loc (MSG_NOTE, vect_location,
    2914              :                                    "Operand %u:\n", i);
    2915            0 :                   for (unsigned j = 0; j < group_size; j++)
    2916            0 :                     dump_printf_loc (MSG_NOTE, vect_location, "\tstmt %u %G",
    2917            0 :                                      j, oprnd_info->def_stmts[j]->stmt);
    2918              :                 }
    2919              : 
    2920            0 :               dump_printf_loc (MSG_NOTE, vect_location,
    2921              :                                "With a single operand:\n");
    2922            0 :               for (unsigned j = 0; j < group_size; j++)
    2923            0 :                 dump_printf_loc (MSG_NOTE, vect_location, "\tstmt %u %G",
    2924            0 :                                  j, new_oprnds_info[0]->def_stmts[j]->stmt);
    2925              :             }
    2926              : 
    2927           98 :           two_op_scalar_stmts[0].safe_splice (oprnds_info[0]->def_stmts);
    2928           98 :           two_op_scalar_stmts[1].safe_splice (oprnds_info[1]->def_stmts);
    2929              : 
    2930           98 :           new_oprnds_info[0]->first_op_type = oprnds_info[0]->first_op_type;
    2931           98 :           new_oprnds_info[0]->first_dt = oprnds_info[0]->first_dt;
    2932           98 :           new_oprnds_info[0]->any_pattern = oprnds_info[0]->any_pattern;
    2933           98 :           new_oprnds_info[0]->first_gs_p = oprnds_info[0]->first_gs_p;
    2934           98 :           new_oprnds_info[0]->first_gs_info = oprnds_info[0]->first_gs_info;
    2935              : 
    2936           98 :           vect_free_oprnd_info (oprnds_info);
    2937           98 :           oprnds_info = new_oprnds_info;
    2938           98 :           nops = 1;
    2939           98 :           has_two_operators_perm = true;
    2940              :         }
    2941              :       else
    2942         3918 :         vect_free_oprnd_info (new_oprnds_info);
    2943         4016 :     }
    2944              : 
    2945      6577906 :   auto_vec<slp_tree, 4> children;
    2946              : 
    2947      3288953 :   stmt_info = stmts[0];
    2948              : 
    2949      3288953 :   int reduc_idx = -1;
    2950      3288953 :   int gs_scale = 0;
    2951      3288953 :   tree gs_base = NULL_TREE;
    2952              : 
    2953              :   /* Create SLP_TREE nodes for the definition node/s.  */
    2954      8461556 :   FOR_EACH_VEC_ELT (oprnds_info, i, oprnd_info)
    2955              :     {
    2956      5284339 :       slp_tree child = nullptr;
    2957      5284339 :       unsigned int j;
    2958      5284339 :       unsigned old_swap_distance;
    2959      5284339 :       bool can_swap;
    2960      5284339 :       bool can_swap_nonmatching;
    2961      5284339 :       bool *stmt_can_swap;
    2962              : 
    2963              :       /* We're skipping certain operands from processing, for example
    2964              :          outer loop reduction initial defs.  */
    2965      5284339 :       if (skip_args[i])
    2966              :         {
    2967       514137 :           children.safe_push (NULL);
    2968      5172603 :           continue;
    2969              :         }
    2970              : 
    2971      4770202 :       if (oprnd_info->first_dt == vect_uninitialized_def)
    2972              :         {
    2973              :           /* COND_EXPR have one too many eventually if the condition
    2974              :              is a SSA name.  */
    2975            0 :           gcc_assert (i == 3 && nops == 4);
    2976            0 :           continue;
    2977              :         }
    2978              : 
    2979      4770202 :       if (oprnd_info->first_gs_p)
    2980              :         {
    2981        23523 :           gs_scale = oprnd_info->first_gs_info.scale;
    2982        23523 :           gs_base = oprnd_info->first_gs_info.base;
    2983              :         }
    2984              : 
    2985      4770202 :       if (is_a <bb_vec_info> (vinfo)
    2986      1694936 :           && oprnd_info->first_dt == vect_internal_def
    2987      5674490 :           && !oprnd_info->any_pattern)
    2988              :         {
    2989              :           /* For BB vectorization, if all defs are the same do not
    2990              :              bother to continue the build along the single-lane
    2991              :              graph but use a splat of the scalar value.  */
    2992       852461 :           stmt_vec_info first_def = oprnd_info->def_stmts[0];
    2993       920019 :           for (j = 1; j < group_size; ++j)
    2994       869481 :             if (oprnd_info->def_stmts[j] != first_def)
    2995              :               break;
    2996       852461 :           if (j == group_size
    2997              :               /* But avoid doing this for loads where we may be
    2998              :                  able to CSE things, unless the stmt is not
    2999              :                  vectorizable.  */
    3000       852461 :               && (!STMT_VINFO_VECTORIZABLE (first_def)
    3001        60644 :                   || !gimple_vuse (first_def->stmt)))
    3002              :             {
    3003        40924 :               if (dump_enabled_p ())
    3004          125 :                 dump_printf_loc (MSG_NOTE, vect_location,
    3005              :                                  "Using a splat of the uniform operand %G",
    3006              :                                  first_def->stmt);
    3007        40924 :               oprnd_info->first_dt = vect_external_def;
    3008              :             }
    3009              :         }
    3010              : 
    3011      4770202 :       if (oprnd_info->first_dt == vect_external_def
    3012      4770202 :           || oprnd_info->first_dt == vect_constant_def)
    3013              :         {
    3014      1573311 :           if (!GET_MODE_SIZE (vinfo->vector_mode).is_constant ())
    3015              :             {
    3016              :               tree op0;
    3017              :               tree uniform_val = op0 = oprnd_info->ops[0];
    3018              :               for (j = 1; j < oprnd_info->ops.length (); ++j)
    3019              :                 if (oprnd_info->ops[j]
    3020              :                     && !operand_equal_p (uniform_val, oprnd_info->ops[j]))
    3021              :                   {
    3022              :                     uniform_val = NULL_TREE;
    3023              :                     break;
    3024              :                   }
    3025              :               if (!uniform_val
    3026              :                   && !can_duplicate_and_interleave_p (vinfo,
    3027              :                                                       oprnd_info->ops.length (),
    3028              :                                                       TREE_TYPE (op0)))
    3029              :                 {
    3030              :                   matches[j] = -1;
    3031              :                   if (dump_enabled_p ())
    3032              :                     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    3033              :                                      "Build SLP failed: invalid type of def "
    3034              :                                      "for variable-length SLP %T\n", op0);
    3035              :                   goto fail;
    3036              :                 }
    3037              :             }
    3038      1573311 :           slp_tree invnode = vect_create_new_slp_node (oprnd_info->ops);
    3039      1573311 :           SLP_TREE_DEF_TYPE (invnode) = oprnd_info->first_dt;
    3040      1573311 :           oprnd_info->ops = vNULL;
    3041      1573311 :           children.safe_push (invnode);
    3042      1573311 :           continue;
    3043      1573311 :         }
    3044              : 
    3045              :       /* See which SLP operand a reduction chain continues on.  We want
    3046              :          to chain even PHIs but not backedges.  */
    3047      3196891 :       if (STMT_VINFO_REDUC_DEF (oprnd_info->def_stmts[0])
    3048      3196891 :           || STMT_VINFO_REDUC_IDX (oprnd_info->def_stmts[0]) != -1)
    3049              :         {
    3050       238277 :           if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle)
    3051              :             {
    3052          776 :               if (oprnd_info->first_dt == vect_double_reduction_def)
    3053          388 :                 reduc_idx = i;
    3054              :             }
    3055       237501 :           else if (is_a <gphi *> (stmt_info->stmt)
    3056       237501 :                    && gimple_phi_num_args
    3057       101951 :                         (as_a <gphi *> (stmt_info->stmt)) != 1)
    3058              :             ;
    3059       135943 :           else if (STMT_VINFO_REDUC_IDX (stmt_info) == -1
    3060          393 :                    && STMT_VINFO_DEF_TYPE (stmt_info) != vect_double_reduction_def)
    3061              :             ;
    3062       135943 :           else if (reduc_idx == -1)
    3063       127451 :             reduc_idx = i;
    3064              :           else
    3065              :             /* For .COND_* reduction operations the else value can be the
    3066              :                same as one of the operation operands.  The other def
    3067              :                stmts have been moved, so we can't check easily.  Check
    3068              :                it's a call at least.  */
    3069         8492 :             gcc_assert (is_a <gcall *> (stmt_info->stmt));
    3070              :         }
    3071              : 
    3072              :       /* When we have a masked load with uniform mask discover this
    3073              :          as a single-lane mask with a splat permute.  This way we can
    3074              :          recognize this as a masked load-lane by stripping the splat.  */
    3075      3196891 :       if (is_a <gcall *> (STMT_VINFO_STMT (stmt_info))
    3076        57187 :           && gimple_call_internal_p (STMT_VINFO_STMT (stmt_info),
    3077              :                                      IFN_MASK_LOAD)
    3078         4751 :           && STMT_VINFO_GROUPED_ACCESS (stmt_info)
    3079      3196968 :           && ! STMT_VINFO_SLP_VECT_ONLY (DR_GROUP_FIRST_ELEMENT (stmt_info)))
    3080              :         {
    3081           35 :           vec<stmt_vec_info> def_stmts2;
    3082           35 :           def_stmts2.create (1);
    3083           35 :           def_stmts2.quick_push (oprnd_info->def_stmts[0]);
    3084           35 :           child = vect_build_slp_tree (vinfo, def_stmts2,
    3085              :                                        matches, limit,
    3086              :                                        &this_tree_size, bst_map);
    3087           35 :           if (child)
    3088              :             {
    3089           35 :               slp_tree pnode = vect_create_new_slp_node (1, VEC_PERM_EXPR);
    3090           35 :               SLP_TREE_VECTYPE (pnode) = SLP_TREE_VECTYPE (child);
    3091           35 :               SLP_TREE_LANES (pnode) = group_size;
    3092           35 :               SLP_TREE_SCALAR_STMTS (pnode).create (group_size);
    3093           35 :               SLP_TREE_LANE_PERMUTATION (pnode).create (group_size);
    3094          245 :               for (unsigned k = 0; k < group_size; ++k)
    3095              :                 {
    3096          175 :                   SLP_TREE_SCALAR_STMTS (pnode)
    3097          175 :                     .quick_push (oprnd_info->def_stmts[0]);
    3098          175 :                   SLP_TREE_LANE_PERMUTATION (pnode)
    3099          175 :                     .quick_push (std::make_pair (0u, 0u));
    3100              :                 }
    3101           35 :               SLP_TREE_CHILDREN (pnode).quick_push (child);
    3102           35 :               children.safe_push (pnode);
    3103           35 :               oprnd_info->def_stmts = vNULL;
    3104           35 :               continue;
    3105           35 :             }
    3106              :           else
    3107            0 :             def_stmts2.release ();
    3108              :         }
    3109              : 
    3110      6393712 :       can_swap = (i == 0
    3111      2361444 :                   && (nops == 2 || nops == 3)
    3112      1530350 :                   && oprnds_info.length () > 1
    3113      1530350 :                   && oprnds_info[1]->first_dt == vect_internal_def
    3114       624038 :                   && (is_gimple_assign (stmt_info->stmt)
    3115        50974 :                       || is_gimple_call (stmt_info->stmt))
    3116              :                   /* Swapping operands for reductions breaks assumptions
    3117              :                      later on.  */
    3118      3774713 :                   && STMT_VINFO_REDUC_IDX (stmt_info) == -1);
    3119      3196856 :       can_swap_nonmatching = can_swap;
    3120      3196856 :       stmt_can_swap = NULL;
    3121      3196856 :       if (can_swap)
    3122              :         {
    3123       522085 :           stmt_can_swap = XALLOCAVEC (bool, group_size);
    3124      8198588 :           for (j = 0; j < group_size; ++j)
    3125              :             {
    3126      7676503 :               stmt_can_swap[j] = false;
    3127      7676503 :               if (!stmts[j])
    3128              :                 /* NULL lanes are gaps and have no stmt to swap.  */
    3129            0 :                 stmt_can_swap[j] = true;
    3130      7676503 :               else if (gassign *stmt = dyn_cast <gassign *> (stmts[j]->stmt))
    3131              :                 {
    3132      7671231 :                   tree_code code = gimple_assign_rhs_code (stmt);
    3133     15342462 :                   stmt_can_swap[j] = (commutative_tree_code (code)
    3134      7671231 :                                       || commutative_ternary_tree_code (code));
    3135              :                 }
    3136         5272 :               else if (gcall *call = dyn_cast <gcall *> (stmts[j]->stmt))
    3137              :                 {
    3138         5272 :                   internal_fn fn = (gimple_call_internal_p (call)
    3139         5272 :                                     ? gimple_call_internal_fn (call) : IFN_LAST);
    3140        10544 :                   stmt_can_swap[j] = ((commutative_binary_fn_p (fn)
    3141         4724 :                                        || commutative_ternary_fn_p (fn))
    3142         5308 :                                       && first_commutative_argument (fn) == 0);
    3143              :                 }
    3144              : 
    3145      7676503 :               if (j != 0 && !stmt_can_swap[j])
    3146      7676503 :                 can_swap_nonmatching = false;
    3147              :             }
    3148              :         }
    3149              : 
    3150      3196856 :       old_swap_distance = least_upthread_swappable_op_distance;
    3151      3196856 :       if (can_swap_nonmatching)
    3152       479777 :         least_upthread_swappable_op_distance = 1;
    3153      2717079 :       else if (least_upthread_swappable_op_distance != -1U)
    3154       349940 :         least_upthread_swappable_op_distance++;
    3155      3196856 :       child = vect_build_slp_tree (vinfo, oprnd_info->def_stmts,
    3156              :                                    matches, limit,
    3157              :                                    &this_tree_size, bst_map);
    3158      3196856 :       least_upthread_swappable_op_distance = old_swap_distance;
    3159      3196856 :       if (child != NULL)
    3160              :         {
    3161      2689703 :           oprnd_info->def_stmts = vNULL;
    3162      2689703 :           children.safe_push (child);
    3163      2689703 :           continue;
    3164              :         }
    3165              : 
    3166              :       /* If the SLP build for operand zero failed and operand zero
    3167              :          and one can be commuted try that for the scalar stmts
    3168              :          that failed the match.  */
    3169       507153 :       if (/* A first scalar stmt mismatch signals a fatal mismatch.  */
    3170       507153 :           matches[0] == 0
    3171       507153 :           && can_swap)
    3172              :         {
    3173              :           /* See whether we can swap the matching or the non-matching
    3174              :              stmt operands.  */
    3175              :           bool swap_not_matching = true;
    3176        74220 :           do
    3177              :             {
    3178      7114026 :               for (j = 0; j < group_size; ++j)
    3179              :                 {
    3180      7057902 :                   if ((matches[j] == 0) != !swap_not_matching)
    3181        88512 :                     continue;
    3182              :                   /* Verify if we can swap operands of this stmt.  */
    3183      6969390 :                   if (!stmt_can_swap[j])
    3184              :                     {
    3185        18096 :                       if (!swap_not_matching)
    3186         7966 :                         goto fail;
    3187              :                       swap_not_matching = false;
    3188              :                       break;
    3189              :                     }
    3190              :                 }
    3191              :             }
    3192        66254 :           while (j != group_size);
    3193              : 
    3194              :           /* Swap mismatched definition stmts.  */
    3195        56124 :           if (dump_enabled_p ())
    3196          425 :             dump_printf_loc (MSG_NOTE, vect_location,
    3197              :                              "Re-trying with swapped operands of stmts ");
    3198      7084743 :           for (j = 0; j < group_size; ++j)
    3199      7028619 :             if ((matches[j] == 0) == !swap_not_matching)
    3200              :               {
    3201     13902180 :                 std::swap (oprnds_info[0]->def_stmts[j],
    3202      6951090 :                            oprnds_info[1]->def_stmts[j]);
    3203     13902180 :                 std::swap (oprnds_info[0]->ops[j],
    3204      6951090 :                            oprnds_info[1]->ops[j]);
    3205      6951090 :                 if (dump_enabled_p ())
    3206         1096 :                   dump_printf (MSG_NOTE, "%d ", j);
    3207              :               }
    3208        56124 :           if (dump_enabled_p ())
    3209          425 :             dump_printf (MSG_NOTE, "\n");
    3210              :           /* After swapping some operands we lost track whether an
    3211              :              operand has any pattern defs so be conservative here.  */
    3212       109103 :           if (oprnds_info[0]->any_pattern || oprnds_info[1]->any_pattern)
    3213         4220 :             oprnds_info[0]->any_pattern = oprnds_info[1]->any_pattern = true;
    3214              :           /* And try again with scratch 'matches' ... */
    3215        56124 :           match_elt_t *tem = XALLOCAVEC (match_elt_t, group_size);
    3216        56124 :           if ((child = vect_build_slp_tree (vinfo, oprnd_info->def_stmts,
    3217              :                                             tem, limit,
    3218              :                                             &this_tree_size, bst_map)) != NULL)
    3219              :             {
    3220         7762 :               oprnd_info->def_stmts = vNULL;
    3221         7762 :               children.safe_push (child);
    3222         7762 :               continue;
    3223              :             }
    3224              :         }
    3225       499391 : fail:
    3226              : 
    3227              :       /* If the SLP build failed and we analyze a basic-block
    3228              :          simply treat nodes we fail to build as externally defined
    3229              :          (and thus build vectors from the scalar defs).
    3230              :          The cost model will reject outright expensive cases.
    3231              :          ???  This doesn't treat cases where permutation ultimatively
    3232              :          fails (or we don't try permutation below).  Ideally we'd
    3233              :          even compute a permutation that will end up with the maximum
    3234              :          SLP tree size...  */
    3235       499391 :       if (is_a <bb_vec_info> (vinfo)
    3236              :           /* ???  Rejecting patterns this way doesn't work.  We'd have to
    3237              :              do extra work to cancel the pattern so the uses see the
    3238              :              scalar version.  */
    3239              :           /* Skip building vector operands from scalars while operand
    3240              :              discovery may still be fixed by retrying with swapped operands.  */
    3241       440389 :           && (least_upthread_swappable_op_distance != 1
    3242              :               /* A first scalar stmt mismatch signals a fatal mismatch
    3243              :                  that the parent commutative retry cannot recover.
    3244              :                  ???  Possibly revisit this with the matches[] improvements
    3245              :                  as we can have matches[0] == -2 here.  */
    3246        27612 :               || matches[0] != 0)
    3247       421394 :           && !is_pattern_stmt_p (stmt_info)
    3248       893888 :           && !oprnd_info->any_pattern)
    3249              :         {
    3250              :           /* But if there's a leading vector sized set of matching stmts
    3251              :              fail here so we can split the group.  This matches the condition
    3252              :              vect_analyze_slp_instance uses.  */
    3253              :           /* ???  We might want to split here and combine the results to support
    3254              :              multiple vector sizes better.  */
    3255       611934 :           for (j = 0; j < group_size; ++j)
    3256       611934 :             if (matches[j] != 0)
    3257              :               break;
    3258       394131 :           if (!known_ge (j, TYPE_VECTOR_SUBPARTS (vectype))
    3259       394097 :               && vect_slp_can_convert_to_external (oprnd_info->def_stmts))
    3260              :             {
    3261       387655 :               if (dump_enabled_p ())
    3262          788 :                 dump_printf_loc (MSG_NOTE, vect_location,
    3263              :                                  "Building vector operands from scalars\n");
    3264       387655 :               this_tree_size++;
    3265       387655 :               child = vect_create_new_slp_node (oprnd_info->ops);
    3266       387655 :               children.safe_push (child);
    3267       387655 :               oprnd_info->ops = vNULL;
    3268       387655 :               continue;
    3269              :             }
    3270              :         }
    3271              : 
    3272       111736 :       gcc_assert (child == NULL);
    3273       243800 :       FOR_EACH_VEC_ELT (children, j, child)
    3274        20328 :         if (child)
    3275        20328 :           vect_free_slp_tree (child);
    3276       111736 :       vect_free_oprnd_info (oprnds_info);
    3277       111736 :       return NULL;
    3278              :     }
    3279              : 
    3280      3177217 :   vect_free_oprnd_info (oprnds_info);
    3281              : 
    3282              :   /* If we have all children of a child built up from uniform scalars
    3283              :      or does more than one possibly expensive vector construction then
    3284              :      just throw that away, causing it built up from scalars.
    3285              :      The exception is the SLP node for the vector store.  */
    3286      3177217 :   if (is_a <bb_vec_info> (vinfo)
    3287      1155187 :       && !STMT_VINFO_GROUPED_ACCESS (stmt_info)
    3288              :       /* ???  Rejecting patterns this way doesn't work.  We'd have to
    3289              :          do extra work to cancel the pattern so the uses see the
    3290              :          scalar version.  */
    3291      3657493 :       && !is_pattern_stmt_p (stmt_info))
    3292              :     {
    3293              :       slp_tree child;
    3294              :       unsigned j;
    3295              :       bool all_uniform_p = true;
    3296              :       unsigned n_vector_builds = 0;
    3297      1340792 :       FOR_EACH_VEC_ELT (children, j, child)
    3298              :         {
    3299       894020 :           if (!child)
    3300              :             ;
    3301       894020 :           else if (SLP_TREE_DEF_TYPE (child) == vect_internal_def)
    3302              :             all_uniform_p = false;
    3303       639112 :           else if (!vect_slp_tree_uniform_p (child))
    3304              :             {
    3305       483396 :               all_uniform_p = false;
    3306       483396 :               if (SLP_TREE_DEF_TYPE (child) == vect_external_def)
    3307       442792 :                 n_vector_builds++;
    3308              :             }
    3309              :         }
    3310       446772 :       if (all_uniform_p
    3311       446772 :           || n_vector_builds > 1
    3312       758926 :           || (n_vector_builds == children.length ()
    3313        35200 :               && is_a <gphi *> (stmt_info->stmt)))
    3314              :         {
    3315              :           /* Roll back.  */
    3316       139528 :           matches[0] = -1;
    3317       441950 :           FOR_EACH_VEC_ELT (children, j, child)
    3318       302422 :             if (child)
    3319       302422 :               vect_free_slp_tree (child);
    3320              : 
    3321       139528 :           if (dump_enabled_p ())
    3322          259 :             dump_printf_loc (MSG_NOTE, vect_location,
    3323              :                              "Building parent vector operands from "
    3324              :                              "scalars instead\n");
    3325      3288953 :           return NULL;
    3326              :         }
    3327              :     }
    3328              : 
    3329      3037689 :   *tree_size += this_tree_size + 1;
    3330              : 
    3331      3037689 :   if (two_operators)
    3332              :     {
    3333              :       /* ???  We'd likely want to either cache in bst_map sth like
    3334              :          { a+b, NULL, a+b, NULL } and { NULL, a-b, NULL, a-b } or
    3335              :          the true { a+b, a+b, a+b, a+b } ... but there we don't have
    3336              :          explicit stmts to put in so the keying on 'stmts' doesn't
    3337              :          work (but we have the same issue with nodes that use 'ops').  */
    3338              : 
    3339         7638 :       if (has_two_operators_perm)
    3340              :         {
    3341           46 :           slp_tree child = children[0];
    3342           46 :           children.truncate (0);
    3343          184 :           for (i = 0; i < 2; i++)
    3344              :             {
    3345           92 :               slp_tree pnode
    3346           92 :                 = vect_create_new_slp_node (two_op_scalar_stmts[i], 2);
    3347           92 :               SLP_TREE_CODE (pnode) = VEC_PERM_EXPR;
    3348           92 :               SLP_TREE_VECTYPE (pnode) = vectype;
    3349           92 :               SLP_TREE_CHILDREN (pnode).quick_push (child);
    3350           92 :               SLP_TREE_CHILDREN (pnode).quick_push (child);
    3351           92 :               SLP_TREE_REPRESENTATIVE (pnode) = NULL;
    3352           92 :               lane_permutation_t& perm = SLP_TREE_LANE_PERMUTATION (pnode);
    3353           92 :               children.safe_push (pnode);
    3354              : 
    3355          808 :               for (unsigned j = 0; j < stmts.length (); j++)
    3356          624 :                 perm.safe_push (std::make_pair (0, two_op_perm_indices[i][j]));
    3357              :             }
    3358              : 
    3359           46 :           SLP_TREE_REF_COUNT (child) += 4;
    3360              :         }
    3361              : 
    3362         7638 :       slp_tree one = new _slp_tree;
    3363         7638 :       slp_tree two = new _slp_tree;
    3364         7638 :       SLP_TREE_DEF_TYPE (one) = vect_internal_def;
    3365         7638 :       SLP_TREE_DEF_TYPE (two) = vect_internal_def;
    3366         7638 :       SLP_TREE_VECTYPE (one) = vectype;
    3367         7638 :       SLP_TREE_VECTYPE (two) = vectype;
    3368         7638 :       SLP_TREE_CHILDREN (one).safe_splice (children);
    3369         7638 :       SLP_TREE_CHILDREN (two).safe_splice (children);
    3370         7638 :       slp_tree child;
    3371        30554 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (two), i, child)
    3372        15278 :         SLP_TREE_REF_COUNT (child)++;
    3373              : 
    3374              :       /* Here we record the original defs since this
    3375              :          node represents the final lane configuration.  */
    3376         7638 :       node = vect_create_new_slp_node (node, stmts, 2);
    3377         7638 :       SLP_TREE_VECTYPE (node) = vectype;
    3378         7638 :       SLP_TREE_CODE (node) = VEC_PERM_EXPR;
    3379         7638 :       SLP_TREE_CHILDREN (node).quick_push (one);
    3380         7638 :       SLP_TREE_CHILDREN (node).quick_push (two);
    3381         7638 :       SLP_TREE_REPRESENTATIVE (node) = NULL;
    3382         7638 :       enum tree_code code0 = ERROR_MARK;
    3383         7638 :       enum tree_code ocode = ERROR_MARK;
    3384         7638 :       if (gassign *stmt = dyn_cast <gassign *> (stmts[0]->stmt))
    3385         7636 :         code0 = gimple_assign_rhs_code (stmt);
    3386         7638 :       stmt_vec_info ostmt_info;
    3387         7638 :       unsigned j = 0;
    3388        27309 :       FOR_EACH_VEC_ELT (stmts, i, ostmt_info)
    3389              :         {
    3390        19671 :           int op = 0;
    3391        19671 :           if (gassign *ostmt = dyn_cast <gassign *> (ostmt_info->stmt))
    3392              :             {
    3393        19667 :               if (gimple_assign_rhs_code (ostmt) != code0)
    3394              :                 {
    3395         9855 :                   ocode = gimple_assign_rhs_code (ostmt);
    3396              :                   op = 1;
    3397              :                   j = i;
    3398              :                 }
    3399              :             }
    3400              :           else
    3401              :             {
    3402            8 :               if (gimple_call_combined_fn (stmts[0]->stmt)
    3403            4 :                   != gimple_call_combined_fn (ostmt_info->stmt))
    3404              :                 {
    3405            2 :                   op = 1;
    3406            2 :                   j = i;
    3407              :                 }
    3408              :             }
    3409        19671 :           SLP_TREE_LANE_PERMUTATION (node).safe_push (std::make_pair (op, i));
    3410              :         }
    3411         7638 :       SLP_TREE_CODE (one) = code0;
    3412         7638 :       SLP_TREE_CODE (two) = ocode;
    3413         7638 :       SLP_TREE_LANES (one) = stmts.length ();
    3414         7638 :       SLP_TREE_LANES (two) = stmts.length ();
    3415         7638 :       SLP_TREE_REPRESENTATIVE (one) = stmts[0];
    3416         7638 :       SLP_TREE_REPRESENTATIVE (two) = stmts[j];
    3417              : 
    3418         7638 :       return node;
    3419              :     }
    3420              : 
    3421      3030051 :   node = vect_create_new_slp_node (node, stmts, nops);
    3422      3030051 :   SLP_TREE_VECTYPE (node) = vectype;
    3423      3030051 :   SLP_TREE_CHILDREN (node).splice (children);
    3424      3030051 :   SLP_TREE_GS_SCALE (node) = gs_scale;
    3425      3030051 :   SLP_TREE_GS_BASE (node) = gs_base;
    3426      3030051 :   if (reduc_idx != -1)
    3427              :     {
    3428       119310 :       gcc_assert (STMT_VINFO_REDUC_IDX (stmt_info) != -1
    3429              :                   || STMT_VINFO_DEF_TYPE (stmt_info) == vect_nested_cycle
    3430              :                   || STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def);
    3431       119310 :       SLP_TREE_REDUC_IDX (node) = reduc_idx;
    3432       119310 :       node->cycle_info.id = SLP_TREE_CHILDREN (node)[reduc_idx]->cycle_info.id;
    3433              :     }
    3434              :   /* When reaching the reduction PHI, create a vect_reduc_info.  */
    3435      2910741 :   else if ((STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def
    3436      2910741 :             || STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    3437      2910741 :            && is_a <gphi *> (STMT_VINFO_STMT (stmt_info)))
    3438              :     {
    3439       103974 :       loop_vec_info loop_vinfo = as_a <loop_vec_info> (vinfo);
    3440       103974 :       gcc_assert (STMT_VINFO_REDUC_IDX (stmt_info) == -1);
    3441       103974 :       node->cycle_info.id = loop_vinfo->reduc_infos.length ();
    3442       103974 :       vect_reduc_info reduc_info = new vect_reduc_info_s ();
    3443       103974 :       loop_vinfo->reduc_infos.safe_push (reduc_info);
    3444       103974 :       stmt_vec_info reduc_phi = stmt_info;
    3445              :       /* ???  For double reductions vect_is_simple_reduction stores the
    3446              :          reduction type and code on the inner loop header PHI.  */
    3447       103974 :       if (STMT_VINFO_DEF_TYPE (stmt_info) == vect_double_reduction_def)
    3448              :         {
    3449          388 :           use_operand_p use_p;
    3450          388 :           gimple *use_stmt;
    3451          388 :           bool res = single_imm_use (gimple_phi_result (stmt_info->stmt),
    3452              :                                      &use_p, &use_stmt);
    3453          388 :           gcc_assert (res);
    3454          388 :           reduc_phi = loop_vinfo->lookup_stmt (use_stmt);
    3455              :         }
    3456       103974 :       VECT_REDUC_INFO_DEF_TYPE (reduc_info) = STMT_VINFO_DEF_TYPE (stmt_info);
    3457       103974 :       VECT_REDUC_INFO_TYPE (reduc_info) = STMT_VINFO_REDUC_TYPE (reduc_phi);
    3458       103974 :       VECT_REDUC_INFO_CODE (reduc_info) = STMT_VINFO_REDUC_CODE (reduc_phi);
    3459       103974 :       VECT_REDUC_INFO_FN (reduc_info) = IFN_LAST;
    3460              :     }
    3461              :   return node;
    3462      9866859 : }
    3463              : 
    3464              : /* Dump a single SLP tree NODE.  */
    3465              : 
    3466              : static void
    3467       467515 : vect_print_slp_tree (dump_flags_t dump_kind, dump_location_t loc,
    3468              :                      slp_tree node)
    3469              : {
    3470       467515 :   unsigned i, j;
    3471       467515 :   slp_tree child;
    3472       467515 :   stmt_vec_info stmt_info;
    3473       467515 :   tree op;
    3474              : 
    3475       467515 :   dump_metadata_t metadata (dump_kind, loc.get_impl_location ());
    3476       467515 :   dump_user_location_t user_loc = loc.get_user_location ();
    3477       467515 :   dump_printf_loc (metadata, user_loc,
    3478              :                    "node%s %p (refcnt=%u)",
    3479       467515 :                    SLP_TREE_DEF_TYPE (node) == vect_external_def
    3480              :                    ? " (external)"
    3481              :                    : (SLP_TREE_DEF_TYPE (node) == vect_constant_def
    3482       450829 :                       ? " (constant)"
    3483              :                       : ""), (void *) node,
    3484              :                    SLP_TREE_REF_COUNT (node));
    3485       467515 :   if (SLP_TREE_VECTYPE (node))
    3486       395546 :     dump_printf (metadata, " %T", SLP_TREE_VECTYPE (node));
    3487       467515 :   dump_printf (metadata, "%s",
    3488       467515 :                node->avoid_stlf_fail ? " (avoid-stlf-fail)" : "");
    3489       467515 :   if (node->cycle_info.id != -1 || node->cycle_info.reduc_idx != -1)
    3490        24505 :     dump_printf (metadata, " cycle %d, link %d", node->cycle_info.id,
    3491              :                  node->cycle_info.reduc_idx);
    3492       467515 :   if (node->si)
    3493         5334 :     dump_printf (metadata, " @%G", node->si);
    3494              :   else
    3495       462181 :     dump_printf (metadata, "\n");
    3496       467515 :   if (SLP_TREE_DEF_TYPE (node) == vect_internal_def)
    3497              :     {
    3498       379963 :       if (SLP_TREE_PERMUTE_P (node))
    3499        17301 :         dump_printf_loc (metadata, user_loc, "op: VEC_PERM_EXPR\n");
    3500              :       else
    3501       362662 :         dump_printf_loc (metadata, user_loc, "op template: %G",
    3502       362662 :                          SLP_TREE_REPRESENTATIVE (node)->stmt);
    3503              :     }
    3504       467515 :   if (SLP_TREE_SCALAR_STMTS (node).exists ())
    3505       912996 :     FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
    3506       542071 :       if (stmt_info)
    3507       535949 :         dump_printf_loc (metadata, user_loc, "\t%sstmt %u %G",
    3508       535949 :                          SLP_TREE_LIVE_LANES (node).contains (i)
    3509       532202 :                          ? "[l*]" : (STMT_VINFO_LIVE_P (stmt_info)
    3510       532202 :                                      ? "[l] " : ""),
    3511              :                          i, stmt_info->stmt);
    3512              :       else
    3513         6122 :         dump_printf_loc (metadata, user_loc, "\tstmt %u ---\n", i);
    3514              :   else
    3515              :     {
    3516        96590 :       dump_printf_loc (metadata, user_loc, "\t{ ");
    3517       214040 :       FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_OPS (node), i, op)
    3518       117450 :         dump_printf (metadata, "%T%s ", op,
    3519       117450 :                      i < SLP_TREE_SCALAR_OPS (node).length () - 1 ? "," : "");
    3520        96590 :       dump_printf (metadata, "}\n");
    3521              :     }
    3522       467515 :   if (SLP_TREE_LOAD_PERMUTATION (node).exists ())
    3523              :     {
    3524        67026 :       dump_printf_loc (metadata, user_loc, "\tload permutation {");
    3525       153193 :       FOR_EACH_VEC_ELT (SLP_TREE_LOAD_PERMUTATION (node), i, j)
    3526        86167 :         dump_printf (dump_kind, " %u", j);
    3527        67026 :       dump_printf (dump_kind, " }\n");
    3528              :     }
    3529       467515 :   if (SLP_TREE_LANE_PERMUTATION (node).exists ())
    3530              :     {
    3531        17309 :       dump_printf_loc (metadata, user_loc, "\tlane permutation {");
    3532        64824 :       for (i = 0; i < SLP_TREE_LANE_PERMUTATION (node).length (); ++i)
    3533        47515 :         dump_printf (dump_kind, " %u[%u]",
    3534        47515 :                      SLP_TREE_LANE_PERMUTATION (node)[i].first,
    3535        47515 :                      SLP_TREE_LANE_PERMUTATION (node)[i].second);
    3536        17309 :       dump_printf (dump_kind, " }%s\n",
    3537        17309 :                    node->ldst_lanes ? " (load-lanes)" : "");
    3538              :     }
    3539       467515 :   if (SLP_TREE_CHILDREN (node).is_empty ())
    3540       177139 :     return;
    3541       290376 :   dump_printf_loc (metadata, user_loc, "\tchildren");
    3542       766157 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
    3543       475781 :     dump_printf (dump_kind, " %p", (void *)child);
    3544       290376 :   dump_printf (dump_kind, "%s\n",
    3545       290376 :                node->ldst_lanes && !SLP_TREE_LANE_PERMUTATION (node).exists ()
    3546              :                ? " (store-lanes)" : "");
    3547              : }
    3548              : 
    3549              : DEBUG_FUNCTION void
    3550            0 : debug (slp_tree node)
    3551              : {
    3552            0 :   debug_dump_context ctx;
    3553            0 :   vect_print_slp_tree (MSG_NOTE,
    3554            0 :                        dump_location_t::from_location_t (UNKNOWN_LOCATION),
    3555              :                        node);
    3556            0 : }
    3557              : 
    3558              : /* Recursive helper for the dot producer below.  */
    3559              : 
    3560              : static void
    3561            0 : dot_slp_tree (FILE *f, slp_tree node, hash_set<slp_tree> &visited)
    3562              : {
    3563            0 :   if (visited.add (node))
    3564              :     return;
    3565              : 
    3566            0 :   fprintf (f, "\"%p\" [label=\"", (void *)node);
    3567            0 :   vect_print_slp_tree (MSG_NOTE,
    3568            0 :                        dump_location_t::from_location_t (UNKNOWN_LOCATION),
    3569              :                        node);
    3570            0 :   fprintf (f, "\"];\n");
    3571              : 
    3572              : 
    3573            0 :   for (slp_tree child : SLP_TREE_CHILDREN (node))
    3574            0 :     fprintf (f, "\"%p\" -> \"%p\";", (void *)node, (void *)child);
    3575              : 
    3576            0 :   for (slp_tree child : SLP_TREE_CHILDREN (node))
    3577            0 :     if (child)
    3578            0 :       dot_slp_tree (f, child, visited);
    3579              : }
    3580              : 
    3581              : DEBUG_FUNCTION void
    3582            0 : dot_slp_tree (const char *fname, slp_tree node)
    3583              : {
    3584            0 :   FILE *f = fopen (fname, "w");
    3585            0 :   fprintf (f, "digraph {\n");
    3586            0 :   fflush (f);
    3587            0 :     {
    3588            0 :       debug_dump_context ctx (f);
    3589            0 :       hash_set<slp_tree> visited;
    3590            0 :       dot_slp_tree (f, node, visited);
    3591            0 :     }
    3592            0 :   fflush (f);
    3593            0 :   fprintf (f, "}\n");
    3594            0 :   fclose (f);
    3595            0 : }
    3596              : 
    3597              : DEBUG_FUNCTION void
    3598            0 : dot_slp_tree (const char *fname, const vec<slp_instance> &slp_instances)
    3599              : {
    3600            0 :   FILE *f = fopen (fname, "w");
    3601            0 :   fprintf (f, "digraph {\n");
    3602            0 :   fflush (f);
    3603            0 :     {
    3604            0 :       debug_dump_context ctx (f);
    3605            0 :       hash_set<slp_tree> visited;
    3606            0 :       for (auto inst : slp_instances)
    3607            0 :         dot_slp_tree (f, SLP_INSTANCE_TREE (inst), visited);
    3608            0 :     }
    3609            0 :   fflush (f);
    3610            0 :   fprintf (f, "}\n");
    3611            0 :   fclose (f);
    3612            0 : }
    3613              : 
    3614              : /* Dump a slp tree NODE using flags specified in DUMP_KIND.  */
    3615              : 
    3616              : static void
    3617       504734 : vect_print_slp_graph (dump_flags_t dump_kind, dump_location_t loc,
    3618              :                       slp_tree node, hash_set<slp_tree> &visited)
    3619              : {
    3620       504734 :   unsigned i;
    3621       504734 :   slp_tree child;
    3622              : 
    3623       504734 :   if (visited.add (node))
    3624       504734 :     return;
    3625              : 
    3626       463684 :   vect_print_slp_tree (dump_kind, loc, node);
    3627              : 
    3628      1398020 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
    3629       470652 :     if (child)
    3630       426537 :       vect_print_slp_graph (dump_kind, loc, child, visited);
    3631              : }
    3632              : 
    3633              : static void
    3634        47942 : vect_print_slp_graph (dump_flags_t dump_kind, dump_location_t loc,
    3635              :                       slp_tree entry)
    3636              : {
    3637        47942 :   hash_set<slp_tree> visited;
    3638        47942 :   vect_print_slp_graph (dump_kind, loc, entry, visited);
    3639        47942 : }
    3640              : 
    3641              : DEBUG_FUNCTION void
    3642            0 : debug (slp_instance instance)
    3643              : {
    3644            0 :   debug_dump_context ctx;
    3645            0 :   vect_print_slp_graph (MSG_NOTE,
    3646            0 :                         dump_location_t::from_location_t (UNKNOWN_LOCATION),
    3647              :                         SLP_INSTANCE_TREE (instance));
    3648            0 : }
    3649              : 
    3650              : 
    3651              : /* Compute the set of scalar stmts participating in external nodes.  */
    3652              : 
    3653              : static void
    3654      1699413 : vect_slp_gather_extern_scalar_stmts (vec_info *vinfo, slp_tree node,
    3655              :                                      hash_set<slp_tree> &visited,
    3656              :                                      hash_set<stmt_vec_info> &estmts)
    3657              : {
    3658      1699413 :   if (visited.add (node))
    3659              :     return;
    3660              : 
    3661      1638705 :   if (SLP_TREE_DEF_TYPE (node) == vect_internal_def)
    3662              :     {
    3663              :       slp_tree child;
    3664              :       int i;
    3665      1921298 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
    3666       981903 :         if (child)
    3667       981903 :           vect_slp_gather_extern_scalar_stmts (vinfo, child, visited, estmts);
    3668              :     }
    3669              :   else
    3670      3915070 :     for (tree def : SLP_TREE_SCALAR_OPS (node))
    3671              :       {
    3672      1819178 :         stmt_vec_info def_stmt = vinfo->lookup_def (def);
    3673      1819178 :         if (def_stmt)
    3674       387629 :           estmts.add (def_stmt);
    3675              :       }
    3676              : }
    3677              : 
    3678              : /* Mark the original scalar stmt coverage of the vector SLP graph of VINFO
    3679              :    with STMT_SLP_TYPE == pure_slp.  */
    3680              : 
    3681              : static void
    3682       247322 : vect_bb_slp_mark_stmts_vectorized (bb_vec_info vinfo)
    3683              : {
    3684              :   /* Gather the scalar stmt leafs of the SLP graph to stop the below DFS
    3685              :      walk on.  */
    3686       247322 :   hash_set<stmt_vec_info> scalar_stmts_in_externs;
    3687       247322 :   hash_set<slp_tree> visited;
    3688      1459476 :   for (auto instance : BB_VINFO_SLP_INSTANCES (vinfo))
    3689       717510 :     vect_slp_gather_extern_scalar_stmts (vinfo, SLP_INSTANCE_TREE (instance),
    3690              :                                          visited, scalar_stmts_in_externs);
    3691              : 
    3692              :   /* DFS walk scalar stmts to compute the vectorized coverage indicated
    3693              :      by STMT_SLP_TYPE (stmt) == pure_slp on the original scalar (non-pattern)
    3694              :      stmts.  */
    3695      1459476 :   for (auto instance : BB_VINFO_SLP_INSTANCES (vinfo))
    3696              :     {
    3697       910497 :       for (auto stmt : SLP_INSTANCE_ROOT_STMTS (instance))
    3698        89203 :         if (!scalar_stmts_in_externs.contains (stmt))
    3699        87955 :           STMT_SLP_TYPE (stmt) = pure_slp;
    3700       717510 :       auto_vec<stmt_vec_info> worklist;
    3701      4044342 :       for (auto stmt : SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance)))
    3702              :         {
    3703      1891812 :           stmt = vect_orig_stmt (stmt);
    3704      1891812 :           if (!scalar_stmts_in_externs.contains (stmt)
    3705      1891812 :               && STMT_SLP_TYPE (stmt) != pure_slp)
    3706              :             {
    3707      1874966 :               STMT_SLP_TYPE (stmt) = pure_slp;
    3708      1874966 :               worklist.safe_push (stmt);
    3709              :             }
    3710              :         }
    3711      3773746 :       while (!worklist.is_empty ())
    3712              :         {
    3713      2343573 :           stmt_vec_info stmt = worklist.pop ();
    3714              : 
    3715              :           /* Now walk relevant parts of the SSA use-def graph.  */
    3716      2343573 :           slp_oprnds child_ops (stmt);
    3717      7309441 :           for (unsigned i = 0; i < child_ops.num_slp_children; ++i)
    3718              :             {
    3719      2622295 :               tree op = child_ops.get_op_for_slp_child (stmt, i);
    3720      2622295 :               stmt_vec_info def = vinfo->lookup_def (op);
    3721      2622295 :               if (def
    3722       939401 :                   && !scalar_stmts_in_externs.contains (def)
    3723      3185796 :                   && STMT_SLP_TYPE (def) != pure_slp)
    3724              :                 {
    3725       468607 :                   STMT_SLP_TYPE (def) = pure_slp;
    3726       468607 :                   worklist.safe_push (def);
    3727              :                 }
    3728              :             }
    3729              :         }
    3730       717510 :     }
    3731       247322 : }
    3732              : 
    3733              : /* Mark the statements of the tree rooted at NODE as relevant (vect_used).  */
    3734              : 
    3735              : static void
    3736      2604824 : vect_mark_slp_stmts_relevant (slp_tree node, hash_set<slp_tree> &visited)
    3737              : {
    3738      2604824 :   if (SLP_TREE_DEF_TYPE (node) != vect_internal_def)
    3739              :     return;
    3740              : 
    3741      1565256 :   if (visited.add (node))
    3742              :     return;
    3743              : 
    3744      7299955 :   for (auto stmt_info : SLP_TREE_SCALAR_STMTS (node))
    3745      3259728 :     if (stmt_info)
    3746              :       {
    3747      3259728 :         gcc_assert (!STMT_VINFO_RELEVANT (stmt_info)
    3748              :                     || STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_scope);
    3749      3259728 :         STMT_VINFO_RELEVANT (stmt_info) = vect_used_in_scope;
    3750              :       }
    3751              : 
    3752      5666895 :   for (auto child: SLP_TREE_CHILDREN (node))
    3753      1782944 :     if (child)
    3754      1782944 :       vect_mark_slp_stmts_relevant (child, visited);
    3755              : }
    3756              : 
    3757              : static void
    3758       821880 : vect_mark_slp_stmts_relevant (slp_tree node)
    3759              : {
    3760       821880 :   hash_set<slp_tree> visited;
    3761       821880 :   vect_mark_slp_stmts_relevant (node, visited);
    3762       821880 : }
    3763              : 
    3764              : 
    3765              : /* Gather loads in the SLP graph NODE and populate the INST loads array.  */
    3766              : 
    3767              : static void
    3768     11170807 : vect_gather_slp_loads (vec<slp_tree> &loads, slp_tree node,
    3769              :                        hash_set<slp_tree> &visited)
    3770              : {
    3771     11170807 :   if (!node || visited.add (node))
    3772              :     return;
    3773              : 
    3774      9340826 :   if (SLP_TREE_DEF_TYPE (node) != vect_internal_def)
    3775              :     return;
    3776              : 
    3777      6907044 :   if (!SLP_TREE_PERMUTE_P (node))
    3778              :     {
    3779      6692327 :       stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (node);
    3780      6692327 :       if (STMT_VINFO_DATA_REF (stmt_info)
    3781      2870662 :           && DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
    3782      1637301 :         loads.safe_push (node);
    3783              :     }
    3784              : 
    3785      6907044 :   unsigned i;
    3786      6907044 :   slp_tree child;
    3787     15743397 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
    3788      8836353 :     vect_gather_slp_loads (loads, child, visited);
    3789              : }
    3790              : 
    3791              : 
    3792              : /* Find the last store in SLP INSTANCE.  */
    3793              : 
    3794              : stmt_vec_info
    3795      2565388 : vect_find_last_scalar_stmt_in_slp (slp_tree node)
    3796              : {
    3797      2565388 :   stmt_vec_info last = NULL;
    3798     14515890 :   for (auto stmt_vinfo : SLP_TREE_SCALAR_STMTS (node))
    3799      6819726 :     if (stmt_vinfo)
    3800              :       {
    3801      6819726 :         stmt_vinfo = vect_orig_stmt (stmt_vinfo);
    3802      6819726 :         last = last ? get_later_stmt (stmt_vinfo, last) : stmt_vinfo;
    3803              :       }
    3804              : 
    3805      2565388 :   return last;
    3806              : }
    3807              : 
    3808              : /* Find the first stmt in NODE.  */
    3809              : 
    3810              : stmt_vec_info
    3811       684581 : vect_find_first_scalar_stmt_in_slp (slp_tree node)
    3812              : {
    3813       684581 :   stmt_vec_info first = NULL;
    3814              : 
    3815      3708828 :   for (auto stmt_vinfo : SLP_TREE_SCALAR_STMTS (node))
    3816      1655085 :     if (stmt_vinfo)
    3817              :       {
    3818      1652377 :         stmt_vinfo = vect_orig_stmt (stmt_vinfo);
    3819      1652377 :         if (!first
    3820      1652377 :             || get_later_stmt (stmt_vinfo, first) == first)
    3821              :           first = stmt_vinfo;
    3822              :       }
    3823              : 
    3824       684581 :   return first;
    3825              : }
    3826              : 
    3827              : /* Splits a group of stores, currently beginning at FIRST_VINFO, into
    3828              :    two groups: one (still beginning at FIRST_VINFO) of size GROUP1_SIZE
    3829              :    (also containing the first GROUP1_SIZE stmts, since stores are
    3830              :    consecutive), the second containing the remainder.
    3831              :    Return the first stmt in the second group.  */
    3832              : 
    3833              : static stmt_vec_info
    3834       136724 : vect_split_slp_store_group (stmt_vec_info first_vinfo, unsigned group1_size)
    3835              : {
    3836       136724 :   gcc_assert (DR_GROUP_FIRST_ELEMENT (first_vinfo) == first_vinfo);
    3837       136724 :   gcc_assert (group1_size > 0);
    3838       136724 :   int group2_size = DR_GROUP_SIZE (first_vinfo) - group1_size;
    3839       136724 :   gcc_assert (group2_size > 0);
    3840       136724 :   DR_GROUP_SIZE (first_vinfo) = group1_size;
    3841              : 
    3842       136724 :   stmt_vec_info stmt_info = first_vinfo;
    3843       459101 :   for (unsigned i = group1_size; i > 1; i--)
    3844              :     {
    3845       322377 :       stmt_info = DR_GROUP_NEXT_ELEMENT (stmt_info);
    3846       322377 :       gcc_assert (DR_GROUP_GAP (stmt_info) == 1);
    3847              :     }
    3848              :   /* STMT is now the last element of the first group.  */
    3849       136724 :   stmt_vec_info group2 = DR_GROUP_NEXT_ELEMENT (stmt_info);
    3850       136724 :   DR_GROUP_NEXT_ELEMENT (stmt_info) = 0;
    3851              : 
    3852       136724 :   DR_GROUP_SIZE (group2) = group2_size;
    3853       406615 :   for (stmt_info = group2; stmt_info;
    3854       269891 :        stmt_info = DR_GROUP_NEXT_ELEMENT (stmt_info))
    3855              :     {
    3856       269891 :       DR_GROUP_FIRST_ELEMENT (stmt_info) = group2;
    3857       269891 :       gcc_assert (DR_GROUP_GAP (stmt_info) == 1);
    3858              :     }
    3859              : 
    3860              :   /* For the second group, the DR_GROUP_GAP is that before the original group,
    3861              :      plus skipping over the first vector.  */
    3862       136724 :   DR_GROUP_GAP (group2) = DR_GROUP_GAP (first_vinfo) + group1_size;
    3863              : 
    3864              :   /* DR_GROUP_GAP of the first group now has to skip over the second group too.  */
    3865       136724 :   DR_GROUP_GAP (first_vinfo) += group2_size;
    3866              : 
    3867       136724 :   if (dump_enabled_p ())
    3868           85 :     dump_printf_loc (MSG_NOTE, vect_location, "Split group into %d and %d\n",
    3869              :                      group1_size, group2_size);
    3870              : 
    3871       136724 :   return group2;
    3872              : }
    3873              : 
    3874              : /* Calculate the unrolling factor for an SLP instance with GROUP_SIZE
    3875              :    statements and a vector of NUNITS elements.  */
    3876              : 
    3877              : static poly_uint64
    3878      2869511 : calculate_unrolling_factor (poly_uint64 nunits, unsigned int group_size)
    3879              : {
    3880      2869511 :   return exact_div (common_multiple (nunits, group_size), group_size);
    3881              : }
    3882              : 
    3883              : /* Helper that checks to see if a node is a load node.  */
    3884              : 
    3885              : static inline bool
    3886          103 : vect_is_slp_load_node  (slp_tree root)
    3887              : {
    3888          103 :   return (!SLP_TREE_PERMUTE_P (root)
    3889          103 :           && SLP_TREE_DEF_TYPE (root) == vect_internal_def
    3890           97 :           && STMT_VINFO_GROUPED_ACCESS (SLP_TREE_REPRESENTATIVE (root))
    3891          167 :           && DR_IS_READ (STMT_VINFO_DATA_REF (SLP_TREE_REPRESENTATIVE (root))));
    3892              : }
    3893              : 
    3894              : 
    3895              : /* Helper function of optimize_load_redistribution that performs the operation
    3896              :    recursively.  */
    3897              : 
    3898              : static slp_tree
    3899        21801 : optimize_load_redistribution_1 (scalar_stmts_to_slp_tree_map_t *bst_map,
    3900              :                                 vec_info *vinfo, unsigned int group_size,
    3901              :                                 hash_map<slp_tree, slp_tree> *load_map,
    3902              :                                 slp_tree root)
    3903              : {
    3904        21801 :   if (slp_tree *leader = load_map->get (root))
    3905         4549 :     return *leader;
    3906              : 
    3907        17252 :   slp_tree node;
    3908        17252 :   unsigned i;
    3909              : 
    3910              :   /* For now, we don't know anything about externals so do not do anything.  */
    3911        17252 :   if (!root || SLP_TREE_DEF_TYPE (root) != vect_internal_def)
    3912              :     return NULL;
    3913        12116 :   else if (SLP_TREE_PERMUTE_P (root))
    3914              :     {
    3915              :       /* First convert this node into a load node and add it to the leaves
    3916              :          list and flatten the permute from a lane to a load one.  If it's
    3917              :          unneeded it will be elided later.  */
    3918           71 :       vec<stmt_vec_info> stmts;
    3919           71 :       stmts.create (SLP_TREE_LANES (root));
    3920           71 :       lane_permutation_t lane_perm = SLP_TREE_LANE_PERMUTATION (root);
    3921          135 :       for (unsigned j = 0; j < lane_perm.length (); j++)
    3922              :         {
    3923          103 :           std::pair<unsigned, unsigned> perm = lane_perm[j];
    3924          103 :           node = SLP_TREE_CHILDREN (root)[perm.first];
    3925              : 
    3926          103 :           if (!vect_is_slp_load_node (node)
    3927          103 :               || SLP_TREE_CHILDREN (node).exists ())
    3928              :             {
    3929           39 :               stmts.release ();
    3930           39 :               goto next;
    3931              :             }
    3932              : 
    3933           64 :           stmts.quick_push (SLP_TREE_SCALAR_STMTS (node)[perm.second]);
    3934              :         }
    3935              : 
    3936           32 :       if (dump_enabled_p ())
    3937            0 :         dump_printf_loc (MSG_NOTE, vect_location,
    3938              :                          "converting stmts on permute node %p\n",
    3939              :                          (void *) root);
    3940              : 
    3941           32 :       match_elt_t *matches = XALLOCAVEC (match_elt_t, group_size);
    3942           32 :       unsigned tree_size = 0, limit = 1;
    3943           32 :       node = vect_build_slp_tree (vinfo, stmts,
    3944              :                                   matches, &limit, &tree_size, bst_map);
    3945           32 :       if (!node)
    3946            0 :         stmts.release ();
    3947              : 
    3948           32 :       load_map->put (root, node);
    3949           32 :       return node;
    3950              :     }
    3951              : 
    3952        12045 : next:
    3953        12084 :   load_map->put (root, NULL);
    3954              : 
    3955        27523 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (root), i , node)
    3956              :     {
    3957        15439 :       slp_tree value
    3958        15439 :         = optimize_load_redistribution_1 (bst_map, vinfo, group_size, load_map,
    3959              :                                           node);
    3960        15439 :       if (value)
    3961              :         {
    3962           32 :           SLP_TREE_REF_COUNT (value)++;
    3963           32 :           SLP_TREE_CHILDREN (root)[i] = value;
    3964              :           /* ???  We know the original leafs of the replaced nodes will
    3965              :              be referenced by bst_map, only the permutes created by
    3966              :              pattern matching are not.  */
    3967           32 :           if (SLP_TREE_REF_COUNT (node) == 1)
    3968           32 :             load_map->remove (node);
    3969           32 :           vect_free_slp_tree (node);
    3970              :         }
    3971              :     }
    3972              : 
    3973              :   return NULL;
    3974              : }
    3975              : 
    3976              : /* Temporary workaround for loads not being CSEd during SLP build.  This
    3977              :    function will traverse the SLP tree rooted in ROOT for INSTANCE and find
    3978              :    VEC_PERM nodes that blend vectors from multiple nodes that all read from the
    3979              :    same DR such that the final operation is equal to a permuted load.  Such
    3980              :    NODES are then directly converted into LOADS themselves.  The nodes are
    3981              :    CSEd using BST_MAP.  */
    3982              : 
    3983              : static void
    3984         4180 : optimize_load_redistribution (scalar_stmts_to_slp_tree_map_t *bst_map,
    3985              :                               vec_info *vinfo, unsigned int group_size,
    3986              :                               hash_map<slp_tree, slp_tree> *load_map,
    3987              :                               slp_tree root)
    3988              : {
    3989         4180 :   slp_tree node;
    3990         4180 :   unsigned i;
    3991              : 
    3992        10542 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (root), i , node)
    3993              :     {
    3994         6362 :       slp_tree value
    3995         6362 :         = optimize_load_redistribution_1 (bst_map, vinfo, group_size, load_map,
    3996              :                                           node);
    3997         6362 :       if (value)
    3998              :         {
    3999            0 :           SLP_TREE_REF_COUNT (value)++;
    4000            0 :           SLP_TREE_CHILDREN (root)[i] = value;
    4001              :           /* ???  We know the original leafs of the replaced nodes will
    4002              :              be referenced by bst_map, only the permutes created by
    4003              :              pattern matching are not.  */
    4004            0 :           if (SLP_TREE_REF_COUNT (node) == 1)
    4005            0 :             load_map->remove (node);
    4006            0 :           vect_free_slp_tree (node);
    4007              :         }
    4008              :     }
    4009         4180 : }
    4010              : 
    4011              : /* Helper function of vect_match_slp_patterns.
    4012              : 
    4013              :    Attempts to match patterns against the slp tree rooted in REF_NODE using
    4014              :    VINFO.  Patterns are matched in post-order traversal.
    4015              : 
    4016              :    If matching is successful the value in REF_NODE is updated and returned, if
    4017              :    not then it is returned unchanged.  */
    4018              : 
    4019              : static bool
    4020      6486159 : vect_match_slp_patterns_2 (slp_tree *ref_node, vec_info *vinfo,
    4021              :                            slp_tree_to_load_perm_map_t *perm_cache,
    4022              :                            slp_compat_nodes_map_t *compat_cache,
    4023              :                            hash_set<slp_tree> *visited)
    4024              : {
    4025      6486159 :   unsigned i;
    4026      6486159 :   slp_tree node = *ref_node;
    4027      6486159 :   bool found_p = false;
    4028      6486159 :   if (!node || visited->add (node))
    4029              :     return false;
    4030              : 
    4031              :   slp_tree child;
    4032     10417232 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
    4033      4857006 :     found_p |= vect_match_slp_patterns_2 (&SLP_TREE_CHILDREN (node)[i],
    4034              :                                           vinfo, perm_cache, compat_cache,
    4035              :                                           visited);
    4036              : 
    4037     16680678 :   for (unsigned x = 0; x < num__slp_patterns; x++)
    4038              :     {
    4039     11120452 :       vect_pattern *pattern
    4040     11120452 :         = slp_patterns[x] (perm_cache, compat_cache, ref_node);
    4041     11120452 :       if (pattern)
    4042              :         {
    4043         1114 :           pattern->build (vinfo);
    4044         1114 :           delete pattern;
    4045              :           found_p = true;
    4046              :         }
    4047              :     }
    4048              : 
    4049              :   return found_p;
    4050              : }
    4051              : 
    4052              : /* Applies pattern matching to the given SLP tree rooted in REF_NODE using
    4053              :    vec_info VINFO.
    4054              : 
    4055              :    The modified tree is returned.  Patterns are tried in order and multiple
    4056              :    patterns may match.  */
    4057              : 
    4058              : static bool
    4059      1629153 : vect_match_slp_patterns (slp_instance instance, vec_info *vinfo,
    4060              :                          hash_set<slp_tree> *visited,
    4061              :                          slp_tree_to_load_perm_map_t *perm_cache,
    4062              :                          slp_compat_nodes_map_t *compat_cache)
    4063              : {
    4064      1629153 :   DUMP_VECT_SCOPE ("vect_match_slp_patterns");
    4065      1629153 :   slp_tree *ref_node = &SLP_INSTANCE_TREE (instance);
    4066              : 
    4067      1629153 :   if (dump_enabled_p ())
    4068        31606 :     dump_printf_loc (MSG_NOTE, vect_location,
    4069              :                      "Analyzing SLP tree %p for patterns\n",
    4070        31606 :                      (void *) SLP_INSTANCE_TREE (instance));
    4071              : 
    4072      1629153 :   return vect_match_slp_patterns_2 (ref_node, vinfo, perm_cache, compat_cache,
    4073      1629153 :                                     visited);
    4074              : }
    4075              : 
    4076              : /* STMT_INFO is a store group of size GROUP_SIZE that we are considering
    4077              :    vectorizing with VECTYPE that might be NULL.  MASKED_P indicates whether
    4078              :    the stores are masked.
    4079              :    Return true if we could use IFN_STORE_LANES instead and if that appears
    4080              :    to be the better approach.  */
    4081              : 
    4082              : static bool
    4083         6160 : vect_slp_prefer_store_lanes_p (vec_info *vinfo, stmt_vec_info stmt_info,
    4084              :                                tree vectype, bool masked_p,
    4085              :                                unsigned int group_size,
    4086              :                                unsigned int new_group_size)
    4087              : {
    4088         6160 :   if (!vectype)
    4089              :     {
    4090         6160 :       tree scalar_type = TREE_TYPE (DR_REF (STMT_VINFO_DATA_REF (stmt_info)));
    4091         6160 :       vectype = get_vectype_for_scalar_type (vinfo, scalar_type);
    4092              :     }
    4093         6160 :   if (!vectype)
    4094              :     return false;
    4095              :   /* Allow the split if one of the two new groups would operate on full
    4096              :      vectors *within* rather than across one scalar loop iteration.
    4097              :      This is purely a heuristic, but it should work well for group
    4098              :      sizes of 3 and 4, where the possible splits are:
    4099              : 
    4100              :        3->2+1:  OK if the vector has exactly two elements
    4101              :        4->2+2:  Likewise
    4102              :        4->3+1:  Less clear-cut.  */
    4103         6160 :   if (multiple_p (group_size - new_group_size, TYPE_VECTOR_SUBPARTS (vectype))
    4104         6160 :       || multiple_p (new_group_size, TYPE_VECTOR_SUBPARTS (vectype)))
    4105              :     return false;
    4106         3482 :   return vect_store_lanes_supported (vectype, group_size, masked_p) != IFN_LAST;
    4107              : }
    4108              : 
    4109              : /* Analyze an SLP instance starting from a group of grouped stores.  Call
    4110              :    vect_build_slp_tree to build a tree of packed stmts if possible.
    4111              :    Return FALSE if it's impossible to SLP any stmt in the loop.  */
    4112              : 
    4113              : static bool
    4114              : vect_analyze_slp_instance (vec_info *vinfo,
    4115              :                            scalar_stmts_to_slp_tree_map_t *bst_map,
    4116              :                            stmt_vec_info stmt_info, slp_instance_kind kind,
    4117              :                            unsigned max_tree_size, unsigned *limit,
    4118              :                            bool force_single_lane);
    4119              : 
    4120              : /* Build an interleaving scheme for the store sources RHS_NODES from
    4121              :    SCALAR_STMTS.  */
    4122              : 
    4123              : static slp_tree
    4124         8263 : vect_build_slp_store_interleaving (vec<slp_tree> &rhs_nodes,
    4125              :                                    vec<stmt_vec_info> &scalar_stmts)
    4126              : {
    4127         8263 :   unsigned int group_size = scalar_stmts.length ();
    4128        16526 :   slp_tree node = vect_create_new_slp_node (scalar_stmts,
    4129         8263 :                                             SLP_TREE_CHILDREN
    4130              :                                               (rhs_nodes[0]).length ());
    4131         8263 :   SLP_TREE_VECTYPE (node) = SLP_TREE_VECTYPE (rhs_nodes[0]);
    4132         8263 :   for (unsigned l = 0;
    4133        16553 :        l < SLP_TREE_CHILDREN (rhs_nodes[0]).length (); ++l)
    4134              :     {
    4135              :       /* And a permute merging all RHS SLP trees.  */
    4136         8290 :       slp_tree perm = vect_create_new_slp_node (rhs_nodes.length (),
    4137         8290 :                                                 VEC_PERM_EXPR);
    4138         8290 :       SLP_TREE_CHILDREN (node).quick_push (perm);
    4139         8290 :       SLP_TREE_LANE_PERMUTATION (perm).create (group_size);
    4140         8290 :       SLP_TREE_VECTYPE (perm) = SLP_TREE_VECTYPE (node);
    4141         8290 :       SLP_TREE_LANES (perm) = group_size;
    4142         8290 :       SLP_TREE_REPRESENTATIVE (perm) = NULL;
    4143        64852 :       for (unsigned j = 0; j < rhs_nodes.length (); ++j)
    4144              :         {
    4145        24136 :           SLP_TREE_CHILDREN (perm)
    4146        24136 :             .quick_push (SLP_TREE_CHILDREN (rhs_nodes[j])[l]);
    4147        24136 :           SLP_TREE_CHILDREN (rhs_nodes[j])[l]->refcnt++;
    4148        24136 :           for (unsigned k = 0;
    4149        50645 :                k < SLP_TREE_LANES (rhs_nodes[j]); ++k)
    4150              :             {
    4151              :               /* ???  We should populate SLP_TREE_SCALAR_STMTS
    4152              :                  or SLP_TREE_SCALAR_OPS but then we might have
    4153              :                  a mix of both in our children.  */
    4154        26509 :               SLP_TREE_LANE_PERMUTATION (perm)
    4155        26509 :                 .quick_push (std::make_pair (j, k));
    4156              :             }
    4157              :         }
    4158              : 
    4159              :       /* Now we have a single permute node but we cannot code-generate
    4160              :          the case with more than two inputs.
    4161              :          Perform pairwise reduction, reducing the two inputs
    4162              :          with the least number of lanes to one and then repeat until
    4163              :          we end up with two inputs.  That scheme makes sure we end
    4164              :          up with permutes satisfying the restriction of requiring at
    4165              :          most two vector inputs to produce a single vector output
    4166              :          when the number of lanes is even.  */
    4167        15846 :       while (SLP_TREE_CHILDREN (perm).length () > 2)
    4168              :         {
    4169              :           /* When we have three equal sized groups left the pairwise
    4170              :              reduction does not result in a scheme that avoids using
    4171              :              three vectors.  Instead merge the first two groups
    4172              :              to the final size with do-not-care elements (chosen
    4173              :              from the first group) and then merge with the third.
    4174              :                   { A0, B0,  x, A1, B1,  x, ... }
    4175              :                -> { A0, B0, C0, A1, B1, C1, ... }
    4176              :              This handles group size of three (and at least
    4177              :              power-of-two multiples of that).  */
    4178         7556 :           if (SLP_TREE_CHILDREN (perm).length () == 3
    4179         3400 :               && (SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[0])
    4180         3400 :                   == SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[1]))
    4181         7556 :               && (SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[0])
    4182         2519 :                   == SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[2])))
    4183              :             {
    4184         2213 :               int ai = 0;
    4185         2213 :               int bi = 1;
    4186         2213 :               slp_tree a = SLP_TREE_CHILDREN (perm)[ai];
    4187         2213 :               slp_tree b = SLP_TREE_CHILDREN (perm)[bi];
    4188         2213 :               unsigned n = SLP_TREE_LANES (perm);
    4189              : 
    4190         2213 :               slp_tree permab = vect_create_new_slp_node (2, VEC_PERM_EXPR);
    4191         2213 :               SLP_TREE_LANES (permab) = n;
    4192         2213 :               SLP_TREE_LANE_PERMUTATION (permab).create (n);
    4193         2213 :               SLP_TREE_VECTYPE (permab) = SLP_TREE_VECTYPE (perm);
    4194              :               /* ???  Should be NULL but that's not expected.  */
    4195         2213 :               SLP_TREE_REPRESENTATIVE (permab) = SLP_TREE_REPRESENTATIVE (perm);
    4196         2213 :               SLP_TREE_CHILDREN (permab).quick_push (a);
    4197         6653 :               for (unsigned k = 0; k < SLP_TREE_LANES (a); ++k)
    4198         2227 :                 SLP_TREE_LANE_PERMUTATION (permab)
    4199         2227 :                   .quick_push (std::make_pair (0, k));
    4200         2213 :               SLP_TREE_CHILDREN (permab).quick_push (b);
    4201         6653 :               for (unsigned k = 0; k < SLP_TREE_LANES (b); ++k)
    4202         2227 :                 SLP_TREE_LANE_PERMUTATION (permab)
    4203         2227 :                   .quick_push (std::make_pair (1, k));
    4204              :               /* Push the do-not-care lanes.  */
    4205         4440 :               for (unsigned k = 0; k < SLP_TREE_LANES (a); ++k)
    4206         2227 :                 SLP_TREE_LANE_PERMUTATION (permab)
    4207         2227 :                   .quick_push (std::make_pair (0, k));
    4208              : 
    4209              :               /* Put the merged node into 'perm', in place of a.  */
    4210         2213 :               SLP_TREE_CHILDREN (perm)[ai] = permab;
    4211              :               /* Adjust the references to b in the permutation
    4212              :                  of perm and to the later children which we'll
    4213              :                  remove.  */
    4214         8894 :               for (unsigned k = 0; k < SLP_TREE_LANES (perm); ++k)
    4215              :                 {
    4216         6681 :                   std::pair<unsigned, unsigned> &p
    4217         6681 :                     = SLP_TREE_LANE_PERMUTATION (perm)[k];
    4218         6681 :                   if (p.first == (unsigned) bi)
    4219              :                     {
    4220         2227 :                       p.first = ai;
    4221         2227 :                       p.second += SLP_TREE_LANES (a);
    4222              :                     }
    4223         4454 :                   else if (p.first > (unsigned) bi)
    4224         2227 :                     p.first--;
    4225              :                 }
    4226         2213 :               SLP_TREE_CHILDREN (perm).ordered_remove (bi);
    4227         2213 :               break;
    4228              :             }
    4229              : 
    4230              :           /* Pick the two nodes with the least number of lanes,
    4231              :              prefer the earliest candidate and maintain ai < bi.  */
    4232              :           int ai = -1;
    4233              :           int bi = -1;
    4234        50446 :           for (unsigned ci = 0; ci < SLP_TREE_CHILDREN (perm).length (); ++ci)
    4235              :             {
    4236        45103 :               if (ai == -1)
    4237         5343 :                 ai = ci;
    4238        39760 :               else if (bi == -1)
    4239         5343 :                 bi = ci;
    4240        34417 :               else if ((SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[ci])
    4241        34417 :                         < SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[ai]))
    4242        34417 :                        || (SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[ci])
    4243        28593 :                            < SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[bi])))
    4244              :                 {
    4245        12538 :                   if (SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[ai])
    4246         6269 :                       <= SLP_TREE_LANES (SLP_TREE_CHILDREN (perm)[bi]))
    4247         2892 :                     bi = ci;
    4248              :                   else
    4249              :                     {
    4250         3377 :                       ai = bi;
    4251         3377 :                       bi = ci;
    4252              :                     }
    4253              :                 }
    4254              :             }
    4255              : 
    4256              :           /* Produce a merge of nodes ai and bi.  */
    4257         5343 :           slp_tree a = SLP_TREE_CHILDREN (perm)[ai];
    4258         5343 :           slp_tree b = SLP_TREE_CHILDREN (perm)[bi];
    4259         5343 :           unsigned n = SLP_TREE_LANES (a) + SLP_TREE_LANES (b);
    4260         5343 :           slp_tree permab = vect_create_new_slp_node (2, VEC_PERM_EXPR);
    4261         5343 :           SLP_TREE_LANES (permab) = n;
    4262         5343 :           SLP_TREE_LANE_PERMUTATION (permab).create (n);
    4263         5343 :           SLP_TREE_VECTYPE (permab) = SLP_TREE_VECTYPE (perm);
    4264              :           /* ???  Should be NULL but that's not expected.  */
    4265         5343 :           SLP_TREE_REPRESENTATIVE (permab) = SLP_TREE_REPRESENTATIVE (perm);
    4266         5343 :           SLP_TREE_CHILDREN (permab).quick_push (a);
    4267        19553 :           for (unsigned k = 0; k < SLP_TREE_LANES (a); ++k)
    4268         8867 :             SLP_TREE_LANE_PERMUTATION (permab)
    4269         8867 :               .quick_push (std::make_pair (0, k));
    4270         5343 :           SLP_TREE_CHILDREN (permab).quick_push (b);
    4271        18829 :           for (unsigned k = 0; k < SLP_TREE_LANES (b); ++k)
    4272         8143 :             SLP_TREE_LANE_PERMUTATION (permab)
    4273         8143 :               .quick_push (std::make_pair (1, k));
    4274              : 
    4275              :           /* Put the merged node into 'perm', in place of a.  */
    4276         5343 :           SLP_TREE_CHILDREN (perm)[ai] = permab;
    4277              :           /* Adjust the references to b in the permutation
    4278              :              of perm and to the later children which we'll
    4279              :              remove.  */
    4280        81265 :           for (unsigned k = 0; k < SLP_TREE_LANES (perm); ++k)
    4281              :             {
    4282        75922 :               std::pair<unsigned, unsigned> &p
    4283        75922 :                 = SLP_TREE_LANE_PERMUTATION (perm)[k];
    4284        75922 :               if (p.first == (unsigned) bi)
    4285              :                 {
    4286         8143 :                   p.first = ai;
    4287         8143 :                   p.second += SLP_TREE_LANES (a);
    4288              :                 }
    4289        67779 :               else if (p.first > (unsigned) bi)
    4290        28686 :                 p.first--;
    4291              :             }
    4292         5343 :           SLP_TREE_CHILDREN (perm).ordered_remove (bi);
    4293              :         }
    4294              :     }
    4295              : 
    4296         8263 :   return node;
    4297              : }
    4298              : 
    4299              : /* Analyze an SLP instance starting from SCALAR_STMTS which are a group
    4300              :    of KIND.  Return true if successful.  SCALAR_STMTS is owned by this
    4301              :    function, REMAIN and ROOT_STMT_INFOS ownership is transferred back to
    4302              :    the caller upon failure.  */
    4303              : 
    4304              : static bool
    4305      2045723 : vect_build_slp_instance (vec_info *vinfo,
    4306              :                          slp_instance_kind kind,
    4307              :                          vec<stmt_vec_info> &scalar_stmts,
    4308              :                          vec<stmt_vec_info> &root_stmt_infos,
    4309              :                          vec<tree> &remain,
    4310              :                          unsigned max_tree_size, unsigned *limit,
    4311              :                          scalar_stmts_to_slp_tree_map_t *bst_map,
    4312              :                          bool force_single_lane)
    4313              : {
    4314              :   /* If there's no budget left bail out early.  */
    4315      2045723 :   if (*limit == 0)
    4316              :     {
    4317        15992 :       scalar_stmts.release ();
    4318        15992 :       return false;
    4319              :     }
    4320              : 
    4321      2029731 :   if (kind == slp_inst_kind_ctor)
    4322              :     {
    4323        14484 :       if (dump_enabled_p ())
    4324           98 :         dump_printf_loc (MSG_NOTE, vect_location,
    4325              :                          "Analyzing vectorizable constructor: %G\n",
    4326           49 :                          root_stmt_infos[0]->stmt);
    4327              :     }
    4328      2015247 :   else if (kind == slp_inst_kind_gcond)
    4329              :     {
    4330       293399 :       if (dump_enabled_p ())
    4331         5864 :         dump_printf_loc (MSG_NOTE, vect_location,
    4332              :                          "Analyzing vectorizable control flow: %G",
    4333         2932 :                          root_stmt_infos[0]->stmt);
    4334              :     }
    4335      1721848 :   else if (kind == slp_inst_kind_bb_reduc)
    4336              :     {
    4337      1331567 :       if (dump_enabled_p ())
    4338         7434 :         dump_printf_loc (MSG_NOTE, vect_location,
    4339              :                          "Analyzing vectorizable BB reduction: %G",
    4340         3717 :                          root_stmt_infos[0]->stmt);
    4341              :     }
    4342              : 
    4343      2029731 :   if (dump_enabled_p ())
    4344              :     {
    4345        26653 :       dump_printf_loc (MSG_NOTE, vect_location,
    4346              :                        "Starting SLP discovery for\n");
    4347        57723 :       for (unsigned i = 0; i < scalar_stmts.length (); ++i)
    4348        62140 :         dump_printf_loc (MSG_NOTE, vect_location,
    4349        31070 :                          "  %G", scalar_stmts[i]->stmt);
    4350              :     }
    4351              : 
    4352              :   /* Build the tree for the SLP instance.  */
    4353      2029731 :   unsigned int group_size = scalar_stmts.length ();
    4354      2029731 :   match_elt_t *matches = XALLOCAVEC (match_elt_t, group_size);
    4355      2029731 :   unsigned tree_size = 0;
    4356              : 
    4357      2029731 :   slp_tree node = NULL;
    4358      2029731 :   if (group_size > 1 && force_single_lane)
    4359              :     {
    4360            0 :       matches[0] = 0;
    4361            0 :       matches[1] = -1;
    4362              :     }
    4363              :   else
    4364      2029731 :     node = vect_build_slp_tree (vinfo, scalar_stmts, matches, limit,
    4365              :                                 &tree_size, bst_map);
    4366      2029731 :   if (node != NULL)
    4367              :     {
    4368              :       /* Create a new SLP instance.  */
    4369       824906 :       slp_instance new_instance = XNEW (class _slp_instance);
    4370       824906 :       SLP_INSTANCE_TREE (new_instance) = node;
    4371       824906 :       SLP_INSTANCE_LOADS (new_instance) = vNULL;
    4372       824906 :       SLP_INSTANCE_ROOT_STMTS (new_instance) = root_stmt_infos;
    4373       824906 :       SLP_INSTANCE_REMAIN_DEFS (new_instance) = remain;
    4374       824906 :       SLP_INSTANCE_KIND (new_instance) = kind;
    4375       824906 :       new_instance->reduc_phis = NULL;
    4376       824906 :       new_instance->cost_vec = vNULL;
    4377       824906 :       new_instance->subgraph_entries = vNULL;
    4378              : 
    4379       824906 :       if (dump_enabled_p ())
    4380        23359 :         dump_printf_loc (MSG_NOTE, vect_location,
    4381              :                          "SLP size %u vs. limit %u.\n",
    4382              :                          tree_size, max_tree_size);
    4383              : 
    4384       824906 :       vinfo->slp_instances.safe_push (new_instance);
    4385              : 
    4386              :       /* ???  We've replaced the old SLP_INSTANCE_GROUP_SIZE with
    4387              :          the number of SLP lanes of the root in a few places.
    4388              :          Verify that assumption holds.  */
    4389       824906 :       gcc_assert (SLP_TREE_LANES (SLP_INSTANCE_TREE (new_instance))
    4390              :                   == group_size);
    4391              : 
    4392       824906 :       if (dump_enabled_p ())
    4393              :         {
    4394        23359 :           if (kind == slp_inst_kind_reduc_group)
    4395         1488 :             dump_printf_loc (MSG_NOTE, vect_location,
    4396              :                              "SLP discovery of size %d reduction group "
    4397              :                              "succeeded\n", group_size);
    4398        23359 :           dump_printf_loc (MSG_NOTE, vect_location,
    4399              :                            "Final SLP tree for instance %p:\n",
    4400              :                            (void *) new_instance);
    4401        23359 :           vect_print_slp_graph (MSG_NOTE, vect_location,
    4402              :                                 SLP_INSTANCE_TREE (new_instance));
    4403              :         }
    4404              : 
    4405       824906 :       return true;
    4406              :     }
    4407              :   /* Failed to SLP.  */
    4408              : 
    4409              :   /* While we arrive here even with slp_inst_kind_store we should only
    4410              :      for group_size == 1.  The code to split store groups is only in
    4411              :      vect_analyze_slp_instance now.  */
    4412      1204825 :   gcc_assert (kind != slp_inst_kind_store || group_size == 1);
    4413              : 
    4414              :   /* For BB vectorization we get failures only in case of the need of
    4415              :      unrolling, as otherwise we'll simply get operands built from scalars.
    4416              :      Iff there is any mismatches in the toplevel stmts those will prevail,
    4417              :      otherwise we get the non-power-of-two tail of the lanes failed.
    4418              :      For BB reductions we mainly want to catch the first case so we pick
    4419              :      a more useful subset of lanes to reduce.  Pick the largest matching
    4420              :      subset of that covers half of the group or more.  */
    4421      1204825 :   if (kind == slp_inst_kind_bb_reduc && matches[0] != -1)
    4422              :     {
    4423       667783 :       unsigned *n_matching = XALLOCAVEC (unsigned, group_size);
    4424       667783 :       memset (n_matching, 0, sizeof (unsigned) * group_size);
    4425      2174660 :       for (unsigned i = 0; i < group_size; ++i)
    4426      1506877 :         if (matches[i] != -2 && matches[i] != -1)
    4427      1270738 :           n_matching[matches[i].v]++;
    4428              :       unsigned largest_i = 0;
    4429      1506877 :       for (unsigned i = 1; i < group_size; ++i)
    4430       839094 :         if (n_matching[i] > n_matching[largest_i])
    4431        62226 :           largest_i = i;
    4432              :       /* Pick the largest matching part and put the rest to remain.  */
    4433       667783 :       if (n_matching[largest_i] >= 2
    4434        50428 :           && n_matching[largest_i] >= group_size / 2)
    4435              :         {
    4436              :           /* As we know the matches[] stmts match up, recursing for
    4437              :              non-power-of-two sizes will just force-fail the tail
    4438              :              for us at hopefully optimal vector size and succesfully
    4439              :              finish discovery.  */
    4440        49030 :           vec<stmt_vec_info> scalar_stmts2;
    4441        49030 :           scalar_stmts2.create (n_matching[largest_i]);
    4442       301730 :           for (unsigned i = 0; i < group_size; ++i)
    4443       203670 :             if (matches[i] == (int)largest_i)
    4444       142403 :               scalar_stmts2.quick_push (scalar_stmts[i]);
    4445              :             else
    4446        61267 :               remain.safe_push
    4447        64916 :                 (gimple_get_lhs (vect_orig_stmt (scalar_stmts[i])->stmt));
    4448        49030 :           if (dump_enabled_p ())
    4449          220 :             dump_printf_loc (MSG_NOTE, vect_location, "Splitting %d "
    4450              :                              "non-matching lanes to scalar remains\n",
    4451          220 :                              scalar_stmts.length () - scalar_stmts2.length ());
    4452        49030 :           scalar_stmts.release ();
    4453        49030 :           return vect_build_slp_instance (vinfo, kind, scalar_stmts2,
    4454              :                                           root_stmt_infos, remain,
    4455              :                                           max_tree_size, limit, bst_map,
    4456              :                                           force_single_lane);
    4457              :         }
    4458              :     }
    4459              : 
    4460              :   /* Free the allocated memory.  */
    4461      1155795 :   scalar_stmts.release ();
    4462              : 
    4463              :   /* Failed to SLP.  */
    4464      1155795 :   if (dump_enabled_p ())
    4465         3184 :     dump_printf_loc (MSG_NOTE, vect_location, "SLP discovery failed\n");
    4466              :   return false;
    4467              : }
    4468              : 
    4469              : /* Analyze an SLP instance starting from a the start of a reduction chain.
    4470              :    Call vect_build_slp_tree to build a tree of packed stmts if possible.
    4471              :    Return FALSE if SLP build fails.  */
    4472              : 
    4473              : static bool
    4474        73463 : vect_analyze_slp_reduc_chain (loop_vec_info vinfo,
    4475              :                               scalar_stmts_to_slp_tree_map_t *bst_map,
    4476              :                               stmt_vec_info scalar_stmt,
    4477              :                               unsigned max_tree_size, unsigned *limit)
    4478              : {
    4479        73463 :   vec<stmt_vec_info> scalar_stmts = vNULL;
    4480              : 
    4481        73463 :   bool fail = false;
    4482              :   /* ???  We could leave operation code checking to SLP discovery.  */
    4483        73463 :   code_helper code = STMT_VINFO_REDUC_CODE (STMT_VINFO_REDUC_DEF
    4484              :                                               (vect_orig_stmt (scalar_stmt)));
    4485        73463 :   bool first = true;
    4486        73463 :   stmt_vec_info next_stmt = scalar_stmt;
    4487        83662 :   do
    4488              :     {
    4489        83662 :       stmt_vec_info stmt = next_stmt;
    4490        83662 :       gimple_match_op op, orig_op;
    4491        83662 :       if (!gimple_extract_op (STMT_VINFO_STMT (stmt), &op))
    4492            0 :         gcc_unreachable ();
    4493       167324 :       tree reduc_def = gimple_arg (STMT_VINFO_STMT (stmt),
    4494        83662 :                                    STMT_VINFO_REDUC_IDX (stmt));
    4495        83662 :       next_stmt = vect_stmt_to_vectorize (vinfo->lookup_def (reduc_def));
    4496        83662 :       gcc_assert (is_a <gphi *> (STMT_VINFO_STMT (next_stmt))
    4497              :                   || STMT_VINFO_REDUC_IDX (next_stmt) != -1);
    4498        89624 :       if (!gimple_extract_op (STMT_VINFO_STMT (vect_orig_stmt (stmt)),
    4499              :                               &orig_op))
    4500            0 :         gcc_unreachable ();
    4501        83662 :       if (CONVERT_EXPR_CODE_P (op.code)
    4502         4995 :           && tree_nop_conversion_p (op.type, TREE_TYPE (op.ops[0]))
    4503        88645 :           && (first
    4504         2496 :               || is_a <gphi *> (STMT_VINFO_STMT (next_stmt))))
    4505              :         ;
    4506        78739 :       else if (code != orig_op.code)
    4507              :         {
    4508         2728 :           fail = true;
    4509         2728 :           break;
    4510              :         }
    4511              :       else
    4512        76011 :         scalar_stmts.safe_push (stmt);
    4513        80934 :       first = false;
    4514              :     }
    4515        80934 :   while (!is_a <gphi *> (STMT_VINFO_STMT (next_stmt)));
    4516        73463 :   if (fail)
    4517         2728 :     return false;
    4518              : 
    4519              :   /* When the SSA def chain through reduc-idx does not form a natural
    4520              :      reduction chain try to linearize an associative operation manually.  */
    4521        70735 :   if (scalar_stmts.length () == 1
    4522        68065 :       && code.is_tree_code ()
    4523        61993 :       && associative_tree_code ((tree_code)code)
    4524              :       /* We may not associate if a fold-left reduction is required.  */
    4525       131315 :       && !needs_fold_left_reduction_p (TREE_TYPE (gimple_get_lhs
    4526              :                                                     (scalar_stmts[0]->stmt)),
    4527              :                                        code))
    4528              :     {
    4529              :       /* Remember a stmt with the actual reduction operation.  */
    4530        57307 :       stmt_vec_info reduc_scalar_stmt = scalar_stmts[0];
    4531        57307 :       auto_vec<chain_op_t> chain;
    4532        57307 :       auto_vec<std::pair<tree_code, gimple *> > worklist;
    4533        57307 :       gimple *op_stmt = NULL, *other_op_stmt = NULL;
    4534        57307 :       if (is_a <gassign *> (scalar_stmts[0]->stmt)
    4535              :           /* We cannot linearize an operation that vect_slp_linearize_chain
    4536              :              would not put on its worklist.  */
    4537        57307 :           && gimple_assign_rhs_code (scalar_stmts[0]->stmt) == (tree_code)code)
    4538              :         {
    4539        56651 :           vect_slp_linearize_chain (vinfo, worklist, chain, (tree_code)code,
    4540        56651 :                                     scalar_stmts[0]->stmt, op_stmt,
    4541              :                                     other_op_stmt,
    4542              :                                     NULL);
    4543              : 
    4544        56651 :           scalar_stmts.truncate (0);
    4545        56651 :           stmt_vec_info tail = NULL;
    4546       283550 :           for (auto el : chain)
    4547              :             {
    4548       113896 :               if (el.dt == vect_external_def
    4549       113896 :                   || el.dt == vect_constant_def
    4550       113896 :                   || el.code != (tree_code) code)
    4551              :                 {
    4552          299 :                   scalar_stmts.release ();
    4553          299 :                   return false;
    4554              :                 }
    4555       113597 :               stmt_vec_info stmt = vinfo->lookup_def (el.op);
    4556       113597 :               if (STMT_VINFO_REDUC_IDX (stmt) != -1
    4557       111313 :                   || STMT_VINFO_REDUC_DEF (stmt))
    4558              :                 {
    4559        56567 :                   gcc_assert (tail == NULL);
    4560        56567 :                   tail = stmt;
    4561        56567 :                   continue;
    4562              :                 }
    4563        57030 :               scalar_stmts.safe_push (stmt);
    4564              :             }
    4565        56352 :           gcc_assert (tail);
    4566              :         }
    4567              : 
    4568              :       /* When this linearization didn't produce a chain see if stripping
    4569              :          a wrapping sign conversion produces one.  */
    4570        57008 :       if (scalar_stmts.length () == 1
    4571        57008 :           && (code == PLUS_EXPR || code == MULT_EXPR || code == BIT_IOR_EXPR
    4572              :               || code == BIT_AND_EXPR || code == BIT_XOR_EXPR))
    4573              :         {
    4574        55197 :           gimple *stmt = scalar_stmts[0]->stmt;
    4575        55197 :           if (!is_gimple_assign (stmt)
    4576        54036 :               || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
    4577         4704 :               || TREE_CODE (gimple_assign_rhs1 (stmt)) != SSA_NAME
    4578        59901 :               || !tree_nop_conversion_p (TREE_TYPE (gimple_assign_lhs (stmt)),
    4579         4704 :                                          TREE_TYPE (gimple_assign_rhs1 (stmt))))
    4580              :             {
    4581        53417 :               scalar_stmts.release ();
    4582        53417 :               return false;
    4583              :             }
    4584         1780 :           stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
    4585         1780 :           if (!is_gimple_assign (stmt)
    4586         1780 :               || gimple_assign_rhs_code (stmt) != (tree_code)code)
    4587              :             {
    4588         1762 :               scalar_stmts.release ();
    4589         1762 :               return false;
    4590              :             }
    4591           18 :           chain.truncate (0);
    4592           18 :           vect_slp_linearize_chain (vinfo, worklist, chain, (tree_code)code,
    4593              :                                     stmt, op_stmt, other_op_stmt, NULL);
    4594              : 
    4595           18 :           scalar_stmts.truncate (0);
    4596           18 :           stmt_vec_info tail = NULL;
    4597           88 :           for (auto el : chain)
    4598              :             {
    4599           42 :               if (el.dt == vect_external_def
    4600           42 :                   || el.dt == vect_constant_def
    4601           42 :                   || el.code != (tree_code) code)
    4602              :                 {
    4603            8 :                   scalar_stmts.release ();
    4604            8 :                   return false;
    4605              :                 }
    4606           34 :               stmt_vec_info stmt = vinfo->lookup_def (el.op);
    4607           34 :               if (STMT_VINFO_REDUC_IDX (stmt) != -1
    4608           34 :                   || STMT_VINFO_REDUC_DEF (stmt))
    4609              :                 {
    4610            0 :                   gcc_assert (tail == NULL);
    4611            0 :                   tail = stmt;
    4612            0 :                   continue;
    4613              :                 }
    4614           34 :               scalar_stmts.safe_push (stmt);
    4615              :             }
    4616              :           /* Unlike the above this does not include the reduction SSA
    4617              :              cycle.  */
    4618           10 :           gcc_assert (!tail);
    4619              :         }
    4620              : 
    4621         1821 :       if (scalar_stmts.length () < 2)
    4622              :         {
    4623         1697 :           scalar_stmts.release ();
    4624         1697 :           return false;
    4625              :         }
    4626              : 
    4627          124 :       if (dump_enabled_p ())
    4628              :         {
    4629           34 :           dump_printf_loc (MSG_NOTE, vect_location,
    4630              :                            "Starting SLP discovery of reduction chain for\n");
    4631          140 :           for (unsigned i = 0; i < scalar_stmts.length (); ++i)
    4632          212 :             dump_printf_loc (MSG_NOTE, vect_location,
    4633          106 :                              "  %G", scalar_stmts[i]->stmt);
    4634              :         }
    4635              : 
    4636          124 :       unsigned int group_size = scalar_stmts.length ();
    4637          124 :       match_elt_t *matches = XALLOCAVEC (match_elt_t, group_size);
    4638          124 :       unsigned tree_size = 0;
    4639          124 :       slp_tree node = vect_build_slp_tree (vinfo, scalar_stmts, matches, limit,
    4640          124 :                                            &tree_size, bst_map);
    4641          124 :       if (!node)
    4642              :         {
    4643           46 :           scalar_stmts.release ();
    4644           46 :           return false;
    4645              :         }
    4646              : 
    4647           78 :       unsigned cycle_id = vinfo->reduc_infos.length ();
    4648           78 :       vect_reduc_info reduc_info = new vect_reduc_info_s ();
    4649           78 :       vinfo->reduc_infos.safe_push (reduc_info);
    4650           78 :       VECT_REDUC_INFO_DEF_TYPE (reduc_info) = STMT_VINFO_DEF_TYPE (next_stmt);
    4651           78 :       VECT_REDUC_INFO_TYPE (reduc_info) = STMT_VINFO_REDUC_TYPE (next_stmt);
    4652           78 :       VECT_REDUC_INFO_CODE (reduc_info) = STMT_VINFO_REDUC_CODE (next_stmt);
    4653           78 :       VECT_REDUC_INFO_FN (reduc_info) = IFN_LAST;
    4654           78 :       reduc_info->is_reduc_chain = true;
    4655              : 
    4656              :       /* Build the node for the PHI and possibly the conversions.  */
    4657           78 :       slp_tree phis = vect_create_new_slp_node (2, ERROR_MARK);
    4658           78 :       SLP_TREE_REPRESENTATIVE (phis) = next_stmt;
    4659           78 :       phis->cycle_info.id = cycle_id;
    4660           78 :       SLP_TREE_LANES (phis) = group_size;
    4661           78 :       if (reduc_scalar_stmt == scalar_stmt)
    4662           74 :         SLP_TREE_VECTYPE (phis) = SLP_TREE_VECTYPE (node);
    4663              :       else
    4664            4 :         SLP_TREE_VECTYPE (phis)
    4665            4 :           = signed_or_unsigned_type_for (TYPE_UNSIGNED
    4666              :                                            (TREE_TYPE (gimple_get_lhs
    4667              :                                                          (scalar_stmt->stmt))),
    4668              :                                          SLP_TREE_VECTYPE (node));
    4669              :       /* ???  vect_cse_slp_nodes cannot cope with cycles without any
    4670              :          SLP_TREE_SCALAR_STMTS.  */
    4671           78 :       SLP_TREE_SCALAR_STMTS (phis).create (group_size);
    4672          471 :       for (unsigned i = 0; i < group_size; ++i)
    4673          315 :         SLP_TREE_SCALAR_STMTS (phis).quick_push (next_stmt);
    4674              : 
    4675           78 :       slp_tree op_input = phis;
    4676           78 :       if (reduc_scalar_stmt != scalar_stmt)
    4677              :         {
    4678            4 :           slp_tree conv = vect_create_new_slp_node (1, ERROR_MARK);
    4679            4 :           SLP_TREE_REPRESENTATIVE (conv)
    4680            4 :             = vinfo->lookup_def (gimple_arg (reduc_scalar_stmt->stmt,
    4681            4 :                                              STMT_VINFO_REDUC_IDX
    4682              :                                                (reduc_scalar_stmt)));
    4683            4 :           SLP_TREE_CHILDREN (conv).quick_push (phis);
    4684            4 :           conv->cycle_info.id = cycle_id;
    4685            4 :           SLP_TREE_REDUC_IDX (conv) = 0;
    4686            4 :           SLP_TREE_LANES (conv) = group_size;
    4687            4 :           SLP_TREE_VECTYPE (conv) = SLP_TREE_VECTYPE (node);
    4688            4 :           SLP_TREE_SCALAR_STMTS (conv) = vNULL;
    4689            4 :           op_input = conv;
    4690              :         }
    4691              : 
    4692           78 :       slp_tree reduc = vect_create_new_slp_node (2, ERROR_MARK);
    4693           78 :       SLP_TREE_REPRESENTATIVE (reduc) = reduc_scalar_stmt;
    4694           78 :       SLP_TREE_CHILDREN (reduc).quick_push (op_input);
    4695           78 :       SLP_TREE_CHILDREN (reduc).quick_push (node);
    4696           78 :       reduc->cycle_info.id = cycle_id;
    4697           78 :       SLP_TREE_REDUC_IDX (reduc) = 0;
    4698           78 :       SLP_TREE_LANES (reduc) = group_size;
    4699           78 :       SLP_TREE_VECTYPE (reduc) = SLP_TREE_VECTYPE (node);
    4700              :       /* ???  For the reduction epilogue we need a live lane.  */
    4701           78 :       SLP_TREE_SCALAR_STMTS (reduc).create (group_size);
    4702           78 :       SLP_TREE_SCALAR_STMTS (reduc).quick_push (reduc_scalar_stmt);
    4703          393 :       for (unsigned i = 1; i < group_size; ++i)
    4704          237 :         SLP_TREE_SCALAR_STMTS (reduc).quick_push (NULL);
    4705              : 
    4706           78 :       if (reduc_scalar_stmt != scalar_stmt)
    4707              :         {
    4708            4 :           slp_tree conv = vect_create_new_slp_node (1, ERROR_MARK);
    4709            4 :           SLP_TREE_REPRESENTATIVE (conv) = scalar_stmt;
    4710            4 :           SLP_TREE_CHILDREN (conv).quick_push (reduc);
    4711            4 :           conv->cycle_info.id = cycle_id;
    4712            4 :           SLP_TREE_REDUC_IDX (conv) = 0;
    4713            4 :           SLP_TREE_LANES (conv) = group_size;
    4714            4 :           SLP_TREE_VECTYPE (conv) = SLP_TREE_VECTYPE (phis);
    4715              :           /* ???  For the reduction epilogue we need a live lane.  */
    4716            4 :           SLP_TREE_SCALAR_STMTS (conv).create (group_size);
    4717            4 :           SLP_TREE_SCALAR_STMTS (conv).quick_push (scalar_stmt);
    4718           12 :           for (unsigned i = 1; i < group_size; ++i)
    4719            4 :             SLP_TREE_SCALAR_STMTS (conv).quick_push (NULL);
    4720            4 :           reduc = conv;
    4721              :         }
    4722              : 
    4723           78 :       edge le = loop_latch_edge (LOOP_VINFO_LOOP (vinfo));
    4724           78 :       SLP_TREE_CHILDREN (phis).quick_push (NULL);
    4725           78 :       SLP_TREE_CHILDREN (phis).quick_push (NULL);
    4726           78 :       SLP_TREE_CHILDREN (phis)[le->dest_idx] = reduc;
    4727           78 :       SLP_TREE_REF_COUNT (reduc)++;
    4728              : 
    4729              :       /* Create a new SLP instance.  */
    4730           78 :       slp_instance new_instance = XNEW (class _slp_instance);
    4731           78 :       SLP_INSTANCE_TREE (new_instance) = reduc;
    4732           78 :       SLP_INSTANCE_LOADS (new_instance) = vNULL;
    4733           78 :       SLP_INSTANCE_ROOT_STMTS (new_instance) = vNULL;
    4734           78 :       SLP_INSTANCE_REMAIN_DEFS (new_instance) = vNULL;
    4735           78 :       SLP_INSTANCE_KIND (new_instance) = slp_inst_kind_reduc_chain;
    4736           78 :       new_instance->reduc_phis = NULL;
    4737           78 :       new_instance->cost_vec = vNULL;
    4738           78 :       new_instance->subgraph_entries = vNULL;
    4739              : 
    4740           78 :       vinfo->slp_instances.safe_push (new_instance);
    4741              : 
    4742           78 :       if (dump_enabled_p ())
    4743              :         {
    4744           24 :           dump_printf_loc (MSG_NOTE, vect_location,
    4745              :                            "Final SLP tree for instance %p:\n",
    4746              :                            (void *) new_instance);
    4747           24 :           vect_print_slp_graph (MSG_NOTE, vect_location,
    4748              :                                 SLP_INSTANCE_TREE (new_instance));
    4749              :         }
    4750              : 
    4751              :       return true;
    4752        57307 :     }
    4753              : 
    4754        13428 :   if (scalar_stmts.length () <= 1)
    4755              :     {
    4756        10764 :       scalar_stmts.release ();
    4757        10764 :       return false;
    4758              :     }
    4759              : 
    4760         2664 :   scalar_stmts.reverse ();
    4761         2664 :   stmt_vec_info reduc_phi_info = next_stmt;
    4762              : 
    4763              :   /* Build the tree for the SLP instance.  */
    4764         2664 :   vec<stmt_vec_info> root_stmt_infos = vNULL;
    4765         2664 :   vec<tree> remain = vNULL;
    4766              : 
    4767         2664 :   if (dump_enabled_p ())
    4768              :     {
    4769          219 :       dump_printf_loc (MSG_NOTE, vect_location,
    4770              :                        "Starting SLP discovery of reduction chain for\n");
    4771         1143 :       for (unsigned i = 0; i < scalar_stmts.length (); ++i)
    4772         1848 :         dump_printf_loc (MSG_NOTE, vect_location,
    4773          924 :                          "  %G", scalar_stmts[i]->stmt);
    4774              :     }
    4775              : 
    4776              :   /* Build the tree for the SLP instance.  */
    4777         2664 :   unsigned int group_size = scalar_stmts.length ();
    4778         2664 :   match_elt_t *matches = XALLOCAVEC (match_elt_t, group_size);
    4779         2664 :   unsigned tree_size = 0;
    4780              : 
    4781              :   /* ???  We need this only for SLP discovery.  */
    4782        10528 :   for (unsigned i = 0; i < scalar_stmts.length (); ++i)
    4783         7864 :     REDUC_GROUP_FIRST_ELEMENT (scalar_stmts[i]) = scalar_stmts[0];
    4784              : 
    4785         2664 :   slp_tree node = vect_build_slp_tree (vinfo, scalar_stmts, matches, limit,
    4786         2664 :                                        &tree_size, bst_map);
    4787              : 
    4788        10528 :   for (unsigned i = 0; i < scalar_stmts.length (); ++i)
    4789         7864 :     REDUC_GROUP_FIRST_ELEMENT (scalar_stmts[i]) = NULL;
    4790              : 
    4791         2664 :   if (node != NULL)
    4792              :     {
    4793              :       /* Create a new SLP instance.  */
    4794         2385 :       slp_instance new_instance = XNEW (class _slp_instance);
    4795         2385 :       SLP_INSTANCE_TREE (new_instance) = node;
    4796         2385 :       SLP_INSTANCE_LOADS (new_instance) = vNULL;
    4797         2385 :       SLP_INSTANCE_ROOT_STMTS (new_instance) = root_stmt_infos;
    4798         2385 :       SLP_INSTANCE_REMAIN_DEFS (new_instance) = remain;
    4799         2385 :       SLP_INSTANCE_KIND (new_instance) = slp_inst_kind_reduc_chain;
    4800         2385 :       new_instance->reduc_phis = NULL;
    4801         2385 :       new_instance->cost_vec = vNULL;
    4802         2385 :       new_instance->subgraph_entries = vNULL;
    4803              : 
    4804         2385 :       vect_reduc_info reduc_info = info_for_reduction (vinfo, node);
    4805         2385 :       reduc_info->is_reduc_chain = true;
    4806              : 
    4807         2385 :       if (dump_enabled_p ())
    4808          153 :         dump_printf_loc (MSG_NOTE, vect_location,
    4809              :                          "SLP size %u vs. limit %u.\n",
    4810              :                          tree_size, max_tree_size);
    4811              : 
    4812              :       /* Fixup SLP reduction chains.  If this is a reduction chain with
    4813              :          a conversion in front amend the SLP tree with a node for that.  */
    4814         2385 :       gimple *scalar_def = STMT_VINFO_REDUC_DEF (reduc_phi_info)->stmt;
    4815         2385 :       if (is_gimple_assign (scalar_def)
    4816         2385 :           && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (scalar_def)))
    4817              :         {
    4818           43 :           stmt_vec_info conv_info = vect_stmt_to_vectorize
    4819           43 :                                         (STMT_VINFO_REDUC_DEF (reduc_phi_info));
    4820           43 :           scalar_stmts = vNULL;
    4821           43 :           scalar_stmts.create (group_size);
    4822          178 :           for (unsigned i = 0; i < group_size; ++i)
    4823           92 :             scalar_stmts.quick_push (conv_info);
    4824           43 :           slp_tree conv = vect_create_new_slp_node (scalar_stmts, 1);
    4825           43 :           SLP_TREE_VECTYPE (conv)
    4826           43 :             = get_vectype_for_scalar_type (vinfo,
    4827           43 :                                            TREE_TYPE
    4828              :                                              (gimple_assign_lhs (scalar_def)),
    4829              :                                            group_size);
    4830           43 :           SLP_TREE_REDUC_IDX (conv) = 0;
    4831           43 :           conv->cycle_info.id = node->cycle_info.id;
    4832           43 :           SLP_TREE_CHILDREN (conv).quick_push (node);
    4833           43 :           SLP_INSTANCE_TREE (new_instance) = conv;
    4834              :         }
    4835              :       /* Fill the backedge child of the PHI SLP node.  The
    4836              :          general matching code cannot find it because the
    4837              :          scalar code does not reflect how we vectorize the
    4838              :          reduction.  */
    4839         2385 :       use_operand_p use_p;
    4840         2385 :       imm_use_iterator imm_iter;
    4841         2385 :       class loop *loop = LOOP_VINFO_LOOP (vinfo);
    4842         9058 :       FOR_EACH_IMM_USE_FAST (use_p, imm_iter,
    4843              :                              gimple_get_lhs (scalar_def))
    4844              :         /* There are exactly two non-debug uses, the reduction
    4845              :            PHI and the loop-closed PHI node.  */
    4846         6673 :         if (!is_gimple_debug (USE_STMT (use_p))
    4847         6673 :             && gimple_bb (USE_STMT (use_p)) == loop->header)
    4848              :           {
    4849         2385 :             auto_vec<stmt_vec_info, 64> phis (group_size);
    4850         2385 :             stmt_vec_info phi_info = vinfo->lookup_stmt (USE_STMT (use_p));
    4851         9541 :             for (unsigned i = 0; i < group_size; ++i)
    4852         7156 :               phis.quick_push (phi_info);
    4853         2385 :             slp_tree *phi_node = bst_map->get (phis);
    4854         2385 :             unsigned dest_idx = loop_latch_edge (loop)->dest_idx;
    4855         4770 :             SLP_TREE_CHILDREN (*phi_node)[dest_idx]
    4856         2385 :               = SLP_INSTANCE_TREE (new_instance);
    4857         2385 :             SLP_INSTANCE_TREE (new_instance)->refcnt++;
    4858         2385 :           }
    4859              : 
    4860         2385 :       vinfo->slp_instances.safe_push (new_instance);
    4861              : 
    4862              :       /* ???  We've replaced the old SLP_INSTANCE_GROUP_SIZE with
    4863              :          the number of SLP lanes of the root in a few places.
    4864              :          Verify that assumption holds.  */
    4865         2385 :       gcc_assert (SLP_TREE_LANES (SLP_INSTANCE_TREE (new_instance))
    4866              :                   == group_size);
    4867              : 
    4868         2385 :       if (dump_enabled_p ())
    4869              :         {
    4870          153 :           dump_printf_loc (MSG_NOTE, vect_location,
    4871              :                            "Final SLP tree for instance %p:\n",
    4872              :                            (void *) new_instance);
    4873          153 :           vect_print_slp_graph (MSG_NOTE, vect_location,
    4874              :                                 SLP_INSTANCE_TREE (new_instance));
    4875              :         }
    4876              : 
    4877         2385 :       return true;
    4878              :     }
    4879              : 
    4880              :   /* Failed to SLP.  */
    4881          279 :   scalar_stmts.release ();
    4882          279 :   if (dump_enabled_p ())
    4883           66 :     dump_printf_loc (MSG_NOTE, vect_location,
    4884              :                      "SLP discovery of reduction chain failed\n");
    4885              :   return false;
    4886              : }
    4887              : 
    4888              : /* Analyze an SLP instance starting from SCALAR_STMTS which are a group
    4889              :    of KIND.  Return true if successful.  */
    4890              : 
    4891              : static bool
    4892       100407 : vect_analyze_slp_reduction (loop_vec_info vinfo,
    4893              :                             stmt_vec_info scalar_stmt,
    4894              :                             unsigned max_tree_size, unsigned *limit,
    4895              :                             scalar_stmts_to_slp_tree_map_t *bst_map,
    4896              :                             bool force_single_lane)
    4897              : {
    4898       100407 :   slp_instance_kind kind = slp_inst_kind_reduc_group;
    4899              : 
    4900              :   /* Try to gather a reduction chain.  Only attempt if there's budget left
    4901              :      since chain analysis may build multi-lane trees that consume limit.  */
    4902       100407 :   if (! force_single_lane
    4903        73748 :       && *limit != 0
    4904        73748 :       && STMT_VINFO_DEF_TYPE (scalar_stmt) == vect_reduction_def
    4905       173870 :       && vect_analyze_slp_reduc_chain (vinfo, bst_map, scalar_stmt,
    4906              :                                        max_tree_size, limit))
    4907              :     return true;
    4908              : 
    4909        97944 :   vec<stmt_vec_info> scalar_stmts;
    4910        97944 :   scalar_stmts.create (1);
    4911        97944 :   scalar_stmts.quick_push (scalar_stmt);
    4912              : 
    4913        97944 :   if (dump_enabled_p ())
    4914              :     {
    4915         3926 :       dump_printf_loc (MSG_NOTE, vect_location,
    4916              :                        "Starting SLP discovery for\n");
    4917         7852 :       for (unsigned i = 0; i < scalar_stmts.length (); ++i)
    4918         7852 :         dump_printf_loc (MSG_NOTE, vect_location,
    4919         3926 :                          "  %G", scalar_stmts[i]->stmt);
    4920              :     }
    4921              : 
    4922              :   /* Build the tree for the SLP instance.  */
    4923        97944 :   unsigned int group_size = scalar_stmts.length ();
    4924        97944 :   match_elt_t *matches = XALLOCAVEC (match_elt_t, group_size);
    4925        97944 :   unsigned tree_size = 0;
    4926              : 
    4927        97944 :   slp_tree node = vect_build_slp_tree (vinfo, scalar_stmts, matches, limit,
    4928              :                                        &tree_size, bst_map);
    4929        97944 :   if (node != NULL)
    4930              :     {
    4931              :       /* Create a new SLP instance.  */
    4932        96057 :       slp_instance new_instance = XNEW (class _slp_instance);
    4933        96057 :       SLP_INSTANCE_TREE (new_instance) = node;
    4934        96057 :       SLP_INSTANCE_LOADS (new_instance) = vNULL;
    4935        96057 :       SLP_INSTANCE_ROOT_STMTS (new_instance) = vNULL;
    4936        96057 :       SLP_INSTANCE_REMAIN_DEFS (new_instance) = vNULL;
    4937        96057 :       SLP_INSTANCE_KIND (new_instance) = kind;
    4938        96057 :       new_instance->reduc_phis = NULL;
    4939        96057 :       new_instance->cost_vec = vNULL;
    4940        96057 :       new_instance->subgraph_entries = vNULL;
    4941              : 
    4942        96057 :       if (dump_enabled_p ())
    4943         3849 :         dump_printf_loc (MSG_NOTE, vect_location,
    4944              :                          "SLP size %u vs. limit %u.\n",
    4945              :                          tree_size, max_tree_size);
    4946              : 
    4947        96057 :       vinfo->slp_instances.safe_push (new_instance);
    4948              : 
    4949              :       /* ???  We've replaced the old SLP_INSTANCE_GROUP_SIZE with
    4950              :          the number of SLP lanes of the root in a few places.
    4951              :          Verify that assumption holds.  */
    4952        96057 :       gcc_assert (SLP_TREE_LANES (SLP_INSTANCE_TREE (new_instance))
    4953              :                   == group_size);
    4954              : 
    4955        96057 :       if (dump_enabled_p ())
    4956              :         {
    4957         3849 :           dump_printf_loc (MSG_NOTE, vect_location,
    4958              :                            "Final SLP tree for instance %p:\n",
    4959              :                            (void *) new_instance);
    4960         3849 :           vect_print_slp_graph (MSG_NOTE, vect_location,
    4961              :                                 SLP_INSTANCE_TREE (new_instance));
    4962              :         }
    4963              : 
    4964        96057 :       return true;
    4965              :     }
    4966              :   /* Failed to SLP.  */
    4967              : 
    4968              :   /* Free the allocated memory.  */
    4969         1887 :   scalar_stmts.release ();
    4970              : 
    4971              :   /* Failed to SLP.  */
    4972         1887 :   if (dump_enabled_p ())
    4973           77 :     dump_printf_loc (MSG_NOTE, vect_location, "SLP discovery failed\n");
    4974              :   return false;
    4975              : }
    4976              : 
    4977              : /* Analyze a single SLP reduction group.  If successful add a SLP instance
    4978              :    for it and return true, otherwise return false and have *MATCHES
    4979              :    populated.  */
    4980              : 
    4981              : static bool
    4982        24242 : vect_analyze_slp_reduction_group (loop_vec_info loop_vinfo,
    4983              :                                   vec<stmt_vec_info> scalar_stmts,
    4984              :                                   scalar_stmts_to_slp_tree_map_t *bst_map,
    4985              :                                   unsigned max_tree_size, unsigned *limit,
    4986              :                                   match_elt_t *matches)
    4987              : {
    4988              :   /* Try to form a reduction group.  Size-1 groups are not suitable
    4989              :      for SLP reduction and should fall back to single-lane reduction.  */
    4990        24242 :   unsigned int group_size = scalar_stmts.length ();
    4991        24242 :   if (group_size <= 1)
    4992              :     return false;
    4993        17523 :   if (!matches)
    4994         4547 :     matches = XALLOCAVEC (match_elt_t, group_size);
    4995        17523 :   unsigned tree_size = 0;
    4996        17523 :   slp_tree node = vect_build_slp_tree (loop_vinfo, scalar_stmts, matches, limit,
    4997              :                                        &tree_size, bst_map);
    4998        17523 :   if (!node)
    4999              :     return false;
    5000              : 
    5001              :   /* Create a new SLP instance.  */
    5002         2784 :   slp_instance new_instance = XNEW (class _slp_instance);
    5003         2784 :   SLP_INSTANCE_TREE (new_instance) = node;
    5004         2784 :   SLP_INSTANCE_LOADS (new_instance) = vNULL;
    5005         2784 :   SLP_INSTANCE_ROOT_STMTS (new_instance) = vNULL;
    5006         2784 :   SLP_INSTANCE_REMAIN_DEFS (new_instance) = vNULL;
    5007         2784 :   SLP_INSTANCE_KIND (new_instance) = slp_inst_kind_reduc_group;
    5008         2784 :   new_instance->reduc_phis = NULL;
    5009         2784 :   new_instance->cost_vec = vNULL;
    5010         2784 :   new_instance->subgraph_entries = vNULL;
    5011              : 
    5012         2784 :   if (dump_enabled_p ())
    5013          203 :     dump_printf_loc (MSG_NOTE, vect_location,
    5014              :                      "SLP size %u vs. limit %u.\n",
    5015              :                      tree_size, max_tree_size);
    5016              : 
    5017         2784 :   loop_vinfo->slp_instances.safe_push (new_instance);
    5018              : 
    5019              :   /* ???  We've replaced the old SLP_INSTANCE_GROUP_SIZE with
    5020              :      the number of SLP lanes of the root in a few places.
    5021              :      Verify that assumption holds.  */
    5022         2784 :   gcc_assert (SLP_TREE_LANES (SLP_INSTANCE_TREE (new_instance))
    5023              :               == group_size);
    5024              : 
    5025         2784 :   if (dump_enabled_p ())
    5026              :     {
    5027          203 :       dump_printf_loc (MSG_NOTE, vect_location,
    5028              :                        "SLP discovery of size %d reduction group "
    5029              :                        "succeeded\n", group_size);
    5030          203 :       dump_printf_loc (MSG_NOTE, vect_location,
    5031              :                        "Final SLP tree for instance %p:\n",
    5032              :                        (void *) new_instance);
    5033          203 :       vect_print_slp_graph (MSG_NOTE, vect_location,
    5034              :                             SLP_INSTANCE_TREE (new_instance));
    5035              :     }
    5036              : 
    5037              :   return true;
    5038              : }
    5039              : 
    5040              : /* Analyze reductions in LOOP_VINFO and populate SLP instances
    5041              :    accordingly.  Returns false if something fails.  */
    5042              : 
    5043              : static bool
    5044       515947 : vect_analyze_slp_reductions (loop_vec_info loop_vinfo,
    5045              :                              unsigned max_tree_size, unsigned *limit,
    5046              :                              scalar_stmts_to_slp_tree_map_t *bst_map,
    5047              :                              bool force_single_lane)
    5048              : {
    5049       515947 :   if (loop_vinfo->reductions.is_empty ())
    5050              :     return true;
    5051              : 
    5052              :   /* Collect reduction statements we can combine into
    5053              :      a SLP reduction.  */
    5054        74590 :   vec<stmt_vec_info> scalar_stmts;
    5055        74590 :   scalar_stmts.create (loop_vinfo->reductions.length ());
    5056       330609 :   for (auto next_info : loop_vinfo->reductions)
    5057              :     {
    5058       106839 :       next_info = vect_stmt_to_vectorize (next_info);
    5059       106839 :       if ((STMT_VINFO_RELEVANT_P (next_info)
    5060           14 :            || STMT_VINFO_LIVE_P (next_info))
    5061              :           /* ???  Make sure we didn't skip a conversion around a
    5062              :              reduction path.  In that case we'd have to reverse
    5063              :              engineer that conversion stmt following the chain using
    5064              :              reduc_idx and from the PHI using reduc_def.  */
    5065       106825 :           && (STMT_VINFO_DEF_TYPE (next_info) == vect_reduction_def
    5066       106825 :               || (STMT_VINFO_DEF_TYPE (next_info)
    5067              :                   == vect_double_reduction_def)))
    5068              :         {
    5069              :           /* Do not discover SLP reductions combining lane-reducing
    5070              :              ops, that will fail later.  */
    5071       106825 :           if (!force_single_lane
    5072       106825 :               && !lane_reducing_stmt_p (STMT_VINFO_STMT (next_info)))
    5073        79451 :             scalar_stmts.quick_push (next_info);
    5074              :           /* Do SLP discovery for single-lane reductions.  */
    5075        27374 :           else if (! vect_analyze_slp_reduction (loop_vinfo, next_info,
    5076              :                                                  max_tree_size, limit,
    5077              :                                                  bst_map,
    5078              :                                                  force_single_lane))
    5079              :             {
    5080            0 :               scalar_stmts.release ();
    5081            0 :               return false;
    5082              :             }
    5083              :         }
    5084              :     }
    5085              : 
    5086        74590 :   if (scalar_stmts.length () > 1)
    5087              :     {
    5088              :       /* Try to form a reduction group.  */
    5089         4675 :       unsigned int group_size = scalar_stmts.length ();
    5090         4675 :       match_elt_t *matches = XALLOCAVEC (match_elt_t, group_size);
    5091         4675 :       if (vect_analyze_slp_reduction_group (loop_vinfo, scalar_stmts, bst_map,
    5092              :                                             max_tree_size, limit, matches))
    5093         1601 :         return true;
    5094              : 
    5095              :       /* When analysis as a single SLP reduction group failed try to
    5096              :          form sub-groups by collecting matching lanes.  Do not recurse
    5097              :          that on failure (to limit compile-time costs), but recurse
    5098              :          for the initial non-matching parts.  Everything not covered
    5099              :          by a sub-group gets single-reduction treatment.  */
    5100              :       /* ???  Improve this with the matches[] improvements.  */
    5101         3526 :       vec<stmt_vec_info> cands = vNULL;
    5102        11397 :       while (matches[0] == 0)
    5103              :         {
    5104        11266 :           cands.truncate (0);
    5105        11266 :           cands.reserve (group_size, true);
    5106        99737 :           for (unsigned i = 0; i < group_size; ++i)
    5107        77205 :             if (matches[i] == 0)
    5108        19596 :               cands.quick_push (scalar_stmts[i]);
    5109              : 
    5110              :           /* Try to form a reduction group.  */
    5111        11266 :           if (vect_analyze_slp_reduction_group (loop_vinfo, cands, bst_map,
    5112              :                                                 max_tree_size, limit, NULL))
    5113         1205 :             cands = vNULL;
    5114              :           else
    5115              :             {
    5116              :               /* Do SLP discovery for single-lane reductions.  */
    5117        47319 :               for (auto stmt_info : cands)
    5118        17158 :                 if (! vect_analyze_slp_reduction (loop_vinfo,
    5119              :                                                   vect_stmt_to_vectorize
    5120              :                                                     (stmt_info),
    5121              :                                                   max_tree_size, limit,
    5122              :                                                   bst_map, force_single_lane))
    5123              :                   {
    5124           22 :                     scalar_stmts.release ();
    5125           22 :                     cands.release ();
    5126           22 :                     return false;
    5127              :                   }
    5128              :             }
    5129              :           /* Remove the handled stmts from scalar_stmts and try again,
    5130              :              possibly repeating the above with updated matches[].  */
    5131        11244 :           unsigned j = 0;
    5132        88387 :           for (unsigned i = 0; i < group_size; ++i)
    5133        77143 :             if (matches[i] != 0)
    5134              :               {
    5135        57582 :                 scalar_stmts[j] = scalar_stmts[i];
    5136        57582 :                 ++j;
    5137              :               }
    5138        11244 :           scalar_stmts.truncate (j);
    5139        11375 :           group_size = scalar_stmts.length ();
    5140        11244 :           if (group_size <= 1)
    5141              :             break;
    5142         8301 :           if (vect_analyze_slp_reduction_group (loop_vinfo, scalar_stmts,
    5143              :                                                 bst_map, max_tree_size, limit,
    5144              :                                                 matches))
    5145              :             return true;
    5146              :         }
    5147              :     }
    5148              :   /* Do SLP discovery for single-lane reductions.  */
    5149       272977 :   for (auto stmt_info : scalar_stmts)
    5150        55875 :     if (! vect_analyze_slp_reduction (loop_vinfo,
    5151              :                                       vect_stmt_to_vectorize (stmt_info),
    5152              :                                       max_tree_size, limit,
    5153              :                                       bst_map, force_single_lane))
    5154              :       {
    5155         1865 :         scalar_stmts.release ();
    5156         1865 :         return false;
    5157              :       }
    5158              : 
    5159        71124 :   scalar_stmts.release ();
    5160        71124 :   return true;
    5161              : }
    5162              : 
    5163              : /* Analyze an SLP instance starting from a group of grouped stores.  Call
    5164              :    vect_build_slp_tree to build a tree of packed stmts if possible.
    5165              :    Return FALSE if it's impossible to SLP any stmt in the group.  */
    5166              : 
    5167              : static bool
    5168      1096340 : vect_analyze_slp_instance (vec_info *vinfo,
    5169              :                            scalar_stmts_to_slp_tree_map_t *bst_map,
    5170              :                            stmt_vec_info stmt_info,
    5171              :                            slp_instance_kind kind,
    5172              :                            unsigned max_tree_size, unsigned *limit,
    5173              :                            bool force_single_lane)
    5174              : {
    5175      1096340 :   vec<stmt_vec_info> scalar_stmts;
    5176              : 
    5177      1096340 :   if (is_a <bb_vec_info> (vinfo))
    5178      1066109 :     vect_location = stmt_info->stmt;
    5179              : 
    5180      1096340 :   gcc_assert (kind == slp_inst_kind_store);
    5181              : 
    5182              :   /* Collect the stores and store them in scalar_stmts.  */
    5183      1096340 :   scalar_stmts.create (DR_GROUP_SIZE (stmt_info));
    5184      1096340 :   stmt_vec_info next_info = stmt_info;
    5185      5448049 :   while (next_info)
    5186              :     {
    5187      3255369 :       scalar_stmts.quick_push (vect_stmt_to_vectorize (next_info));
    5188      3255369 :       next_info = DR_GROUP_NEXT_ELEMENT (next_info);
    5189              :     }
    5190              : 
    5191      1096340 :   vec<stmt_vec_info> root_stmt_infos = vNULL;
    5192      1096340 :   vec<tree> remain = vNULL;
    5193              : 
    5194              :   /* Build the tree for the SLP instance.  */
    5195              : 
    5196              :   /* If there's no budget left bail out early.  */
    5197      1096340 :   if (*limit == 0)
    5198              :     return false;
    5199              : 
    5200      1096320 :   if (dump_enabled_p ())
    5201              :     {
    5202         4215 :       dump_printf_loc (MSG_NOTE, vect_location,
    5203              :                        "Starting SLP discovery for\n");
    5204        24525 :       for (unsigned i = 0; i < scalar_stmts.length (); ++i)
    5205        40620 :         dump_printf_loc (MSG_NOTE, vect_location,
    5206        20310 :                          "  %G", scalar_stmts[i]->stmt);
    5207              :     }
    5208              : 
    5209              :   /* Build the tree for the SLP instance.  */
    5210      1096320 :   unsigned int group_size = scalar_stmts.length ();
    5211      1096320 :   match_elt_t *matches = XALLOCAVEC (match_elt_t, group_size);
    5212      1096320 :   unsigned tree_size = 0;
    5213      1096320 :   unsigned i;
    5214              : 
    5215      1096320 :   slp_tree node = NULL;
    5216      1096320 :   if (group_size > 1 && force_single_lane)
    5217              :     {
    5218         1770 :       matches[0] = 0;
    5219         1770 :       matches[1] = -1;
    5220              :     }
    5221              :   else
    5222      1094550 :     node = vect_build_slp_tree (vinfo, scalar_stmts, matches, limit,
    5223              :                                 &tree_size, bst_map);
    5224      1096320 :   if (node != NULL)
    5225              :     {
    5226              :       /* Create a new SLP instance.  */
    5227       696753 :       slp_instance new_instance = XNEW (class _slp_instance);
    5228       696753 :       SLP_INSTANCE_TREE (new_instance) = node;
    5229       696753 :       SLP_INSTANCE_LOADS (new_instance) = vNULL;
    5230       696753 :       SLP_INSTANCE_ROOT_STMTS (new_instance) = root_stmt_infos;
    5231       696753 :       SLP_INSTANCE_REMAIN_DEFS (new_instance) = remain;
    5232       696753 :       SLP_INSTANCE_KIND (new_instance) = kind;
    5233       696753 :       new_instance->reduc_phis = NULL;
    5234       696753 :       new_instance->cost_vec = vNULL;
    5235       696753 :       new_instance->subgraph_entries = vNULL;
    5236              : 
    5237       696753 :       if (dump_enabled_p ())
    5238         3211 :         dump_printf_loc (MSG_NOTE, vect_location,
    5239              :                          "SLP size %u vs. limit %u.\n",
    5240              :                          tree_size, max_tree_size);
    5241              : 
    5242       696753 :       vinfo->slp_instances.safe_push (new_instance);
    5243              : 
    5244              :       /* ???  We've replaced the old SLP_INSTANCE_GROUP_SIZE with
    5245              :          the number of SLP lanes of the root in a few places.
    5246              :          Verify that assumption holds.  */
    5247       696753 :       gcc_assert (SLP_TREE_LANES (SLP_INSTANCE_TREE (new_instance))
    5248              :                   == group_size);
    5249              : 
    5250       696753 :       if (dump_enabled_p ())
    5251              :         {
    5252         3211 :           dump_printf_loc (MSG_NOTE, vect_location,
    5253              :                            "Final SLP tree for instance %p:\n",
    5254              :                            (void *) new_instance);
    5255         3211 :           vect_print_slp_graph (MSG_NOTE, vect_location,
    5256              :                                 SLP_INSTANCE_TREE (new_instance));
    5257              :         }
    5258       696753 :       return true;
    5259              :     }
    5260              :   /* Failed to SLP.  */
    5261              : 
    5262              :   /* Try to break the group up into pieces.  */
    5263              :   /* ???  Improve this with the matches[] improvements.  */
    5264       399567 :   if (*limit > 0 && kind == slp_inst_kind_store)
    5265              :     {
    5266              :       /* ???  We could delay all the actual splitting of store-groups
    5267              :          until after SLP discovery of the original group completed.
    5268              :          Then we can recurse to vect_build_slp_instance directly.  */
    5269      1004392 :       for (i = 0; i < group_size; i++)
    5270      1004392 :         if (matches[i] != 0)
    5271              :           break;
    5272              : 
    5273              :       /* For basic block SLP, try to break the group up into multiples of
    5274              :          a vector size.  */
    5275       399566 :       if (is_a <bb_vec_info> (vinfo)
    5276       399566 :           && (i > 1 && i < group_size))
    5277              :         {
    5278              :           /* Free the allocated memory.  */
    5279       133476 :           scalar_stmts.release ();
    5280              : 
    5281       133476 :           tree scalar_type
    5282       133476 :             = TREE_TYPE (DR_REF (STMT_VINFO_DATA_REF (stmt_info)));
    5283       266952 :           tree vectype = get_vectype_for_scalar_type (vinfo, scalar_type,
    5284       133476 :                                                       1 << floor_log2 (i));
    5285       133476 :           unsigned HOST_WIDE_INT const_nunits;
    5286       133476 :           if (vectype
    5287       133476 :               && TYPE_VECTOR_SUBPARTS (vectype).is_constant (&const_nunits))
    5288              :             {
    5289              :               /* Split into two groups at the first vector boundary.  */
    5290       133476 :               gcc_assert ((const_nunits & (const_nunits - 1)) == 0);
    5291       133476 :               unsigned group1_size = i & ~(const_nunits - 1);
    5292              : 
    5293       133476 :               if (dump_enabled_p ())
    5294           81 :                 dump_printf_loc (MSG_NOTE, vect_location,
    5295              :                                  "Splitting SLP group at stmt %u\n", i);
    5296       133476 :               stmt_vec_info rest = vect_split_slp_store_group (stmt_info,
    5297              :                                                                group1_size);
    5298       133476 :               bool res = vect_analyze_slp_instance (vinfo, bst_map, stmt_info,
    5299              :                                                     kind, max_tree_size,
    5300              :                                                     limit, false);
    5301              :               /* Split the rest at the failure point and possibly
    5302              :                  re-analyze the remaining matching part if it has
    5303              :                  at least two lanes.  */
    5304       133476 :               if (group1_size < i
    5305         5770 :                   && (i + 1 < group_size
    5306         2558 :                       || i - group1_size > 1))
    5307              :                 {
    5308         3248 :                   stmt_vec_info rest2 = rest;
    5309         3248 :                   rest = vect_split_slp_store_group (rest, i - group1_size);
    5310         3248 :                   if (i - group1_size > 1)
    5311           71 :                     res |= vect_analyze_slp_instance (vinfo, bst_map, rest2,
    5312              :                                                       kind, max_tree_size,
    5313              :                                                       limit, false);
    5314              :                 }
    5315              :               /* Re-analyze the non-matching tail if it has at least
    5316              :                  two lanes.  */
    5317       133476 :               if (i + 1 < group_size)
    5318        22355 :                 res |= vect_analyze_slp_instance (vinfo, bst_map,
    5319              :                                                   rest, kind, max_tree_size,
    5320              :                                                   limit, false);
    5321      1096340 :               return res;
    5322              :             }
    5323              :         }
    5324              : 
    5325              :       /* For loop vectorization split the RHS into arbitrary pieces of
    5326              :          size >= 1.  */
    5327       266090 :       else if (is_a <loop_vec_info> (vinfo)
    5328       266090 :                && (group_size != 1 && i < group_size))
    5329              :         {
    5330         8378 :           gcall *call = dyn_cast <gcall *> (stmt_info->stmt);
    5331           28 :           bool masked_p = call
    5332           28 :               && gimple_call_internal_p (call)
    5333           28 :               && internal_fn_mask_index (gimple_call_internal_fn (call)) != -1;
    5334              :           /* There are targets that cannot do even/odd interleaving schemes
    5335              :              so they absolutely need to use load/store-lanes.  For now
    5336              :              force single-lane SLP for them - they would be happy with
    5337              :              uniform power-of-two lanes (but depending on element size),
    5338              :              but even if we can use 'i' as indicator we would need to
    5339              :              backtrack when later lanes fail to discover with the same
    5340              :              granularity.  We cannot turn any of strided or scatter store
    5341              :              into store-lanes.  */
    5342              :           /* ???  If this is not in sync with what get_load_store_type
    5343              :              later decides the SLP representation is not good for other
    5344              :              store vectorization methods.  */
    5345         8378 :           bool want_store_lanes
    5346         8378 :             = (! STMT_VINFO_GATHER_SCATTER_P (stmt_info)
    5347         8378 :                && ! STMT_VINFO_STRIDED_P (stmt_info)
    5348         6269 :                && ! STMT_VINFO_SLP_VECT_ONLY (stmt_info)
    5349         6265 :                && compare_step_with_zero (vinfo, stmt_info) > 0
    5350        14538 :                && vect_slp_prefer_store_lanes_p (vinfo, stmt_info, NULL_TREE,
    5351        16756 :                                                  masked_p, group_size, i));
    5352         8378 :           if (want_store_lanes || force_single_lane)
    5353              :             i = 1;
    5354              : 
    5355              :           /* A fatal discovery fail doesn't always mean single-lane SLP
    5356              :              isn't a possibility, so try.  */
    5357         6608 :           if (i == 0)
    5358              :             i = 1;
    5359              : 
    5360         8378 :           if (dump_enabled_p ())
    5361          873 :             dump_printf_loc (MSG_NOTE, vect_location,
    5362              :                              "Splitting SLP group at stmt %u\n", i);
    5363              : 
    5364              :           /* Analyze the stored values and pinch them together with
    5365              :              a permute node so we can preserve the whole store group.  */
    5366         8378 :           auto_vec<slp_tree> rhs_nodes;
    5367              : 
    5368         8378 :           unsigned int rhs_common_nlanes = 0;
    5369         8378 :           unsigned int start = 0, end = i;
    5370        38420 :           while (start < group_size)
    5371              :             {
    5372        30157 :               gcc_assert (end - start >= 1);
    5373        30157 :               vec<stmt_vec_info> substmts;
    5374        30157 :               substmts.create (end - start);
    5375       126654 :               for (unsigned j = start; j < end; ++j)
    5376        66340 :                 substmts.quick_push (scalar_stmts[j]);
    5377        30157 :               node = vect_build_slp_tree (vinfo, substmts,
    5378              :                                           matches, limit, &tree_size, bst_map);
    5379        30157 :               if (node)
    5380              :                 {
    5381        24073 :                   rhs_nodes.safe_push (node);
    5382        24073 :                   if (start == 0)
    5383         8263 :                     rhs_common_nlanes = SLP_TREE_LANES (node);
    5384        15810 :                   else if (rhs_common_nlanes != SLP_TREE_LANES (node))
    5385         1413 :                     rhs_common_nlanes = 0;
    5386        24073 :                   start = end;
    5387        24073 :                   if (want_store_lanes || force_single_lane)
    5388         5321 :                     end = start + 1;
    5389              :                   else
    5390              :                     end = group_size;
    5391              :                 }
    5392              :               else
    5393              :                 {
    5394         6084 :                   substmts.release ();
    5395         6084 :                   if (end - start == 1)
    5396              :                     {
    5397              :                       /* Single-lane discovery failed.  Free resources.  */
    5398          115 :                       for (auto node : rhs_nodes)
    5399            0 :                         vect_free_slp_tree (node);
    5400          115 :                       scalar_stmts.release ();
    5401          115 :                       if (dump_enabled_p ())
    5402           14 :                         dump_printf_loc (MSG_NOTE, vect_location,
    5403              :                                          "SLP discovery failed\n");
    5404          115 :                       return false;
    5405              :                     }
    5406              : 
    5407              :                   /* ???  It really happens that we soft-fail SLP
    5408              :                      build at a mismatch but the matching part hard-fails
    5409              :                      later.  As we know we arrived here with a group
    5410              :                      larger than one try a group of size one!  */
    5411         5969 :                   if (matches[0] != 0)
    5412           12 :                     end = start + 1;
    5413              :                   else
    5414        13085 :                     for (unsigned j = start; j < end; j++)
    5415        13085 :                       if (matches[j - start] != 0)
    5416              :                         {
    5417              :                           end = j;
    5418              :                           break;
    5419              :                         }
    5420              :                 }
    5421              :             }
    5422              : 
    5423              :           /* Now re-assess whether we want store lanes in case the
    5424              :              discovery ended up producing all single-lane RHSs.  */
    5425         8263 :           if (! want_store_lanes
    5426         8263 :               && rhs_common_nlanes == 1
    5427         7183 :               && ! STMT_VINFO_GATHER_SCATTER_P (stmt_info)
    5428         7183 :               && ! STMT_VINFO_STRIDED_P (stmt_info)
    5429         5445 :               && ! STMT_VINFO_SLP_VECT_ONLY (stmt_info)
    5430         5442 :               && compare_step_with_zero (vinfo, stmt_info) > 0
    5431        13618 :               && (vect_store_lanes_supported (SLP_TREE_VECTYPE (rhs_nodes[0]),
    5432              :                                               group_size, masked_p)
    5433              :                   != IFN_LAST))
    5434              :             want_store_lanes = true;
    5435              : 
    5436              :           /* Now we assume we can build the root SLP node from all stores.  */
    5437         8263 :           if (want_store_lanes)
    5438              :             {
    5439              :               /* For store-lanes feed the store node with all RHS nodes
    5440              :                  in order.  */
    5441            0 :               node = vect_create_new_slp_node (scalar_stmts,
    5442            0 :                                                SLP_TREE_CHILDREN
    5443              :                                                  (rhs_nodes[0]).length ());
    5444            0 :               SLP_TREE_VECTYPE (node) = SLP_TREE_VECTYPE (rhs_nodes[0]);
    5445            0 :               node->ldst_lanes = true;
    5446            0 :               SLP_TREE_CHILDREN (node)
    5447            0 :                 .reserve_exact (SLP_TREE_CHILDREN (rhs_nodes[0]).length ()
    5448            0 :                                 + rhs_nodes.length () - 1);
    5449              :               /* First store value and possibly mask.  */
    5450            0 :               SLP_TREE_CHILDREN (node)
    5451            0 :                 .splice (SLP_TREE_CHILDREN (rhs_nodes[0]));
    5452              :               /* Rest of the store values.  All mask nodes are the same,
    5453              :                  this should be guaranteed by dataref group discovery.  */
    5454            0 :               for (unsigned j = 1; j < rhs_nodes.length (); ++j)
    5455            0 :                 SLP_TREE_CHILDREN (node)
    5456            0 :                   .quick_push (SLP_TREE_CHILDREN (rhs_nodes[j])[0]);
    5457            0 :               for (slp_tree child : SLP_TREE_CHILDREN (node))
    5458            0 :                 child->refcnt++;
    5459              :             }
    5460              :           else
    5461         8263 :             node = vect_build_slp_store_interleaving (rhs_nodes, scalar_stmts);
    5462              : 
    5463        32336 :           while (!rhs_nodes.is_empty ())
    5464        24073 :             vect_free_slp_tree (rhs_nodes.pop ());
    5465              : 
    5466              :           /* Create a new SLP instance.  */
    5467         8263 :           slp_instance new_instance = XNEW (class _slp_instance);
    5468         8263 :           SLP_INSTANCE_TREE (new_instance) = node;
    5469         8263 :           SLP_INSTANCE_LOADS (new_instance) = vNULL;
    5470         8263 :           SLP_INSTANCE_ROOT_STMTS (new_instance) = root_stmt_infos;
    5471         8263 :           SLP_INSTANCE_REMAIN_DEFS (new_instance) = remain;
    5472         8263 :           SLP_INSTANCE_KIND (new_instance) = kind;
    5473         8263 :           new_instance->reduc_phis = NULL;
    5474         8263 :           new_instance->cost_vec = vNULL;
    5475         8263 :           new_instance->subgraph_entries = vNULL;
    5476              : 
    5477         8263 :           if (dump_enabled_p ())
    5478          859 :             dump_printf_loc (MSG_NOTE, vect_location,
    5479              :                              "SLP size %u vs. limit %u.\n",
    5480              :                              tree_size, max_tree_size);
    5481              : 
    5482         8263 :           vinfo->slp_instances.safe_push (new_instance);
    5483              : 
    5484              :           /* ???  We've replaced the old SLP_INSTANCE_GROUP_SIZE with
    5485              :              the number of SLP lanes of the root in a few places.
    5486              :              Verify that assumption holds.  */
    5487         8263 :           gcc_assert (SLP_TREE_LANES (SLP_INSTANCE_TREE (new_instance))
    5488              :                       == group_size);
    5489              : 
    5490         8263 :           if (dump_enabled_p ())
    5491              :             {
    5492          859 :               dump_printf_loc (MSG_NOTE, vect_location,
    5493              :                                "Final SLP tree for instance %p:\n",
    5494              :                                (void *) new_instance);
    5495          859 :               vect_print_slp_graph (MSG_NOTE, vect_location,
    5496              :                                     SLP_INSTANCE_TREE (new_instance));
    5497              :             }
    5498              :           return true;
    5499         8378 :         }
    5500              :       else
    5501              :         /* Free the allocated memory.  */
    5502       257712 :         scalar_stmts.release ();
    5503              : 
    5504              :       /* Even though the first vector did not all match, we might be able to SLP
    5505              :          (some) of the remainder.  FORNOW ignore this possibility.  */
    5506              :     }
    5507              :   else
    5508              :     /* Free the allocated memory.  */
    5509            1 :     scalar_stmts.release ();
    5510              : 
    5511              :   /* Failed to SLP.  */
    5512       257713 :   if (dump_enabled_p ())
    5513           50 :     dump_printf_loc (MSG_NOTE, vect_location, "SLP discovery failed\n");
    5514              :   return false;
    5515              : }
    5516              : 
    5517              : /* qsort comparator ordering SLP load nodes.  */
    5518              : 
    5519              : static int
    5520      2690328 : vllp_cmp (const void *a_, const void *b_)
    5521              : {
    5522      2690328 :   const slp_tree a = *(const slp_tree *)a_;
    5523      2690328 :   const slp_tree b = *(const slp_tree *)b_;
    5524      2690328 :   stmt_vec_info a0 = SLP_TREE_SCALAR_STMTS (a)[0];
    5525      2690328 :   stmt_vec_info b0 = SLP_TREE_SCALAR_STMTS (b)[0];
    5526      2690328 :   if (STMT_VINFO_GROUPED_ACCESS (a0)
    5527      1547899 :       && STMT_VINFO_GROUPED_ACCESS (b0)
    5528      4176179 :       && DR_GROUP_FIRST_ELEMENT (a0) == DR_GROUP_FIRST_ELEMENT (b0))
    5529              :     {
    5530              :       /* Same group, order after lanes used.  */
    5531       350037 :       if (SLP_TREE_LANES (a) < SLP_TREE_LANES (b))
    5532              :         return 1;
    5533       341064 :       else if (SLP_TREE_LANES (a) > SLP_TREE_LANES (b))
    5534              :         return -1;
    5535              :       else
    5536              :         {
    5537              :           /* Try to order loads using the same lanes together, breaking
    5538              :              the tie with the lane number that first differs.  */
    5539       331327 :           if (!SLP_TREE_LOAD_PERMUTATION (a).exists ()
    5540       331327 :               && !SLP_TREE_LOAD_PERMUTATION (b).exists ())
    5541              :             return 0;
    5542       331327 :           else if (SLP_TREE_LOAD_PERMUTATION (a).exists ()
    5543       331327 :                    && !SLP_TREE_LOAD_PERMUTATION (b).exists ())
    5544              :             return 1;
    5545       327260 :           else if (!SLP_TREE_LOAD_PERMUTATION (a).exists ()
    5546       327260 :                    && SLP_TREE_LOAD_PERMUTATION (b).exists ())
    5547              :             return -1;
    5548              :           else
    5549              :             {
    5550       319770 :               for (unsigned i = 0; i < SLP_TREE_LANES (a); ++i)
    5551       319770 :                 if (SLP_TREE_LOAD_PERMUTATION (a)[i]
    5552       319770 :                     != SLP_TREE_LOAD_PERMUTATION (b)[i])
    5553              :                   {
    5554              :                     /* In-order lane first, that's what the above case for
    5555              :                        no permutation does.  */
    5556       318458 :                     if (SLP_TREE_LOAD_PERMUTATION (a)[i] == i)
    5557              :                       return -1;
    5558       195596 :                     else if (SLP_TREE_LOAD_PERMUTATION (b)[i] == i)
    5559              :                       return 1;
    5560       103282 :                     else if (SLP_TREE_LOAD_PERMUTATION (a)[i]
    5561       103282 :                              < SLP_TREE_LOAD_PERMUTATION (b)[i])
    5562              :                       return -1;
    5563              :                     else
    5564        38668 :                       return 1;
    5565              :                   }
    5566              :               return 0;
    5567              :             }
    5568              :         }
    5569              :     }
    5570              :   else /* Different groups or non-groups.  */
    5571              :     {
    5572              :       /* Order groups as their first element to keep them together.  */
    5573      2340291 :       if (STMT_VINFO_GROUPED_ACCESS (a0))
    5574      2340291 :         a0 = DR_GROUP_FIRST_ELEMENT (a0);
    5575      2340291 :       if (STMT_VINFO_GROUPED_ACCESS (b0))
    5576      2340291 :         b0 = DR_GROUP_FIRST_ELEMENT (b0);
    5577      2340291 :       if (a0 == b0)
    5578              :         return 0;
    5579              :       /* Tie using UID.  */
    5580      2340171 :       else if (gimple_uid (STMT_VINFO_STMT (a0))
    5581      2340171 :                < gimple_uid (STMT_VINFO_STMT (b0)))
    5582              :         return -1;
    5583              :       else
    5584              :         {
    5585      1040005 :           gcc_assert (gimple_uid (STMT_VINFO_STMT (a0))
    5586              :                       != gimple_uid (STMT_VINFO_STMT (b0)));
    5587              :           return 1;
    5588              :         }
    5589              :     }
    5590              : }
    5591              : 
    5592              : /* Return whether if the load permutation of NODE is consecutive starting
    5593              :    with value START_VAL in the first element.  If START_VAL is not given
    5594              :    the first element's value is used.  */
    5595              : 
    5596              : bool
    5597       649513 : vect_load_perm_consecutive_p (slp_tree node, unsigned start_val)
    5598              : {
    5599       649513 :   load_permutation_t perm = SLP_TREE_LOAD_PERMUTATION (node);
    5600              : 
    5601       649513 :   if (!perm.exists () || !perm.length ())
    5602              :     return false;
    5603              : 
    5604       649513 :   if (start_val == UINT_MAX)
    5605        79957 :     start_val = perm[0];
    5606              : 
    5607      1282956 :   for (unsigned int i = 0; i < perm.length (); i++)
    5608       657139 :     if (perm[i] != start_val + (unsigned int) i)
    5609              :       return false;
    5610              : 
    5611              :   return true;
    5612              : }
    5613              : 
    5614              : /* Process the set of LOADS that are all from the same dataref group.  */
    5615              : 
    5616              : static void
    5617       162196 : vect_lower_load_permutations (loop_vec_info loop_vinfo,
    5618              :                               scalar_stmts_to_slp_tree_map_t *bst_map,
    5619              :                               const array_slice<slp_tree> &loads,
    5620              :                               bool force_single_lane)
    5621              : {
    5622              :   /* We at this point want to lower without a fixed VF or vector
    5623              :      size in mind which means we cannot actually compute whether we
    5624              :      need three or more vectors for a load permutation yet.  So always
    5625              :      lower.  */
    5626       162196 :   stmt_vec_info first
    5627       162196 :     = DR_GROUP_FIRST_ELEMENT (SLP_TREE_SCALAR_STMTS (loads[0])[0]);
    5628       162196 :   unsigned group_lanes = DR_GROUP_SIZE (first);
    5629              : 
    5630              :   /* Verify if all load permutations can be implemented with a suitably
    5631              :      large element load-lanes operation.  */
    5632       162196 :   unsigned ld_lanes_lanes = SLP_TREE_LANES (loads[0]);
    5633       162196 :   if (STMT_VINFO_STRIDED_P (first)
    5634       159718 :       || compare_step_with_zero (loop_vinfo, first) <= 0
    5635       157086 :       || exact_log2 (ld_lanes_lanes) == -1
    5636              :       /* ???  For now only support the single-lane case as there is
    5637              :          missing support on the store-lane side and code generation
    5638              :          isn't up to the task yet.  */
    5639       154243 :       || ld_lanes_lanes != 1
    5640       305377 :       || vect_load_lanes_supported (SLP_TREE_VECTYPE (loads[0]),
    5641              :                                     group_lanes / ld_lanes_lanes,
    5642              :                                     false) == IFN_LAST)
    5643              :     ld_lanes_lanes = 0;
    5644              :   else
    5645              :     /* Verify the loads access the same number of lanes aligned to
    5646              :        ld_lanes_lanes.  */
    5647            0 :     for (slp_tree load : loads)
    5648              :       {
    5649            0 :         if (SLP_TREE_LANES (load) != ld_lanes_lanes)
    5650              :           {
    5651              :             ld_lanes_lanes = 0;
    5652              :             break;
    5653              :           }
    5654            0 :         unsigned first = SLP_TREE_LOAD_PERMUTATION (load)[0];
    5655            0 :         if (first % ld_lanes_lanes != 0)
    5656              :           {
    5657              :             ld_lanes_lanes = 0;
    5658              :             break;
    5659              :           }
    5660            0 :         if (!vect_load_perm_consecutive_p (load))
    5661              :           {
    5662              :             ld_lanes_lanes = 0;
    5663              :             break;
    5664              :           }
    5665              :       }
    5666              : 
    5667              :   /* Only a power-of-two number of lanes matches interleaving with N levels.
    5668              :      ???  An even number of lanes could be reduced to 1<<ceil_log2(N)-1 lanes
    5669              :      at each step.  */
    5670       263009 :   if (ld_lanes_lanes == 0 && exact_log2 (group_lanes) == -1 && group_lanes != 3)
    5671              :     return;
    5672              : 
    5673       267060 :   for (slp_tree load : loads)
    5674              :     {
    5675              :       /* Leave masked or gather loads alone for now.  */
    5676       188455 :       if (!SLP_TREE_CHILDREN (load).is_empty ())
    5677        61169 :         continue;
    5678              : 
    5679              :       /* For single-element interleaving spanning multiple vectors avoid
    5680              :          lowering, we want to use VMAT_ELEMENTWISE later.  */
    5681       188449 :       if (ld_lanes_lanes == 0
    5682       188449 :           && SLP_TREE_LANES (load) == 1
    5683       168919 :           && !DR_GROUP_NEXT_ELEMENT (first)
    5684       268331 :           && maybe_gt (group_lanes,
    5685              :                        TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (load))))
    5686        51387 :         return;
    5687              : 
    5688              :       /* We want to pattern-match special cases here and keep those
    5689              :          alone.  Candidates are splats and load-lane.  */
    5690              : 
    5691              :       /* We need to lower only loads of less than half of the groups
    5692              :          lanes, including duplicate lanes.  Note this leaves nodes
    5693              :          with a non-1:1 load permutation around instead of canonicalizing
    5694              :          those into a load and a permute node.  Removing this early
    5695              :          check would do such canonicalization.  */
    5696       137062 :       if (SLP_TREE_LANES (load) >= (group_lanes + 1) / 2
    5697        57594 :           && ld_lanes_lanes == 0)
    5698        57594 :         continue;
    5699              : 
    5700              :       /* Build the permute to get the original load permutation order.  */
    5701        79468 :       bool contiguous = vect_load_perm_consecutive_p (load);
    5702        79468 :       lane_permutation_t final_perm;
    5703        79468 :       final_perm.create (SLP_TREE_LANES (load));
    5704       239348 :       for (unsigned i = 0; i < SLP_TREE_LANES (load); ++i)
    5705       160824 :         final_perm.quick_push (
    5706        80412 :           std::make_pair (0, SLP_TREE_LOAD_PERMUTATION (load)[i]));
    5707              : 
    5708              :       /* When the load permutation accesses a contiguous unpermuted,
    5709              :          power-of-two aligned and sized chunk leave the load alone.
    5710              :          We can likely (re-)load it more efficiently rather than
    5711              :          extracting it from the larger load.
    5712              :          ???  Long-term some of the lowering should move to where
    5713              :          the vector types involved are fixed.  */
    5714        83037 :       if (!force_single_lane
    5715        79468 :           && ld_lanes_lanes == 0
    5716        53591 :           && contiguous
    5717        53331 :           && (SLP_TREE_LANES (load) > 1 || loads.size () == 1)
    5718         6575 :           && pow2p_hwi (SLP_TREE_LANES (load))
    5719         6539 :           && pow2p_hwi (group_lanes)
    5720         3569 :           && SLP_TREE_LOAD_PERMUTATION (load)[0] % SLP_TREE_LANES (load) == 0
    5721        83037 :           && group_lanes % SLP_TREE_LANES (load) == 0)
    5722              :         {
    5723         3569 :           final_perm.release ();
    5724         3569 :           continue;
    5725              :         }
    5726              : 
    5727              :       /* First build (and possibly re-use) a load node for the
    5728              :          unpermuted group.  Gaps in the middle and on the end are
    5729              :          represented with NULL stmts.  */
    5730        75899 :       vec<stmt_vec_info> stmts;
    5731        75899 :       stmts.create (group_lanes);
    5732       270993 :       for (stmt_vec_info s = first; s; s = DR_GROUP_NEXT_ELEMENT (s))
    5733              :         {
    5734       195094 :           if (s != first)
    5735       124250 :             for (unsigned i = 1; i < DR_GROUP_GAP (s); ++i)
    5736         5055 :               stmts.quick_push (NULL);
    5737       195094 :           stmts.quick_push (s);
    5738              :         }
    5739       139731 :       for (unsigned i = 0; i < DR_GROUP_GAP (first); ++i)
    5740        63832 :         stmts.quick_push (NULL);
    5741        75899 :       match_elt_t *matches = XALLOCAVEC (match_elt_t, group_lanes);
    5742        75899 :       unsigned limit = 1;
    5743        75899 :       unsigned tree_size = 0;
    5744        75899 :       slp_tree l0 = vect_build_slp_tree (loop_vinfo, stmts, matches, &limit,
    5745        75899 :                                          &tree_size, bst_map);
    5746        75899 :       gcc_assert (!SLP_TREE_LOAD_PERMUTATION (l0).exists ());
    5747              : 
    5748        75899 :       if (ld_lanes_lanes != 0)
    5749              :         {
    5750              :           /* ???  If this is not in sync with what get_load_store_type
    5751              :              later decides the SLP representation is not good for other
    5752              :              store vectorization methods.  */
    5753            0 :           l0->ldst_lanes = true;
    5754            0 :           load->ldst_lanes = true;
    5755              :         }
    5756              : 
    5757       236343 :       while (1)
    5758              :         {
    5759       156121 :           unsigned group_lanes = SLP_TREE_LANES (l0);
    5760       156121 :           if (ld_lanes_lanes != 0
    5761       156121 :               || SLP_TREE_LANES (load) >= (group_lanes + 1) / 2)
    5762              :             break;
    5763              : 
    5764              :           /* Try to lower by reducing the group to half its size using an
    5765              :              interleaving scheme.  For this try to compute whether all
    5766              :              elements needed for this load are in even or odd elements of
    5767              :              an even/odd decomposition with N consecutive elements.
    5768              :              Thus { e, e, o, o, e, e, o, o } would be an even/odd decomposition
    5769              :              with N == 2.  */
    5770              :           /* ???  Only an even number of lanes can be handed this way, but the
    5771              :              fallback below could work for any number.  We have to make sure
    5772              :              to round up in that case.  */
    5773        80222 :           gcc_assert ((group_lanes & 1) == 0 || group_lanes == 3);
    5774        12119 :           unsigned even = 0, odd = 0;
    5775        12119 :           if ((group_lanes & 1) == 0)
    5776              :             {
    5777        12119 :               even = (1 << ceil_log2 (group_lanes)) - 1;
    5778        12119 :               odd = even;
    5779        49225 :               for (auto l : final_perm)
    5780              :                 {
    5781        12868 :                   even &= ~l.second;
    5782        12868 :                   odd &= l.second;
    5783              :                 }
    5784              :             }
    5785              : 
    5786              :           /* Now build an even or odd extraction from the unpermuted load.  */
    5787        80222 :           lane_permutation_t perm;
    5788        80222 :           perm.create ((group_lanes + 1) / 2);
    5789        80222 :           unsigned even_level = even ? 1 << ctz_hwi (even) : 0;
    5790        80222 :           unsigned odd_level = odd ? 1 << ctz_hwi (odd) : 0;
    5791        80222 :           if (even_level
    5792        11141 :               && group_lanes % (2 * even_level) == 0
    5793              :               /* ???  When code generating permutes we do not try to pun
    5794              :                  to larger component modes so level != 1 isn't a natural
    5795              :                  even/odd extract.  Prefer one if possible.  */
    5796        11141 :               && (even_level == 1 || !odd_level || odd_level != 1))
    5797              :             {
    5798              :               /* { 0, 1, ... 4, 5 ..., } */
    5799        39435 :               for (unsigned i = 0; i < group_lanes / 2 / even_level; ++i)
    5800        62245 :                 for (unsigned j = 0; j < even_level; ++j)
    5801        31318 :                   perm.quick_push (std::make_pair (0, 2 * i * even_level + j));
    5802              :             }
    5803        69081 :           else if (odd_level)
    5804              :             {
    5805              :               /* { ..., 2, 3, ... 6, 7 } */
    5806         3581 :               gcc_assert (group_lanes % (2 * odd_level) == 0);
    5807        15445 :               for (unsigned i = 0; i < group_lanes / 2 / odd_level; ++i)
    5808        23782 :                 for (unsigned j = 0; j < odd_level; ++j)
    5809        11918 :                   perm.quick_push
    5810        11918 :                     (std::make_pair (0, (2 * i + 1) * odd_level + j));
    5811              :             }
    5812              :           else
    5813              :             {
    5814              :               /* As fallback extract all used lanes and fill to half the
    5815              :                  group size by repeating the last element.
    5816              :                  ???  This is quite a bad strathegy for re-use - we could
    5817              :                  brute force our way to find more optimal filling lanes to
    5818              :                  maximize re-use when looking at all loads from the group.  */
    5819        68133 :               auto_bitmap l;
    5820       272588 :               for (auto p : final_perm)
    5821        68189 :                 bitmap_set_bit (l, p.second);
    5822        68133 :               unsigned i = 0;
    5823        68133 :               bitmap_iterator bi;
    5824       136322 :               EXECUTE_IF_SET_IN_BITMAP (l, 0, i, bi)
    5825        68189 :                   perm.quick_push (std::make_pair (0, i));
    5826       272684 :               while (perm.length () < (group_lanes + 1) / 2)
    5827        68209 :                 perm.quick_push (perm.last ());
    5828        68133 :             }
    5829              : 
    5830              :           /* Update final_perm with the intermediate permute.  */
    5831       161193 :           for (unsigned i = 0; i < final_perm.length (); ++i)
    5832              :             {
    5833        80971 :               unsigned l = final_perm[i].second;
    5834        80971 :               unsigned j;
    5835        90542 :               for (j = 0; j < perm.length (); ++j)
    5836        90542 :                 if (perm[j].second == l)
    5837              :                   {
    5838        80971 :                     final_perm[i].second = j;
    5839        80971 :                     break;
    5840              :                   }
    5841        80971 :               gcc_assert (j < perm.length ());
    5842              :             }
    5843              : 
    5844              :           /* And create scalar stmts.  */
    5845        80222 :           vec<stmt_vec_info> perm_stmts;
    5846        80222 :           perm_stmts.create (perm.length ());
    5847       340078 :           for (unsigned i = 0; i < perm.length (); ++i)
    5848       179634 :             perm_stmts.quick_push (SLP_TREE_SCALAR_STMTS (l0)[perm[i].second]);
    5849              : 
    5850        80222 :           slp_tree p = vect_create_new_slp_node (1, VEC_PERM_EXPR);
    5851        80222 :           SLP_TREE_CHILDREN (p).quick_push (l0);
    5852        80222 :           SLP_TREE_LANE_PERMUTATION (p) = perm;
    5853        80222 :           SLP_TREE_VECTYPE (p) = SLP_TREE_VECTYPE (load);
    5854        80222 :           SLP_TREE_LANES (p) = perm.length ();
    5855              :           /* ???  As we have scalar stmts for this intermediate permute we
    5856              :              could CSE it via bst_map but we do not want to pick up
    5857              :              another SLP node with a load permutation.  We instead should
    5858              :              have a "local" CSE map here.  */
    5859        80222 :           SLP_TREE_SCALAR_STMTS (p) = perm_stmts;
    5860              : 
    5861              :           /* We now have a node for (group_lanes + 1) / 2 lanes.  */
    5862        80222 :           l0 = p;
    5863        80222 :         }
    5864              : 
    5865              :       /* And finally from the ordered reduction node create the
    5866              :          permute to shuffle the lanes into the original load-permutation
    5867              :          order.  We replace the original load node with this.  */
    5868        75899 :       SLP_TREE_CODE (load) = VEC_PERM_EXPR;
    5869        75899 :       SLP_TREE_LOAD_PERMUTATION (load).release ();
    5870        75899 :       SLP_TREE_LANE_PERMUTATION (load) = final_perm;
    5871        75899 :       SLP_TREE_CHILDREN (load).create (1);
    5872        75899 :       SLP_TREE_CHILDREN (load).quick_push (l0);
    5873        75899 :       SLP_TREE_REPRESENTATIVE (load) = NULL;
    5874              :     }
    5875              : }
    5876              : 
    5877              : /* Transform SLP loads in the SLP graph created by SLP discovery to
    5878              :    group loads from the same group and lower load permutations that
    5879              :    are unlikely to be supported into a series of permutes.
    5880              :    In the degenerate case of having only single-lane SLP instances
    5881              :    this should result in a series of permute nodes emulating an
    5882              :    interleaving scheme.  */
    5883              : 
    5884              : static void
    5885       501509 : vect_lower_load_permutations (loop_vec_info loop_vinfo,
    5886              :                               scalar_stmts_to_slp_tree_map_t *bst_map,
    5887              :                               bool force_single_lane)
    5888              : {
    5889              :   /* Gather and sort loads across all instances.  */
    5890       501509 :   hash_set<slp_tree> visited;
    5891       501509 :   auto_vec<slp_tree> loads;
    5892      2301121 :   for (auto inst : loop_vinfo->slp_instances)
    5893       798564 :     vect_gather_slp_loads (loads, SLP_INSTANCE_TREE (inst), visited);
    5894       501509 :   if (loads.is_empty ())
    5895        93441 :     return;
    5896       408068 :   loads.qsort (vllp_cmp);
    5897              : 
    5898              :   /* Now process each dataref group separately.  */
    5899       408068 :   unsigned firsti = 0;
    5900      1160895 :   for (unsigned i = 1; i < loads.length (); ++i)
    5901              :     {
    5902       344759 :       slp_tree first = loads[firsti];
    5903       344759 :       slp_tree next = loads[i];
    5904       344759 :       stmt_vec_info a0 = SLP_TREE_SCALAR_STMTS (first)[0];
    5905       344759 :       stmt_vec_info b0 = SLP_TREE_SCALAR_STMTS (next)[0];
    5906       344759 :       if (STMT_VINFO_GROUPED_ACCESS (a0)
    5907       158976 :           && STMT_VINFO_GROUPED_ACCESS (b0)
    5908       490541 :           && DR_GROUP_FIRST_ELEMENT (a0) == DR_GROUP_FIRST_ELEMENT (b0))
    5909        63652 :         continue;
    5910              :       /* Now we have one or multiple SLP loads of the same group from
    5911              :          firsti to i - 1.  */
    5912       281107 :       if (STMT_VINFO_GROUPED_ACCESS (a0))
    5913        95324 :         vect_lower_load_permutations (loop_vinfo, bst_map,
    5914        95324 :                                       make_array_slice (&loads[firsti],
    5915              :                                                         i - firsti),
    5916              :                                       force_single_lane);
    5917              :       firsti = i;
    5918              :     }
    5919       816136 :   if (firsti < loads.length ()
    5920       816136 :       && STMT_VINFO_GROUPED_ACCESS (SLP_TREE_SCALAR_STMTS (loads[firsti])[0]))
    5921        66872 :     vect_lower_load_permutations (loop_vinfo, bst_map,
    5922        66872 :                                   make_array_slice (&loads[firsti],
    5923        66872 :                                                     loads.length () - firsti),
    5924              :                                   force_single_lane);
    5925       501509 : }
    5926              : 
    5927              : /* Check if there are stmts in the loop can be vectorized using SLP.  Build SLP
    5928              :    trees of packed scalar stmts if SLP is possible.  */
    5929              : 
    5930              : opt_result
    5931      1180843 : vect_analyze_slp (vec_info *vinfo, unsigned max_tree_size,
    5932              :                   bool force_single_lane)
    5933              : {
    5934      1180843 :   loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo);
    5935      1180843 :   unsigned int i;
    5936      1180843 :   stmt_vec_info first_element;
    5937      1180843 :   slp_instance instance;
    5938              : 
    5939      1180843 :   DUMP_VECT_SCOPE ("vect_analyze_slp");
    5940              : 
    5941      1180843 :   unsigned limit = max_tree_size;
    5942              : 
    5943      1180843 :   scalar_stmts_to_slp_tree_map_t *bst_map
    5944      1180843 :     = new scalar_stmts_to_slp_tree_map_t ();
    5945              : 
    5946              :   /* Find SLP sequences starting from groups of grouped stores.  */
    5947      3302001 :   FOR_EACH_VEC_ELT (vinfo->grouped_stores, i, first_element)
    5948       940438 :     if (! vect_analyze_slp_instance (vinfo, bst_map, first_element,
    5949              :                                      slp_inst_kind_store, max_tree_size, &limit,
    5950              :                                      force_single_lane)
    5951       940438 :         && loop_vinfo)
    5952              :       {
    5953          123 :         release_scalar_stmts_to_slp_tree_map (bst_map);
    5954          123 :         return opt_result::failure_at (vect_location, "SLP build failed.\n");
    5955              :       }
    5956              : 
    5957              :   /* For loops also start SLP discovery from non-grouped stores.  */
    5958      1180720 :   if (loop_vinfo)
    5959              :     {
    5960              :       data_reference_p dr;
    5961      1690933 :       FOR_EACH_VEC_ELT (vinfo->shared->datarefs, i, dr)
    5962      1174986 :         if (DR_IS_WRITE (dr))
    5963              :           {
    5964       380112 :             stmt_vec_info stmt_info = vinfo->lookup_dr (dr)->stmt;
    5965              :             /* Grouped stores are already handled above.  */
    5966       380112 :             if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
    5967       103274 :               continue;
    5968       276838 :             vec<stmt_vec_info> stmts;
    5969       276838 :             vec<stmt_vec_info> roots = vNULL;
    5970       276838 :             vec<tree> remain = vNULL;
    5971       276838 :             stmts.create (1);
    5972       276838 :             stmts.quick_push (stmt_info);
    5973       276838 :             if (! vect_build_slp_instance (vinfo, slp_inst_kind_store,
    5974              :                                            stmts, roots, remain, max_tree_size,
    5975              :                                            &limit, bst_map, force_single_lane))
    5976              :               {
    5977         3592 :                 release_scalar_stmts_to_slp_tree_map (bst_map);
    5978         3592 :                 return opt_result::failure_at (vect_location,
    5979              :                                                "SLP build failed.\n");
    5980              :               }
    5981              :           }
    5982              : 
    5983              :       stmt_vec_info stmt_info;
    5984       515987 :       FOR_EACH_VEC_ELT (LOOP_VINFO_ALTERNATE_DEFS (loop_vinfo), i, stmt_info)
    5985              :         {
    5986           20 :           vec<stmt_vec_info> stmts;
    5987           20 :           vec<stmt_vec_info> roots = vNULL;
    5988           20 :           vec<tree> remain = vNULL;
    5989           20 :           stmts.create (1);
    5990           20 :           stmts.quick_push (stmt_info);
    5991           20 :           if (! vect_build_slp_instance (vinfo, slp_inst_kind_store,
    5992              :                                          stmts, roots, remain, max_tree_size,
    5993              :                                          &limit, bst_map, force_single_lane))
    5994              :             {
    5995            0 :               release_scalar_stmts_to_slp_tree_map (bst_map);
    5996            0 :               return opt_result::failure_at (vect_location,
    5997              :                                              "SLP build failed.\n");
    5998              :             }
    5999              :         }
    6000              :     }
    6001              : 
    6002      1177128 :   if (bb_vec_info bb_vinfo = dyn_cast <bb_vec_info> (vinfo))
    6003              :     {
    6004      1974194 :       for (unsigned i = 0; i < bb_vinfo->roots.length (); ++i)
    6005              :         {
    6006      1313013 :           vect_location = bb_vinfo->roots[i].roots[0]->stmt;
    6007              :           /* Apply patterns.  */
    6008      4302962 :           for (unsigned j = 0; j < bb_vinfo->roots[i].stmts.length (); ++j)
    6009      5979898 :             bb_vinfo->roots[i].stmts[j]
    6010      3082937 :               = vect_stmt_to_vectorize (bb_vinfo->roots[i].stmts[j]);
    6011      1313013 :           if (vect_build_slp_instance (bb_vinfo, bb_vinfo->roots[i].kind,
    6012      1313013 :                                        bb_vinfo->roots[i].stmts,
    6013      1313013 :                                        bb_vinfo->roots[i].roots,
    6014      1313013 :                                        bb_vinfo->roots[i].remain,
    6015              :                                        max_tree_size, &limit, bst_map, false))
    6016              :             {
    6017       155681 :               bb_vinfo->roots[i].roots = vNULL;
    6018       155681 :               bb_vinfo->roots[i].remain = vNULL;
    6019              :             }
    6020      1313013 :           bb_vinfo->roots[i].stmts = vNULL;
    6021              :         }
    6022              :     }
    6023              : 
    6024      1177128 :   if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
    6025              :     {
    6026              :       /* Find SLP sequences starting from groups of reductions.  */
    6027       515947 :       if (!vect_analyze_slp_reductions (loop_vinfo, max_tree_size, &limit,
    6028              :                                         bst_map, force_single_lane))
    6029              :         {
    6030         1887 :           release_scalar_stmts_to_slp_tree_map (bst_map);
    6031         1887 :           return opt_result::failure_at (vect_location, "SLP build failed.\n");
    6032              :         }
    6033              : 
    6034              :       /* Make sure to vectorize only-live stmts, usually inductions.  */
    6035      2316161 :       for (edge e : get_loop_exit_edges (LOOP_VINFO_LOOP (loop_vinfo)))
    6036      1496199 :         for (auto gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi);
    6037       712262 :              gsi_next (&gsi))
    6038              :           {
    6039       722218 :             gphi *lc_phi = *gsi;
    6040       722218 :             tree def = gimple_phi_arg_def_from_edge (lc_phi, e);
    6041       722218 :             stmt_vec_info stmt_info;
    6042       722218 :             if (TREE_CODE (def) == SSA_NAME
    6043       606171 :                 && !virtual_operand_p (def)
    6044       312410 :                 && (stmt_info = loop_vinfo->lookup_def (def))
    6045       279972 :                 && ((stmt_info = vect_stmt_to_vectorize (stmt_info)), true)
    6046       279972 :                 && STMT_VINFO_RELEVANT (stmt_info) == vect_used_only_live
    6047       217783 :                 && STMT_VINFO_LIVE_P (stmt_info)
    6048       217783 :                 && !VECTORIZABLE_CYCLE_DEF (STMT_VINFO_DEF_TYPE (stmt_info))
    6049       835729 :                 && STMT_VINFO_REDUC_IDX (stmt_info) == -1)
    6050              :               {
    6051       113423 :                 vec<stmt_vec_info> stmts;
    6052       113423 :                 vec<stmt_vec_info> roots = vNULL;
    6053       113423 :                 vec<tree> remain = vNULL;
    6054       113423 :                 stmts.create (1);
    6055       113423 :                 stmts.quick_push (vect_stmt_to_vectorize (stmt_info));
    6056       113423 :                 if (! vect_build_slp_instance (vinfo,
    6057              :                                                slp_inst_kind_reduc_group,
    6058              :                                                stmts, roots, remain,
    6059              :                                                max_tree_size, &limit,
    6060              :                                                bst_map, force_single_lane))
    6061              :                   {
    6062         9956 :                     release_scalar_stmts_to_slp_tree_map (bst_map);
    6063         9956 :                     return opt_result::failure_at (vect_location,
    6064              :                                                    "SLP build failed.\n");
    6065              :                   }
    6066              :               }
    6067         9956 :           }
    6068              : 
    6069              :       /* Find SLP sequences starting from gconds.  */
    6070      1263794 :       for (auto cond : LOOP_VINFO_LOOP_CONDS (loop_vinfo))
    6071              :         {
    6072       295087 :           auto cond_info = loop_vinfo->lookup_stmt (cond);
    6073              : 
    6074       295087 :           cond_info = vect_stmt_to_vectorize (cond_info);
    6075       295087 :           vec<stmt_vec_info> roots = vNULL;
    6076       295087 :           roots.safe_push (cond_info);
    6077       295087 :           gimple *stmt = STMT_VINFO_STMT (cond_info);
    6078       295087 :           tree args0 = gimple_cond_lhs (stmt);
    6079       295087 :           tree args1 = gimple_cond_rhs (stmt);
    6080              : 
    6081              :           /* These should be enforced by cond lowering, but if it failed
    6082              :              bail.  */
    6083       295087 :           if (gimple_cond_code (stmt) != NE_EXPR
    6084       293995 :               || TREE_TYPE (args0) != boolean_type_node
    6085       588486 :               || !integer_zerop (args1))
    6086              :             {
    6087         1688 :               roots.release ();
    6088         1688 :               release_scalar_stmts_to_slp_tree_map (bst_map);
    6089         1688 :               return opt_result::failure_at (vect_location,
    6090              :                                              "SLP build failed.\n");
    6091              :             }
    6092              : 
    6093              :           /* An argument without a loop def will be codegened from vectorizing the
    6094              :              root gcond itself.  As such we don't need to try to build an SLP tree
    6095              :              from them.  It's highly likely that the resulting SLP tree here if both
    6096              :              arguments have a def will be incompatible, but we rely on it being split
    6097              :              later on.  */
    6098       293399 :           auto varg = loop_vinfo->lookup_def (args0);
    6099       293399 :           vec<stmt_vec_info> stmts;
    6100       293399 :           vec<tree> remain = vNULL;
    6101       293399 :           stmts.create (1);
    6102       293399 :           stmts.quick_push (vect_stmt_to_vectorize (varg));
    6103              : 
    6104       293399 :           if (! vect_build_slp_instance (vinfo, slp_inst_kind_gcond,
    6105              :                                          stmts, roots, remain,
    6106              :                                          max_tree_size, &limit,
    6107              :                                          bst_map, force_single_lane))
    6108              :             {
    6109          907 :               roots.release ();
    6110          907 :               release_scalar_stmts_to_slp_tree_map (bst_map);
    6111          907 :               return opt_result::failure_at (vect_location,
    6112              :                                              "SLP build failed.\n");
    6113              :             }
    6114              :         }
    6115              :     }
    6116              : 
    6117      1162690 :   hash_set<slp_tree> visited_patterns;
    6118      1162690 :   slp_tree_to_load_perm_map_t perm_cache;
    6119      1162690 :   slp_compat_nodes_map_t compat_cache;
    6120              : 
    6121              :   /* See if any patterns can be found in the SLP tree.  */
    6122      1162690 :   bool pattern_found = false;
    6123      3954533 :   FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
    6124      1629153 :     pattern_found |= vect_match_slp_patterns (instance, vinfo,
    6125              :                                               &visited_patterns, &perm_cache,
    6126              :                                               &compat_cache);
    6127              : 
    6128              :   /* If any were found optimize permutations of loads.  */
    6129      1162690 :   if (pattern_found)
    6130              :     {
    6131          267 :       hash_map<slp_tree, slp_tree> load_map;
    6132         4981 :       FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
    6133              :         {
    6134         4180 :           slp_tree root = SLP_INSTANCE_TREE (instance);
    6135         4180 :           optimize_load_redistribution (bst_map, vinfo, SLP_TREE_LANES (root),
    6136              :                                         &load_map, root);
    6137              :         }
    6138          267 :     }
    6139              : 
    6140              :   /* Check whether we should force some SLP instances to use load/store-lanes
    6141              :      and do so by forcing SLP re-discovery with single lanes.  We used
    6142              :      to cancel SLP when this applied to all instances in a loop but now
    6143              :      we decide this per SLP instance.  It's important to do this only
    6144              :      after SLP pattern recognition.  */
    6145      1162690 :   if (is_a <loop_vec_info> (vinfo))
    6146      1300073 :     FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
    6147       798564 :       if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_store
    6148       301955 :           && !SLP_INSTANCE_TREE (instance)->ldst_lanes)
    6149              :         {
    6150       301955 :           slp_tree slp_root = SLP_INSTANCE_TREE (instance);
    6151       301955 :           unsigned int group_size = SLP_TREE_LANES (slp_root);
    6152       301955 :           tree vectype = SLP_TREE_VECTYPE (slp_root);
    6153              : 
    6154       301955 :           stmt_vec_info rep_info = SLP_TREE_REPRESENTATIVE (slp_root);
    6155       301955 :           gimple *rep = STMT_VINFO_STMT (rep_info);
    6156       301955 :           bool masked = (is_gimple_call (rep)
    6157         2446 :                          && gimple_call_internal_p (rep)
    6158       304381 :                          && internal_fn_mask_index
    6159         2426 :                               (gimple_call_internal_fn (rep)) != -1);
    6160       301935 :           if (!STMT_VINFO_GROUPED_ACCESS (rep_info)
    6161        30073 :               || slp_root->ldst_lanes
    6162       332028 :               || (vect_store_lanes_supported (vectype, group_size, masked)
    6163              :                   == IFN_LAST))
    6164       301955 :             continue;
    6165              : 
    6166            0 :           auto_vec<slp_tree> loads;
    6167            0 :           hash_set<slp_tree> visited;
    6168            0 :           vect_gather_slp_loads (loads, slp_root, visited);
    6169              : 
    6170              :           /* Check whether any load in the SLP instance is possibly
    6171              :              permuted.  */
    6172            0 :           bool loads_permuted = false;
    6173            0 :           slp_tree load_node;
    6174            0 :           unsigned j;
    6175            0 :           FOR_EACH_VEC_ELT (loads, j, load_node)
    6176              :             {
    6177            0 :               if (!SLP_TREE_LOAD_PERMUTATION (load_node).exists ())
    6178            0 :                 continue;
    6179            0 :               for (unsigned k = 0; k < SLP_TREE_LANES (load_node); k++)
    6180            0 :                 if (SLP_TREE_LOAD_PERMUTATION (load_node)[k] != k)
    6181              :                   {
    6182              :                     loads_permuted = true;
    6183              :                     break;
    6184              :                   }
    6185              :             }
    6186              : 
    6187              :           /* If the loads and stores can use load/store-lanes force re-discovery
    6188              :              with single lanes.  */
    6189            0 :           if (loads_permuted)
    6190              :             {
    6191            0 :               bool can_use_lanes = true;
    6192              :               bool prefer_load_lanes = false;
    6193            0 :               FOR_EACH_VEC_ELT (loads, j, load_node)
    6194            0 :                 if (STMT_VINFO_GROUPED_ACCESS
    6195              :                       (SLP_TREE_REPRESENTATIVE (load_node)))
    6196              :                   {
    6197            0 :                     stmt_vec_info stmt_vinfo = DR_GROUP_FIRST_ELEMENT
    6198              :                         (SLP_TREE_REPRESENTATIVE (load_node));
    6199            0 :                     rep = STMT_VINFO_STMT (stmt_vinfo);
    6200            0 :                     masked = (is_gimple_call (rep)
    6201            0 :                               && gimple_call_internal_p (rep)
    6202            0 :                               && internal_fn_mask_index
    6203            0 :                                    (gimple_call_internal_fn (rep)));
    6204              :                     /* Use SLP for strided accesses (or if we can't
    6205              :                        load-lanes).  */
    6206            0 :                     if (STMT_VINFO_STRIDED_P (stmt_vinfo)
    6207            0 :                         || compare_step_with_zero (vinfo, stmt_vinfo) <= 0
    6208            0 :                         || vect_load_lanes_supported
    6209            0 :                              (SLP_TREE_VECTYPE (load_node),
    6210            0 :                               DR_GROUP_SIZE (stmt_vinfo), masked) == IFN_LAST
    6211              :                         /* ???  During SLP re-discovery with a single lane
    6212              :                            a masked grouped load will appear permuted and
    6213              :                            discovery will fail.  We have to rework this
    6214              :                            on the discovery side - for now avoid ICEing.  */
    6215            0 :                         || masked)
    6216              :                       {
    6217              :                         can_use_lanes = false;
    6218              :                         break;
    6219              :                       }
    6220              :                     /* Make sure that the target would prefer store-lanes
    6221              :                        for at least one of the loads.
    6222              : 
    6223              :                        ??? Perhaps we should instead require this for
    6224              :                        all loads?  */
    6225            0 :                     prefer_load_lanes
    6226              :                       = (prefer_load_lanes
    6227            0 :                          || SLP_TREE_LANES (load_node) == group_size
    6228            0 :                          || (vect_slp_prefer_store_lanes_p
    6229            0 :                              (vinfo, stmt_vinfo,
    6230              :                               SLP_TREE_VECTYPE (load_node), masked,
    6231              :                               group_size, SLP_TREE_LANES (load_node))));
    6232              :                   }
    6233              : 
    6234            0 :               if (can_use_lanes && prefer_load_lanes)
    6235              :                 {
    6236            0 :                   if (dump_enabled_p ())
    6237            0 :                     dump_printf_loc (MSG_NOTE, vect_location,
    6238              :                                      "SLP instance %p can use load/store-lanes,"
    6239              :                                      " re-discovering with single-lanes\n",
    6240              :                                      (void *) instance);
    6241              : 
    6242            0 :                   stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (slp_root);
    6243              : 
    6244            0 :                   vect_free_slp_instance (instance);
    6245            0 :                   limit = max_tree_size;
    6246            0 :                   bool res = vect_analyze_slp_instance (vinfo, bst_map,
    6247              :                                                         stmt_info,
    6248              :                                                         slp_inst_kind_store,
    6249              :                                                         max_tree_size, &limit,
    6250              :                                                         true);
    6251            0 :                   gcc_assert (res);
    6252            0 :                   auto new_inst = LOOP_VINFO_SLP_INSTANCES (vinfo).pop ();
    6253            0 :                   LOOP_VINFO_SLP_INSTANCES (vinfo)[i] = new_inst;
    6254              :                 }
    6255              :             }
    6256            0 :         }
    6257              : 
    6258              :   /* When we end up with load permutations that we cannot possibly handle,
    6259              :      like those requiring three vector inputs, lower them using interleaving
    6260              :      like schemes.  */
    6261      1162690 :   if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
    6262              :     {
    6263       501509 :       vect_lower_load_permutations (loop_vinfo, bst_map, force_single_lane);
    6264       501509 :       if (dump_enabled_p ())
    6265              :         {
    6266        20777 :           dump_printf_loc (MSG_NOTE, vect_location,
    6267              :                            "SLP graph after lowering permutations:\n");
    6268        20777 :           hash_set<slp_tree> visited;
    6269        92384 :           FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
    6270        30080 :             vect_print_slp_graph (MSG_NOTE, vect_location,
    6271              :                                   SLP_INSTANCE_TREE (instance), visited);
    6272        20777 :         }
    6273              :     }
    6274              : 
    6275      1162690 :   release_scalar_stmts_to_slp_tree_map (bst_map);
    6276              : 
    6277      1162690 :   if (pattern_found && dump_enabled_p ())
    6278              :     {
    6279           20 :       dump_printf_loc (MSG_NOTE, vect_location,
    6280              :                        "Pattern matched SLP tree\n");
    6281           20 :       hash_set<slp_tree> visited;
    6282          101 :       FOR_EACH_VEC_ELT (LOOP_VINFO_SLP_INSTANCES (vinfo), i, instance)
    6283           41 :         vect_print_slp_graph (MSG_NOTE, vect_location,
    6284              :                               SLP_INSTANCE_TREE (instance), visited);
    6285           20 :     }
    6286              : 
    6287      1162690 :   return opt_result::success ();
    6288      1162690 : }
    6289              : 
    6290              : /* Estimates the cost of inserting layout changes into the SLP graph.
    6291              :    It can also say that the insertion is impossible.  */
    6292              : 
    6293              : struct slpg_layout_cost
    6294              : {
    6295     11212297 :   slpg_layout_cost () = default;
    6296              :   slpg_layout_cost (sreal, bool);
    6297              : 
    6298       523073 :   static slpg_layout_cost impossible () { return { sreal::max (), 0 }; }
    6299      5548573 :   bool is_possible () const { return depth != sreal::max (); }
    6300              : 
    6301              :   bool operator== (const slpg_layout_cost &) const;
    6302              :   bool operator!= (const slpg_layout_cost &) const;
    6303              : 
    6304              :   bool is_better_than (const slpg_layout_cost &, bool) const;
    6305              : 
    6306              :   void add_parallel_cost (const slpg_layout_cost &);
    6307              :   void add_serial_cost (const slpg_layout_cost &);
    6308              :   void split (unsigned int);
    6309              : 
    6310              :   /* The longest sequence of layout changes needed during any traversal
    6311              :      of the partition dag, weighted by execution frequency.
    6312              : 
    6313              :      This is the most important metric when optimizing for speed, since
    6314              :      it helps to ensure that we keep the number of operations on
    6315              :      critical paths to a minimum.  */
    6316              :   sreal depth = 0;
    6317              : 
    6318              :   /* An estimate of the total number of operations needed.  It is weighted by
    6319              :      execution frequency when optimizing for speed but not when optimizing for
    6320              :      size.  In order to avoid double-counting, a node with a fanout of N will
    6321              :      distribute 1/N of its total cost to each successor.
    6322              : 
    6323              :      This is the most important metric when optimizing for size, since
    6324              :      it helps to keep the total number of operations to a minimum,  */
    6325              :   sreal total = 0;
    6326              : };
    6327              : 
    6328              : /* Construct costs for a node with weight WEIGHT.  A higher weight
    6329              :    indicates more frequent execution.  IS_FOR_SIZE is true if we are
    6330              :    optimizing for size rather than speed.  */
    6331              : 
    6332      1309898 : slpg_layout_cost::slpg_layout_cost (sreal weight, bool is_for_size)
    6333      1317505 :   : depth (weight), total (is_for_size && weight > 0 ? 1 : weight)
    6334              : {
    6335      1309898 : }
    6336              : 
    6337              : bool
    6338            0 : slpg_layout_cost::operator== (const slpg_layout_cost &other) const
    6339              : {
    6340            0 :   return depth == other.depth && total == other.total;
    6341              : }
    6342              : 
    6343              : bool
    6344            0 : slpg_layout_cost::operator!= (const slpg_layout_cost &other) const
    6345              : {
    6346            0 :   return !operator== (other);
    6347              : }
    6348              : 
    6349              : /* Return true if these costs are better than OTHER.  IS_FOR_SIZE is
    6350              :    true if we are optimizing for size rather than speed.  */
    6351              : 
    6352              : bool
    6353       315660 : slpg_layout_cost::is_better_than (const slpg_layout_cost &other,
    6354              :                                   bool is_for_size) const
    6355              : {
    6356       315660 :   if (is_for_size)
    6357              :     {
    6358         3260 :       if (total != other.total)
    6359         1666 :         return total < other.total;
    6360         1594 :       return depth < other.depth;
    6361              :     }
    6362              :   else
    6363              :     {
    6364       312400 :       if (depth != other.depth)
    6365       127685 :         return depth < other.depth;
    6366       184715 :       return total < other.total;
    6367              :     }
    6368              : }
    6369              : 
    6370              : /* Increase the costs to account for something with cost INPUT_COST
    6371              :    happening in parallel with the current costs.  */
    6372              : 
    6373              : void
    6374       378553 : slpg_layout_cost::add_parallel_cost (const slpg_layout_cost &input_cost)
    6375              : {
    6376       378553 :   depth = std::max (depth, input_cost.depth);
    6377       378553 :   total += input_cost.total;
    6378       378553 : }
    6379              : 
    6380              : /* Increase the costs to account for something with cost INPUT_COST
    6381              :    happening in series with the current costs.  */
    6382              : 
    6383              : void
    6384      1556756 : slpg_layout_cost::add_serial_cost (const slpg_layout_cost &other)
    6385              : {
    6386      1556756 :   depth += other.depth;
    6387      1556756 :   total += other.total;
    6388      1556756 : }
    6389              : 
    6390              : /* Split the total cost among TIMES successors or predecessors.  */
    6391              : 
    6392              : void
    6393      1239937 : slpg_layout_cost::split (unsigned int times)
    6394              : {
    6395      1239937 :   if (times > 1)
    6396       599771 :     total /= times;
    6397      1239937 : }
    6398              : 
    6399              : /* Information about one node in the SLP graph, for use during
    6400              :    vect_optimize_slp_pass.  */
    6401              : 
    6402              : struct slpg_vertex
    6403              : {
    6404     10475599 :   slpg_vertex (slp_tree node_) : node (node_) {}
    6405              : 
    6406              :   /* The node itself.  */
    6407              :   slp_tree node;
    6408              : 
    6409              :   /* Which partition the node belongs to, or -1 if none.  Nodes outside of
    6410              :      partitions are flexible; they can have whichever layout consumers
    6411              :      want them to have.  */
    6412              :   int partition = -1;
    6413              : 
    6414              :   /* The number of nodes that directly use the result of this one
    6415              :      (i.e. the number of nodes that count this one as a child).  */
    6416              :   unsigned int out_degree = 0;
    6417              : 
    6418              :   /* The execution frequency of the node.  */
    6419              :   sreal weight = 0;
    6420              : 
    6421              :   /* The total execution frequency of all nodes that directly use the
    6422              :      result of this one.  */
    6423              :   sreal out_weight = 0;
    6424              : };
    6425              : 
    6426              : /* Information about one partition of the SLP graph, for use during
    6427              :    vect_optimize_slp_pass.  */
    6428              : 
    6429              : struct slpg_partition_info
    6430              : {
    6431              :   /* The nodes in the partition occupy indices [NODE_BEGIN, NODE_END)
    6432              :      of m_partitioned_nodes.  */
    6433              :   unsigned int node_begin = 0;
    6434              :   unsigned int node_end = 0;
    6435              : 
    6436              :   /* Which layout we've chosen to use for this partition, or -1 if
    6437              :      we haven't picked one yet.  */
    6438              :   int layout = -1;
    6439              : 
    6440              :   /* The number of predecessors and successors in the partition dag.
    6441              :      The predecessors always have lower partition numbers and the
    6442              :      successors always have higher partition numbers.
    6443              : 
    6444              :      Note that the directions of these edges are not necessarily the
    6445              :      same as in the data flow graph.  For example, if an SCC has separate
    6446              :      partitions for an inner loop and an outer loop, the inner loop's
    6447              :      partition will have at least two incoming edges from the outer loop's
    6448              :      partition: one for a live-in value and one for a live-out value.
    6449              :      In data flow terms, one of these edges would also be from the outer loop
    6450              :      to the inner loop, but the other would be in the opposite direction.  */
    6451              :   unsigned int in_degree = 0;
    6452              :   unsigned int out_degree = 0;
    6453              : };
    6454              : 
    6455              : /* Information about the costs of using a particular layout for a
    6456              :    particular partition.  It can also say that the combination is
    6457              :    impossible.  */
    6458              : 
    6459              : struct slpg_partition_layout_costs
    6460              : {
    6461      1631093 :   bool is_possible () const { return internal_cost.is_possible (); }
    6462        67316 :   void mark_impossible () { internal_cost = slpg_layout_cost::impossible (); }
    6463              : 
    6464              :   /* The costs inherited from predecessor partitions.  */
    6465              :   slpg_layout_cost in_cost;
    6466              : 
    6467              :   /* The inherent cost of the layout within the node itself.  For example,
    6468              :      this is nonzero for a load if choosing a particular layout would require
    6469              :      the load to permute the loaded elements.  It is nonzero for a
    6470              :      VEC_PERM_EXPR if the permutation cannot be eliminated or converted
    6471              :      to full-vector moves.  */
    6472              :   slpg_layout_cost internal_cost;
    6473              : 
    6474              :   /* The costs inherited from successor partitions.  */
    6475              :   slpg_layout_cost out_cost;
    6476              : };
    6477              : 
    6478              : /* This class tries to optimize the layout of vectors in order to avoid
    6479              :    unnecessary shuffling.  At the moment, the set of possible layouts are
    6480              :    restricted to bijective permutations.
    6481              : 
    6482              :    The goal of the pass depends on whether we're optimizing for size or
    6483              :    for speed.  When optimizing for size, the goal is to reduce the overall
    6484              :    number of layout changes (including layout changes implied by things
    6485              :    like load permutations).  When optimizing for speed, the goal is to
    6486              :    reduce the maximum latency attributable to layout changes on any
    6487              :    non-cyclical path through the data flow graph.
    6488              : 
    6489              :    For example, when optimizing a loop nest for speed, we will prefer
    6490              :    to make layout changes outside of a loop rather than inside of a loop,
    6491              :    and will prefer to make layout changes in parallel rather than serially,
    6492              :    even if that increases the overall number of layout changes.
    6493              : 
    6494              :    The high-level procedure is:
    6495              : 
    6496              :    (1) Build a graph in which edges go from uses (parents) to definitions
    6497              :        (children).
    6498              : 
    6499              :    (2) Divide the graph into a dag of strongly-connected components (SCCs).
    6500              : 
    6501              :    (3) When optimizing for speed, partition the nodes in each SCC based
    6502              :        on their containing cfg loop.  When optimizing for size, treat
    6503              :        each SCC as a single partition.
    6504              : 
    6505              :        This gives us a dag of partitions.  The goal is now to assign a
    6506              :        layout to each partition.
    6507              : 
    6508              :    (4) Construct a set of vector layouts that are worth considering.
    6509              :        Record which nodes must keep their current layout.
    6510              : 
    6511              :    (5) Perform a forward walk over the partition dag (from loads to stores)
    6512              :        accumulating the "forward" cost of using each layout.  When visiting
    6513              :        each partition, assign a tentative choice of layout to the partition
    6514              :        and use that choice when calculating the cost of using a different
    6515              :        layout in successor partitions.
    6516              : 
    6517              :    (6) Perform a backward walk over the partition dag (from stores to loads),
    6518              :        accumulating the "backward" cost of using each layout.  When visiting
    6519              :        each partition, make a final choice of layout for that partition based
    6520              :        on the accumulated forward costs (from (5)) and backward costs
    6521              :        (from (6)).
    6522              : 
    6523              :    (7) Apply the chosen layouts to the SLP graph.
    6524              : 
    6525              :    For example, consider the SLP statements:
    6526              : 
    6527              :    S1:      a_1 = load
    6528              :        loop:
    6529              :    S2:      a_2 = PHI<a_1, a_3>
    6530              :    S3:      b_1 = load
    6531              :    S4:      a_3 = a_2 + b_1
    6532              :        exit:
    6533              :    S5:      a_4 = PHI<a_3>
    6534              :    S6:      store a_4
    6535              : 
    6536              :    S2 and S4 form an SCC and are part of the same loop.  Every other
    6537              :    statement is in a singleton SCC.  In this example there is a one-to-one
    6538              :    mapping between SCCs and partitions and the partition dag looks like this;
    6539              : 
    6540              :         S1     S3
    6541              :          \     /
    6542              :           S2+S4
    6543              :             |
    6544              :            S5
    6545              :             |
    6546              :            S6
    6547              : 
    6548              :    S2, S3 and S4 will have a higher execution frequency than the other
    6549              :    statements, so when optimizing for speed, the goal is to avoid any
    6550              :    layout changes:
    6551              : 
    6552              :    - within S3
    6553              :    - within S2+S4
    6554              :    - on the S3->S2+S4 edge
    6555              : 
    6556              :    For example, if S3 was originally a reversing load, the goal of the
    6557              :    pass is to make it an unreversed load and change the layout on the
    6558              :    S1->S2+S4 and S2+S4->S5 edges to compensate.  (Changing the layout
    6559              :    on S1->S2+S4 and S5->S6 would also be acceptable.)
    6560              : 
    6561              :    The difference between SCCs and partitions becomes important if we
    6562              :    add an outer loop:
    6563              : 
    6564              :    S1:      a_1 = ...
    6565              :        loop1:
    6566              :    S2:      a_2 = PHI<a_1, a_6>
    6567              :    S3:      b_1 = load
    6568              :    S4:      a_3 = a_2 + b_1
    6569              :        loop2:
    6570              :    S5:      a_4 = PHI<a_3, a_5>
    6571              :    S6:      c_1 = load
    6572              :    S7:      a_5 = a_4 + c_1
    6573              :        exit2:
    6574              :    S8:      a_6 = PHI<a_5>
    6575              :    S9:      store a_6
    6576              :        exit1:
    6577              : 
    6578              :    Here, S2, S4, S5, S7 and S8 form a single SCC.  However, when optimizing
    6579              :    for speed, we usually do not want restrictions in the outer loop to "infect"
    6580              :    the decision for the inner loop.  For example, if an outer-loop node
    6581              :    in the SCC contains a statement with a fixed layout, that should not
    6582              :    prevent the inner loop from using a different layout.  Conversely,
    6583              :    the inner loop should not dictate a layout to the outer loop: if the
    6584              :    outer loop does a lot of computation, then it may not be efficient to
    6585              :    do all of that computation in the inner loop's preferred layout.
    6586              : 
    6587              :    So when optimizing for speed, we partition the SCC into S2+S4+S8 (outer)
    6588              :    and S5+S7 (inner).  We also try to arrange partitions so that:
    6589              : 
    6590              :    - the partition for an outer loop comes before the partition for
    6591              :      an inner loop
    6592              : 
    6593              :    - if a sibling loop A dominates a sibling loop B, A's partition
    6594              :      comes before B's
    6595              : 
    6596              :    This gives the following partition dag for the example above:
    6597              : 
    6598              :         S1        S3
    6599              :          \        /
    6600              :           S2+S4+S8   S6
    6601              :            |   \\    /
    6602              :            |    S5+S7
    6603              :            |
    6604              :           S9
    6605              : 
    6606              :    There are two edges from S2+S4+S8 to S5+S7: one for the edge S4->S5 and
    6607              :    one for a reversal of the edge S7->S8.
    6608              : 
    6609              :    The backward walk picks a layout for S5+S7 before S2+S4+S8.  The choice
    6610              :    for S2+S4+S8 therefore has to balance the cost of using the outer loop's
    6611              :    preferred layout against the cost of changing the layout on entry to the
    6612              :    inner loop (S4->S5) and on exit from the inner loop (S7->S8 reversed).
    6613              : 
    6614              :    Although this works well when optimizing for speed, it has the downside
    6615              :    when optimizing for size that the choice of layout for S5+S7 is completely
    6616              :    independent of S9, which lessens the chance of reducing the overall number
    6617              :    of permutations.  We therefore do not partition SCCs when optimizing
    6618              :    for size.
    6619              : 
    6620              :    To give a concrete example of the difference between optimizing
    6621              :    for size and speed, consider:
    6622              : 
    6623              :    a[0] = (b[1] << c[3]) - d[1];
    6624              :    a[1] = (b[0] << c[2]) - d[0];
    6625              :    a[2] = (b[3] << c[1]) - d[3];
    6626              :    a[3] = (b[2] << c[0]) - d[2];
    6627              : 
    6628              :    There are three different layouts here: one for a, one for b and d,
    6629              :    and one for c.  When optimizing for speed it is better to permute each
    6630              :    of b, c and d into the order required by a, since those permutations
    6631              :    happen in parallel.  But when optimizing for size, it is better to:
    6632              : 
    6633              :    - permute c into the same order as b
    6634              :    - do the arithmetic
    6635              :    - permute the result into the order required by a
    6636              : 
    6637              :    This gives 2 permutations rather than 3.  */
    6638              : 
    6639              : class vect_optimize_slp_pass
    6640              : {
    6641              : public:
    6642       716297 :   vect_optimize_slp_pass (vec_info *vinfo) : m_vinfo (vinfo) {}
    6643              :   void run ();
    6644              : 
    6645              : private:
    6646              :   /* Graph building.  */
    6647              :   struct loop *containing_loop (slp_tree);
    6648              :   bool is_cfg_latch_edge (graph_edge *);
    6649              :   void build_vertices (hash_set<slp_tree> &, slp_tree);
    6650              :   void build_vertices ();
    6651              :   void build_graph ();
    6652              : 
    6653              :   /* Partitioning.  */
    6654              :   void create_partitions ();
    6655              :   template<typename T> void for_each_partition_edge (unsigned int, T);
    6656              : 
    6657              :   /* Layout selection.  */
    6658              :   bool is_compatible_layout (slp_tree, unsigned int);
    6659              :   bool is_compatible_layout (const slpg_partition_info &, unsigned int);
    6660              :   int change_layout_cost (slp_tree, unsigned int, unsigned int);
    6661              :   slpg_partition_layout_costs &partition_layout_costs (unsigned int,
    6662              :                                                        unsigned int);
    6663              :   void change_vec_perm_layout (slp_tree, lane_permutation_t &,
    6664              :                                int, unsigned int);
    6665              :   int internal_node_cost (slp_tree, int, unsigned int);
    6666              :   void start_choosing_layouts ();
    6667              :   bool legitimize ();
    6668              : 
    6669              :   /* Cost propagation.  */
    6670              :   slpg_layout_cost edge_layout_cost (graph_edge *, unsigned int,
    6671              :                                      unsigned int, unsigned int);
    6672              :   slpg_layout_cost total_in_cost (unsigned int);
    6673              :   slpg_layout_cost forward_cost (graph_edge *, unsigned int, unsigned int);
    6674              :   slpg_layout_cost backward_cost (graph_edge *, unsigned int, unsigned int);
    6675              :   void forward_pass ();
    6676              :   void backward_pass ();
    6677              : 
    6678              :   /* Rematerialization.  */
    6679              :   slp_tree get_result_with_layout (slp_tree, unsigned int);
    6680              :   void materialize ();
    6681              : 
    6682              :   /* Clean-up.  */
    6683              :   void remove_redundant_permutations ();
    6684              : 
    6685              :   /* Masked load lanes discovery.  */
    6686              :   void decide_masked_load_lanes ();
    6687              : 
    6688              :   void dump ();
    6689              : 
    6690              :   vec_info *m_vinfo;
    6691              : 
    6692              :   /* True if we should optimize the graph for size, false if we should
    6693              :      optimize it for speed.  (It wouldn't be easy to make this decision
    6694              :      more locally.)  */
    6695              :   bool m_optimize_size;
    6696              : 
    6697              :   /* A graph of all SLP nodes, with edges leading from uses to definitions.
    6698              :      In other words, a node's predecessors are its slp_tree parents and
    6699              :      a node's successors are its slp_tree children.  */
    6700              :   graph *m_slpg = nullptr;
    6701              : 
    6702              :   /* The vertices of M_SLPG, indexed by slp_tree::vertex.  */
    6703              :   auto_vec<slpg_vertex> m_vertices;
    6704              : 
    6705              :   /* The list of all leaves of M_SLPG. such as external definitions, constants,
    6706              :      and loads.  */
    6707              :   auto_vec<int> m_leafs;
    6708              : 
    6709              :   /* This array has one entry for every vector layout that we're considering.
    6710              :      Element 0 is null and indicates "no change".  Other entries describe
    6711              :      permutations that are inherent in the current graph and that we would
    6712              :      like to reverse if possible.
    6713              : 
    6714              :      For example, a permutation { 1, 2, 3, 0 } means that something has
    6715              :      effectively been permuted in that way, such as a load group
    6716              :      { a[1], a[2], a[3], a[0] } (viewed as a permutation of a[0:3]).
    6717              :      We'd then like to apply the reverse permutation { 3, 0, 1, 2 }
    6718              :      in order to put things "back" in order.  */
    6719              :   auto_vec<vec<unsigned> > m_perms;
    6720              : 
    6721              :   /* A partitioning of the nodes for which a layout must be chosen.
    6722              :      Each partition represents an <SCC, cfg loop> pair; that is,
    6723              :      nodes in different SCCs belong to different partitions, and nodes
    6724              :      within an SCC can be further partitioned according to a containing
    6725              :      cfg loop.  Partition <SCC1, L1> comes before <SCC2, L2> if:
    6726              : 
    6727              :      - SCC1 != SCC2 and SCC1 is a predecessor of SCC2 in a forward walk
    6728              :        from leaves (such as loads) to roots (such as stores).
    6729              : 
    6730              :      - SCC1 == SCC2 and L1's header strictly dominates L2's header.  */
    6731              :   auto_vec<slpg_partition_info> m_partitions;
    6732              : 
    6733              :   /* The list of all nodes for which a layout must be chosen.  Nodes for
    6734              :      partition P come before the nodes for partition P+1.  Nodes within a
    6735              :      partition are in reverse postorder.  */
    6736              :   auto_vec<unsigned int> m_partitioned_nodes;
    6737              : 
    6738              :   /* Index P * num-layouts + L contains the cost of using layout L
    6739              :      for partition P.  */
    6740              :   auto_vec<slpg_partition_layout_costs> m_partition_layout_costs;
    6741              : 
    6742              :   /* Index N * num-layouts + L, if nonnull, is a node that provides the
    6743              :      original output of node N adjusted to have layout L.  */
    6744              :   auto_vec<slp_tree> m_node_layouts;
    6745              : };
    6746              : 
    6747              : /* Fill the vertices and leafs vector with all nodes in the SLP graph.
    6748              :    Also record whether we should optimize anything for speed rather
    6749              :    than size.  */
    6750              : 
    6751              : void
    6752     11317809 : vect_optimize_slp_pass::build_vertices (hash_set<slp_tree> &visited,
    6753              :                                         slp_tree node)
    6754              : {
    6755     11317809 :   unsigned i;
    6756     11317809 :   slp_tree child;
    6757              : 
    6758     11317809 :   if (visited.add (node))
    6759     11317809 :     return;
    6760              : 
    6761     10475599 :   if (stmt_vec_info rep = SLP_TREE_REPRESENTATIVE (node))
    6762              :     {
    6763      8000918 :       basic_block bb = gimple_bb (vect_orig_stmt (rep)->stmt);
    6764      7059088 :       if (optimize_bb_for_speed_p (bb))
    6765      6929190 :         m_optimize_size = false;
    6766              :     }
    6767              : 
    6768     10475599 :   node->vertex = m_vertices.length ();
    6769     10475599 :   m_vertices.safe_push (slpg_vertex (node));
    6770              : 
    6771     10475599 :   bool leaf = true;
    6772     10475599 :   bool force_leaf = false;
    6773     19636588 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
    6774      9160989 :     if (child)
    6775              :       {
    6776      8246029 :         leaf = false;
    6777      8246029 :         build_vertices (visited, child);
    6778              :       }
    6779              :     else
    6780              :       force_leaf = true;
    6781              :   /* Since SLP discovery works along use-def edges all cycles have an
    6782              :      entry - but there's the exception of cycles where we do not handle
    6783              :      the entry explicitly (but with a NULL SLP node), like some reductions
    6784              :      and inductions.  Force those SLP PHIs to act as leafs to make them
    6785              :      backwards reachable.  */
    6786     10475599 :   if (leaf || force_leaf)
    6787      5192434 :     m_leafs.safe_push (node->vertex);
    6788              : }
    6789              : 
    6790              : /* Fill the vertices and leafs vector with all nodes in the SLP graph.  */
    6791              : 
    6792              : void
    6793      1432594 : vect_optimize_slp_pass::build_vertices ()
    6794              : {
    6795      1432594 :   hash_set<slp_tree> visited;
    6796      1432594 :   unsigned i;
    6797      1432594 :   slp_instance instance;
    6798      1432594 :   m_vertices.truncate (0);
    6799      1432594 :   m_leafs.truncate (0);
    6800      7369562 :   FOR_EACH_VEC_ELT (m_vinfo->slp_instances, i, instance)
    6801      3071780 :     build_vertices (visited, SLP_INSTANCE_TREE (instance));
    6802      1432594 : }
    6803              : 
    6804              : /* Apply (reverse) bijectite PERM to VEC.  */
    6805              : 
    6806              : template <class T>
    6807              : static void
    6808       229408 : vect_slp_permute (vec<unsigned> perm,
    6809              :                   vec<T> &vec, bool reverse)
    6810              : {
    6811       229408 :   auto_vec<T, 64> saved;
    6812       229408 :   saved.create (vec.length ());
    6813       761682 :   for (unsigned i = 0; i < vec.length (); ++i)
    6814       532274 :     saved.quick_push (vec[i]);
    6815              : 
    6816       229408 :   if (reverse)
    6817              :     {
    6818      1504304 :       for (unsigned i = 0; i < vec.length (); ++i)
    6819       530230 :         vec[perm[i]] = saved[i];
    6820       758684 :       for (unsigned i = 0; i < vec.length (); ++i)
    6821       897685 :         gcc_assert (vec[perm[i]] == saved[i]);
    6822              :     }
    6823              :   else
    6824              :     {
    6825         5996 :       for (unsigned i = 0; i < vec.length (); ++i)
    6826         2044 :         vec[i] = saved[perm[i]];
    6827       231452 :       for (unsigned i = 0; i < vec.length (); ++i)
    6828         3066 :         gcc_assert (vec[i] == saved[perm[i]]);
    6829              :     }
    6830       229408 : }
    6831              : 
    6832              : /* Return the cfg loop that contains NODE.  */
    6833              : 
    6834              : struct loop *
    6835      4077981 : vect_optimize_slp_pass::containing_loop (slp_tree node)
    6836              : {
    6837      4077981 :   stmt_vec_info rep = SLP_TREE_REPRESENTATIVE (node);
    6838              :   /* ???  This is imprecise, VEC_PERM nodes do not have a representative
    6839              :      but are laid out close to their children.  */
    6840      4077981 :   if (!rep)
    6841       144957 :     return m_vinfo->bbs[0]->loop_father;
    6842      4417287 :   return gimple_bb (vect_orig_stmt (rep)->stmt)->loop_father;
    6843              : }
    6844              : 
    6845              : /* Return true if UD (an edge from a use to a definition) is associated
    6846              :    with a loop latch edge in the cfg.  */
    6847              : 
    6848              : bool
    6849      8246029 : vect_optimize_slp_pass::is_cfg_latch_edge (graph_edge *ud)
    6850              : {
    6851      8246029 :   slp_tree use = m_vertices[ud->src].node;
    6852      8246029 :   slp_tree def = m_vertices[ud->dest].node;
    6853      8246029 :   if ((SLP_TREE_DEF_TYPE (use) != vect_internal_def
    6854      8246029 :        || SLP_TREE_PERMUTE_P (use))
    6855      7925200 :       || SLP_TREE_DEF_TYPE (def) != vect_internal_def)
    6856              :     return false;
    6857              : 
    6858      4798186 :   stmt_vec_info use_rep = vect_orig_stmt (SLP_TREE_REPRESENTATIVE (use));
    6859      4798186 :   return (is_a<gphi *> (use_rep->stmt)
    6860       385596 :           && bb_loop_header_p (gimple_bb (use_rep->stmt))
    6861      5016076 :           && containing_loop (def) == containing_loop (use));
    6862              : }
    6863              : 
    6864              : /* Build the graph.  Mark edges that correspond to cfg loop latch edges with
    6865              :    a nonnull data field.  */
    6866              : 
    6867              : void
    6868      1432594 : vect_optimize_slp_pass::build_graph ()
    6869              : {
    6870      1432594 :   m_optimize_size = true;
    6871      1432594 :   build_vertices ();
    6872              : 
    6873      2865188 :   m_slpg = new_graph (m_vertices.length ());
    6874     14773381 :   for (slpg_vertex &v : m_vertices)
    6875     31302842 :     for (slp_tree child : SLP_TREE_CHILDREN (v.node))
    6876      9160989 :       if (child)
    6877              :         {
    6878      8246029 :           graph_edge *ud = add_edge (m_slpg, v.node->vertex, child->vertex);
    6879      8246029 :           if (is_cfg_latch_edge (ud))
    6880       208144 :             ud->data = this;
    6881              :         }
    6882      1432594 : }
    6883              : 
    6884              : /* Return true if E corresponds to a loop latch edge in the cfg.  */
    6885              : 
    6886              : static bool
    6887      4226529 : skip_cfg_latch_edges (graph_edge *e)
    6888              : {
    6889      4226529 :   return e->data;
    6890              : }
    6891              : 
    6892              : /* Create the node partitions.  */
    6893              : 
    6894              : void
    6895       716297 : vect_optimize_slp_pass::create_partitions ()
    6896              : {
    6897              :   /* Calculate a postorder of the graph, ignoring edges that correspond
    6898              :      to natural latch edges in the cfg.  Reading the vector from the end
    6899              :      to the beginning gives the reverse postorder.  */
    6900       716297 :   auto_vec<int> initial_rpo;
    6901      1432594 :   graphds_dfs (m_slpg, &m_leafs[0], m_leafs.length (), &initial_rpo,
    6902              :                false, NULL, skip_cfg_latch_edges);
    6903      2148891 :   gcc_assert (initial_rpo.length () == m_vertices.length ());
    6904              : 
    6905              :   /* Calculate the strongly connected components of the graph.  */
    6906       716297 :   auto_vec<int> scc_grouping;
    6907       716297 :   unsigned int num_sccs = graphds_scc (m_slpg, NULL, NULL, &scc_grouping);
    6908              : 
    6909              :   /* Create a new index order in which all nodes from the same SCC are
    6910              :      consecutive.  Use scc_pos to record the index of the first node in
    6911              :      each SCC.  */
    6912       716297 :   auto_vec<unsigned int> scc_pos (num_sccs);
    6913       716297 :   int last_component = -1;
    6914       716297 :   unsigned int node_count = 0;
    6915      7386139 :   for (unsigned int node_i : scc_grouping)
    6916              :     {
    6917      5237248 :       if (last_component != m_slpg->vertices[node_i].component)
    6918              :         {
    6919      5106682 :           last_component = m_slpg->vertices[node_i].component;
    6920     10213364 :           gcc_assert (last_component == int (scc_pos.length ()));
    6921      5106682 :           scc_pos.quick_push (node_count);
    6922              :         }
    6923      5237248 :       node_count += 1;
    6924              :     }
    6925      1432594 :   gcc_assert (node_count == initial_rpo.length ()
    6926              :               && last_component + 1 == int (num_sccs));
    6927              : 
    6928              :   /* Use m_partitioned_nodes to group nodes into SCC order, with the nodes
    6929              :      inside each SCC following the RPO we calculated above.  The fact that
    6930              :      we ignored natural latch edges when calculating the RPO should ensure
    6931              :      that, for natural loop nests:
    6932              : 
    6933              :      - the first node that we encounter in a cfg loop is the loop header phi
    6934              :      - the loop header phis are in dominance order
    6935              : 
    6936              :      Arranging for this is an optimization (see below) rather than a
    6937              :      correctness issue.  Unnatural loops with a tangled mess of backedges
    6938              :      will still work correctly, but might give poorer results.
    6939              : 
    6940              :      Also update scc_pos so that it gives 1 + the index of the last node
    6941              :      in the SCC.  */
    6942       716297 :   m_partitioned_nodes.safe_grow (node_count);
    6943      6669842 :   for (unsigned int old_i = initial_rpo.length (); old_i-- > 0;)
    6944              :     {
    6945      5237248 :       unsigned int node_i = initial_rpo[old_i];
    6946      5237248 :       unsigned int new_i = scc_pos[m_slpg->vertices[node_i].component]++;
    6947      5237248 :       m_partitioned_nodes[new_i] = node_i;
    6948              :     }
    6949              : 
    6950              :   /* When optimizing for speed, partition each SCC based on the containing
    6951              :      cfg loop. The order we constructed above should ensure that, for natural
    6952              :      cfg loops, we'll create sub-SCC partitions for outer loops before
    6953              :      the corresponding sub-SCC partitions for inner loops.  Similarly,
    6954              :      when one sibling loop A dominates another sibling loop B, we should
    6955              :      create a sub-SCC partition for A before a sub-SCC partition for B.
    6956              : 
    6957              :      As above, nothing depends for correctness on whether this achieves
    6958              :      a natural nesting, but we should get better results when it does.  */
    6959      1432594 :   m_partitions.reserve (m_vertices.length ());
    6960       716297 :   unsigned int next_partition_i = 0;
    6961       716297 :   hash_map<struct loop *, int> loop_partitions;
    6962       716297 :   unsigned int rpo_begin = 0;
    6963       716297 :   unsigned int num_partitioned_nodes = 0;
    6964      7255573 :   for (unsigned int rpo_end : scc_pos)
    6965              :     {
    6966      5106682 :       loop_partitions.empty ();
    6967      5106682 :       unsigned int partition_i = next_partition_i;
    6968     10343930 :       for (unsigned int rpo_i = rpo_begin; rpo_i < rpo_end; ++rpo_i)
    6969              :         {
    6970              :           /* Handle externals and constants optimistically throughout.
    6971              :              But treat existing vectors as fixed since we do not handle
    6972              :              permuting them.  */
    6973      5237248 :           unsigned int node_i = m_partitioned_nodes[rpo_i];
    6974      5237248 :           auto &vertex = m_vertices[node_i];
    6975      5237248 :           if ((SLP_TREE_DEF_TYPE (vertex.node) == vect_external_def
    6976       529349 :                && !SLP_TREE_VEC_DEFS (vertex.node).exists ())
    6977      5240241 :               || SLP_TREE_DEF_TYPE (vertex.node) == vect_constant_def)
    6978      1564731 :             vertex.partition = -1;
    6979              :           else
    6980              :             {
    6981      3672517 :               bool existed;
    6982      3672517 :               if (m_optimize_size)
    6983        30316 :                 existed = next_partition_i > partition_i;
    6984              :               else
    6985              :                 {
    6986      3642201 :                   struct loop *loop = containing_loop (vertex.node);
    6987      3642201 :                   auto &entry = loop_partitions.get_or_insert (loop, &existed);
    6988      3642201 :                   if (!existed)
    6989      3512862 :                     entry = next_partition_i;
    6990      3642201 :                   partition_i = entry;
    6991              :                 }
    6992      3672517 :               if (!existed)
    6993              :                 {
    6994      3543086 :                   m_partitions.quick_push (slpg_partition_info ());
    6995      3543086 :                   next_partition_i += 1;
    6996              :                 }
    6997      3672517 :               vertex.partition = partition_i;
    6998      3672517 :               num_partitioned_nodes += 1;
    6999      3672517 :               m_partitions[partition_i].node_end += 1;
    7000              :             }
    7001              :         }
    7002      5106682 :       rpo_begin = rpo_end;
    7003              :     }
    7004              : 
    7005              :   /* Assign ranges of consecutive node indices to each partition,
    7006              :      in partition order.  Start with node_end being the same as
    7007              :      node_begin so that the next loop can use it as a counter.  */
    7008       716297 :   unsigned int node_begin = 0;
    7009      5691977 :   for (auto &partition : m_partitions)
    7010              :     {
    7011      3543086 :       partition.node_begin = node_begin;
    7012      3543086 :       node_begin += partition.node_end;
    7013      3543086 :       partition.node_end = partition.node_begin;
    7014              :     }
    7015       716297 :   gcc_assert (node_begin == num_partitioned_nodes);
    7016              : 
    7017              :   /* Finally build the list of nodes in partition order.  */
    7018       716297 :   m_partitioned_nodes.truncate (num_partitioned_nodes);
    7019      6669842 :   for (unsigned int node_i = 0; node_i < m_vertices.length (); ++node_i)
    7020              :     {
    7021      5237248 :       int partition_i = m_vertices[node_i].partition;
    7022      5237248 :       if (partition_i >= 0)
    7023              :         {
    7024      3672517 :           unsigned int order_i = m_partitions[partition_i].node_end++;
    7025      3672517 :           m_partitioned_nodes[order_i] = node_i;
    7026              :         }
    7027              :     }
    7028       716297 : }
    7029              : 
    7030              : /* Look for edges from earlier partitions into node NODE_I and edges from
    7031              :    node NODE_I into later partitions.  Call:
    7032              : 
    7033              :       FN (ud, other_node_i)
    7034              : 
    7035              :    for each such use-to-def edge ud, where other_node_i is the node at the
    7036              :    other end of the edge.  */
    7037              : 
    7038              : template<typename T>
    7039              : void
    7040      4130490 : vect_optimize_slp_pass::for_each_partition_edge (unsigned int node_i, T fn)
    7041              : {
    7042      4130490 :   int partition_i = m_vertices[node_i].partition;
    7043      4130490 :   for (graph_edge *pred = m_slpg->vertices[node_i].pred;
    7044      7138955 :        pred; pred = pred->pred_next)
    7045              :     {
    7046      3008465 :       int src_partition_i = m_vertices[pred->src].partition;
    7047      3008465 :       if (src_partition_i >= 0 && src_partition_i != partition_i)
    7048      2678537 :         fn (pred, pred->src);
    7049              :     }
    7050      4130490 :   for (graph_edge *succ = m_slpg->vertices[node_i].succ;
    7051      8872060 :        succ; succ = succ->succ_next)
    7052              :     {
    7053      4741570 :       int dest_partition_i = m_vertices[succ->dest].partition;
    7054      4741570 :       if (dest_partition_i >= 0 && dest_partition_i != partition_i)
    7055      2714579 :         fn (succ, succ->dest);
    7056              :     }
    7057      4130490 : }
    7058              : 
    7059              : /* Return true if layout LAYOUT_I is compatible with the number of SLP lanes
    7060              :    that NODE would operate on.  This test is independent of NODE's actual
    7061              :    operation.  */
    7062              : 
    7063              : bool
    7064      1753986 : vect_optimize_slp_pass::is_compatible_layout (slp_tree node,
    7065              :                                               unsigned int layout_i)
    7066              : {
    7067      1753986 :   if (layout_i == 0)
    7068              :     return true;
    7069              : 
    7070      1033190 :   if (SLP_TREE_LANES (node) != m_perms[layout_i].length ())
    7071        18355 :     return false;
    7072              : 
    7073              :   return true;
    7074              : }
    7075              : 
    7076              : /* Return true if layout LAYOUT_I is compatible with the number of SLP lanes
    7077              :    that NODE would operate on for each NODE in PARTITION.
    7078              :    This test is independent of NODE's actual operations.  */
    7079              : 
    7080              : bool
    7081        25071 : vect_optimize_slp_pass::is_compatible_layout (const slpg_partition_info
    7082              :                                                 &partition,
    7083              :                                               unsigned int layout_i)
    7084              : {
    7085        50525 :   for (unsigned int order_i = partition.node_begin;
    7086        50525 :        order_i < partition.node_end; ++order_i)
    7087              :     {
    7088        25567 :       unsigned int node_i = m_partitioned_nodes[order_i];
    7089        25567 :       auto &vertex = m_vertices[node_i];
    7090              : 
    7091              :       /* The layout is incompatible if it is individually incompatible
    7092              :          with any node in the partition.  */
    7093        25567 :       if (!is_compatible_layout (vertex.node, layout_i))
    7094              :         return false;
    7095              :     }
    7096              :   return true;
    7097              : }
    7098              : 
    7099              : /* Return the cost (in arbitrary units) of going from layout FROM_LAYOUT_I
    7100              :    to layout TO_LAYOUT_I for a node like NODE.  Return -1 if either of the
    7101              :    layouts is incompatible with NODE or if the change is not possible for
    7102              :    some other reason.
    7103              : 
    7104              :    The properties taken from NODE include the number of lanes and the
    7105              :    vector type.  The actual operation doesn't matter.  */
    7106              : 
    7107              : int
    7108       739433 : vect_optimize_slp_pass::change_layout_cost (slp_tree node,
    7109              :                                             unsigned int from_layout_i,
    7110              :                                             unsigned int to_layout_i)
    7111              : {
    7112       739433 :   if (!is_compatible_layout (node, from_layout_i)
    7113       739433 :       || !is_compatible_layout (node, to_layout_i))
    7114              :     return -1;
    7115              : 
    7116       738793 :   if (from_layout_i == to_layout_i)
    7117              :     return 0;
    7118              : 
    7119       305920 :   auto_vec<slp_tree, 1> children (1);
    7120       305920 :   children.quick_push (node);
    7121       305920 :   auto_lane_permutation_t perm (SLP_TREE_LANES (node));
    7122       305920 :   if (from_layout_i > 0)
    7123       863419 :     for (unsigned int i : m_perms[from_layout_i])
    7124       383785 :       perm.quick_push ({ 0, i });
    7125              :   else
    7126       479499 :     for (unsigned int i = 0; i < SLP_TREE_LANES (node); ++i)
    7127       333457 :       perm.quick_push ({ 0, i });
    7128       305920 :   if (to_layout_i > 0)
    7129       146791 :     vect_slp_permute (m_perms[to_layout_i], perm, true);
    7130       305920 :   auto count = vectorizable_slp_permutation_1 (m_vinfo, nullptr, node, perm,
    7131              :                                                children, false);
    7132       305920 :   if (count >= 0)
    7133       300547 :     return MAX (count, 1);
    7134              : 
    7135              :   /* ??? In principle we could try changing via layout 0, giving two
    7136              :      layout changes rather than 1.  Doing that would require
    7137              :      corresponding support in get_result_with_layout.  */
    7138              :   return -1;
    7139       305920 : }
    7140              : 
    7141              : /* Return the costs of assigning layout LAYOUT_I to partition PARTITION_I.  */
    7142              : 
    7143              : inline slpg_partition_layout_costs &
    7144      1108800 : vect_optimize_slp_pass::partition_layout_costs (unsigned int partition_i,
    7145              :                                                 unsigned int layout_i)
    7146              : {
    7147      2217600 :   return m_partition_layout_costs[partition_i * m_perms.length () + layout_i];
    7148              : }
    7149              : 
    7150              : /* Change PERM in one of two ways:
    7151              : 
    7152              :    - if IN_LAYOUT_I < 0, accept input operand I in the layout that has been
    7153              :      chosen for child I of NODE.
    7154              : 
    7155              :    - if IN_LAYOUT >= 0, accept all inputs operands with that layout.
    7156              : 
    7157              :    In both cases, arrange for the output to have layout OUT_LAYOUT_I  */
    7158              : 
    7159              : void
    7160        38180 : vect_optimize_slp_pass::
    7161              : change_vec_perm_layout (slp_tree node, lane_permutation_t &perm,
    7162              :                         int in_layout_i, unsigned int out_layout_i)
    7163              : {
    7164       223810 :   for (auto &entry : perm)
    7165              :     {
    7166       109270 :       int this_in_layout_i = in_layout_i;
    7167       109270 :       if (this_in_layout_i < 0)
    7168              :         {
    7169        74683 :           slp_tree in_node = SLP_TREE_CHILDREN (node)[entry.first];
    7170        74683 :           unsigned int in_partition_i = m_vertices[in_node->vertex].partition;
    7171        74683 :           if (in_partition_i == -1u)
    7172          329 :             continue;
    7173        74354 :           this_in_layout_i = m_partitions[in_partition_i].layout;
    7174              :         }
    7175       108941 :       if (this_in_layout_i > 0)
    7176        25039 :         entry.second = m_perms[this_in_layout_i][entry.second];
    7177              :     }
    7178        38180 :   if (out_layout_i > 0)
    7179        10567 :     vect_slp_permute (m_perms[out_layout_i], perm, true);
    7180        38180 : }
    7181              : 
    7182              : /* Check whether the target allows NODE to be rearranged so that the node's
    7183              :    output has layout OUT_LAYOUT_I.  Return the cost of the change if so,
    7184              :    in the same arbitrary units as for change_layout_cost.  Return -1 otherwise.
    7185              : 
    7186              :    If NODE is a VEC_PERM_EXPR and IN_LAYOUT_I < 0, also check whether
    7187              :    NODE can adapt to the layout changes that have (perhaps provisionally)
    7188              :    been chosen for NODE's children, so that no extra permutations are
    7189              :    needed on either the input or the output of NODE.
    7190              : 
    7191              :    If NODE is a VEC_PERM_EXPR and IN_LAYOUT_I >= 0, instead assume
    7192              :    that all inputs will be forced into layout IN_LAYOUT_I beforehand.
    7193              : 
    7194              :    IN_LAYOUT_I has no meaning for other types of node.
    7195              : 
    7196              :    Keeping the node as-is is always valid.  If the target doesn't appear
    7197              :    to support the node as-is, but might realistically support other layouts,
    7198              :    then layout 0 instead has the cost of a worst-case permutation.  On the
    7199              :    one hand, this ensures that every node has at least one valid layout,
    7200              :    avoiding what would otherwise be an awkward special case.  On the other,
    7201              :    it still encourages the pass to change an invalid pre-existing layout
    7202              :    choice into a valid one.  */
    7203              : 
    7204              : int
    7205       245204 : vect_optimize_slp_pass::internal_node_cost (slp_tree node, int in_layout_i,
    7206              :                                             unsigned int out_layout_i)
    7207              : {
    7208       245204 :   const int fallback_cost = 1;
    7209              : 
    7210       245204 :   if (SLP_TREE_PERMUTE_P (node))
    7211              :     {
    7212        31737 :       auto_lane_permutation_t tmp_perm;
    7213        31737 :       tmp_perm.safe_splice (SLP_TREE_LANE_PERMUTATION (node));
    7214              : 
    7215              :       /* Check that the child nodes support the chosen layout.  Checking
    7216              :          the first child is enough, since any second child would have the
    7217              :          same shape.  */
    7218        31737 :       auto first_child = SLP_TREE_CHILDREN (node)[0];
    7219        31737 :       if (in_layout_i > 0
    7220        31737 :           && !is_compatible_layout (first_child, in_layout_i))
    7221              :         return -1;
    7222              : 
    7223        31102 :       change_vec_perm_layout (node, tmp_perm, in_layout_i, out_layout_i);
    7224        62204 :       int count = vectorizable_slp_permutation_1 (m_vinfo, nullptr,
    7225              :                                                   node, tmp_perm,
    7226        31102 :                                                   SLP_TREE_CHILDREN (node),
    7227              :                                                   false);
    7228        31102 :       if (count < 0)
    7229              :         {
    7230         2430 :           if (in_layout_i == 0 && out_layout_i == 0)
    7231              :             {
    7232              :               /* Use the fallback cost if the node could in principle support
    7233              :                  some nonzero layout for both the inputs and the outputs.
    7234              :                  Otherwise assume that the node will be rejected later
    7235              :                  and rebuilt from scalars.  */
    7236          595 :               if (SLP_TREE_LANES (node) == SLP_TREE_LANES (first_child))
    7237              :                 return fallback_cost;
    7238          314 :               return 0;
    7239              :             }
    7240              :           return -1;
    7241              :         }
    7242              : 
    7243              :       /* We currently have no way of telling whether the new layout is cheaper
    7244              :          or more expensive than the old one.  But at least in principle,
    7245              :          it should be worth making zero permutations (whole-vector shuffles)
    7246              :          cheaper than real permutations, in case the pass is able to remove
    7247              :          the latter.  */
    7248        28672 :       return count == 0 ? 0 : 1;
    7249        31737 :     }
    7250              : 
    7251       213467 :   stmt_vec_info rep = SLP_TREE_REPRESENTATIVE (node);
    7252       213467 :   if (rep
    7253       211686 :       && STMT_VINFO_DATA_REF (rep)
    7254        71491 :       && DR_IS_READ (STMT_VINFO_DATA_REF (rep))
    7255       260788 :       && SLP_TREE_LOAD_PERMUTATION (node).exists ())
    7256              :     {
    7257        38837 :       auto_load_permutation_t tmp_perm;
    7258        38837 :       tmp_perm.safe_splice (SLP_TREE_LOAD_PERMUTATION (node));
    7259        38837 :       if (out_layout_i > 0)
    7260        14918 :         vect_slp_permute (m_perms[out_layout_i], tmp_perm, true);
    7261              : 
    7262        38837 :       poly_uint64 vf = 1;
    7263        38837 :       if (auto loop_vinfo = dyn_cast<loop_vec_info> (m_vinfo))
    7264        12176 :         vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    7265        38837 :       unsigned int n_perms;
    7266        38837 :       if (!vect_transform_slp_perm_load_1 (m_vinfo, node, tmp_perm, vNULL,
    7267              :                                            nullptr, vf, true, false, &n_perms))
    7268              :         {
    7269         1991 :           auto rep = SLP_TREE_REPRESENTATIVE (node);
    7270         1991 :           if (out_layout_i == 0)
    7271              :             {
    7272              :               /* Use the fallback cost if the load is an N-to-N permutation.
    7273              :                  Otherwise assume that the node will be rejected later
    7274              :                  and rebuilt from scalars.  */
    7275         1467 :               if (STMT_VINFO_GROUPED_ACCESS (rep)
    7276         2934 :                   && (DR_GROUP_SIZE (DR_GROUP_FIRST_ELEMENT (rep))
    7277         1467 :                       == SLP_TREE_LANES (node)))
    7278          667 :                 return fallback_cost;
    7279              :               return 0;
    7280              :             }
    7281              :           return -1;
    7282              :         }
    7283              : 
    7284              :       /* See the comment above the corresponding VEC_PERM_EXPR handling.  */
    7285        36846 :       return n_perms == 0 ? 0 : 1;
    7286        38837 :     }
    7287              : 
    7288              :   return 0;
    7289              : }
    7290              : 
    7291              : /* Decide which element layouts we should consider using.  Calculate the
    7292              :    weights associated with inserting layout changes on partition edges.
    7293              :    Also mark partitions that cannot change layout, by setting their
    7294              :    layout to zero.  */
    7295              : 
    7296              : void
    7297       716297 : vect_optimize_slp_pass::start_choosing_layouts ()
    7298              : {
    7299              :   /* Used to assign unique permutation indices.  */
    7300       716297 :   using perm_hash = unbounded_hashmap_traits<
    7301              :     vec_free_hash_base<int_hash_base<unsigned>>,
    7302              :     int_hash<int, -1, -2>
    7303              :   >;
    7304       716297 :   hash_map<vec<unsigned>, int, perm_hash> layout_ids;
    7305              : 
    7306              :   /* Layout 0 is "no change".  */
    7307       716297 :   m_perms.safe_push (vNULL);
    7308              : 
    7309              :   /* Create layouts from existing permutations.  */
    7310       716297 :   auto_load_permutation_t tmp_perm;
    7311      5821408 :   for (unsigned int node_i : m_partitioned_nodes)
    7312              :     {
    7313              :       /* Leafs also double as entries to the reverse graph.  Allow the
    7314              :          layout of those to be changed.  */
    7315      3672517 :       auto &vertex = m_vertices[node_i];
    7316      3672517 :       auto &partition = m_partitions[vertex.partition];
    7317      3672517 :       if (!m_slpg->vertices[node_i].succ)
    7318       939004 :         partition.layout = 0;
    7319              : 
    7320              :       /* Loads and VEC_PERM_EXPRs are the only things generating permutes.  */
    7321      3672517 :       slp_tree node = vertex.node;
    7322      3672517 :       stmt_vec_info dr_stmt = SLP_TREE_REPRESENTATIVE (node);
    7323      3672517 :       slp_tree child;
    7324      3672517 :       unsigned HOST_WIDE_INT imin, imax = 0;
    7325      3672517 :       bool any_permute = false;
    7326      3672517 :       tmp_perm.truncate (0);
    7327      3672517 :       if (SLP_TREE_LOAD_PERMUTATION (node).exists ())
    7328              :         {
    7329              :           /* If splitting out a SLP_TREE_LANE_PERMUTATION can make the node
    7330              :              unpermuted, record a layout that reverses this permutation.
    7331              : 
    7332              :              We would need more work to cope with loads that are internally
    7333              :              permuted and also have inputs (such as masks for
    7334              :              IFN_MASK_LOADs).  */
    7335       633439 :           gcc_assert (partition.layout == 0 && !m_slpg->vertices[node_i].succ);
    7336       633439 :           if (!STMT_VINFO_GROUPED_ACCESS (dr_stmt))
    7337              :             {
    7338       447813 :               partition.layout = -1;
    7339      3650712 :               continue;
    7340              :             }
    7341       185626 :           dr_stmt = DR_GROUP_FIRST_ELEMENT (dr_stmt);
    7342       185626 :           imin = DR_GROUP_SIZE (dr_stmt) + 1;
    7343       185626 :           tmp_perm.safe_splice (SLP_TREE_LOAD_PERMUTATION (node));
    7344              :         }
    7345      5958063 :       else if (SLP_TREE_PERMUTE_P (node)
    7346       139975 :                && SLP_TREE_CHILDREN (node).length () == 1
    7347       120093 :                && (child = SLP_TREE_CHILDREN (node)[0])
    7348      3179053 :                && (TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (child))
    7349       120093 :                    .is_constant (&imin)))
    7350              :         {
    7351              :           /* If the child has the same vector size as this node,
    7352              :              reversing the permutation can make the permutation a no-op.
    7353              :              In other cases it can change a true permutation into a
    7354              :              full-vector extract.  */
    7355       120093 :           tmp_perm.reserve (SLP_TREE_LANES (node));
    7356       444538 :           for (unsigned j = 0; j < SLP_TREE_LANES (node); ++j)
    7357       204352 :             tmp_perm.quick_push (SLP_TREE_LANE_PERMUTATION (node)[j].second);
    7358              :         }
    7359              :       else
    7360      2918985 :         continue;
    7361              : 
    7362       818723 :       for (unsigned j = 0; j < SLP_TREE_LANES (node); ++j)
    7363              :         {
    7364       513004 :           unsigned idx = tmp_perm[j];
    7365       513004 :           imin = MIN (imin, idx);
    7366       513004 :           imax = MAX (imax, idx);
    7367       513004 :           if (idx - tmp_perm[0] != j)
    7368       163450 :             any_permute = true;
    7369              :         }
    7370              :       /* If the span doesn't match we'd disrupt VF computation, avoid
    7371              :          that for now.  */
    7372       305719 :       if (imax - imin + 1 != SLP_TREE_LANES (node))
    7373        91633 :         continue;
    7374              :       /* If there's no permute no need to split one out.  In this case
    7375              :          we can consider turning a load into a permuted load, if that
    7376              :          turns out to be cheaper than alternatives.  */
    7377       214086 :       if (!any_permute)
    7378              :         {
    7379       192126 :           partition.layout = -1;
    7380       192126 :           continue;
    7381              :         }
    7382              : 
    7383              :       /* For now only handle true permutes, like
    7384              :          vect_attempt_slp_rearrange_stmts did.  This allows us to be lazy
    7385              :          when permuting constants and invariants keeping the permute
    7386              :          bijective.  */
    7387        21960 :       auto_sbitmap load_index (SLP_TREE_LANES (node));
    7388        21960 :       bitmap_clear (load_index);
    7389       110534 :       for (unsigned j = 0; j < SLP_TREE_LANES (node); ++j)
    7390        66614 :         bitmap_set_bit (load_index, tmp_perm[j] - imin);
    7391              :       unsigned j;
    7392        87731 :       for (j = 0; j < SLP_TREE_LANES (node); ++j)
    7393        65926 :         if (!bitmap_bit_p (load_index, j))
    7394              :           break;
    7395        21960 :       if (j != SLP_TREE_LANES (node))
    7396          155 :         continue;
    7397              : 
    7398        21805 :       vec<unsigned> perm = vNULL;
    7399        21805 :       perm.safe_grow (SLP_TREE_LANES (node), true);
    7400       109257 :       for (unsigned j = 0; j < SLP_TREE_LANES (node); ++j)
    7401        65647 :         perm[j] = tmp_perm[j] - imin;
    7402              : 
    7403        43610 :       if (int (m_perms.length ()) >= param_vect_max_layout_candidates)
    7404              :         {
    7405              :           /* Continue to use existing layouts, but don't add any more.  */
    7406            0 :           int *entry = layout_ids.get (perm);
    7407            0 :           partition.layout = entry ? *entry : 0;
    7408            0 :           perm.release ();
    7409              :         }
    7410              :       else
    7411              :         {
    7412        21805 :           bool existed;
    7413        21805 :           int &layout_i = layout_ids.get_or_insert (perm, &existed);
    7414        21805 :           if (existed)
    7415         7771 :             perm.release ();
    7416              :           else
    7417              :             {
    7418        14034 :               layout_i = m_perms.length ();
    7419        14034 :               m_perms.safe_push (perm);
    7420              :             }
    7421        21805 :           partition.layout = layout_i;
    7422              :         }
    7423        21960 :     }
    7424              : 
    7425              :   /* Initially assume that every layout is possible and has zero cost
    7426              :      in every partition.  */
    7427       716297 :   m_partition_layout_costs.safe_grow_cleared (m_partitions.length ()
    7428      1432594 :                                               * m_perms.length ());
    7429              : 
    7430              :   /* We have to mark outgoing permutations facing non-associating-reduction
    7431              :      graph entries that are not represented as to be materialized.
    7432              :      slp_inst_kind_bb_reduc currently only covers associatable reductions.  */
    7433      3684781 :   for (slp_instance instance : m_vinfo->slp_instances)
    7434      1535890 :     if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_ctor)
    7435              :       {
    7436         7085 :         unsigned int node_i = SLP_INSTANCE_TREE (instance)->vertex;
    7437         7085 :         m_partitions[m_vertices[node_i].partition].layout = 0;
    7438              :       }
    7439      1528805 :     else if (SLP_INSTANCE_KIND (instance) == slp_inst_kind_reduc_chain)
    7440              :       {
    7441         2348 :         stmt_vec_info stmt_info
    7442         2348 :           = SLP_TREE_REPRESENTATIVE (SLP_INSTANCE_TREE (instance));
    7443         2348 :         vect_reduc_info reduc_info
    7444         2348 :           = info_for_reduction (as_a <loop_vec_info> (m_vinfo),
    7445              :                                 SLP_INSTANCE_TREE (instance));
    7446         2348 :         if (needs_fold_left_reduction_p (TREE_TYPE
    7447              :                                            (gimple_get_lhs (stmt_info->stmt)),
    7448              :                                          VECT_REDUC_INFO_CODE (reduc_info)))
    7449              :           {
    7450          124 :             unsigned int node_i = SLP_INSTANCE_TREE (instance)->vertex;
    7451          124 :             m_partitions[m_vertices[node_i].partition].layout = 0;
    7452              :           }
    7453              :       }
    7454              : 
    7455              :   /* Check which layouts each node and partition can handle.  Calculate the
    7456              :      weights associated with inserting layout changes on edges.  */
    7457      5821408 :   for (unsigned int node_i : m_partitioned_nodes)
    7458              :     {
    7459      3672517 :       auto &vertex = m_vertices[node_i];
    7460      3672517 :       auto &partition = m_partitions[vertex.partition];
    7461      3672517 :       slp_tree node = vertex.node;
    7462              : 
    7463      3672517 :       vertex.weight = vect_slp_node_weight (m_vinfo, node);
    7464              : 
    7465      3672517 :       if (stmt_vec_info rep = SLP_TREE_REPRESENTATIVE (node))
    7466              :         {
    7467              :           /* We do not handle stores with a permutation, so all
    7468              :              incoming permutations must have been materialized.
    7469              : 
    7470              :              We also don't handle masked grouped loads, which lack a
    7471              :              permutation vector.  In this case the memory locations
    7472              :              form an implicit second input to the loads, on top of the
    7473              :              explicit mask input, and the memory input's layout cannot
    7474              :              be changed.
    7475              : 
    7476              :              On the other hand, we do support permuting gather loads and
    7477              :              masked gather loads, where each scalar load is independent
    7478              :              of the others.  This can be useful if the address/index input
    7479              :              benefits from permutation.  */
    7480      3529544 :           if (STMT_VINFO_DATA_REF (rep)
    7481      1701816 :               && STMT_VINFO_GROUPED_ACCESS (rep)
    7482      4532025 :               && !SLP_TREE_LOAD_PERMUTATION (node).exists ())
    7483       816855 :             partition.layout = 0;
    7484              : 
    7485              :           /* We cannot change the layout of an operation that is
    7486              :              not independent on lanes.  Note this is an explicit
    7487              :              negative list since that's much shorter than the respective
    7488              :              positive one but it's critical to keep maintaining it.  */
    7489      3529544 :           if (is_gimple_call (STMT_VINFO_STMT (rep)))
    7490        32635 :             switch (gimple_call_combined_fn (STMT_VINFO_STMT (rep)))
    7491              :               {
    7492         1098 :               case CFN_COMPLEX_ADD_ROT90:
    7493         1098 :               case CFN_COMPLEX_ADD_ROT270:
    7494         1098 :               case CFN_COMPLEX_MUL:
    7495         1098 :               case CFN_COMPLEX_MUL_CONJ:
    7496         1098 :               case CFN_VEC_ADDSUB:
    7497         1098 :               case CFN_VEC_FMADDSUB:
    7498         1098 :               case CFN_VEC_FMSUBADD:
    7499         1098 :                 partition.layout = 0;
    7500              :               default:;
    7501              :               }
    7502              :         }
    7503              : 
    7504      8294323 :       auto process_edge = [&](graph_edge *ud, unsigned int other_node_i)
    7505              :         {
    7506      4621806 :           auto &other_vertex = m_vertices[other_node_i];
    7507              : 
    7508              :           /* Count the number of edges from earlier partitions and the number
    7509              :              of edges to later partitions.  */
    7510      4621806 :           if (other_vertex.partition < vertex.partition)
    7511      2310903 :             partition.in_degree += 1;
    7512              :           else
    7513      2310903 :             partition.out_degree += 1;
    7514              : 
    7515              :           /* If the current node uses the result of OTHER_NODE_I, accumulate
    7516              :              the effects of that.  */
    7517      4621806 :           if (ud->src == int (node_i))
    7518              :             {
    7519      2310903 :               other_vertex.out_weight += vertex.weight;
    7520      2310903 :               other_vertex.out_degree += 1;
    7521              :             }
    7522      8294323 :         };
    7523      3672517 :       for_each_partition_edge (node_i, process_edge);
    7524              :     }
    7525       716297 : }
    7526              : 
    7527              : /* Return the incoming costs for node NODE_I, assuming that each input keeps
    7528              :    its current (provisional) choice of layout.  The inputs do not necessarily
    7529              :    have the same layout as each other.  */
    7530              : 
    7531              : slpg_layout_cost
    7532         4284 : vect_optimize_slp_pass::total_in_cost (unsigned int node_i)
    7533              : {
    7534         4284 :   auto &vertex = m_vertices[node_i];
    7535         4284 :   slpg_layout_cost cost;
    7536        14349 :   auto add_cost = [&](graph_edge *, unsigned int other_node_i)
    7537              :     {
    7538        10065 :       auto &other_vertex = m_vertices[other_node_i];
    7539        10065 :       if (other_vertex.partition < vertex.partition)
    7540              :         {
    7541         6718 :           auto &other_partition = m_partitions[other_vertex.partition];
    7542        13436 :           auto &other_costs = partition_layout_costs (other_vertex.partition,
    7543         6718 :                                                       other_partition.layout);
    7544         6718 :           slpg_layout_cost this_cost = other_costs.in_cost;
    7545         6718 :           this_cost.add_serial_cost (other_costs.internal_cost);
    7546         6718 :           this_cost.split (other_partition.out_degree);
    7547         6718 :           cost.add_parallel_cost (this_cost);
    7548              :         }
    7549        14349 :     };
    7550         4284 :   for_each_partition_edge (node_i, add_cost);
    7551         4284 :   return cost;
    7552              : }
    7553              : 
    7554              : /* Return the cost of switching between layout LAYOUT1_I (at node NODE1_I)
    7555              :    and layout LAYOUT2_I on cross-partition use-to-def edge UD.  Return
    7556              :    slpg_layout_cost::impossible () if the change isn't possible.  */
    7557              : 
    7558              : slpg_layout_cost
    7559       739433 : vect_optimize_slp_pass::
    7560              : edge_layout_cost (graph_edge *ud, unsigned int node1_i, unsigned int layout1_i,
    7561              :                   unsigned int layout2_i)
    7562              : {
    7563       739433 :   auto &def_vertex = m_vertices[ud->dest];
    7564       739433 :   auto &use_vertex = m_vertices[ud->src];
    7565       739433 :   auto def_layout_i = ud->dest == int (node1_i) ? layout1_i : layout2_i;
    7566       739433 :   auto use_layout_i = ud->dest == int (node1_i) ? layout2_i : layout1_i;
    7567       739433 :   auto factor = change_layout_cost (def_vertex.node, def_layout_i,
    7568              :                                     use_layout_i);
    7569       739433 :   if (factor < 0)
    7570         6013 :     return slpg_layout_cost::impossible ();
    7571              : 
    7572              :   /* We have a choice of putting the layout change at the site of the
    7573              :      definition or at the site of the use.  Prefer the former when
    7574              :      optimizing for size or when the execution frequency of the
    7575              :      definition is no greater than the combined execution frequencies of
    7576              :      the uses.  When putting the layout change at the site of the definition,
    7577              :      divvy up the cost among all consumers.  */
    7578       733420 :   if (m_optimize_size || def_vertex.weight <= def_vertex.out_weight)
    7579              :     {
    7580       690785 :       slpg_layout_cost cost = { def_vertex.weight * factor, m_optimize_size };
    7581       690785 :       cost.split (def_vertex.out_degree);
    7582       690785 :       return cost;
    7583              :     }
    7584        42635 :   return { use_vertex.weight * factor, m_optimize_size };
    7585              : }
    7586              : 
    7587              : /* UD represents a use-def link between FROM_NODE_I and a node in a later
    7588              :    partition; FROM_NODE_I could be the definition node or the use node.
    7589              :    The node at the other end of the link wants to use layout TO_LAYOUT_I.
    7590              :    Return the cost of any necessary fix-ups on edge UD, or return
    7591              :    slpg_layout_cost::impossible () if the change isn't possible.
    7592              : 
    7593              :    At this point, FROM_NODE_I's partition has chosen the cheapest
    7594              :    layout based on the information available so far, but this choice
    7595              :    is only provisional.  */
    7596              : 
    7597              : slpg_layout_cost
    7598       197502 : vect_optimize_slp_pass::forward_cost (graph_edge *ud, unsigned int from_node_i,
    7599              :                                       unsigned int to_layout_i)
    7600              : {
    7601       197502 :   auto &from_vertex = m_vertices[from_node_i];
    7602       197502 :   unsigned int from_partition_i = from_vertex.partition;
    7603       197502 :   slpg_partition_info &from_partition = m_partitions[from_partition_i];
    7604       197502 :   gcc_assert (from_partition.layout >= 0);
    7605              : 
    7606              :   /* First calculate the cost on the assumption that FROM_PARTITION sticks
    7607              :      with its current layout preference.  */
    7608       197502 :   slpg_layout_cost cost = slpg_layout_cost::impossible ();
    7609       197502 :   auto edge_cost = edge_layout_cost (ud, from_node_i,
    7610       197502 :                                      from_partition.layout, to_layout_i);
    7611       197502 :   if (edge_cost.is_possible ())
    7612              :     {
    7613       388684 :       auto &from_costs = partition_layout_costs (from_partition_i,
    7614       194342 :                                                  from_partition.layout);
    7615       194342 :       cost = from_costs.in_cost;
    7616       194342 :       cost.add_serial_cost (from_costs.internal_cost);
    7617       194342 :       cost.split (from_partition.out_degree);
    7618       194342 :       cost.add_serial_cost (edge_cost);
    7619              :     }
    7620         3160 :   else if (from_partition.layout == 0)
    7621              :     /* We must allow the source partition to have layout 0 as a fallback,
    7622              :        in case all other options turn out to be impossible.  */
    7623         3160 :     return cost;
    7624              : 
    7625              :   /* Take the minimum of that cost and the cost that applies if
    7626              :      FROM_PARTITION instead switches to TO_LAYOUT_I.  */
    7627       194342 :   auto &direct_layout_costs = partition_layout_costs (from_partition_i,
    7628              :                                                       to_layout_i);
    7629       194342 :   if (direct_layout_costs.is_possible ())
    7630              :     {
    7631       170599 :       slpg_layout_cost direct_cost = direct_layout_costs.in_cost;
    7632       170599 :       direct_cost.add_serial_cost (direct_layout_costs.internal_cost);
    7633       170599 :       direct_cost.split (from_partition.out_degree);
    7634       170599 :       if (!cost.is_possible ()
    7635       170599 :           || direct_cost.is_better_than (cost, m_optimize_size))
    7636        33731 :         cost = direct_cost;
    7637              :     }
    7638              : 
    7639       194342 :   return cost;
    7640              : }
    7641              : 
    7642              : /* UD represents a use-def link between TO_NODE_I and a node in an earlier
    7643              :    partition; TO_NODE_I could be the definition node or the use node.
    7644              :    The node at the other end of the link wants to use layout FROM_LAYOUT_I;
    7645              :    return the cost of any necessary fix-ups on edge UD, or
    7646              :    slpg_layout_cost::impossible () if the choice cannot be made.
    7647              : 
    7648              :    At this point, TO_NODE_I's partition has a fixed choice of layout.  */
    7649              : 
    7650              : slpg_layout_cost
    7651       177493 : vect_optimize_slp_pass::backward_cost (graph_edge *ud, unsigned int to_node_i,
    7652              :                                        unsigned int from_layout_i)
    7653              : {
    7654       177493 :   auto &to_vertex = m_vertices[to_node_i];
    7655       177493 :   unsigned int to_partition_i = to_vertex.partition;
    7656       177493 :   slpg_partition_info &to_partition = m_partitions[to_partition_i];
    7657       177493 :   gcc_assert (to_partition.layout >= 0);
    7658              : 
    7659              :   /* If TO_NODE_I is a VEC_PERM_EXPR consumer, see whether it can be
    7660              :      adjusted for this input having layout FROM_LAYOUT_I.  Assume that
    7661              :      any other inputs keep their current choice of layout.  */
    7662       177493 :   auto &to_costs = partition_layout_costs (to_partition_i,
    7663              :                                            to_partition.layout);
    7664       177493 :   if (ud->src == int (to_node_i)
    7665       177211 :       && SLP_TREE_PERMUTE_P (to_vertex.node))
    7666              :     {
    7667        11468 :       auto &from_partition = m_partitions[m_vertices[ud->dest].partition];
    7668        11468 :       auto old_layout = from_partition.layout;
    7669        11468 :       from_partition.layout = from_layout_i;
    7670        22936 :       int factor = internal_node_cost (to_vertex.node, -1,
    7671        11468 :                                        to_partition.layout);
    7672        11468 :       from_partition.layout = old_layout;
    7673        11468 :       if (factor >= 0)
    7674              :         {
    7675        10610 :           slpg_layout_cost cost = to_costs.out_cost;
    7676        10610 :           cost.add_serial_cost ({ to_vertex.weight * factor,
    7677              :                                   m_optimize_size });
    7678        10610 :           cost.split (to_partition.in_degree);
    7679        10610 :           return cost;
    7680              :         }
    7681              :     }
    7682              : 
    7683              :   /* Compute the cost if we insert any necessary layout change on edge UD.  */
    7684       166883 :   auto edge_cost = edge_layout_cost (ud, to_node_i,
    7685       166883 :                                      to_partition.layout, from_layout_i);
    7686       166883 :   if (edge_cost.is_possible ())
    7687              :     {
    7688       166883 :       slpg_layout_cost cost = to_costs.out_cost;
    7689       166883 :       cost.add_serial_cost (to_costs.internal_cost);
    7690       166883 :       cost.split (to_partition.in_degree);
    7691       166883 :       cost.add_serial_cost (edge_cost);
    7692       166883 :       return cost;
    7693              :     }
    7694              : 
    7695            0 :   return slpg_layout_cost::impossible ();
    7696              : }
    7697              : 
    7698              : /* Make a forward pass through the partitions, accumulating input costs.
    7699              :    Make a tentative (provisional) choice of layout for each partition,
    7700              :    ensuring that this choice still allows later partitions to keep
    7701              :    their original layout.  */
    7702              : 
    7703              : void
    7704         6532 : vect_optimize_slp_pass::forward_pass ()
    7705              : {
    7706       132653 :   for (unsigned int partition_i = 0; partition_i < m_partitions.length ();
    7707              :        ++partition_i)
    7708              :     {
    7709       126121 :       auto &partition = m_partitions[partition_i];
    7710              : 
    7711              :       /* If the partition consists of a single VEC_PERM_EXPR, precompute
    7712              :          the incoming cost that would apply if every predecessor partition
    7713              :          keeps its current layout.  This is used within the loop below.  */
    7714       126121 :       slpg_layout_cost in_cost;
    7715       126121 :       slp_tree single_node = nullptr;
    7716       126121 :       if (partition.node_end == partition.node_begin + 1)
    7717              :         {
    7718       119687 :           unsigned int node_i = m_partitioned_nodes[partition.node_begin];
    7719       119687 :           single_node = m_vertices[node_i].node;
    7720       119687 :           if (SLP_TREE_PERMUTE_P (single_node))
    7721         4284 :             in_cost = total_in_cost (node_i);
    7722              :         }
    7723              : 
    7724              :       /* Go through the possible layouts.  Decide which ones are valid
    7725              :          for this partition and record which of the valid layouts has
    7726              :          the lowest cost.  */
    7727       126121 :       unsigned int min_layout_i = 0;
    7728       126121 :       slpg_layout_cost min_layout_cost = slpg_layout_cost::impossible ();
    7729       388693 :       for (unsigned int layout_i = 0; layout_i < m_perms.length (); ++layout_i)
    7730              :         {
    7731       262572 :           auto &layout_costs = partition_layout_costs (partition_i, layout_i);
    7732       262572 :           if (!layout_costs.is_possible ())
    7733        67316 :             continue;
    7734              : 
    7735              :           /* If the recorded layout is already 0 then the layout cannot
    7736              :              change.  */
    7737       262572 :           if (partition.layout == 0 && layout_i != 0)
    7738              :             {
    7739        46012 :               layout_costs.mark_impossible ();
    7740        46012 :               continue;
    7741              :             }
    7742              : 
    7743       216560 :           bool is_possible = true;
    7744       441369 :           for (unsigned int order_i = partition.node_begin;
    7745       441369 :                order_i < partition.node_end; ++order_i)
    7746              :             {
    7747       243235 :               unsigned int node_i = m_partitioned_nodes[order_i];
    7748       243235 :               auto &vertex = m_vertices[node_i];
    7749              : 
    7750              :               /* Reject the layout if it is individually incompatible
    7751              :                  with any node in the partition.  */
    7752       243235 :               if (!is_compatible_layout (vertex.node, layout_i))
    7753              :                 {
    7754        16967 :                   is_possible = false;
    7755        18426 :                   break;
    7756              :                 }
    7757              : 
    7758       604955 :               auto add_cost = [&](graph_edge *ud, unsigned int other_node_i)
    7759              :                 {
    7760       378687 :                   auto &other_vertex = m_vertices[other_node_i];
    7761       378687 :                   if (other_vertex.partition < vertex.partition)
    7762              :                     {
    7763              :                       /* Accumulate the incoming costs from earlier
    7764              :                          partitions, plus the cost of any layout changes
    7765              :                          on UD itself.  */
    7766       197502 :                       auto cost = forward_cost (ud, other_node_i, layout_i);
    7767       197502 :                       if (!cost.is_possible ())
    7768         3160 :                         is_possible = false;
    7769              :                       else
    7770       194342 :                         layout_costs.in_cost.add_parallel_cost (cost);
    7771              :                     }
    7772              :                   else
    7773              :                     /* Reject the layout if it would make layout 0 impossible
    7774              :                        for later partitions.  This amounts to testing that the
    7775              :                        target supports reversing the layout change on edges
    7776              :                        to later partitions.
    7777              : 
    7778              :                        In principle, it might be possible to push a layout
    7779              :                        change all the way down a graph, so that it never
    7780              :                        needs to be reversed and so that the target doesn't
    7781              :                        need to support the reverse operation.  But it would
    7782              :                        be awkward to bail out if we hit a partition that
    7783              :                        does not support the new layout, especially since
    7784              :                        we are not dealing with a lattice.  */
    7785       181185 :                     is_possible &= edge_layout_cost (ud, other_node_i, 0,
    7786       181185 :                                                      layout_i).is_possible ();
    7787       604955 :                 };
    7788       226268 :               for_each_partition_edge (node_i, add_cost);
    7789              : 
    7790              :               /* Accumulate the cost of using LAYOUT_I within NODE,
    7791              :                  both for the inputs and the outputs.  */
    7792       226268 :               int factor = internal_node_cost (vertex.node, layout_i,
    7793              :                                                layout_i);
    7794       226268 :               if (factor < 0)
    7795              :                 {
    7796         1459 :                   is_possible = false;
    7797         1459 :                   break;
    7798              :                 }
    7799       224809 :               else if (factor)
    7800        36004 :                 layout_costs.internal_cost.add_serial_cost
    7801        36004 :                   ({ vertex.weight * factor, m_optimize_size });
    7802              :             }
    7803       216560 :           if (!is_possible)
    7804              :             {
    7805        21304 :               layout_costs.mark_impossible ();
    7806        21304 :               continue;
    7807              :             }
    7808              : 
    7809              :           /* Combine the incoming and partition-internal costs.  */
    7810       195256 :           slpg_layout_cost combined_cost = layout_costs.in_cost;
    7811       195256 :           combined_cost.add_serial_cost (layout_costs.internal_cost);
    7812              : 
    7813              :           /* If this partition consists of a single VEC_PERM_EXPR, see
    7814              :              if the VEC_PERM_EXPR can be changed to support output layout
    7815              :              LAYOUT_I while keeping all the provisional choices of input
    7816              :              layout.  */
    7817       195256 :           if (single_node && SLP_TREE_PERMUTE_P (single_node))
    7818              :             {
    7819         7468 :               int factor = internal_node_cost (single_node, -1, layout_i);
    7820         7468 :               if (factor >= 0)
    7821              :                 {
    7822         6791 :                   auto weight = m_vertices[single_node->vertex].weight;
    7823         6791 :                   slpg_layout_cost internal_cost
    7824         6791 :                     = { weight * factor, m_optimize_size };
    7825              : 
    7826         6791 :                   slpg_layout_cost alt_cost = in_cost;
    7827         6791 :                   alt_cost.add_serial_cost (internal_cost);
    7828         6791 :                   if (alt_cost.is_better_than (combined_cost, m_optimize_size))
    7829              :                     {
    7830         1622 :                       combined_cost = alt_cost;
    7831         1622 :                       layout_costs.in_cost = in_cost;
    7832         1622 :                       layout_costs.internal_cost = internal_cost;
    7833              :                     }
    7834              :                 }
    7835              :             }
    7836              : 
    7837              :           /* Record the layout with the lowest cost.  Prefer layout 0 in
    7838              :              the event of a tie between it and another layout.  */
    7839       195256 :           if (!min_layout_cost.is_possible ()
    7840        69135 :               || combined_cost.is_better_than (min_layout_cost,
    7841              :                                                m_optimize_size))
    7842              :             {
    7843       143347 :               min_layout_i = layout_i;
    7844       143347 :               min_layout_cost = combined_cost;
    7845              :             }
    7846              :         }
    7847              : 
    7848              :       /* This loop's handling of earlier partitions should ensure that
    7849              :          choosing the original layout for the current partition is no
    7850              :          less valid than it was in the original graph, even with the
    7851              :          provisional layout choices for those earlier partitions.  */
    7852       126121 :       gcc_assert (min_layout_cost.is_possible ());
    7853       126121 :       partition.layout = min_layout_i;
    7854              :     }
    7855         6532 : }
    7856              : 
    7857              : /* Make a backward pass through the partitions, accumulating output costs.
    7858              :    Make a final choice of layout for each partition.  */
    7859              : 
    7860              : void
    7861         6532 : vect_optimize_slp_pass::backward_pass ()
    7862              : {
    7863       139185 :   for (unsigned int partition_i = m_partitions.length (); partition_i-- > 0;)
    7864              :     {
    7865       126121 :       auto &partition = m_partitions[partition_i];
    7866              : 
    7867       126121 :       unsigned int min_layout_i = 0;
    7868       126121 :       slpg_layout_cost min_layout_cost = slpg_layout_cost::impossible ();
    7869       388693 :       for (unsigned int layout_i = 0; layout_i < m_perms.length (); ++layout_i)
    7870              :         {
    7871       262572 :           auto &layout_costs = partition_layout_costs (partition_i, layout_i);
    7872       262572 :           if (!layout_costs.is_possible ())
    7873        67316 :             continue;
    7874              : 
    7875              :           /* Accumulate the costs from successor partitions.  */
    7876       195256 :           bool is_possible = true;
    7877       417162 :           for (unsigned int order_i = partition.node_begin;
    7878       417162 :                order_i < partition.node_end; ++order_i)
    7879              :             {
    7880       221906 :               unsigned int node_i = m_partitioned_nodes[order_i];
    7881       221906 :               auto &vertex = m_vertices[node_i];
    7882       593262 :               auto add_cost = [&](graph_edge *ud, unsigned int other_node_i)
    7883              :                 {
    7884       371356 :                   auto &other_vertex = m_vertices[other_node_i];
    7885       371356 :                   auto &other_partition = m_partitions[other_vertex.partition];
    7886       371356 :                   if (other_vertex.partition > vertex.partition)
    7887              :                     {
    7888              :                       /* Accumulate the incoming costs from later
    7889              :                          partitions, plus the cost of any layout changes
    7890              :                          on UD itself.  */
    7891       177493 :                       auto cost = backward_cost (ud, other_node_i, layout_i);
    7892       177493 :                       if (!cost.is_possible ())
    7893            0 :                         is_possible = false;
    7894              :                       else
    7895       177493 :                         layout_costs.out_cost.add_parallel_cost (cost);
    7896              :                     }
    7897              :                   else
    7898              :                     /* Make sure that earlier partitions can (if necessary
    7899              :                        or beneficial) keep the layout that they chose in
    7900              :                        the forward pass.  This ensures that there is at
    7901              :                        least one valid choice of layout.  */
    7902       193863 :                     is_possible &= edge_layout_cost (ud, other_node_i,
    7903       193863 :                                                      other_partition.layout,
    7904       193863 :                                                      layout_i).is_possible ();
    7905       593262 :                 };
    7906       221906 :               for_each_partition_edge (node_i, add_cost);
    7907              :             }
    7908       195256 :           if (!is_possible)
    7909              :             {
    7910            0 :               layout_costs.mark_impossible ();
    7911            0 :               continue;
    7912              :             }
    7913              : 
    7914              :           /* Locally combine the costs from the forward and backward passes.
    7915              :              (This combined cost is not passed on, since that would lead
    7916              :              to double counting.)  */
    7917       195256 :           slpg_layout_cost combined_cost = layout_costs.in_cost;
    7918       195256 :           combined_cost.add_serial_cost (layout_costs.internal_cost);
    7919       195256 :           combined_cost.add_serial_cost (layout_costs.out_cost);
    7920              : 
    7921              :           /* Record the layout with the lowest cost.  Prefer layout 0 in
    7922              :              the event of a tie between it and another layout.  */
    7923       195256 :           if (!min_layout_cost.is_possible ()
    7924        69135 :               || combined_cost.is_better_than (min_layout_cost,
    7925              :                                                m_optimize_size))
    7926              :             {
    7927       137082 :               min_layout_i = layout_i;
    7928       137082 :               min_layout_cost = combined_cost;
    7929              :             }
    7930              :         }
    7931              : 
    7932       126121 :       gcc_assert (min_layout_cost.is_possible ());
    7933       126121 :       partition.layout = min_layout_i;
    7934              :     }
    7935         6532 : }
    7936              : 
    7937              : /* Return a node that applies layout TO_LAYOUT_I to the original form of NODE.
    7938              :    NODE already has the layout that was selected for its partition.  */
    7939              : 
    7940              : slp_tree
    7941       177356 : vect_optimize_slp_pass::get_result_with_layout (slp_tree node,
    7942              :                                                 unsigned int to_layout_i)
    7943              : {
    7944       177356 :   unsigned int result_i = node->vertex * m_perms.length () + to_layout_i;
    7945       177356 :   slp_tree result = m_node_layouts[result_i];
    7946       177356 :   if (result)
    7947              :     return result;
    7948              : 
    7949       176480 :   if (SLP_TREE_DEF_TYPE (node) == vect_constant_def
    7950       176480 :       || (SLP_TREE_DEF_TYPE (node) == vect_external_def
    7951              :           /* We can't permute vector defs in place.  */
    7952        21412 :           && SLP_TREE_VEC_DEFS (node).is_empty ()))
    7953              :     {
    7954              :       /* If the vector is uniform or unchanged, there's nothing to do.  */
    7955        44965 :       if (to_layout_i == 0 || vect_slp_tree_uniform_p (node))
    7956              :         result = node;
    7957              :       else
    7958              :         {
    7959         3602 :           auto scalar_ops = SLP_TREE_SCALAR_OPS (node).copy ();
    7960         3602 :           result = vect_create_new_slp_node (scalar_ops);
    7961         3602 :           vect_slp_permute (m_perms[to_layout_i], scalar_ops, true);
    7962              :         }
    7963              :     }
    7964              :   else
    7965              :     {
    7966       131515 :       unsigned int partition_i = m_vertices[node->vertex].partition;
    7967       131515 :       unsigned int from_layout_i = m_partitions[partition_i].layout;
    7968       131515 :       if (from_layout_i == to_layout_i)
    7969       130321 :         return node;
    7970              : 
    7971              :       /* If NODE is itself a VEC_PERM_EXPR, try to create a parallel
    7972              :          permutation instead of a serial one.  Leave the new permutation
    7973              :          in TMP_PERM on success.  */
    7974         1194 :       auto_lane_permutation_t tmp_perm;
    7975         1194 :       unsigned int num_inputs = 1;
    7976         1194 :       if (SLP_TREE_PERMUTE_P (node))
    7977              :         {
    7978          104 :           tmp_perm.safe_splice (SLP_TREE_LANE_PERMUTATION (node));
    7979          104 :           if (from_layout_i != 0)
    7980           44 :             vect_slp_permute (m_perms[from_layout_i], tmp_perm, false);
    7981          104 :           if (to_layout_i != 0)
    7982           64 :             vect_slp_permute (m_perms[to_layout_i], tmp_perm, true);
    7983          104 :           if (vectorizable_slp_permutation_1 (m_vinfo, nullptr, node,
    7984              :                                               tmp_perm,
    7985          104 :                                               SLP_TREE_CHILDREN (node),
    7986              :                                               false) >= 0)
    7987          104 :             num_inputs = SLP_TREE_CHILDREN (node).length ();
    7988              :           else
    7989            0 :             tmp_perm.truncate (0);
    7990              :         }
    7991              : 
    7992         1194 :       if (dump_enabled_p ())
    7993              :         {
    7994           70 :           if (tmp_perm.length () > 0)
    7995            6 :             dump_printf_loc (MSG_NOTE, vect_location,
    7996              :                              "duplicating permutation node %p with"
    7997              :                              " layout %d\n",
    7998              :                              (void *) node, to_layout_i);
    7999              :           else
    8000           64 :             dump_printf_loc (MSG_NOTE, vect_location,
    8001              :                              "inserting permutation node in place of %p\n",
    8002              :                              (void *) node);
    8003              :         }
    8004              : 
    8005         1194 :       unsigned int num_lanes = SLP_TREE_LANES (node);
    8006         1194 :       result = vect_create_new_slp_node (num_inputs, VEC_PERM_EXPR);
    8007         1194 :       if (SLP_TREE_SCALAR_STMTS (node).exists ())
    8008              :         {
    8009         1194 :           auto &stmts = SLP_TREE_SCALAR_STMTS (result);
    8010         1194 :           stmts.safe_splice (SLP_TREE_SCALAR_STMTS (node));
    8011         1194 :           if (from_layout_i != 0)
    8012          477 :             vect_slp_permute (m_perms[from_layout_i], stmts, false);
    8013         1194 :           if (to_layout_i != 0)
    8014          721 :             vect_slp_permute (m_perms[to_layout_i], stmts, true);
    8015              :         }
    8016         1194 :       SLP_TREE_LANES (result) = num_lanes;
    8017         1194 :       SLP_TREE_VECTYPE (result) = SLP_TREE_VECTYPE (node);
    8018         1194 :       result->vertex = -1;
    8019              : 
    8020         1194 :       auto &lane_perm = SLP_TREE_LANE_PERMUTATION (result);
    8021         1194 :       if (tmp_perm.length ())
    8022              :         {
    8023          104 :           lane_perm.safe_splice (tmp_perm);
    8024          104 :           SLP_TREE_CHILDREN (result).safe_splice (SLP_TREE_CHILDREN (node));
    8025              :         }
    8026              :       else
    8027              :         {
    8028         1090 :           lane_perm.create (num_lanes);
    8029         4448 :           for (unsigned j = 0; j < num_lanes; ++j)
    8030         2268 :             lane_perm.quick_push ({ 0, j });
    8031         1090 :           if (from_layout_i != 0)
    8032          433 :             vect_slp_permute (m_perms[from_layout_i], lane_perm, false);
    8033         1090 :           if (to_layout_i != 0)
    8034          657 :             vect_slp_permute (m_perms[to_layout_i], lane_perm, true);
    8035         1090 :           SLP_TREE_CHILDREN (result).safe_push (node);
    8036              :         }
    8037         4848 :       for (slp_tree child : SLP_TREE_CHILDREN (result))
    8038         1266 :         child->refcnt++;
    8039         1194 :     }
    8040        46159 :   m_node_layouts[result_i] = result;
    8041        46159 :   return result;
    8042              : }
    8043              : 
    8044              : /* Apply the chosen vector layouts to the SLP graph.  */
    8045              : 
    8046              : void
    8047        13467 : vect_optimize_slp_pass::materialize ()
    8048              : {
    8049              :   /* We no longer need the costs, so avoid having two O(N * P) arrays
    8050              :      live at the same time.  */
    8051        13467 :   m_partition_layout_costs.release ();
    8052        40401 :   m_node_layouts.safe_grow_cleared (m_vertices.length () * m_perms.length ());
    8053              : 
    8054        26934 :   auto_sbitmap fully_folded (m_vertices.length ());
    8055        13467 :   bitmap_clear (fully_folded);
    8056       196517 :   for (unsigned int node_i : m_partitioned_nodes)
    8057              :     {
    8058       156116 :       auto &vertex = m_vertices[node_i];
    8059       156116 :       slp_tree node = vertex.node;
    8060       156116 :       int layout_i = m_partitions[vertex.partition].layout;
    8061       156116 :       gcc_assert (layout_i >= 0);
    8062              : 
    8063              :       /* Rearrange the scalar statements to match the chosen layout.  */
    8064       156116 :       if (layout_i > 0)
    8065        25963 :         vect_slp_permute (m_perms[layout_i],
    8066        25963 :                           SLP_TREE_SCALAR_STMTS (node), true);
    8067              : 
    8068              :       /* Update load and lane permutations.  */
    8069       156116 :       if (SLP_TREE_PERMUTE_P (node))
    8070              :         {
    8071              :           /* First try to absorb the input vector layouts.  If that fails,
    8072              :              force the inputs to have layout LAYOUT_I too.  We checked that
    8073              :              that was possible before deciding to use nonzero output layouts.
    8074              :              (Note that at this stage we don't really have any guarantee that
    8075              :              the target supports the original VEC_PERM_EXPR.)  */
    8076         6483 :           auto &perm = SLP_TREE_LANE_PERMUTATION (node);
    8077         6483 :           auto_lane_permutation_t tmp_perm;
    8078         6483 :           tmp_perm.safe_splice (perm);
    8079         6483 :           change_vec_perm_layout (node, tmp_perm, -1, layout_i);
    8080         6483 :           if (vectorizable_slp_permutation_1 (m_vinfo, nullptr, node,
    8081              :                                               tmp_perm,
    8082         6483 :                                               SLP_TREE_CHILDREN (node),
    8083              :                                               false) >= 0)
    8084              :             {
    8085         5888 :               if (dump_enabled_p ()
    8086         6816 :                   && !std::equal (tmp_perm.begin (), tmp_perm.end (),
    8087              :                                   perm.begin ()))
    8088           58 :                 dump_printf_loc (MSG_NOTE, vect_location,
    8089              :                                  "absorbing input layouts into %p\n",
    8090              :                                  (void *) node);
    8091        33303 :               std::copy (tmp_perm.begin (), tmp_perm.end (), perm.begin ());
    8092         5888 :               bitmap_set_bit (fully_folded, node_i);
    8093              :             }
    8094              :           else
    8095              :             {
    8096              :               /* Not MSG_MISSED because it would make no sense to users.  */
    8097          595 :               if (dump_enabled_p ())
    8098           46 :                 dump_printf_loc (MSG_NOTE, vect_location,
    8099              :                                  "failed to absorb input layouts into %p\n",
    8100              :                                  (void *) node);
    8101          595 :               change_vec_perm_layout (nullptr, perm, layout_i, layout_i);
    8102              :             }
    8103         6483 :         }
    8104              :       else
    8105              :         {
    8106       149633 :           gcc_assert (!SLP_TREE_LANE_PERMUTATION (node).exists ());
    8107       149633 :           auto &load_perm = SLP_TREE_LOAD_PERMUTATION (node);
    8108       149633 :           if (layout_i > 0)
    8109              :             /* ???  When we handle non-bijective permutes the idea
    8110              :                is that we can force the load-permutation to be
    8111              :                { min, min + 1, min + 2, ... max }.  But then the
    8112              :                scalar defs might no longer match the lane content
    8113              :                which means wrong-code with live lane vectorization.
    8114              :                So we possibly have to have NULL entries for those.  */
    8115        25171 :             vect_slp_permute (m_perms[layout_i], load_perm, true);
    8116              :         }
    8117              :     }
    8118              : 
    8119              :   /* Do this before any nodes disappear, since it involves a walk
    8120              :      over the leaves.  */
    8121        13467 :   remove_redundant_permutations ();
    8122              : 
    8123              :   /* Replace each child with a correctly laid-out version.  */
    8124       196517 :   for (unsigned int node_i : m_partitioned_nodes)
    8125              :     {
    8126              :       /* Skip nodes that have already been handled above.  */
    8127       156116 :       if (bitmap_bit_p (fully_folded, node_i))
    8128         5888 :         continue;
    8129              : 
    8130       150228 :       auto &vertex = m_vertices[node_i];
    8131       150228 :       int in_layout_i = m_partitions[vertex.partition].layout;
    8132       150228 :       gcc_assert (in_layout_i >= 0);
    8133              : 
    8134              :       unsigned j;
    8135              :       slp_tree child;
    8136       447588 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (vertex.node), j, child)
    8137              :         {
    8138       183403 :           if (!child)
    8139         6047 :             continue;
    8140              : 
    8141       177356 :           slp_tree new_child = get_result_with_layout (child, in_layout_i);
    8142       177356 :           if (new_child != child)
    8143              :             {
    8144         5379 :               vect_free_slp_tree (child);
    8145         5379 :               SLP_TREE_CHILDREN (vertex.node)[j] = new_child;
    8146         5379 :               new_child->refcnt += 1;
    8147              :             }
    8148              :         }
    8149              :     }
    8150        13467 : }
    8151              : 
    8152              : /* Elide load permutations that are not necessary.  Such permutations might
    8153              :    be pre-existing, rather than created by the layout optimizations.  */
    8154              : 
    8155              : void
    8156       716297 : vect_optimize_slp_pass::remove_redundant_permutations ()
    8157              : {
    8158      4745108 :   for (unsigned int node_i : m_leafs)
    8159              :     {
    8160      2596217 :       slp_tree node = m_vertices[node_i].node;
    8161      2596217 :       if (!SLP_TREE_LOAD_PERMUTATION (node).exists ())
    8162      1962778 :         continue;
    8163              : 
    8164              :       /* In basic block vectorization we allow any subchain of an interleaving
    8165              :          chain.
    8166              :          FORNOW: not in loop SLP because of realignment complications.  */
    8167       633439 :       if (is_a <bb_vec_info> (m_vinfo))
    8168              :         {
    8169       188823 :           bool subchain_p = true;
    8170              :           stmt_vec_info next_load_info = NULL;
    8171              :           stmt_vec_info load_info;
    8172              :           unsigned j;
    8173       188823 :           FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), j, load_info)
    8174              :             {
    8175       156063 :               if (j != 0
    8176       156063 :                   && (next_load_info != load_info
    8177        69285 :                       || ! load_info
    8178        69285 :                       || DR_GROUP_GAP (load_info) != 1))
    8179              :                 {
    8180              :                   subchain_p = false;
    8181              :                   break;
    8182              :                 }
    8183       124940 :               next_load_info = DR_GROUP_NEXT_ELEMENT (load_info);
    8184              :             }
    8185        63883 :           if (subchain_p)
    8186              :             {
    8187        32760 :               SLP_TREE_LOAD_PERMUTATION (node).release ();
    8188        32760 :               continue;
    8189              :             }
    8190              :         }
    8191              :       else
    8192              :         {
    8193       569556 :           loop_vec_info loop_vinfo = as_a<loop_vec_info> (m_vinfo);
    8194       569556 :           bool this_load_permuted = !vect_load_perm_consecutive_p (node, 0);
    8195              :           /* When this isn't a grouped access we know it's single element
    8196              :              and contiguous.  */
    8197       569556 :           if (!STMT_VINFO_GROUPED_ACCESS (SLP_TREE_SCALAR_STMTS (node)[0]))
    8198              :             {
    8199       447813 :               if (!this_load_permuted
    8200       447813 :                   && (known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), 1U)
    8201       447040 :                       || SLP_TREE_LANES (node) == 1))
    8202       447052 :                 SLP_TREE_LOAD_PERMUTATION (node).release ();
    8203       447813 :               continue;
    8204              :             }
    8205       121743 :           stmt_vec_info first_stmt_info
    8206       121743 :             = DR_GROUP_FIRST_ELEMENT (SLP_TREE_SCALAR_STMTS (node)[0]);
    8207       122276 :           if (!this_load_permuted
    8208              :               /* The load requires permutation when unrolling exposes
    8209              :                  a gap either because the group is larger than the SLP
    8210              :                  group-size or because there is a gap between the groups.  */
    8211       121743 :               && (known_eq (LOOP_VINFO_VECT_FACTOR (loop_vinfo), 1U)
    8212        99057 :                   || ((SLP_TREE_LANES (node) == DR_GROUP_SIZE (first_stmt_info))
    8213          147 :                       && DR_GROUP_GAP (first_stmt_info) == 0)))
    8214              :             {
    8215          533 :               SLP_TREE_LOAD_PERMUTATION (node).release ();
    8216          533 :               continue;
    8217              :             }
    8218              :         }
    8219              :     }
    8220       716297 : }
    8221              : 
    8222              : /* Print the partition graph and layout information to the dump file.  */
    8223              : 
    8224              : void
    8225          687 : vect_optimize_slp_pass::dump ()
    8226              : {
    8227          687 :   dump_printf_loc (MSG_NOTE, vect_location,
    8228              :                    "SLP optimize permutations:\n");
    8229         1387 :   for (unsigned int layout_i = 1; layout_i < m_perms.length (); ++layout_i)
    8230              :     {
    8231          700 :       dump_printf_loc (MSG_NOTE, vect_location, "  %d: { ", layout_i);
    8232          700 :       const char *sep = "";
    8233         5953 :       for (unsigned int idx : m_perms[layout_i])
    8234              :         {
    8235         3853 :           dump_printf (MSG_NOTE, "%s%d", sep, idx);
    8236         3853 :           sep = ", ";
    8237              :         }
    8238          700 :       dump_printf (MSG_NOTE, " }\n");
    8239              :     }
    8240          687 :   dump_printf_loc (MSG_NOTE, vect_location,
    8241              :                    "SLP optimize partitions:\n");
    8242         5968 :   for (unsigned int partition_i = 0; partition_i < m_partitions.length ();
    8243              :        ++partition_i)
    8244              :     {
    8245         5281 :       auto &partition = m_partitions[partition_i];
    8246         5281 :       dump_printf_loc (MSG_NOTE, vect_location,  "  -------------\n");
    8247         5281 :       dump_printf_loc (MSG_NOTE, vect_location,
    8248              :                        "  partition %d (layout %d):\n",
    8249              :                        partition_i, partition.layout);
    8250         5281 :       dump_printf_loc (MSG_NOTE, vect_location, "    nodes:\n");
    8251        10796 :       for (unsigned int order_i = partition.node_begin;
    8252        10796 :            order_i < partition.node_end; ++order_i)
    8253              :         {
    8254         5515 :           auto &vertex = m_vertices[m_partitioned_nodes[order_i]];
    8255        11030 :           dump_printf_loc (MSG_NOTE, vect_location, "      - %p:\n",
    8256         5515 :                            (void *) vertex.node);
    8257         5515 :           dump_printf_loc (MSG_NOTE, vect_location,
    8258              :                            "          weight: %f\n",
    8259              :                            vertex.weight.to_double ());
    8260         5515 :           if (vertex.out_degree)
    8261         4326 :             dump_printf_loc (MSG_NOTE, vect_location,
    8262              :                              "          out weight: %f (degree %d)\n",
    8263              :                              vertex.out_weight.to_double (),
    8264              :                              vertex.out_degree);
    8265         5515 :           if (SLP_TREE_PERMUTE_P (vertex.node))
    8266          510 :             dump_printf_loc (MSG_NOTE, vect_location,
    8267              :                              "          op: VEC_PERM_EXPR\n");
    8268         5005 :           else if (auto rep = SLP_TREE_REPRESENTATIVE (vertex.node))
    8269         4987 :             dump_printf_loc (MSG_NOTE, vect_location,
    8270              :                              "          op template: %G", rep->stmt);
    8271              :         }
    8272         5281 :       dump_printf_loc (MSG_NOTE, vect_location, "    edges:\n");
    8273        10796 :       for (unsigned int order_i = partition.node_begin;
    8274        10796 :            order_i < partition.node_end; ++order_i)
    8275              :         {
    8276         5515 :           unsigned int node_i = m_partitioned_nodes[order_i];
    8277         5515 :           auto &vertex = m_vertices[node_i];
    8278        16717 :           auto print_edge = [&](graph_edge *, unsigned int other_node_i)
    8279              :             {
    8280        11202 :               auto &other_vertex = m_vertices[other_node_i];
    8281        11202 :               if (other_vertex.partition < vertex.partition)
    8282         5601 :                 dump_printf_loc (MSG_NOTE, vect_location,
    8283              :                                  "      - %p [%d] --> %p\n",
    8284         5601 :                                  (void *) other_vertex.node,
    8285              :                                  other_vertex.partition,
    8286         5601 :                                  (void *) vertex.node);
    8287              :               else
    8288         5601 :                 dump_printf_loc (MSG_NOTE, vect_location,
    8289              :                                  "      - %p --> [%d] %p\n",
    8290         5601 :                                  (void *) vertex.node,
    8291              :                                  other_vertex.partition,
    8292         5601 :                                  (void *) other_vertex.node);
    8293        16717 :             };
    8294         5515 :           for_each_partition_edge (node_i, print_edge);
    8295              :         }
    8296              : 
    8297        16042 :       for (unsigned int layout_i = 0; layout_i < m_perms.length (); ++layout_i)
    8298              :         {
    8299        10761 :           auto &layout_costs = partition_layout_costs (partition_i, layout_i);
    8300        10761 :           if (layout_costs.is_possible ())
    8301              :             {
    8302         8908 :               dump_printf_loc (MSG_NOTE, vect_location,
    8303              :                                "    layout %d:%s\n", layout_i,
    8304         8908 :                                partition.layout == int (layout_i)
    8305              :                                ? " (*)" : "");
    8306         8908 :               slpg_layout_cost combined_cost = layout_costs.in_cost;
    8307         8908 :               combined_cost.add_serial_cost (layout_costs.internal_cost);
    8308         8908 :               combined_cost.add_serial_cost (layout_costs.out_cost);
    8309              : #define TEMPLATE "{depth: %f, total: %f}"
    8310         8908 :               dump_printf_loc (MSG_NOTE, vect_location,
    8311              :                                "        " TEMPLATE "\n",
    8312              :                                layout_costs.in_cost.depth.to_double (),
    8313              :                                layout_costs.in_cost.total.to_double ());
    8314         8908 :               dump_printf_loc (MSG_NOTE, vect_location,
    8315              :                                "      + " TEMPLATE "\n",
    8316              :                                layout_costs.internal_cost.depth.to_double (),
    8317              :                                layout_costs.internal_cost.total.to_double ());
    8318         8908 :               dump_printf_loc (MSG_NOTE, vect_location,
    8319              :                                "      + " TEMPLATE "\n",
    8320              :                                layout_costs.out_cost.depth.to_double (),
    8321              :                                layout_costs.out_cost.total.to_double ());
    8322         8908 :               dump_printf_loc (MSG_NOTE, vect_location,
    8323              :                                "      = " TEMPLATE "\n",
    8324              :                                combined_cost.depth.to_double (),
    8325              :                                combined_cost.total.to_double ());
    8326              : #undef TEMPLATE
    8327              :             }
    8328              :           else
    8329         1853 :             dump_printf_loc (MSG_NOTE, vect_location,
    8330              :                              "    layout %d: rejected\n", layout_i);
    8331              :         }
    8332              :     }
    8333          687 : }
    8334              : 
    8335              : /* Masked load lanes discovery.  */
    8336              : 
    8337              : void
    8338       716297 : vect_optimize_slp_pass::decide_masked_load_lanes ()
    8339              : {
    8340      7387242 :   for (auto v : m_vertices)
    8341              :     {
    8342      5238351 :       slp_tree node = v.node;
    8343      5238351 :       if (SLP_TREE_DEF_TYPE (node) != vect_internal_def
    8344      3670622 :           || SLP_TREE_PERMUTE_P (node))
    8345      1708807 :         continue;
    8346      3529544 :       stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (node);
    8347      1701816 :       if (! STMT_VINFO_GROUPED_ACCESS (stmt_info)
    8348              :           /* The mask has to be uniform.  */
    8349      1002481 :           || STMT_VINFO_SLP_VECT_ONLY (stmt_info)
    8350      1002403 :           || ! is_a <gcall *> (STMT_VINFO_STMT (stmt_info))
    8351      3529629 :           || ! gimple_call_internal_p (STMT_VINFO_STMT (stmt_info),
    8352              :                                        IFN_MASK_LOAD))
    8353      3529511 :         continue;
    8354           33 :       stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
    8355           66 :       if (STMT_VINFO_STRIDED_P (stmt_info)
    8356           33 :           || compare_step_with_zero (m_vinfo, stmt_info) <= 0
    8357           63 :           || vect_load_lanes_supported (SLP_TREE_VECTYPE (node),
    8358           30 :                                         DR_GROUP_SIZE (stmt_info),
    8359              :                                         true) == IFN_LAST)
    8360           33 :         continue;
    8361              : 
    8362              :       /* Uniform masks need to be suitably represented.  */
    8363            0 :       slp_tree mask = SLP_TREE_CHILDREN (node)[0];
    8364            0 :       if (!SLP_TREE_PERMUTE_P (mask)
    8365            0 :           || SLP_TREE_CHILDREN (mask).length () != 1)
    8366            0 :         continue;
    8367            0 :       bool match = true;
    8368            0 :       for (auto perm : SLP_TREE_LANE_PERMUTATION (mask))
    8369            0 :         if (perm.first != 0 || perm.second != 0)
    8370              :           {
    8371              :             match = false;
    8372              :             break;
    8373              :           }
    8374            0 :       if (!match)
    8375            0 :         continue;
    8376              : 
    8377              :       /* Now see if the consumer side matches.  */
    8378            0 :       for (graph_edge *pred = m_slpg->vertices[node->vertex].pred;
    8379            0 :            pred; pred = pred->pred_next)
    8380              :         {
    8381            0 :           slp_tree pred_node = m_vertices[pred->src].node;
    8382              :           /* All consumers should be a permute with a single outgoing lane.  */
    8383            0 :           if (!SLP_TREE_PERMUTE_P (pred_node)
    8384            0 :               || SLP_TREE_LANES (pred_node) != 1)
    8385              :             {
    8386              :               match = false;
    8387              :               break;
    8388              :             }
    8389            0 :           gcc_assert (SLP_TREE_CHILDREN (pred_node).length () == 1);
    8390              :         }
    8391            0 :       if (!match)
    8392            0 :         continue;
    8393              :       /* Now we can mark the nodes as to use load lanes.  */
    8394            0 :       node->ldst_lanes = true;
    8395            0 :       for (graph_edge *pred = m_slpg->vertices[node->vertex].pred;
    8396            0 :            pred; pred = pred->pred_next)
    8397            0 :         m_vertices[pred->src].node->ldst_lanes = true;
    8398              :       /* The catch is we have to massage the mask.  We have arranged
    8399              :          analyzed uniform masks to be represented by a splat VEC_PERM
    8400              :          which we can now simply elide as we cannot easily re-do SLP
    8401              :          discovery here.  */
    8402            0 :       slp_tree new_mask = SLP_TREE_CHILDREN (mask)[0];
    8403            0 :       SLP_TREE_REF_COUNT (new_mask)++;
    8404            0 :       SLP_TREE_CHILDREN (node)[0] = new_mask;
    8405            0 :       vect_free_slp_tree (mask);
    8406              :     }
    8407       716297 : }
    8408              : 
    8409              : /* Perform legitimizing attempts.  This is intended to improve the
    8410              :    situation when layout 0 is not valid which is a situation the cost
    8411              :    based propagation does not handle well.
    8412              :    Return true if further layout optimization is possible, false if
    8413              :    the layout configuration should be considered final.  */
    8414              : 
    8415              : bool
    8416        13467 : vect_optimize_slp_pass::legitimize ()
    8417              : {
    8418              :   /* Perform a very simple legitimizing attempt by attempting to choose
    8419              :      a single layout for all partitions that will make all permutations
    8420              :      a noop.  That should also be the optimal layout choice in case
    8421              :      layout zero is legitimate.
    8422              :      ???  Disconnected components of the SLP graph could have distinct
    8423              :      single layouts.  */
    8424        13467 :   int single_layout_i = -1;
    8425        13467 :   unsigned deferred_up_to = -1U;
    8426        41788 :   for (unsigned partition_i = 0; partition_i < m_partitions.length ();
    8427              :        ++partition_i)
    8428              :     {
    8429        34836 :       auto &partition = m_partitions[partition_i];
    8430        34836 :       if (single_layout_i == -1)
    8431              :         {
    8432        17423 :           single_layout_i = partition.layout;
    8433        17423 :           deferred_up_to = partition_i;
    8434              :         }
    8435        17413 :       else if (partition.layout == single_layout_i || partition.layout == -1)
    8436              :         ;
    8437              :       else
    8438              :         single_layout_i = 0;
    8439        31619 :       if (single_layout_i == 0)
    8440              :         return true;
    8441              : 
    8442        28417 :       if (single_layout_i != -1
    8443        28417 :           && !is_compatible_layout (partition, single_layout_i))
    8444              :         return true;
    8445              :     }
    8446              : 
    8447         6952 :   if (single_layout_i <= 0)
    8448              :     return true;
    8449              : 
    8450         7545 :   for (unsigned partition_i = 0; partition_i < deferred_up_to; ++partition_i)
    8451          610 :     if (!is_compatible_layout (m_partitions[partition_i],
    8452              :                                single_layout_i))
    8453              :       return true;
    8454              : 
    8455        21362 :   for (unsigned partition_i = 0; partition_i < m_partitions.length ();
    8456              :        ++partition_i)
    8457              :     {
    8458        14427 :       auto &partition = m_partitions[partition_i];
    8459        14427 :       partition.layout = single_layout_i;
    8460              :     }
    8461              : 
    8462              :   return false;
    8463              : }
    8464              : 
    8465              : /* Main entry point for the SLP graph optimization pass.  */
    8466              : 
    8467              : void
    8468       716297 : vect_optimize_slp_pass::run ()
    8469              : {
    8470       716297 :   build_graph ();
    8471       716297 :   create_partitions ();
    8472       716297 :   start_choosing_layouts ();
    8473       716297 :   if (m_perms.length () > 1)
    8474              :     {
    8475        13467 :       if (legitimize ())
    8476              :         {
    8477         6532 :           forward_pass ();
    8478         6532 :           backward_pass ();
    8479              :         }
    8480        13467 :       if (dump_enabled_p ())
    8481          687 :         dump ();
    8482        13467 :       materialize ();
    8483        54435 :       while (!m_perms.is_empty ())
    8484        27501 :         m_perms.pop ().release ();
    8485              :     }
    8486              :   else
    8487       702830 :     remove_redundant_permutations ();
    8488       716297 :   free_graph (m_slpg);
    8489       716297 :   build_graph ();
    8490       716297 :   decide_masked_load_lanes ();
    8491       716297 :   free_graph (m_slpg);
    8492       716297 : }
    8493              : 
    8494              : /* Apply CSE to NODE and its children using BST_MAP.  */
    8495              : 
    8496              : static void
    8497      5655294 : vect_cse_slp_nodes (scalar_stmts_to_slp_tree_map_t *bst_map, slp_tree& node)
    8498              : {
    8499      5655294 :   bool put_p = false;
    8500      5655294 :   if (SLP_TREE_DEF_TYPE (node) == vect_internal_def
    8501              :       /* Besides some VEC_PERM_EXPR, two-operator nodes also
    8502              :          lack scalar stmts and thus CSE doesn't work via bst_map.  Ideally
    8503              :          we'd have sth that works for all internal and external nodes.  */
    8504      5655294 :       && !SLP_TREE_SCALAR_STMTS (node).is_empty ())
    8505              :     {
    8506      4059163 :       slp_tree *leader = bst_map->get (SLP_TREE_SCALAR_STMTS (node));
    8507      4059163 :       if (leader)
    8508              :         {
    8509              :           /* We've visited this node already.  */
    8510       420201 :           if (!*leader || *leader == node)
    8511              :             return;
    8512              : 
    8513         4393 :           if (dump_enabled_p ())
    8514          915 :             dump_printf_loc (MSG_NOTE, vect_location,
    8515              :                              "re-using SLP tree %p for %p\n",
    8516              :                              (void *)*leader, (void *)node);
    8517         4393 :           vect_free_slp_tree (node);
    8518         4393 :           (*leader)->refcnt += 1;
    8519         4393 :           node = *leader;
    8520         4393 :           return;
    8521              :         }
    8522              : 
    8523              :       /* Avoid creating a cycle by populating the map only after recursion.  */
    8524      3638962 :       bst_map->put (SLP_TREE_SCALAR_STMTS (node).copy (), nullptr);
    8525      3638962 :       node->refcnt += 1;
    8526      3638962 :       put_p = true;
    8527              :       /* And recurse.  */
    8528              :     }
    8529              : 
    8530     15638027 :   for (slp_tree &child : SLP_TREE_CHILDREN (node))
    8531      4576878 :     if (child)
    8532      4119404 :       vect_cse_slp_nodes (bst_map, child);
    8533              : 
    8534              :   /* Now record the node for CSE in other siblings.  */
    8535      5235093 :   if (put_p)
    8536      3638962 :     *bst_map->get (SLP_TREE_SCALAR_STMTS (node)) = node;
    8537              : }
    8538              : 
    8539              : /* Associate stmts with possible starts of a subset of lanes of NODE
    8540              :    in PART_STARTS.  */
    8541              : 
    8542              : static void
    8543      2149344 : vect_cse_gather_part_starts (hash_set<slp_tree> &visited,
    8544              :                              vec<vec<slp_tree>> part_starts, slp_tree node)
    8545              : {
    8546              :   /* CSEing external nodes complicates scheduling since we materialize
    8547              :      those at the latest position, so avoid that.  */
    8548      2149344 :   if (SLP_TREE_DEF_TYPE (node) != vect_internal_def
    8549      2149344 :       || visited.add (node))
    8550              :     return;
    8551              : 
    8552              :   /* Besides some VEC_PERM_EXPR, two-operator nodes also lack scalar stmts
    8553              :      and thus CSE doesn't work.  For now gather two-lane aligned starts
    8554              :      of nodes with a multiple of two number of lanes.  */
    8555      1153727 :   if (!SLP_TREE_SCALAR_STMTS (node).is_empty ()
    8556      1146183 :       && SLP_TREE_LANES (node) > 2
    8557       149849 :       && (SLP_TREE_LANES (node) & 1) == 0)
    8558              :     {
    8559       149849 :       auto_vec<unsigned, 8> uids;
    8560       623601 :       for (unsigned i = 0; i < SLP_TREE_LANES (node); i += 2)
    8561              :         {
    8562       473752 :           stmt_vec_info s = SLP_TREE_SCALAR_STMTS (node)[i];
    8563       473752 :           if (!s)
    8564            0 :             continue;
    8565       473752 :           unsigned uid = gimple_uid (s->stmt);
    8566       473752 :           if (!uids.contains (uid))
    8567              :             {
    8568       469757 :               uids.safe_push (uid);
    8569       469757 :               part_starts[uid].safe_push (node);
    8570              :             }
    8571              :         }
    8572       149849 :     }
    8573              : 
    8574      4492864 :   for (slp_tree &child : SLP_TREE_CHILDREN (node))
    8575      1318755 :     if (child)
    8576      1318755 :       vect_cse_gather_part_starts (visited, part_starts, child);
    8577              : }
    8578              : 
    8579              : /* Apply CSE to NODE and its children using lowparts of nodes in BST_MAP.  */
    8580              : 
    8581              : static void
    8582      2145669 : vect_cse_slp_node_parts (hash_set<slp_tree> &visited,
    8583              :                          const vec<vec<slp_tree>> part_starts,
    8584              :                          vec<slp_tree> &drops, slp_tree node)
    8585              : {
    8586      2145669 :   if (SLP_TREE_DEF_TYPE (node) != vect_internal_def
    8587      2145669 :       || visited.add (node))
    8588              :     return;
    8589              : 
    8590              :   /* Besides some VEC_PERM_EXPR, two-operator nodes also
    8591              :      lack scalar stmts and thus CSE doesn't work.  */
    8592      1152039 :   unsigned HOST_WIDE_INT c;
    8593      1152039 :   if (!SLP_TREE_SCALAR_STMTS (node).is_empty ()
    8594      1144499 :       && SLP_TREE_SCALAR_STMTS (node)[0]
    8595              :       /* Avoid touching loads which need care with load permutations
    8596              :          and specialities like load-lane representations.  */
    8597      1144499 :       && (SLP_TREE_PERMUTE_P (node)
    8598      1137055 :           || !STMT_VINFO_DATA_REF (SLP_TREE_REPRESENTATIVE (node))))
    8599        36206 :     for (slp_tree cand
    8600       427801 :          : part_starts[gimple_uid (SLP_TREE_SCALAR_STMTS (node)[0]->stmt)])
    8601              :       /* ???  There is a possible ordering/optimality problem in that
    8602              :          the CSE then can keep a wider feeding live even though it itself
    8603              :          becomes dead by means of CSE.  Which might be solvable by doing
    8604              :          the CSE in a wide-to-narrow order.  */
    8605        36673 :       if (SLP_TREE_LANES (cand) > SLP_TREE_LANES (node)
    8606              :           /* We can do high/lo extracts and full vector copies.  */
    8607              :           && constant_multiple_p
    8608         4458 :                (TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (cand)),
    8609        37163 :                 TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (node)), &c)
    8610        41131 :           && c <= 2)
    8611              :         {
    8612         3968 :           unsigned HOST_WIDE_INT s;
    8613         3968 :           bool const_p
    8614         3968 :             = TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (node)).is_constant (&s);
    8615         3968 :           unsigned i;
    8616        14230 :           for (i = 0; i <= SLP_TREE_LANES (cand) - SLP_TREE_LANES (node);)
    8617              :             {
    8618              :               unsigned j;
    8619        15195 :               for (j = 0; j < SLP_TREE_LANES (node); ++j)
    8620        14728 :                 if (!SLP_TREE_SCALAR_STMTS (node)[j]
    8621        14728 :                     || (SLP_TREE_SCALAR_STMTS (cand)[i+j]
    8622        14728 :                         != SLP_TREE_SCALAR_STMTS (node)[j]))
    8623              :                   break;
    8624        10729 :               if (j == SLP_TREE_LANES (node))
    8625              :                 break;
    8626        10262 :               if (!const_p)
    8627              :                 {
    8628              :                   i = SLP_TREE_LANES (cand);
    8629              :                   break;
    8630              :                 }
    8631              :               /* We can extract only aligned on node vector type boundary.  */
    8632        10262 :               i += s;
    8633              :             }
    8634         3968 :           if (i > SLP_TREE_LANES (cand) - SLP_TREE_LANES (node))
    8635         3501 :             continue;
    8636              :           /* Found node within cand at i.  Put a permute in place
    8637              :              of it, selecting the subset from cand.  */
    8638          467 :           if (dump_enabled_p ())
    8639           43 :             dump_printf (MSG_NOTE, "CSEd node %p as %spart of node %p\n",
    8640              :                          (void *)node, i == 0 ? "low" : "high", (void *)cand);
    8641         2298 :           for (slp_tree child : SLP_TREE_CHILDREN (node))
    8642              :             /* Delay SLP tree release since we might still reference a node
    8643              :                from the part_starts map.  */
    8644          897 :             drops.safe_push (child);
    8645          467 :           SLP_TREE_CHILDREN (node).truncate (1);
    8646          467 :           SLP_TREE_REF_COUNT (cand)++;
    8647          467 :           SLP_TREE_CHILDREN (node)[0] = cand;
    8648          467 :           SLP_TREE_CODE (node) = VEC_PERM_EXPR;
    8649          467 :           SLP_TREE_REPRESENTATIVE (node) = NULL;
    8650          467 :           SLP_TREE_LANE_PERMUTATION (node).create (SLP_TREE_LANES (node));
    8651         2000 :           for (unsigned j = i; j < i + SLP_TREE_LANES (node); ++j)
    8652         1066 :             SLP_TREE_LANE_PERMUTATION (node).quick_push (std::make_pair (0, j));
    8653      2145669 :           return;
    8654              :         }
    8655              : 
    8656      4483290 :   for (slp_tree &child : SLP_TREE_CHILDREN (node))
    8657      1315080 :     if (child)
    8658      1315080 :       vect_cse_slp_node_parts (visited, part_starts, drops, child);
    8659              : }
    8660              : 
    8661              : /* Optimize the SLP graph of VINFO.  */
    8662              : 
    8663              : void
    8664      1096083 : vect_optimize_slp (vec_info *vinfo)
    8665              : {
    8666      1096083 :   if (vinfo->slp_instances.is_empty ())
    8667       814688 :     return;
    8668       716297 :   vect_optimize_slp_pass (vinfo).run ();
    8669              : 
    8670              :   /* Apply CSE again to nodes after permute optimization.  */
    8671       716297 :   scalar_stmts_to_slp_tree_map_t *bst_map
    8672       716297 :     = new scalar_stmts_to_slp_tree_map_t ();
    8673              : 
    8674      3684781 :   for (auto inst : vinfo->slp_instances)
    8675      1535890 :     vect_cse_slp_nodes (bst_map, SLP_INSTANCE_TREE (inst));
    8676              : 
    8677       716297 :   release_scalar_stmts_to_slp_tree_map (bst_map);
    8678              : 
    8679       716297 :   if (!is_a <bb_vec_info> (vinfo))
    8680              :     return;
    8681              : 
    8682              :   /* Attempt to merge SLP sub-graphs that intersect in low or highparts of
    8683              :      each other.  Build the reverse mapping from stmt to SLP node for
    8684              :      lanes starting at the low or high part.
    8685              :      ???  In the future we can extend this to do a two-step permute
    8686              :      and extract or extract and permute to put the high/low part in
    8687              :      place on the original vector or permute the hogh/low part to
    8688              :      match up the target lane order.  */
    8689       281395 :   hash_set<slp_tree> visited;
    8690       281395 :   vec<vec<slp_tree>> start_for_part;
    8691       562790 :   start_for_part.create (vinfo->stmt_vec_infos.length () + 1);
    8692       562790 :   start_for_part.quick_grow_cleared (vinfo->stmt_vec_infos.length () + 1);
    8693      1674774 :   for (auto inst : vinfo->slp_instances)
    8694       830589 :     vect_cse_gather_part_starts (visited,
    8695              :                                  start_for_part, SLP_INSTANCE_TREE (inst));
    8696              : 
    8697              :   /* Now replace low/highpart copies with extracting permutes.  */
    8698       281395 :   auto_vec<slp_tree> drops;
    8699       281395 :   visited.empty ();
    8700      1674774 :   for (auto inst : vinfo->slp_instances)
    8701       830589 :     vect_cse_slp_node_parts (visited, start_for_part, drops,
    8702              :                              SLP_INSTANCE_TREE (inst));
    8703              : 
    8704              :   /* Now perform delayed releases of nodes.  */
    8705       282786 :   for (slp_tree node : drops)
    8706          897 :     vect_free_slp_tree (node);
    8707              : 
    8708     24176618 :   for (auto v : start_for_part)
    8709     23332433 :     v.release ();
    8710       281395 :   start_for_part.release ();
    8711       281395 : }
    8712              : 
    8713              : /* Gather loads reachable from the individual SLP graph entries.  */
    8714              : 
    8715              : void
    8716      1096083 : vect_gather_slp_loads (vec_info *vinfo)
    8717              : {
    8718      1096083 :   unsigned i;
    8719      1096083 :   slp_instance instance;
    8720      2631973 :   FOR_EACH_VEC_ELT (vinfo->slp_instances, i, instance)
    8721              :     {
    8722      1535890 :       hash_set<slp_tree> visited;
    8723      1535890 :       vect_gather_slp_loads (SLP_INSTANCE_LOADS (instance),
    8724              :                              SLP_INSTANCE_TREE (instance), visited);
    8725      1535890 :     }
    8726      1096083 : }
    8727              : 
    8728              : /* For NODE update VF based on the number of lanes and the vector types
    8729              :    used.  */
    8730              : 
    8731              : static void
    8732      4488549 : vect_update_slp_vf_for_node (slp_tree node, poly_uint64 &vf,
    8733              :                              hash_set<slp_tree> &visited)
    8734              : {
    8735      4488549 :   if (!node || SLP_TREE_DEF_TYPE (node) != vect_internal_def)
    8736      1622728 :     return;
    8737      3240288 :   if (visited.add (node))
    8738              :     return;
    8739              : 
    8740     10901580 :   for (slp_tree child : SLP_TREE_CHILDREN (node))
    8741      3689985 :     vect_update_slp_vf_for_node (child, vf, visited);
    8742              : 
    8743              :   /* We do not visit SLP nodes for constants or externals - those neither
    8744              :      have a vector type set yet (vectorizable_* does this).
    8745              :      Note that when we stop using fixed size vectors externs and constants
    8746              :      shouldn't influence the (minimum) vectorization factor, instead
    8747              :      vectorizable_* should honor the vectorization factor when trying to
    8748              :      assign vector types to constants and externals and cause iteration
    8749              :      to a higher vectorization factor when required.  */
    8750      2865841 :   tree vectype = SLP_TREE_VECTYPE (node);
    8751      2865841 :   if (!vectype)
    8752              :     /* OMP SIMD calls w/o LHS have no SLP_TREE_VECTYPE set.  */
    8753              :     return;
    8754      2865821 :   poly_uint64 node_vf
    8755      2865821 :     = calculate_unrolling_factor (TYPE_VECTOR_SUBPARTS (vectype),
    8756              :                                   SLP_TREE_LANES (node));
    8757      2865821 :   vf = force_common_multiple (vf, node_vf);
    8758              : 
    8759              :   /* For permute nodes that are fed from externs or constants we have to
    8760              :      consider their number of lanes as well.  Likewise for store-lanes.  */
    8761      2865821 :   if (SLP_TREE_PERMUTE_P (node) || node->ldst_lanes)
    8762       718313 :     for (slp_tree child : SLP_TREE_CHILDREN (node))
    8763       193622 :       if (SLP_TREE_DEF_TYPE (child) != vect_internal_def)
    8764              :         {
    8765         3690 :           poly_uint64 child_vf
    8766         3690 :             = calculate_unrolling_factor (TYPE_VECTOR_SUBPARTS (vectype),
    8767              :                                           SLP_TREE_LANES (child));
    8768         3690 :           vf = force_common_multiple (vf, child_vf);
    8769              :         }
    8770              : }
    8771              : 
    8772              : /* For each possible SLP instance decide whether to SLP it and calculate overall
    8773              :    unrolling factor needed to SLP the loop.  Return TRUE if decided to SLP at
    8774              :    least one instance.  */
    8775              : 
    8776              : bool
    8777       501509 : vect_make_slp_decision (loop_vec_info loop_vinfo)
    8778              : {
    8779       501509 :   unsigned int i;
    8780       501509 :   poly_uint64 unrolling_factor = 1;
    8781       501509 :   const vec<slp_instance> &slp_instances
    8782              :     = LOOP_VINFO_SLP_INSTANCES (loop_vinfo);
    8783       501509 :   slp_instance instance;
    8784       501509 :   int decided_to_slp = 0;
    8785              : 
    8786       501509 :   DUMP_VECT_SCOPE ("vect_make_slp_decision");
    8787              : 
    8788       501509 :   hash_set<slp_tree> visited;
    8789      1801582 :   FOR_EACH_VEC_ELT (slp_instances, i, instance)
    8790              :     {
    8791       798564 :       slp_tree root = SLP_INSTANCE_TREE (instance);
    8792              : 
    8793              :       /* All unroll factors have the form:
    8794              : 
    8795              :            GET_MODE_SIZE (vinfo->vector_mode) * X
    8796              : 
    8797              :          for some rational X, so they must have a common multiple.  */
    8798       798564 :       vect_update_slp_vf_for_node (root, unrolling_factor, visited);
    8799              : 
    8800              :       /* If all instances ended up with vector(1) T roots make sure to
    8801              :          not vectorize.  RVV for example relies on loop vectorization
    8802              :          when some instances are essentially kept scalar.  See PR121048.  */
    8803       798564 :       if (SLP_TREE_VECTYPE (root)
    8804       798564 :           && known_gt (TYPE_VECTOR_SUBPARTS (SLP_TREE_VECTYPE (root)), 1U))
    8805       648657 :         decided_to_slp++;
    8806              :     }
    8807              : 
    8808       501509 :   LOOP_VINFO_VECT_FACTOR (loop_vinfo) = unrolling_factor;
    8809              : 
    8810       501509 :   if (decided_to_slp && dump_enabled_p ())
    8811              :     {
    8812        19664 :       dump_printf_loc (MSG_NOTE, vect_location,
    8813              :                        "Decided to SLP %d instances. Unrolling factor ",
    8814              :                        decided_to_slp);
    8815        19664 :       dump_dec (MSG_NOTE, unrolling_factor);
    8816        19664 :       dump_printf (MSG_NOTE, "\n");
    8817              :     }
    8818              : 
    8819       501509 :   return (decided_to_slp > 0);
    8820       501509 : }
    8821              : 
    8822              : /* Initialize a bb_vec_info struct for the statements in BBS basic blocks.  */
    8823              : 
    8824      2285514 : _bb_vec_info::_bb_vec_info (vec<basic_block> _bbs, vec_info_shared *shared)
    8825              :   : vec_info (vec_info::bb, shared),
    8826      2285514 :     roots (vNULL)
    8827              : {
    8828              :   /* The region we are operating on.  bbs[0] is the entry, excluding
    8829              :      its PHI nodes.  In the future we might want to track an explicit
    8830              :      entry edge to cover bbs[0] PHI nodes and have a region entry
    8831              :      insert location.  */
    8832      2285514 :   bbs = _bbs.address ();
    8833      2285514 :   nbbs = _bbs.length ();
    8834              : 
    8835     18297430 :   for (unsigned i = 0; i < nbbs; ++i)
    8836              :     {
    8837     16011916 :       if (i != 0)
    8838     20816991 :         for (gphi_iterator si = gsi_start_phis (bbs[i]); !gsi_end_p (si);
    8839      7090589 :              gsi_next (&si))
    8840              :           {
    8841      7090589 :             gphi *phi = si.phi ();
    8842      7090589 :             gimple_set_uid (phi, 0);
    8843      7090589 :             add_stmt (phi);
    8844              :           }
    8845     32023832 :       for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
    8846    147758515 :            !gsi_end_p (gsi); gsi_next (&gsi))
    8847              :         {
    8848    131746599 :           gimple *stmt = gsi_stmt (gsi);
    8849    131746599 :           gimple_set_uid (stmt, 0);
    8850    131746599 :           if (is_gimple_debug (stmt) || is_a <glabel *> (stmt))
    8851     85429894 :             continue;
    8852     46316705 :           add_stmt (stmt);
    8853              :         }
    8854              :     }
    8855      2285514 : }
    8856              : 
    8857              : 
    8858              : /* Free BB_VINFO struct, as well as all the stmt_vec_info structs of all the
    8859              :    stmts in the basic block.  */
    8860              : 
    8861      2285514 : _bb_vec_info::~_bb_vec_info ()
    8862              : {
    8863              :   /* Reset region marker.  */
    8864     18297430 :   for (unsigned i = 0; i < nbbs; ++i)
    8865              :     {
    8866     16011916 :       if (i != 0)
    8867     20833772 :         for (gphi_iterator si = gsi_start_phis (bbs[i]); !gsi_end_p (si);
    8868      7107370 :              gsi_next (&si))
    8869              :           {
    8870      7107370 :             gphi *phi = si.phi ();
    8871      7107370 :             gimple_set_uid (phi, -1);
    8872              :           }
    8873     32023832 :       for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
    8874    147752280 :            !gsi_end_p (gsi); gsi_next (&gsi))
    8875              :         {
    8876    131740364 :           gimple *stmt = gsi_stmt (gsi);
    8877    131740364 :           gimple_set_uid (stmt, -1);
    8878              :         }
    8879              :     }
    8880              : 
    8881      3598527 :   for (unsigned i = 0; i < roots.length (); ++i)
    8882              :     {
    8883      1313013 :       roots[i].stmts.release ();
    8884      1313013 :       roots[i].roots.release ();
    8885      1313013 :       roots[i].remain.release ();
    8886              :     }
    8887      2285514 :   roots.release ();
    8888      2285514 : }
    8889              : 
    8890              : /* Subroutine of vect_slp_analyze_node_operations.  Handle the root of NODE,
    8891              :    given then that child nodes have already been processed, and that
    8892              :    their def types currently match their SLP node's def type.  */
    8893              : 
    8894              : static bool
    8895      2722803 : vect_slp_analyze_node_operations_1 (vec_info *vinfo, slp_tree node,
    8896              :                                     slp_instance node_instance,
    8897              :                                     stmt_vector_for_cost *cost_vec)
    8898              : {
    8899              :   /* Handle purely internal nodes.  */
    8900      2722803 :   if (SLP_TREE_PERMUTE_P (node))
    8901              :     {
    8902        82995 :       gcc_checking_assert (!SLP_TREE_REPRESENTATIVE (node));
    8903        82995 :       if (!vectorizable_slp_permutation (vinfo, NULL, node, cost_vec))
    8904              :         return false;
    8905              : 
    8906              :       stmt_vec_info slp_stmt_info;
    8907              :       unsigned int i;
    8908       204446 :       FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, slp_stmt_info)
    8909              :         {
    8910       122982 :           if (slp_stmt_info
    8911       117283 :               && STMT_VINFO_LIVE_P (slp_stmt_info)
    8912       122982 :               && !vectorizable_live_operation (vinfo, slp_stmt_info, node,
    8913              :                                                node_instance, i,
    8914              :                                                false, cost_vec))
    8915              :             return false;
    8916              :         }
    8917        81464 :       SLP_TREE_TYPE (node) = permute_info_type;
    8918        81464 :       return true;
    8919              :     }
    8920              : 
    8921      2639808 :   return vect_analyze_stmt (vinfo, node, node_instance, cost_vec);
    8922              : }
    8923              : 
    8924              : static int
    8925      1918494 : sort_ints (const void *a_, const void *b_)
    8926              : {
    8927      1918494 :   int a = *(const int *)a_;
    8928      1918494 :   int b = *(const int *)b_;
    8929      1918494 :   return a - b;
    8930              : }
    8931              : 
    8932              : /* Verify if we can externalize a set of internal defs.  */
    8933              : 
    8934              : static bool
    8935       409771 : vect_slp_can_convert_to_external (const vec<stmt_vec_info> &stmts)
    8936              : {
    8937              :   /* Constant generation uses get_later_stmt which can only handle
    8938              :      defs from the same BB or a set of defs that can be ordered
    8939              :      with a dominance query.  */
    8940       409771 :   basic_block bb = NULL;
    8941       409771 :   bool all_same = true;
    8942       409771 :   auto_vec<int> bbs;
    8943       819542 :   bbs.reserve_exact (stmts.length ());
    8944      2192569 :   for (stmt_vec_info stmt : stmts)
    8945              :     {
    8946       963256 :       if (!stmt)
    8947              :         return false;
    8948       963256 :       else if (!bb)
    8949       409771 :         bb = gimple_bb (stmt->stmt);
    8950       553485 :       else if (gimple_bb (stmt->stmt) != bb)
    8951       187040 :         all_same = false;
    8952       963256 :       bbs.quick_push (gimple_bb (stmt->stmt)->index);
    8953              :     }
    8954       409771 :   if (all_same)
    8955              :     return true;
    8956              : 
    8957              :   /* Produce a vector of unique BB indexes for the defs.  */
    8958       140897 :   bbs.qsort (sort_ints);
    8959       140897 :   unsigned i, j;
    8960       339412 :   for (i = 1, j = 1; i < bbs.length (); ++i)
    8961       198515 :     if (bbs[i] != bbs[j-1])
    8962       150326 :       bbs[j++] = bbs[i];
    8963       140897 :   gcc_assert (j >= 2);
    8964       140897 :   bbs.truncate (j);
    8965              : 
    8966       281794 :   if (bbs.length () == 2)
    8967       137494 :     return (dominated_by_p (CDI_DOMINATORS,
    8968       137494 :                             BASIC_BLOCK_FOR_FN (cfun, bbs[0]),
    8969       137494 :                             BASIC_BLOCK_FOR_FN (cfun, bbs[1]))
    8970       268632 :             || dominated_by_p (CDI_DOMINATORS,
    8971       131138 :                                BASIC_BLOCK_FOR_FN (cfun, bbs[1]),
    8972       131138 :                                BASIC_BLOCK_FOR_FN (cfun, bbs[0])));
    8973              : 
    8974              :   /* ???  For more than two BBs we can sort the vector and verify the
    8975              :      result is a total order.  But we can't use vec::qsort with a
    8976              :      compare function using a dominance query since there's no way to
    8977              :      signal failure and any fallback for an unordered pair would
    8978              :      fail qsort_chk later.
    8979              :      For now simply hope that ordering after BB index provides the
    8980              :      best candidate total order.  If required we can implement our
    8981              :      own mergesort or export an entry without checking.  */
    8982       425948 :   for (unsigned i = 1; i < bbs.length (); ++i)
    8983        12808 :     if (!dominated_by_p (CDI_DOMINATORS,
    8984        12808 :                          BASIC_BLOCK_FOR_FN (cfun, bbs[i]),
    8985        12808 :                          BASIC_BLOCK_FOR_FN (cfun, bbs[i-1])))
    8986              :       return false;
    8987              : 
    8988              :   return true;
    8989       409771 : }
    8990              : 
    8991              : /* Try to build NODE from scalars, returning true on success.
    8992              :    NODE_INSTANCE is the SLP instance that contains NODE.  */
    8993              : 
    8994              : static bool
    8995       640205 : vect_slp_convert_to_external (vec_info *vinfo, slp_tree node,
    8996              :                               slp_instance node_instance)
    8997              : {
    8998       640205 :   stmt_vec_info stmt_info;
    8999       640205 :   unsigned int i;
    9000              : 
    9001       640205 :   if (!is_a <bb_vec_info> (vinfo)
    9002        89645 :       || node == SLP_INSTANCE_TREE (node_instance)
    9003        29819 :       || !SLP_TREE_SCALAR_STMTS (node).exists ()
    9004        29778 :       || vect_contains_pattern_stmt_p (SLP_TREE_SCALAR_STMTS (node))
    9005              :       /* Force the mask use to be built from scalars instead.  */
    9006        22345 :       || VECTOR_BOOLEAN_TYPE_P (SLP_TREE_VECTYPE (node))
    9007       662287 :       || !vect_slp_can_convert_to_external (SLP_TREE_SCALAR_STMTS (node)))
    9008              :     return false;
    9009              : 
    9010        22082 :   if (dump_enabled_p ())
    9011           82 :     dump_printf_loc (MSG_NOTE, vect_location,
    9012              :                      "Building vector operands of %p from scalars instead\n",
    9013              :                      (void *) node);
    9014              : 
    9015              :   /* Don't remove and free the child nodes here, since they could be
    9016              :      referenced by other structures.  The analysis and scheduling phases
    9017              :      (need to) ignore child nodes of anything that isn't vect_internal_def.  */
    9018        22082 :   unsigned int group_size = SLP_TREE_LANES (node);
    9019        22082 :   SLP_TREE_DEF_TYPE (node) = vect_external_def;
    9020              :   /* Invariants get their vector type from the uses.  */
    9021        22082 :   SLP_TREE_VECTYPE (node) = NULL_TREE;
    9022        22082 :   SLP_TREE_SCALAR_OPS (node).safe_grow (group_size, true);
    9023        22082 :   SLP_TREE_LOAD_PERMUTATION (node).release ();
    9024        99048 :   FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
    9025              :     {
    9026        54884 :       tree lhs = gimple_get_lhs (vect_orig_stmt (stmt_info)->stmt);
    9027        54884 :       SLP_TREE_SCALAR_OPS (node)[i] = lhs;
    9028              :     }
    9029              :   return true;
    9030              : }
    9031              : 
    9032              : /* Return true if all elements of the slice are the same.  */
    9033              : bool
    9034       449055 : vect_scalar_ops_slice::all_same_p () const
    9035              : {
    9036       500805 :   for (unsigned int i = 1; i < length; ++i)
    9037       413700 :     if (!operand_equal_p (op (0), op (i)))
    9038              :       return false;
    9039              :   return true;
    9040              : }
    9041              : 
    9042              : hashval_t
    9043       424573 : vect_scalar_ops_slice_hash::hash (const value_type &s)
    9044              : {
    9045       424573 :   hashval_t hash = 0;
    9046      1625201 :   for (unsigned i = 0; i < s.length; ++i)
    9047      1200628 :     hash = iterative_hash_expr (s.op (i), hash);
    9048       424573 :   return hash;
    9049              : }
    9050              : 
    9051              : bool
    9052       233034 : vect_scalar_ops_slice_hash::equal (const value_type &s1,
    9053              :                                    const compare_type &s2)
    9054              : {
    9055       233034 :   if (s1.length != s2.length)
    9056              :     return false;
    9057       401321 :   for (unsigned i = 0; i < s1.length; ++i)
    9058       350167 :     if (!operand_equal_p (s1.op (i), s2.op (i)))
    9059              :       return false;
    9060              :   return true;
    9061              : }
    9062              : 
    9063              : /* Like vect_get_num_copies but N copies of the vector might have
    9064              :    excess elements in the last vector.  Stores the number of excess
    9065              :    elements in the last vector in *EXCESS_ELTS.
    9066              :    Returns false if *NVECTORS or *EXCESS_ELTS cannot be computed.  */
    9067              : 
    9068              : bool
    9069      1597250 : vect_get_num_copies_for_invariant (vec_info *vinfo, slp_tree node,
    9070              :                                    unsigned *nvectors,
    9071              :                                    unsigned *excess_elts)
    9072              : {
    9073      1597250 :   poly_uint64 vf;
    9074              : 
    9075      1597250 :   if (loop_vec_info loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
    9076       374260 :     vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
    9077              :   else
    9078      1222990 :     vf = 1;
    9079      1597250 :   vf *= SLP_TREE_LANES (node);
    9080              : 
    9081      1597250 :   tree vectype = SLP_TREE_VECTYPE (node);
    9082      1597250 :   uint64_t rem;
    9083      1597250 :   if (can_div_away_from_zero_p (vf, TYPE_VECTOR_SUBPARTS (vectype),
    9084              :                                 nvectors)
    9085      1597250 :       && (TYPE_VECTOR_SUBPARTS (vectype) * *nvectors - vf) .is_constant (&rem))
    9086              :     {
    9087      1597250 :       *excess_elts = rem;
    9088      1597250 :       return true;
    9089              :     }
    9090              :   return false;
    9091              : }
    9092              : 
    9093              : /* Compute the prologue cost for invariant or constant operands represented
    9094              :    by NODE.  */
    9095              : 
    9096              : static void
    9097      1094129 : vect_prologue_cost_for_slp (slp_tree node, unsigned nvectors,
    9098              :                             stmt_vector_for_cost *cost_vec)
    9099              : {
    9100              :   /* There's a special case of an existing vector, that costs nothing.  */
    9101      1094129 :   if (SLP_TREE_SCALAR_OPS (node).length () == 0
    9102      1094129 :       && !SLP_TREE_VEC_DEFS (node).is_empty ())
    9103         2146 :     return;
    9104              :   /* Without looking at the actual initializer a vector of
    9105              :      constants can be implemented as load from the constant pool.
    9106              :      When all elements are the same we can use a splat.  */
    9107      1091983 :   tree vectype = SLP_TREE_VECTYPE (node);
    9108      1091983 :   unsigned group_size = SLP_TREE_LANES (node);
    9109      1091983 :   unsigned HOST_WIDE_INT const_nunits;
    9110      1091983 :   unsigned nelt_limit;
    9111      1091983 :   auto ops = &SLP_TREE_SCALAR_OPS (node);
    9112      1091983 :   auto_vec<unsigned int> starts (nvectors);
    9113      1091983 :   if (TYPE_VECTOR_SUBPARTS (vectype).is_constant (&const_nunits)
    9114      1091983 :       && ! multiple_p (const_nunits, group_size))
    9115              :     {
    9116        67227 :       nelt_limit = const_nunits;
    9117        67227 :       hash_set<vect_scalar_ops_slice_hash> vector_ops;
    9118       345287 :       for (unsigned int i = 0; i < nvectors; ++i)
    9119       210833 :         if (!vector_ops.add ({ ops, i * nelt_limit, nelt_limit }))
    9120       159679 :           starts.quick_push (i * nelt_limit);
    9121        67227 :     }
    9122              :   else
    9123              :     {
    9124              :       /* If either the vector has variable length or the vectors
    9125              :          are composed of repeated whole groups we only need to
    9126              :          cost construction once.  All vectors will be the same.  */
    9127      1024756 :       nelt_limit = group_size;
    9128      1024756 :       starts.quick_push (0);
    9129              :     }
    9130              :   /* ???  We're just tracking whether vectors in a single node are the same.
    9131              :      Ideally we'd do something more global.  */
    9132      4460384 :   for (unsigned int start : starts)
    9133              :     {
    9134      1184435 :       vect_cost_for_stmt kind;
    9135      1184435 :       if (SLP_TREE_DEF_TYPE (node) == vect_constant_def)
    9136              :         kind = vector_load;
    9137       449055 :       else if (vect_scalar_ops_slice { ops, start, nelt_limit }.all_same_p ())
    9138              :         kind = scalar_to_vec;
    9139              :       else
    9140       361950 :         kind = vec_construct;
    9141      1184435 :       record_stmt_cost (cost_vec, 1, kind, nullptr, node,
    9142              :                         vectype, 0, vect_prologue);
    9143              :     }
    9144      1091983 : }
    9145              : 
    9146              : /* Analyze statements contained in SLP tree NODE after recursively analyzing
    9147              :    the subtree.  NODE_INSTANCE contains NODE and VINFO contains INSTANCE.
    9148              : 
    9149              :    Return true if the operations are supported.  */
    9150              : 
    9151              : static bool
    9152      5053948 : vect_slp_analyze_node_operations (vec_info *vinfo, slp_tree node,
    9153              :                                   slp_instance node_instance,
    9154              :                                   hash_set<slp_tree> &visited_set,
    9155              :                                   vec<slp_tree> &visited_vec,
    9156              :                                   stmt_vector_for_cost *cost_vec)
    9157              : {
    9158      5053948 :   int i, j;
    9159      5053948 :   slp_tree child;
    9160              : 
    9161              :   /* Costing and analysis of invariants is delayed.  */
    9162      5053948 :   if (!node
    9163      4660003 :       || SLP_TREE_DEF_TYPE (node) == vect_constant_def
    9164      3868456 :       || SLP_TREE_DEF_TYPE (node) == vect_external_def)
    9165              :     return true;
    9166              : 
    9167      3383763 :   if (SLP_TREE_DEF_TYPE (node) == vect_uninitialized_def)
    9168              :     {
    9169            5 :       if (dump_enabled_p ())
    9170            0 :         dump_printf_loc (MSG_NOTE, vect_location,
    9171              :                          "Failed cyclic SLP reference in %p\n", (void *) node);
    9172              :       return false;
    9173              :     }
    9174      3383758 :   gcc_assert (SLP_TREE_DEF_TYPE (node) == vect_internal_def);
    9175              : 
    9176              :   /* If we already analyzed the exact same set of scalar stmts we're done.
    9177              :      We share the generated vector stmts for those.  */
    9178      3383758 :   if (visited_set.add (node))
    9179              :     return true;
    9180      3084518 :   visited_vec.safe_push (node);
    9181              : 
    9182      3084518 :   bool res = true;
    9183      3084518 :   unsigned visited_rec_start = visited_vec.length ();
    9184      3084518 :   unsigned cost_vec_rec_start = cost_vec->length ();
    9185      3084518 :   bool seen_non_constant_child = false;
    9186      8928629 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
    9187              :     {
    9188      3685583 :       res = vect_slp_analyze_node_operations (vinfo, child, node_instance,
    9189              :                                               visited_set, visited_vec,
    9190              :                                               cost_vec);
    9191      3685583 :       if (!res)
    9192              :         break;
    9193      3324082 :       if (child && SLP_TREE_DEF_TYPE (child) != vect_constant_def)
    9194      3324082 :         seen_non_constant_child = true;
    9195              :     }
    9196              :   /* We're having difficulties scheduling nodes with just constant
    9197              :      operands and no scalar stmts since we then cannot compute a stmt
    9198              :      insertion place.  */
    9199      3084518 :   if (res
    9200      3084518 :       && !seen_non_constant_child
    9201      3084518 :       && SLP_TREE_SCALAR_STMTS (node).is_empty ())
    9202              :     {
    9203          214 :       if (dump_enabled_p ())
    9204            6 :         dump_printf_loc (MSG_NOTE, vect_location,
    9205              :                          "Cannot vectorize all-constant op node %p\n",
    9206              :                          (void *) node);
    9207              :       res = false;
    9208              :     }
    9209              : 
    9210      3084310 :   if (res)
    9211      2722803 :     res = vect_slp_analyze_node_operations_1 (vinfo, node, node_instance,
    9212              :                                               cost_vec);
    9213              :   /* If analysis failed we have to pop all recursive visited nodes
    9214              :      plus ourselves.  */
    9215      3084518 :   if (!res)
    9216              :     {
    9217      3158768 :       while (visited_vec.length () >= visited_rec_start)
    9218       939179 :         visited_set.remove (visited_vec.pop ());
    9219       640205 :       cost_vec->truncate (cost_vec_rec_start);
    9220              :     }
    9221              : 
    9222              :   /* When the node can be vectorized cost invariant nodes it references.
    9223              :      This is not done in DFS order to allow the referring node
    9224              :      vectorizable_* calls to nail down the invariant nodes vector type
    9225              :      and possibly unshare it if it needs a different vector type than
    9226              :      other referrers.  */
    9227      3084518 :   if (res)
    9228      9392736 :     FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), j, child)
    9229      2969583 :       if (child
    9230      2648655 :           && (SLP_TREE_DEF_TYPE (child) == vect_constant_def
    9231      2648655 :               || SLP_TREE_DEF_TYPE (child) == vect_external_def)
    9232              :           /* Perform usual caching, note code-generation still
    9233              :              code-gens these nodes multiple times but we expect
    9234              :              to CSE them later.  */
    9235      4104399 :           && !visited_set.add (child))
    9236              :         {
    9237      1131599 :           visited_vec.safe_push (child);
    9238              :           /* ???  After auditing more code paths make a "default"
    9239              :              and push the vector type from NODE to all children
    9240              :              if it is not already set.  */
    9241              :           /* Compute the number of vectors to be generated.  */
    9242      1131599 :           tree vector_type = SLP_TREE_VECTYPE (child);
    9243      1131599 :           if (!vector_type)
    9244              :             {
    9245              :               /* Masked loads can have an undefined (default SSA definition)
    9246              :                  else operand.  We do not need to cost it.  */
    9247        37470 :               vec<tree> ops = SLP_TREE_SCALAR_OPS (child);
    9248        38901 :               if (SLP_TREE_TYPE (node) == load_vec_info_type
    9249        38901 :                   && ((ops.length ()
    9250         1431 :                        && TREE_CODE (ops[0]) == SSA_NAME
    9251            0 :                        && SSA_NAME_IS_DEFAULT_DEF (ops[0])
    9252            0 :                        && VAR_P (SSA_NAME_VAR (ops[0])))
    9253         1431 :                       || SLP_TREE_DEF_TYPE (child) == vect_constant_def))
    9254         1431 :                 continue;
    9255              : 
    9256              :               /* For shifts with a scalar argument we don't need
    9257              :                  to cost or code-generate anything.
    9258              :                  ???  Represent this more explicitly.  */
    9259        36039 :               gcc_assert (SLP_TREE_TYPE (node) == shift_vec_info_type
    9260              :                           && j == 1);
    9261        36039 :               continue;
    9262        36039 :             }
    9263              : 
    9264              :           /* Make sure we can generate them and then cost them.  */
    9265      1094129 :           unsigned nvectors, excess_elts;
    9266      1094129 :           if (!vect_get_num_copies_for_invariant (vinfo, child, &nvectors,
    9267              :                                                   &excess_elts))
    9268            0 :             return false;
    9269      1094129 :           vect_prologue_cost_for_slp (child, nvectors, cost_vec);
    9270              :         }
    9271              : 
    9272              :   /* If this node or any of its children can't be vectorized, try pruning
    9273              :      the tree here rather than felling the whole thing.  */
    9274       640205 :   if (!res && vect_slp_convert_to_external (vinfo, node, node_instance))
    9275              :     {
    9276              :       /* We'll need to revisit this for invariant costing and number
    9277              :          of vectorized stmt setting.   */
    9278              :       res = true;
    9279              :     }
    9280              : 
    9281              :   return res;
    9282              : }
    9283              : 
    9284              : /* Mark lanes of NODE that are live outside of the basic-block vectorized
    9285              :    region and that can be vectorized using vectorizable_live_operation
    9286              :    with STMT_VINFO_LIVE_P.  Not handled live operations will cause the
    9287              :    scalar code computing it to be retained.  */
    9288              : 
    9289              : static void
    9290       997441 : vect_bb_slp_mark_live_stmts (bb_vec_info bb_vinfo, slp_tree node,
    9291              :                              slp_instance instance,
    9292              :                              stmt_vector_for_cost *cost_vec,
    9293              :                              hash_set<stmt_vec_info> &svisited,
    9294              :                              hash_set<slp_tree> &visited)
    9295              : {
    9296       997441 :   if (visited.add (node))
    9297        58023 :     return;
    9298              : 
    9299              :   unsigned i;
    9300              :   stmt_vec_info stmt_info;
    9301              :   gimple *last_stmt = NULL;
    9302      3372726 :   FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (node), i, stmt_info)
    9303              :     {
    9304      2433308 :       if (!stmt_info || svisited.contains (stmt_info))
    9305        93611 :         continue;
    9306      2398534 :       stmt_vec_info orig_stmt_info = vect_orig_stmt (stmt_info);
    9307      2398534 :       if (STMT_VINFO_IN_PATTERN_P (orig_stmt_info)
    9308        35698 :           && STMT_VINFO_RELATED_STMT (orig_stmt_info) != stmt_info)
    9309              :         /* Only the pattern root stmt computes the original scalar value.  */
    9310        29737 :         continue;
    9311      2368797 :       if (!PURE_SLP_STMT (orig_stmt_info))
    9312              :         /* Iff the stmt is not part of the vector coverage because it or
    9313              :            uses of it are used by SLP graph leafs as extern input there is
    9314              :            no point in trying to live code-generate from a vector stmt as
    9315              :            the scalar stmt will survive anyway.  */
    9316        29100 :         continue;
    9317      2339697 :       bool mark_visited = true;
    9318      2339697 :       gimple *orig_stmt = orig_stmt_info->stmt;
    9319      2339697 :       ssa_op_iter op_iter;
    9320      2339697 :       def_operand_p def_p;
    9321      5245773 :       FOR_EACH_PHI_OR_STMT_DEF (def_p, orig_stmt, op_iter, SSA_OP_DEF)
    9322              :         {
    9323              :           /* We have to verify whether we can insert the lane extract
    9324              :              before all uses.  The following is a conservative approximation.
    9325              :              We cannot put this into vectorizable_live_operation because
    9326              :              iterating over all use stmts from inside a FOR_EACH_IMM_USE_STMT
    9327              :              doesn't work.
    9328              :              Note that while the fact that we emit code for loads at the
    9329              :              first load should make this a non-problem leafs we construct
    9330              :              from scalars are vectorized after the last scalar def.
    9331              :              ???  If we'd actually compute the insert location during
    9332              :              analysis we could use sth less conservative than the last
    9333              :              scalar stmt in the node for the dominance check.  */
    9334              :           /* ???  What remains is "live" uses in vector CTORs in the same
    9335              :              SLP graph which is where those uses can end up code-generated
    9336              :              right after their definition instead of close to their original
    9337              :              use.  But that would restrict us to code-generate lane-extracts
    9338              :              from the latest stmt in a node.  So we compensate for this
    9339              :              during code-generation, simply not replacing uses for those
    9340              :              hopefully rare cases.  */
    9341       566379 :           imm_use_iterator use_iter;
    9342              : 
    9343       566379 :           bool live_p = false;
    9344       566379 :           bool can_insert = true;
    9345       566379 :           use_operand_p use_p;
    9346      1699664 :           FOR_EACH_IMM_USE_FAST (use_p, use_iter, DEF_FROM_PTR (def_p))
    9347              :             {
    9348      1141374 :               gimple *use_stmt = USE_STMT (use_p);
    9349      1141374 :               stmt_vec_info use_stmt_info;
    9350      1141374 :               if (!(!is_gimple_debug (use_stmt)
    9351       878633 :                     && (!(use_stmt_info = bb_vinfo->lookup_stmt (use_stmt))
    9352       868103 :                         || !PURE_SLP_STMT (use_stmt_info))))
    9353       931460 :                 continue;
    9354       209914 :               live_p = true;
    9355       209914 :               if (!last_stmt)
    9356        65103 :                 last_stmt
    9357        65365 :                   = (node->si ? node->si
    9358          262 :                      : vect_find_last_scalar_stmt_in_slp (node)->stmt);
    9359       209914 :               if (is_a <gphi *> (use_stmt))
    9360              :                 {
    9361        72076 :                   if (!dominated_by_p (CDI_DOMINATORS,
    9362        36038 :                                        phi_arg_edge_from_use (use_p)->src,
    9363        36038 :                                        gimple_bb (last_stmt)))
    9364              :                     can_insert = false;
    9365              :                 }
    9366              :               /* As we instert after last_stmt it may not be the use_stmt
    9367              :                  itself.  */
    9368       173876 :               else if (last_stmt == use_stmt
    9369       173876 :                        || !vect_stmt_dominates_stmt_p (last_stmt, use_stmt))
    9370              :                 can_insert = false;
    9371              :               if (!can_insert)
    9372              :                 {
    9373         8089 :                   if (dump_enabled_p ())
    9374           80 :                     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9375              :                                      "Cannot determine insertion place for "
    9376              :                                      "lane extract of %T at node %p\n",
    9377              :                                      DEF_FROM_PTR (def_p), (void *)node);
    9378              :                   can_insert = false;
    9379              :                   break;
    9380              :                 }
    9381       566379 :             }
    9382       566379 :           if (live_p && can_insert)
    9383              :             {
    9384              :               /* Only record a live stmt when we can replace all uses.  We
    9385              :                  record from which SLP tree we vectorize the uses, so we'll
    9386              :                  cost once and can deal with the case that not all SLP nodes
    9387              :                  may be suitable for code-generation of all live uses.
    9388              :                  ???  But we never split up the work between multiple SLP
    9389              :                  nodes.  */
    9390       104993 :               STMT_VINFO_LIVE_P (stmt_info) = true;
    9391       104993 :               if (!vectorizable_live_operation (bb_vinfo, stmt_info, node,
    9392              :                                                 instance, i, false, cost_vec))
    9393              :                 {
    9394            0 :                   STMT_VINFO_LIVE_P (stmt_info) = false;
    9395            0 :                   mark_visited = false;
    9396              :                 }
    9397              :             }
    9398              :         }
    9399      2339697 :       if (mark_visited)
    9400      2339697 :         svisited.add (stmt_info);
    9401              :     }
    9402              : 
    9403              :   slp_tree child;
    9404      2747493 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
    9405       981921 :     if (child && SLP_TREE_DEF_TYPE (child) == vect_internal_def)
    9406       279931 :       vect_bb_slp_mark_live_stmts (bb_vinfo, child, instance, cost_vec,
    9407              :                                    svisited, visited);
    9408              : }
    9409              : 
    9410              : /* Traverse all slp instances of BB_VINFO, and mark lanes of every node that
    9411              :    are live outside of the basic-block vectorized region and that can be
    9412              :    vectorized using vectorizable_live_operation with STMT_VINFO_LIVE_P.  */
    9413              : 
    9414              : static void
    9415       247322 : vect_bb_slp_mark_live_stmts (bb_vec_info bb_vinfo)
    9416              : {
    9417       247322 :   if (bb_vinfo->slp_instances.is_empty ())
    9418            0 :     return;
    9419              : 
    9420       247322 :   hash_set<slp_tree> visited;
    9421       247322 :   hash_set<stmt_vec_info> svisited;
    9422      1459476 :   for (slp_instance instance : bb_vinfo->slp_instances)
    9423              :     {
    9424       717510 :       if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
    9425        51892 :         STMT_VINFO_LIVE_P (SLP_INSTANCE_ROOT_STMTS (instance)[0]) = true;
    9426       717510 :       vect_location = instance->location ();
    9427       717510 :       vect_bb_slp_mark_live_stmts (bb_vinfo, SLP_INSTANCE_TREE (instance),
    9428              :                                    instance, &instance->cost_vec,
    9429              :                                    svisited, visited);
    9430              :     }
    9431       247322 : }
    9432              : 
    9433              : /* Determine whether we can vectorize the reduction epilogue for INSTANCE.  */
    9434              : 
    9435              : static bool
    9436        90113 : vectorizable_bb_reduc_epilogue (slp_instance instance,
    9437              :                                 stmt_vector_for_cost *cost_vec)
    9438              : {
    9439        90113 :   gassign *stmt = as_a <gassign *> (instance->root_stmts[0]->stmt);
    9440        90113 :   enum tree_code reduc_code = gimple_assign_rhs_code (stmt);
    9441        90113 :   if (reduc_code == MINUS_EXPR)
    9442            0 :     reduc_code = PLUS_EXPR;
    9443        90113 :   internal_fn reduc_fn;
    9444        90113 :   tree vectype = SLP_TREE_VECTYPE (SLP_INSTANCE_TREE (instance));
    9445        90113 :   if (!vectype
    9446        90101 :       || !useless_type_conversion_p (TREE_TYPE (gimple_assign_lhs (stmt)),
    9447        90101 :                                      TREE_TYPE (vectype))
    9448        53212 :       || (maybe_ne (TYPE_VECTOR_SUBPARTS (vectype), 2u)
    9449          993 :           && (!reduction_fn_for_scalar_code (reduc_code, &reduc_fn)
    9450          993 :               || reduc_fn == IFN_LAST
    9451          993 :               || !direct_internal_fn_supported_p (reduc_fn, vectype,
    9452              :                                                   OPTIMIZE_FOR_BOTH)))
    9453              :       /* Two-element reductions do not need special-handling for fold-left,
    9454              :          other cases are not yet implemented.  remain_defs also have to
    9455              :          be included here.  */
    9456       180262 :       || (needs_fold_left_reduction_p (TREE_TYPE (vectype), reduc_code)
    9457         5948 :           && (!instance->remain_defs.is_empty ()
    9458         1878 :               || SLP_TREE_LANES (SLP_INSTANCE_TREE (instance)) != 2)))
    9459              :     {
    9460        38986 :       if (dump_enabled_p ())
    9461           60 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
    9462              :                          "not vectorized: basic block reduction epilogue "
    9463              :                          "operation unsupported.\n");
    9464              :       return false;
    9465              :     }
    9466              : 
    9467              :   /* There's no way to cost a horizontal vector reduction via REDUC_FN so
    9468              :      cost log2 vector operations plus shuffles and one extraction.  */
    9469        51127 :   unsigned steps = floor_log2 (vect_nunits_for_cost (vectype));
    9470        51127 :   record_stmt_cost (cost_vec, steps, vector_stmt, instance->root_stmts[0],
    9471              :                     vectype, 0, vect_body);
    9472        51127 :   record_stmt_cost (cost_vec, steps, vec_perm, instance->root_stmts[0],
    9473              :                     vectype, 0, vect_body);
    9474        51127 :   record_stmt_cost (cost_vec, 1, vec_to_scalar, instance->root_stmts[0],
    9475              :                     vectype, 0, vect_body);
    9476              : 
    9477              :   /* Since we replace all stmts of a possibly longer scalar reduction
    9478              :      chain account for the extra scalar stmts for that.  */
    9479        51127 :   if (!instance->remain_defs.is_empty ())
    9480        31990 :     record_stmt_cost (cost_vec, instance->remain_defs.length (), scalar_stmt,
    9481        15995 :                       instance->root_stmts[0], 0, vect_body);
    9482              :   return true;
    9483              : }
    9484              : 
    9485              : /* Prune from ROOTS all stmts that are computed as part of lanes of NODE
    9486              :    and recurse to children.  */
    9487              : 
    9488              : static void
    9489       362246 : vect_slp_prune_covered_roots (slp_tree node, hash_set<stmt_vec_info> &roots,
    9490              :                               hash_set<slp_tree> &visited)
    9491              : {
    9492       362246 :   if (SLP_TREE_DEF_TYPE (node) != vect_internal_def
    9493       362246 :       || visited.add (node))
    9494              :     return;
    9495              : 
    9496      1014792 :   for (auto stmt : SLP_TREE_SCALAR_STMTS (node))
    9497       450898 :     if (stmt)
    9498       482333 :       roots.remove (vect_orig_stmt (stmt));
    9499              : 
    9500       766290 :   for (auto child : SLP_TREE_CHILDREN (node))
    9501       255786 :     if (child)
    9502       254244 :       vect_slp_prune_covered_roots (child, roots, visited);
    9503              : }
    9504              : 
    9505              : /* Hand over COST_VEC to the target COSTS grouped by SLP node.  */
    9506              : 
    9507              : static void
    9508      1029856 : add_slp_costs (vector_costs *costs, stmt_vector_for_cost& cost_vec)
    9509              : {
    9510      3828528 :   for (unsigned start = 0; start < cost_vec.length ();)
    9511              :     {
    9512      2798672 :       unsigned end = start + 1;
    9513      3460377 :       while (end < cost_vec.length ()
    9514      5899621 :              && cost_vec[start].node == cost_vec[end].node)
    9515       661705 :         end++;
    9516      2798672 :       if (cost_vec[start].node)
    9517      2756324 :         costs->add_slp_cost (cost_vec[start].node,
    9518      2756324 :                              array_slice<stmt_info_for_cost>
    9519      2756324 :                                (cost_vec.begin () + start, end - start));
    9520              :       else
    9521        42348 :         costs->vector_costs::add_slp_cost (cost_vec[start].node,
    9522        42348 :                              array_slice<stmt_info_for_cost>
    9523        42348 :                                (cost_vec.begin () + start, end - start));
    9524      2798672 :       start = end;
    9525              :     }
    9526      1029856 : }
    9527              : 
    9528              : /* Analyze statements in SLP instances of VINFO.  Return true if the
    9529              :    operations are supported. */
    9530              : 
    9531              : bool
    9532       696476 : vect_slp_analyze_operations (vec_info *vinfo)
    9533              : {
    9534       696476 :   slp_instance instance;
    9535       696476 :   int i;
    9536              : 
    9537       696476 :   DUMP_VECT_SCOPE ("vect_slp_analyze_operations");
    9538              : 
    9539       696476 :   hash_set<slp_tree> visited;
    9540      2501152 :   for (i = 0; vinfo->slp_instances.iterate (i, &instance); )
    9541              :     {
    9542      1368365 :       auto_vec<slp_tree> visited_vec;
    9543      1368365 :       stmt_vector_for_cost cost_vec;
    9544      1368365 :       cost_vec.create (2);
    9545      1368365 :       if (is_a <bb_vec_info> (vinfo))
    9546       821880 :         vect_location = instance->location ();
    9547      1368365 :       if (!vect_slp_analyze_node_operations (vinfo,
    9548              :                                              SLP_INSTANCE_TREE (instance),
    9549              :                                              instance, visited, visited_vec,
    9550              :                                              &cost_vec)
    9551              :           /* CTOR instances require vectorized defs for the SLP tree root.  */
    9552      1111738 :           || (SLP_INSTANCE_KIND (instance) == slp_inst_kind_ctor
    9553         6315 :               && (SLP_TREE_DEF_TYPE (SLP_INSTANCE_TREE (instance))
    9554              :                   != vect_internal_def
    9555              :                   /* Make sure we vectorized with the expected type.  */
    9556         6315 :                   || !useless_type_conversion_p
    9557         6315 :                         (TREE_TYPE (TREE_TYPE (gimple_assign_rhs1
    9558              :                                               (instance->root_stmts[0]->stmt))),
    9559         6315 :                          TREE_TYPE (SLP_TREE_VECTYPE
    9560              :                                             (SLP_INSTANCE_TREE (instance))))))
    9561              :           /* Check we can vectorize the reduction.  */
    9562      1111723 :           || (SLP_INSTANCE_KIND (instance) == slp_inst_kind_bb_reduc
    9563        90113 :               && !vectorizable_bb_reduc_epilogue (instance, &cost_vec))
    9564              :           /* Check we can vectorize the gcond.  */
    9565      2441102 :           || (SLP_INSTANCE_KIND (instance) == slp_inst_kind_gcond
    9566        66034 :               && !vectorizable_early_exit (as_a <loop_vec_info> (vinfo),
    9567        66034 :                                            SLP_INSTANCE_ROOT_STMTS (instance)[0],
    9568              :                                            NULL,
    9569              :                                            SLP_INSTANCE_TREE (instance),
    9570              :                                            &cost_vec)))
    9571              :         {
    9572       358992 :           cost_vec.release ();
    9573       358992 :           slp_tree node = SLP_INSTANCE_TREE (instance);
    9574       358992 :           stmt_vec_info stmt_info;
    9575       358992 :           if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
    9576       268599 :             stmt_info = SLP_INSTANCE_ROOT_STMTS (instance)[0];
    9577        90393 :           else if (!SLP_TREE_SCALAR_STMTS (node).is_empty ()
    9578        90393 :                    && SLP_TREE_SCALAR_STMTS (node)[0])
    9579              :             stmt_info = SLP_TREE_SCALAR_STMTS (node)[0];
    9580              :           else
    9581            0 :             stmt_info = SLP_TREE_REPRESENTATIVE (node);
    9582       358992 :           if (is_a <loop_vec_info> (vinfo))
    9583              :             {
    9584       260165 :               if (dump_enabled_p ())
    9585         6899 :                 dump_printf_loc (MSG_NOTE, vect_location,
    9586              :                                  "unsupported SLP instance starting from: %G",
    9587              :                                  stmt_info->stmt);
    9588       260165 :               return false;
    9589              :             }
    9590        98827 :           if (dump_enabled_p ())
    9591          120 :             dump_printf_loc (MSG_NOTE, vect_location,
    9592              :                              "removing SLP instance operations starting from: %G",
    9593              :                              stmt_info->stmt);
    9594       235558 :           while (!visited_vec.is_empty ())
    9595              :             {
    9596       136731 :               slp_tree node = visited_vec.pop ();
    9597       136731 :               SLP_TREE_TYPE (node) = undef_vec_info_type;
    9598       136731 :               if (node->data)
    9599              :                 {
    9600         8545 :                   delete node->data;
    9601         8545 :                   node->data = nullptr;
    9602              :                 }
    9603       136731 :               visited.remove (node);
    9604              :             }
    9605        98827 :           vect_free_slp_instance (instance);
    9606        98827 :           vinfo->slp_instances.ordered_remove (i);
    9607              :         }
    9608              :       else
    9609              :         {
    9610      1009373 :           i++;
    9611      1009373 :           if (loop_vec_info loop_vinfo = dyn_cast<loop_vec_info> (vinfo))
    9612              :             {
    9613       286320 :               add_slp_costs (loop_vinfo->vector_costs, cost_vec);
    9614       286320 :               cost_vec.release ();
    9615              :             }
    9616              :           else
    9617              :             /* For BB vectorization remember the SLP graph entry
    9618              :                cost for later.  */
    9619       723053 :             instance->cost_vec = cost_vec;
    9620              :         }
    9621      1368365 :     }
    9622              : 
    9623              :   /* Now look for SLP instances with a root that are covered by other
    9624              :      instances and remove them.  */
    9625       436311 :   hash_set<stmt_vec_info> roots;
    9626      1810824 :   for (i = 0; vinfo->slp_instances.iterate (i, &instance); ++i)
    9627       998287 :     if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
    9628        60085 :       roots.add (SLP_INSTANCE_ROOT_STMTS (instance)[0]);
    9629       436311 :   if (!roots.is_empty ())
    9630              :     {
    9631        24420 :       visited.empty ();
    9632       132422 :       for (i = 0; vinfo->slp_instances.iterate (i, &instance); ++i)
    9633       108002 :         vect_slp_prune_covered_roots (SLP_INSTANCE_TREE (instance), roots,
    9634              :                                       visited);
    9635       132422 :       for (i = 0; vinfo->slp_instances.iterate (i, &instance); )
    9636       108002 :         if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ()
    9637        60085 :             && !roots.contains (SLP_INSTANCE_ROOT_STMTS (instance)[0]))
    9638              :           {
    9639         5503 :             stmt_vec_info root = SLP_INSTANCE_ROOT_STMTS (instance)[0];
    9640         5503 :             if (dump_enabled_p ())
    9641          287 :               dump_printf_loc (MSG_NOTE, vect_location,
    9642              :                                "removing SLP instance operations starting "
    9643              :                                "from: %G", root->stmt);
    9644         5503 :             vect_free_slp_instance (instance);
    9645         5503 :             vinfo->slp_instances.ordered_remove (i);
    9646              :           }
    9647              :         else
    9648       102499 :           ++i;
    9649              :     }
    9650              : 
    9651       872622 :   return !vinfo->slp_instances.is_empty ();
    9652      1132787 : }
    9653              : 
    9654              : /* Get the SLP instance leader from INSTANCE_LEADER thereby transitively
    9655              :    closing the eventual chain.  */
    9656              : 
    9657              : static slp_instance
    9658       806856 : get_ultimate_leader (slp_instance instance,
    9659              :                      hash_map<slp_instance, slp_instance> &instance_leader)
    9660              : {
    9661       806856 :   auto_vec<slp_instance *, 8> chain;
    9662       806856 :   slp_instance *tem;
    9663       915864 :   while (*(tem = instance_leader.get (instance)) != instance)
    9664              :     {
    9665       109008 :       chain.safe_push (tem);
    9666       109008 :       instance = *tem;
    9667              :     }
    9668       915864 :   while (!chain.is_empty ())
    9669       109008 :     *chain.pop () = instance;
    9670       806856 :   return instance;
    9671       806856 : }
    9672              : 
    9673              : namespace {
    9674              : /* Subroutine of vect_bb_partition_graph_r.  Map KEY to INSTANCE in
    9675              :    KEY_TO_INSTANCE, making INSTANCE the leader of any previous mapping
    9676              :    for KEY.  Return true if KEY was already in KEY_TO_INSTANCE.
    9677              : 
    9678              :    INSTANCE_LEADER is as for get_ultimate_leader.  */
    9679              : 
    9680              : template<typename T>
    9681              : bool
    9682      3567685 : vect_map_to_instance (slp_instance instance, T key,
    9683              :                       hash_map<T, slp_instance> &key_to_instance,
    9684              :                       hash_map<slp_instance, slp_instance> &instance_leader)
    9685              : {
    9686              :   bool existed_p;
    9687      3567685 :   slp_instance &key_instance = key_to_instance.get_or_insert (key, &existed_p);
    9688      3567685 :   if (!existed_p)
    9689              :     ;
    9690       242402 :   else if (key_instance != instance)
    9691              :     {
    9692              :       /* If we're running into a previously marked key make us the
    9693              :          leader of the current ultimate leader.  This keeps the
    9694              :          leader chain acyclic and works even when the current instance
    9695              :          connects two previously independent graph parts.  */
    9696        89346 :       slp_instance key_leader
    9697        89346 :         = get_ultimate_leader (key_instance, instance_leader);
    9698        89346 :       if (key_leader != instance)
    9699        26948 :         instance_leader.put (key_leader, instance);
    9700              :     }
    9701      3567685 :   key_instance = instance;
    9702      3567685 :   return existed_p;
    9703              : }
    9704              : }
    9705              : 
    9706              : /* Worker of vect_bb_partition_graph, recurse on NODE.  */
    9707              : 
    9708              : static void
    9709       997441 : vect_bb_partition_graph_r (bb_vec_info bb_vinfo,
    9710              :                            slp_instance instance, slp_tree node,
    9711              :                            hash_map<stmt_vec_info, slp_instance> &stmt_to_instance,
    9712              :                            hash_map<slp_tree, slp_instance> &node_to_instance,
    9713              :                            hash_map<slp_instance, slp_instance> &instance_leader)
    9714              : {
    9715      5551151 :   for (auto stmt_info : SLP_TREE_SCALAR_STMTS (node))
    9716      2570244 :     if (stmt_info)
    9717      2570244 :       vect_map_to_instance (instance, stmt_info, stmt_to_instance,
    9718              :                             instance_leader);
    9719              : 
    9720       997441 :   if (vect_map_to_instance (instance, node, node_to_instance,
    9721              :                             instance_leader))
    9722              :     return;
    9723              : 
    9724      3573647 :   for (auto child : SLP_TREE_CHILDREN (node))
    9725       981921 :     if (child && SLP_TREE_DEF_TYPE (child) == vect_internal_def)
    9726       279931 :       vect_bb_partition_graph_r (bb_vinfo, instance, child, stmt_to_instance,
    9727              :                                  node_to_instance, instance_leader);
    9728              : }
    9729              : 
    9730              : /* Partition the SLP graph into pieces that can be costed independently.  */
    9731              : 
    9732              : static void
    9733       247322 : vect_bb_partition_graph (bb_vec_info bb_vinfo)
    9734              : {
    9735       247322 :   DUMP_VECT_SCOPE ("vect_bb_partition_graph");
    9736              : 
    9737              :   /* First walk the SLP graph assigning each involved scalar stmt a
    9738              :      corresponding SLP graph entry and upon visiting a previously
    9739              :      marked stmt, make the stmts leader the current SLP graph entry.  */
    9740       247322 :   hash_map<stmt_vec_info, slp_instance> stmt_to_instance;
    9741       247322 :   hash_map<slp_tree, slp_instance> node_to_instance;
    9742       247322 :   hash_map<slp_instance, slp_instance> instance_leader;
    9743       247322 :   slp_instance instance;
    9744      1212154 :   for (unsigned i = 0; bb_vinfo->slp_instances.iterate (i, &instance); ++i)
    9745              :     {
    9746       717510 :       instance_leader.put (instance, instance);
    9747       717510 :       vect_bb_partition_graph_r (bb_vinfo,
    9748              :                                  instance, SLP_INSTANCE_TREE (instance),
    9749              :                                  stmt_to_instance, node_to_instance,
    9750              :                                  instance_leader);
    9751              :     }
    9752              : 
    9753              :   /* Then collect entries to each independent subgraph.  */
    9754      1212154 :   for (unsigned i = 0; bb_vinfo->slp_instances.iterate (i, &instance); ++i)
    9755              :     {
    9756       717510 :       slp_instance leader = get_ultimate_leader (instance, instance_leader);
    9757       717510 :       leader->subgraph_entries.safe_push (instance);
    9758       717510 :       if (dump_enabled_p ()
    9759       717510 :           && leader != instance)
    9760           99 :         dump_printf_loc (MSG_NOTE, vect_location,
    9761              :                          "instance %p is leader of %p\n",
    9762              :                          (void *) leader, (void *) instance);
    9763              :     }
    9764       247322 : }
    9765              : 
    9766              : /* Compute the scalar cost of the SLP node NODE and its children
    9767              :    and return it.  Do not account defs that are marked in LIFE and
    9768              :    update LIFE according to uses of NODE.  */
    9769              : 
    9770              : static void
    9771       713425 : vect_bb_slp_scalar_cost (bb_vec_info vinfo,
    9772              :                          vec<stmt_vec_info> &worklist,
    9773              :                          stmt_vector_for_cost *cost_vec,
    9774              :                          hash_set<stmt_vec_info> &visited)
    9775              : {
    9776      3323394 :   while (!worklist.is_empty ())
    9777              :     {
    9778      2609969 :       stmt_vec_info stmt = worklist.pop ();
    9779      2932617 :       if (!PURE_SLP_STMT (stmt))
    9780       331073 :         continue;
    9781              : 
    9782              :       /* When the stmt is live but not actually vectorized we have
    9783              :          to keep the feeding scalar defs.  */
    9784      2292932 :       if (!STMT_VINFO_LIVE_P (vect_stmt_to_vectorize (stmt)))
    9785              :         {
    9786      2184651 :           bool live_p = false;
    9787      2184651 :           ssa_op_iter op_iter;
    9788      2184651 :           def_operand_p def_p;
    9789      4803697 :           FOR_EACH_PHI_OR_STMT_DEF (def_p, stmt->stmt, op_iter, SSA_OP_DEF)
    9790              :             {
    9791       434395 :               imm_use_iterator use_iter;
    9792       434395 :               gimple *use_stmt;
    9793      1112603 :               FOR_EACH_IMM_USE_STMT (use_stmt, use_iter, DEF_FROM_PTR (def_p))
    9794       678208 :                 if (!is_gimple_debug (use_stmt))
    9795              :                   {
    9796       511025 :                     stmt_vec_info use_stmt_info = vinfo->lookup_stmt (use_stmt);
    9797       511025 :                     if (!use_stmt_info || !PURE_SLP_STMT (use_stmt_info))
    9798              :                       {
    9799        15578 :                         if (dump_enabled_p ())
    9800              :                           {
    9801           74 :                             dump_printf_loc (MSG_NOTE, vect_location,
    9802              :                                              "stmt considered live: %G",
    9803              :                                              stmt->stmt);
    9804           74 :                             dump_printf_loc (MSG_NOTE, vect_location,
    9805              :                                              "because of use in: %G",
    9806              :                                              use_stmt);
    9807              :                           }
    9808              :                         live_p = true;
    9809              :                       }
    9810       434395 :                   }
    9811              :             }
    9812      2184651 :           if (live_p)
    9813         8425 :             continue;
    9814              :         }
    9815              : 
    9816              :       /* The following assert verifies that vect_bb_partition_graph
    9817              :          partitions the SLP graph in a way that each scalar stmt of
    9818              :          the coverage of the SLP graph belongs to exactly one subgraph.
    9819              :          ???  This is currently not guaranteed since the function
    9820              :          works purely on SLP_TREE_SCALAR_STMTS, resulting in the assert
    9821              :          tripping or scalar stmts costed multiple times, making vectorization
    9822              :          more profitable than it really is.  */
    9823              :       /* gcc_checking_assert (!gimple_visited_p (stmt->stmt)); */
    9824              : 
    9825      2278896 :       if (vect_nop_conversion_p (stmt))
    9826              :         ;
    9827              :       /* For single-argument PHIs assume coalescing which means zero
    9828              :          cost for the scalar and the vector PHIs.  This avoids
    9829              :          artificially favoring the vector path (but may pessimize it
    9830              :          in some cases).  */
    9831      2248029 :       else if (is_a <gphi *> (stmt->stmt)
    9832      2248029 :                && gimple_phi_num_args (as_a <gphi *> (stmt->stmt)) == 1)
    9833              :         ;
    9834              :       else
    9835              :         {
    9836      2237515 :           vect_cost_for_stmt kind;
    9837      2237515 :           if (STMT_VINFO_DATA_REF (stmt))
    9838              :             {
    9839      2012889 :               data_reference_p dr = STMT_VINFO_DATA_REF (stmt);
    9840      2012889 :               tree base = get_base_address (DR_REF (dr));
    9841              :               /* When the scalar access is to a non-global not
    9842              :                  address-taken decl that is not BLKmode assume we can
    9843              :                  access it with a single non-load/store instruction.  */
    9844      2012889 :               if (DECL_P (base)
    9845      1546018 :                   && !is_global_var (base)
    9846      1468407 :                   && !TREE_ADDRESSABLE (base)
    9847      2571164 :                   && DECL_MODE (base) != BLKmode)
    9848              :                 kind = scalar_stmt;
    9849      1868754 :               else if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt)))
    9850              :                 kind = scalar_load;
    9851              :               else
    9852      1623062 :                 kind = scalar_store;
    9853              :             }
    9854              :           else
    9855              :             kind = scalar_stmt;
    9856              :           /* Cost each scalar stmt only once.  */
    9857      2237515 :           gimple_set_visited (stmt->stmt, true);
    9858      2237515 :           record_stmt_cost (cost_vec, 1, kind, stmt, NULL_TREE, 0, vect_body);
    9859              :         }
    9860              : 
    9861              :       /* Now walk relevant parts of the SSA use-def graph.  */
    9862      2278896 :       slp_oprnds child_ops (stmt);
    9863      7093589 :       for (unsigned i = 0; i < child_ops.num_slp_children; ++i)
    9864              :         {
    9865      2535797 :           tree op = child_ops.get_op_for_slp_child (stmt, i);
    9866      2535797 :           stmt_vec_info def = vinfo->lookup_def (op);
    9867      2535797 :           if (def && !visited.add (def))
    9868       758903 :             worklist.safe_push (def);
    9869              :         }
    9870              :     }
    9871       713425 : }
    9872              : 
    9873              : 
    9874              : /* Comparator for the loop-index sorted cost vectors.  */
    9875              : 
    9876              : static int
    9877     20055598 : li_cost_vec_cmp (const void *a_, const void *b_, void *)
    9878              : {
    9879     20055598 :   auto *a = (const std::pair<unsigned, stmt_info_for_cost *> *)a_;
    9880     20055598 :   auto *b = (const std::pair<unsigned, stmt_info_for_cost *> *)b_;
    9881     20055598 :   if (a->first < b->first)
    9882              :     return -1;
    9883     18625603 :   else if (a->first == b->first)
    9884     17483316 :     return 0;
    9885              :   return 1;
    9886              : }
    9887              : 
    9888              : /* Check if vectorization of the basic block is profitable for the
    9889              :    subgraph denoted by SLP_INSTANCES.  */
    9890              : 
    9891              : static bool
    9892       686679 : vect_bb_vectorization_profitable_p (bb_vec_info bb_vinfo,
    9893              :                                     vec<slp_instance> slp_instances,
    9894              :                                     loop_p orig_loop)
    9895              : {
    9896       686679 :   slp_instance instance;
    9897       686679 :   int i;
    9898       686679 :   unsigned int vec_inside_cost = 0, vec_outside_cost = 0, scalar_cost = 0;
    9899       686679 :   unsigned int vec_prologue_cost = 0, vec_epilogue_cost = 0;
    9900              : 
    9901       686679 :   if (dump_enabled_p ())
    9902              :     {
    9903          125 :       dump_printf_loc (MSG_NOTE, vect_location, "Costing subgraph:\n");
    9904          259 :       FOR_EACH_VEC_ELT (slp_instances, i, instance)
    9905          134 :         dump_printf_loc (MSG_NOTE, vect_location, "   entry instance %p -> "
    9906              :                          "node %p\n", (void *)instance,
    9907          134 :                          (void *)SLP_INSTANCE_TREE (instance));
    9908          125 :       hash_set<slp_tree> visited;
    9909          509 :       FOR_EACH_VEC_ELT (slp_instances, i, instance)
    9910          134 :         vect_print_slp_graph (MSG_NOTE, vect_location,
    9911              :                               SLP_INSTANCE_TREE (instance), visited);
    9912          125 :     }
    9913              : 
    9914              :   /* Then DFS walk scalar stmts, performing costing and handling
    9915              :      still live scalar stmts via the previously computed vector coverage.  */
    9916       686679 :   stmt_vector_for_cost scalar_costs = vNULL;
    9917       686679 :   stmt_vector_for_cost vector_costs = vNULL;
    9918       686679 :   hash_set<slp_tree> visited;
    9919       686679 :   hash_set<stmt_vec_info> svisited;
    9920      2086783 :   FOR_EACH_VEC_ELT (slp_instances, i, instance)
    9921              :     {
    9922       713425 :       auto_vec<stmt_vec_info> worklist;
    9923       713425 :       if (SLP_INSTANCE_ROOT_STMTS (instance).exists ())
    9924       102246 :         record_stmt_cost (&scalar_costs,
    9925        51123 :                           SLP_INSTANCE_ROOT_STMTS (instance).length (),
    9926              :                           scalar_stmt,
    9927        51123 :                           SLP_INSTANCE_ROOT_STMTS (instance)[0], 0, vect_body);
    9928      4006649 :       for (auto stmt : SLP_TREE_SCALAR_STMTS (SLP_INSTANCE_TREE (instance)))
    9929              :         {
    9930      1866374 :           stmt = vect_orig_stmt (stmt);
    9931      1866374 :           if (!svisited.add (stmt))
    9932      1851066 :             worklist.safe_push (stmt);
    9933              :         }
    9934       713425 :       vect_bb_slp_scalar_cost (bb_vinfo, worklist, &scalar_costs, svisited);
    9935       713425 :       vector_costs.safe_splice (instance->cost_vec);
    9936       713425 :       instance->cost_vec.release ();
    9937       713425 :     }
    9938              : 
    9939       686679 :   if (dump_enabled_p ())
    9940          125 :     dump_printf_loc (MSG_NOTE, vect_location, "Cost model analysis: \n");
    9941              : 
    9942              :   /* When costing non-loop vectorization we need to consider each covered
    9943              :      loop independently and make sure vectorization is profitable.  For
    9944              :      now we assume a loop may be not entered or executed an arbitrary
    9945              :      number of iterations (???  static information can provide more
    9946              :      precise info here) which means we can simply cost each containing
    9947              :      loops stmts separately.  */
    9948              : 
    9949              :   /* First produce cost vectors sorted by loop index.  */
    9950       686679 :   auto_vec<std::pair<unsigned, stmt_info_for_cost *> >
    9951      1373358 :     li_scalar_costs (scalar_costs.length ());
    9952       686679 :   auto_vec<std::pair<unsigned, stmt_info_for_cost *> >
    9953      1373345 :     li_vector_costs (vector_costs.length ());
    9954       686679 :   stmt_info_for_cost *cost;
    9955      3661996 :   FOR_EACH_VEC_ELT (scalar_costs, i, cost)
    9956              :     {
    9957      2288638 :       unsigned l = gimple_bb (cost->stmt_info->stmt)->loop_father->num;
    9958      2288638 :       li_scalar_costs.quick_push (std::make_pair (l, cost));
    9959              :     }
    9960              :   /* Use a random used loop as fallback in case the first vector_costs
    9961              :      entry does not have a location associated with it.  */
    9962       686679 :   unsigned l = li_scalar_costs[0].first;
    9963      2637251 :   FOR_EACH_VEC_ELT (vector_costs, i, cost)
    9964              :     {
    9965              :       /* Use SLP node placement according to the computed schedule.  */
    9966      1950572 :       if (cost->node && cost->node->si)
    9967      1214010 :         l = gimple_bb (cost->node->si)->loop_father->num;
    9968              :       /* For schedules at region boundary use the region entry loop.  */
    9969       736562 :       else if (cost->node)
    9970       588077 :         l = bb_vinfo->bbs[0]->loop_father->num;
    9971              :       /* SLP instance root stmts do not have an associated SLP node.  */
    9972       148485 :       else if (cost->stmt_info)
    9973       148485 :         l = gimple_bb (cost->stmt_info->stmt)->loop_father->num;
    9974              :       /* And since vect_prologue_cost_for_slp can end up costing with
    9975              :          neither, inherit from the previous node.  */
    9976      1950572 :       li_vector_costs.quick_push (std::make_pair (l, cost));
    9977              :     }
    9978       686679 :   li_scalar_costs.stablesort (li_cost_vec_cmp, NULL);
    9979       686679 :   li_vector_costs.stablesort (li_cost_vec_cmp, NULL);
    9980              : 
    9981       686679 :   unsigned total_vec_outside_cost = 0;
    9982       686679 :   unsigned total_vec_inside_cost = 0;
    9983       686679 :   unsigned total_scalar_cost = 0;
    9984              : 
    9985              :   /* Now cost the portions individually.  */
    9986       686679 :   unsigned vi = 0;
    9987       686679 :   unsigned si = 0;
    9988       686679 :   bool profitable = true;
    9989      1374685 :   while (si < li_scalar_costs.length ()
    9990      2120044 :          || vi < li_vector_costs.length ())
    9991              :     {
    9992       745372 :       unsigned sl
    9993      1489417 :         = si < li_scalar_costs.length () ? li_scalar_costs[si].first : -1U;
    9994       745372 :       unsigned vl
    9995      1490676 :         = vi < li_vector_costs.length () ? li_vector_costs[vi].first : -1U;
    9996              : 
    9997       745372 :       class vector_costs *scalar_target_cost_data = nullptr;
    9998       745372 :       scalar_cost = 0;
    9999       745372 :       if (sl <= vl)
   10000              :         {
   10001       702016 :           if (dump_enabled_p ())
   10002          145 :             dump_printf_loc (MSG_NOTE, vect_location,
   10003              :                              "Scalar cost for part in loop %d\n", sl);
   10004       702016 :           scalar_target_cost_data = init_cost (bb_vinfo, true);
   10005      2288638 :           do
   10006              :             {
   10007      2288638 :               add_stmt_cost (scalar_target_cost_data,
   10008      2288638 :                              li_scalar_costs[si].second);
   10009      2288638 :               si++;
   10010              :             }
   10011      2288638 :           while (si < li_scalar_costs.length ()
   10012      4592613 :                  && li_scalar_costs[si].first == sl);
   10013       702016 :           scalar_target_cost_data->finish_cost (nullptr);
   10014       702016 :           scalar_cost = scalar_target_cost_data->body_cost ();
   10015       702016 :           total_scalar_cost += scalar_cost;
   10016       702016 :           if (sl < vl)
   10017              :             {
   10018         1836 :               if (dump_enabled_p ())
   10019            2 :                 dump_printf_loc (MSG_NOTE, vect_location,
   10020              :                                  "Scalar %d loop part does not "
   10021              :                                  "have corresponding vector part\n", sl);
   10022         1836 :               delete scalar_target_cost_data;
   10023       648374 :               continue;
   10024              :             }
   10025              :         }
   10026              : 
   10027              :       /* Complete the target-specific vector cost calculation.  */
   10028       743536 :       if (dump_enabled_p ())
   10029          147 :         dump_printf_loc (MSG_NOTE, vect_location,
   10030              :                          "Vector cost for part in loop %d\n", vl);
   10031       743536 :       class vector_costs *vect_target_cost_data = init_cost (bb_vinfo, false);
   10032       743536 :       auto_vec<stmt_info_for_cost> tem;
   10033      1950572 :       do
   10034              :         {
   10035      1950572 :           tem.safe_push (*li_vector_costs[vi].second);
   10036      1950572 :           vi++;
   10037              :         }
   10038      1950572 :       while (vi < li_vector_costs.length ()
   10039      3958014 :              && li_vector_costs[vi].first == vl);
   10040       743536 :       add_slp_costs (vect_target_cost_data, tem);
   10041       743536 :       vect_target_cost_data->finish_cost (scalar_target_cost_data);
   10042       743536 :       vec_prologue_cost = vect_target_cost_data->prologue_cost ();
   10043       743536 :       vec_inside_cost = vect_target_cost_data->body_cost ();
   10044       743536 :       vec_epilogue_cost = vect_target_cost_data->epilogue_cost ();
   10045       743536 :       if (scalar_target_cost_data)
   10046       700180 :         delete scalar_target_cost_data;
   10047       743536 :       delete vect_target_cost_data;
   10048              : 
   10049       743536 :       vec_outside_cost = vec_prologue_cost + vec_epilogue_cost;
   10050              : 
   10051       743536 :       total_vec_outside_cost += vec_outside_cost;
   10052       743536 :       total_vec_inside_cost += vec_inside_cost;
   10053              : 
   10054       743536 :       if (sl > vl && dump_enabled_p ())
   10055            4 :         dump_printf_loc (MSG_NOTE, vect_location,
   10056              :                          "Vector %d loop part does not "
   10057              :                          "have corresponding scalar part\n", vl);
   10058              : 
   10059              :       /* When this is vector costs for the region entry delay costing
   10060              :          and instead only require the total costs to be profitable.  */
   10061       743536 :       if (vl == (unsigned) bb_vinfo->bbs[0]->loop_father->num)
   10062       646538 :         continue;
   10063              : 
   10064        96998 :       if (dump_enabled_p ())
   10065              :         {
   10066           50 :           dump_printf_loc (MSG_NOTE, vect_location,
   10067              :                            "Cost model analysis for part in loop %d:\n",
   10068           50 :                            std::min (sl, vl));
   10069           50 :           dump_printf (MSG_NOTE, "  Vector cost: %d\n",
   10070              :                        vec_inside_cost + vec_outside_cost);
   10071           50 :           dump_printf (MSG_NOTE, "  Scalar cost: %d\n", scalar_cost);
   10072              :         }
   10073              : 
   10074              :       /* Vectorization is profitable if its cost is more than the cost of scalar
   10075              :          version.  Note that we err on the vector side for equal cost because
   10076              :          the cost estimate is otherwise quite pessimistic (constant uses are
   10077              :          free on the scalar side but cost a load on the vector side for
   10078              :          example).  */
   10079        96998 :       if (vec_outside_cost + vec_inside_cost > scalar_cost)
   10080        42198 :         profitable = false;
   10081       743536 :     }
   10082              : 
   10083       686679 :   if (dump_enabled_p ())
   10084              :     {
   10085          125 :       dump_printf_loc (MSG_NOTE, vect_location,
   10086              :                        "Cost model analysis for whole subgraph:\n");
   10087          125 :       dump_printf (MSG_NOTE, "  Vector cost: %d\n",
   10088              :                    total_vec_inside_cost + total_vec_outside_cost);
   10089          125 :       dump_printf (MSG_NOTE, "  Scalar cost: %d\n", total_scalar_cost);
   10090              :     }
   10091              : 
   10092              :   /* For the case where the outermost region had no scalar cost require
   10093              :      overall profitability.  */
   10094       686679 :   if (total_vec_outside_cost + total_vec_inside_cost > total_scalar_cost)
   10095       195157 :     profitable = false;
   10096              : 
   10097              :   /* Unset visited flag.  This is delayed when the subgraph is profitable
   10098              :      and we process the loop for remaining unvectorized if-converted code.  */
   10099       686679 :   if (!orig_loop || !profitable)
   10100      2973082 :     FOR_EACH_VEC_ELT (scalar_costs, i, cost)
   10101      2286563 :       gimple_set_visited  (cost->stmt_info->stmt, false);
   10102              : 
   10103       686679 :   scalar_costs.release ();
   10104       686679 :   vector_costs.release ();
   10105              : 
   10106       686679 :   return profitable;
   10107       686679 : }
   10108              : 
   10109              : /* qsort comparator for lane defs.  */
   10110              : 
   10111              : static int
   10112          128 : vld_cmp (const void *a_, const void *b_)
   10113              : {
   10114          128 :   auto *a = (const std::pair<unsigned, tree> *)a_;
   10115          128 :   auto *b = (const std::pair<unsigned, tree> *)b_;
   10116          128 :   return a->first - b->first;
   10117              : }
   10118              : 
   10119              : /* Return true if USE_STMT is a vector lane insert into VEC and set
   10120              :    *THIS_LANE to the lane number that is set.  */
   10121              : 
   10122              : static bool
   10123          295 : vect_slp_is_lane_insert (gimple *use_stmt, tree vec, unsigned *this_lane)
   10124              : {
   10125          295 :   gassign *use_ass = dyn_cast <gassign *> (use_stmt);
   10126          110 :   if (!use_ass
   10127          110 :       || gimple_assign_rhs_code (use_ass) != BIT_INSERT_EXPR
   10128           35 :       || (vec
   10129           35 :           ? gimple_assign_rhs1 (use_ass) != vec
   10130           26 :           : ((vec = gimple_assign_rhs1 (use_ass)), false))
   10131           61 :       || !useless_type_conversion_p (TREE_TYPE (TREE_TYPE (vec)),
   10132           61 :                                      TREE_TYPE (gimple_assign_rhs2 (use_ass)))
   10133           61 :       || !constant_multiple_p
   10134           61 :             (tree_to_poly_uint64 (gimple_assign_rhs3 (use_ass)),
   10135          356 :              tree_to_poly_uint64 (TYPE_SIZE (TREE_TYPE (TREE_TYPE (vec)))),
   10136              :              this_lane))
   10137              :     return false;
   10138              :   return true;
   10139              : }
   10140              : 
   10141              : /* Find any vectorizable constructors and add them to the grouped_store
   10142              :    array.  */
   10143              : 
   10144              : static void
   10145      2285514 : vect_slp_check_for_roots (bb_vec_info bb_vinfo)
   10146              : {
   10147     18297430 :   for (unsigned i = 0; i < bb_vinfo->nbbs; ++i)
   10148     32023832 :     for (gimple_stmt_iterator gsi = gsi_start_bb (bb_vinfo->bbs[i]);
   10149    147758515 :          !gsi_end_p (gsi); gsi_next (&gsi))
   10150              :     {
   10151    131746599 :       gassign *assign = dyn_cast<gassign *> (gsi_stmt (gsi));
   10152              :       /* This can be used to start SLP discovery for early breaks for BB early breaks
   10153              :          when we get that far.  */
   10154    131746599 :       if (!assign)
   10155    101206953 :         continue;
   10156              : 
   10157     32660029 :       tree rhs = gimple_assign_rhs1 (assign);
   10158     32660029 :       enum tree_code code = gimple_assign_rhs_code (assign);
   10159     32660029 :       use_operand_p use_p;
   10160     32660029 :       gimple *use_stmt;
   10161     32660029 :       if (code == CONSTRUCTOR)
   10162              :         {
   10163      1738289 :           if (!VECTOR_TYPE_P (TREE_TYPE (rhs))
   10164      1784247 :               || maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)),
   10165       100453 :                            CONSTRUCTOR_NELTS (rhs))
   10166        45958 :               || VECTOR_TYPE_P (TREE_TYPE (CONSTRUCTOR_ELT (rhs, 0)->value))
   10167      1784227 :               || uniform_vector_p (rhs))
   10168      1723813 :             continue;
   10169              : 
   10170              :           unsigned j;
   10171              :           tree val;
   10172        71600 :           FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), j, val)
   10173        57124 :             if (TREE_CODE (val) != SSA_NAME
   10174        57124 :                 || !bb_vinfo->lookup_def (val))
   10175              :               break;
   10176        35884 :           if (j != CONSTRUCTOR_NELTS (rhs))
   10177         3466 :             continue;
   10178              : 
   10179        14476 :           vec<stmt_vec_info> roots = vNULL;
   10180        14476 :           roots.safe_push (bb_vinfo->lookup_stmt (assign));
   10181        14476 :           vec<stmt_vec_info> stmts;
   10182        14476 :           stmts.create (CONSTRUCTOR_NELTS (rhs));
   10183        80678 :           FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (rhs), j, val)
   10184        51726 :             stmts.quick_push
   10185        51726 :               (vect_stmt_to_vectorize (bb_vinfo->lookup_def (val)));
   10186        14476 :           bb_vinfo->roots.safe_push (slp_root (slp_inst_kind_ctor,
   10187        14476 :                                                stmts, roots));
   10188              :         }
   10189     30921740 :       else if (code == BIT_INSERT_EXPR
   10190         1037 :                && VECTOR_TYPE_P (TREE_TYPE (rhs))
   10191          711 :                && TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)).is_constant ()
   10192          711 :                && TYPE_VECTOR_SUBPARTS (TREE_TYPE (rhs)).to_constant () > 1
   10193          708 :                && integer_zerop (gimple_assign_rhs3 (assign))
   10194          392 :                && useless_type_conversion_p
   10195          392 :                     (TREE_TYPE (TREE_TYPE (rhs)),
   10196          392 :                      TREE_TYPE (gimple_assign_rhs2 (assign)))
   10197     30922464 :                && bb_vinfo->lookup_def (gimple_assign_rhs2 (assign)))
   10198              :         {
   10199              :           /* We start to match on insert to lane zero but since the
   10200              :              inserts need not be ordered we'd have to search both
   10201              :              the def and the use chains.  */
   10202          257 :           tree vectype = TREE_TYPE (rhs);
   10203          257 :           unsigned nlanes = TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
   10204          257 :           auto_vec<std::pair<unsigned, tree> > lane_defs (nlanes);
   10205          257 :           auto_sbitmap lanes (nlanes);
   10206          257 :           bitmap_clear (lanes);
   10207          257 :           bitmap_set_bit (lanes, 0);
   10208          257 :           tree def = gimple_assign_lhs (assign);
   10209          257 :           lane_defs.quick_push
   10210          257 :                       (std::make_pair (0, gimple_assign_rhs2 (assign)));
   10211          257 :           unsigned lanes_found = 1;
   10212              :           /* Start with the use chains, the last stmt will be the root.  */
   10213          257 :           stmt_vec_info last = bb_vinfo->lookup_stmt (assign);
   10214          257 :           vec<stmt_vec_info> roots = vNULL;
   10215          257 :           roots.safe_push (last);
   10216          268 :           do
   10217              :             {
   10218          268 :               use_operand_p use_p;
   10219          268 :               gimple *use_stmt;
   10220          268 :               if (!single_imm_use (def, &use_p, &use_stmt))
   10221              :                 break;
   10222          256 :               unsigned this_lane;
   10223          256 :               if (!bb_vinfo->lookup_stmt (use_stmt)
   10224          256 :                   || !vect_slp_is_lane_insert (use_stmt, def, &this_lane)
   10225          291 :                   || !bb_vinfo->lookup_def (gimple_assign_rhs2 (use_stmt)))
   10226              :                 break;
   10227           35 :               if (bitmap_bit_p (lanes, this_lane))
   10228              :                 break;
   10229           15 :               lanes_found++;
   10230           15 :               bitmap_set_bit (lanes, this_lane);
   10231           15 :               gassign *use_ass = as_a <gassign *> (use_stmt);
   10232           15 :               lane_defs.quick_push (std::make_pair
   10233           15 :                                      (this_lane, gimple_assign_rhs2 (use_ass)));
   10234           15 :               last = bb_vinfo->lookup_stmt (use_ass);
   10235           15 :               roots.safe_push (last);
   10236           15 :               def = gimple_assign_lhs (use_ass);
   10237              :             }
   10238           15 :           while (lanes_found < nlanes);
   10239          257 :           if (roots.length () > 1)
   10240            7 :             std::swap(roots[0], roots[roots.length () - 1]);
   10241          257 :           if (lanes_found < nlanes)
   10242              :             {
   10243              :               /* Now search the def chain.  */
   10244          253 :               def = gimple_assign_rhs1 (assign);
   10245          255 :               do
   10246              :                 {
   10247          255 :                   if (TREE_CODE (def) != SSA_NAME
   10248          255 :                       || !has_single_use (def))
   10249              :                     break;
   10250           59 :                   gimple *def_stmt = SSA_NAME_DEF_STMT (def);
   10251           59 :                   unsigned this_lane;
   10252           59 :                   if (!bb_vinfo->lookup_stmt (def_stmt)
   10253           39 :                       || !vect_slp_is_lane_insert (def_stmt,
   10254              :                                                    NULL_TREE, &this_lane)
   10255           85 :                       || !bb_vinfo->lookup_def (gimple_assign_rhs2 (def_stmt)))
   10256              :                     break;
   10257           26 :                   if (bitmap_bit_p (lanes, this_lane))
   10258              :                     break;
   10259            6 :                   lanes_found++;
   10260            6 :                   bitmap_set_bit (lanes, this_lane);
   10261           12 :                   lane_defs.quick_push (std::make_pair
   10262            6 :                                           (this_lane,
   10263            6 :                                            gimple_assign_rhs2 (def_stmt)));
   10264            6 :                   roots.safe_push (bb_vinfo->lookup_stmt (def_stmt));
   10265            6 :                   def = gimple_assign_rhs1 (def_stmt);
   10266              :                 }
   10267            6 :               while (lanes_found < nlanes);
   10268              :             }
   10269          257 :           if (lanes_found == nlanes)
   10270              :             {
   10271              :               /* Sort lane_defs after the lane index and register the root.  */
   10272            8 :               lane_defs.qsort (vld_cmp);
   10273            8 :               vec<stmt_vec_info> stmts;
   10274            8 :               stmts.create (nlanes);
   10275           44 :               for (unsigned i = 0; i < nlanes; ++i)
   10276           28 :                 stmts.quick_push (bb_vinfo->lookup_def (lane_defs[i].second));
   10277            8 :               bb_vinfo->roots.safe_push (slp_root (slp_inst_kind_ctor,
   10278            8 :                                                    stmts, roots));
   10279              :             }
   10280              :           else
   10281          249 :             roots.release ();
   10282          257 :         }
   10283     30921483 :       else if (!VECTOR_TYPE_P (TREE_TYPE (rhs))
   10284     29884365 :                && (associative_tree_code (code) || code == MINUS_EXPR)
   10285              :                /* Ops with constants at the tail can be stripped here.  */
   10286      6573867 :                && TREE_CODE (rhs) == SSA_NAME
   10287      6511987 :                && TREE_CODE (gimple_assign_rhs2 (assign)) == SSA_NAME
   10288              :                /* Should be the chain end.  */
   10289     33720303 :                && (!single_imm_use (gimple_assign_lhs (assign),
   10290              :                                     &use_p, &use_stmt)
   10291      2253042 :                    || !is_gimple_assign (use_stmt)
   10292      1627925 :                    || (gimple_assign_rhs_code (use_stmt) != code
   10293      1084681 :                        && ((code != PLUS_EXPR && code != MINUS_EXPR)
   10294       619996 :                            || (gimple_assign_rhs_code (use_stmt)
   10295       619996 :                                != (code == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR))))))
   10296              :         {
   10297              :           /* We start the match at the end of a possible association
   10298              :              chain.  */
   10299      2140204 :           auto_vec<chain_op_t> chain;
   10300      2140204 :           auto_vec<std::pair<tree_code, gimple *> > worklist;
   10301      2140204 :           auto_vec<gimple *> chain_stmts;
   10302      2140204 :           gimple *code_stmt = NULL, *alt_code_stmt = NULL;
   10303      2140204 :           if (code == MINUS_EXPR)
   10304       360559 :             code = PLUS_EXPR;
   10305      2140204 :           internal_fn reduc_fn;
   10306      2536774 :           if (!reduction_fn_for_scalar_code (code, &reduc_fn)
   10307      2140204 :               || reduc_fn == IFN_LAST)
   10308       396570 :             continue;
   10309      1743634 :           vect_slp_linearize_chain (bb_vinfo, worklist, chain, code, assign,
   10310              :                                     /* ??? */
   10311              :                                     code_stmt, alt_code_stmt, &chain_stmts,
   10312              :                                     false);
   10313      3487268 :           if (chain.length () > 1)
   10314              :             {
   10315              :               /* Sort the chain according to def_type and operation.  */
   10316      1743634 :               chain.sort (dt_sort_cmp, bb_vinfo);
   10317              :               /* ???  Now we'd want to strip externals and constants
   10318              :                  but record those to be handled in the epilogue.  */
   10319              :               /* ???  For now do not allow mixing ops or externs/constants.  */
   10320      1743634 :               bool invalid = false;
   10321      1743634 :               unsigned remain_cnt = 0;
   10322      7179900 :               for (unsigned i = 0; i < chain.length (); ++i)
   10323              :                 {
   10324      4053191 :                   if (chain[i].code != code)
   10325              :                     {
   10326              :                       invalid = true;
   10327              :                       break;
   10328              :                     }
   10329      3692632 :                   if (chain[i].dt != vect_internal_def
   10330              :                       /* Avoid stmts where the def is not the LHS, like
   10331              :                          ASMs.  */
   10332      7033895 :                       || (gimple_get_lhs (bb_vinfo->lookup_def
   10333      3341263 :                                                       (chain[i].op)->stmt)
   10334      3341263 :                           != chain[i].op))
   10335       354465 :                     remain_cnt++;
   10336              :                 }
   10337      1743634 :               if (!invalid && chain.length () - remain_cnt > 1)
   10338              :                 {
   10339      1298529 :                   vec<stmt_vec_info> stmts;
   10340      1298529 :                   vec<tree> remain = vNULL;
   10341      1298529 :                   stmts.create (chain.length ());
   10342      1298529 :                   if (remain_cnt > 0)
   10343        47561 :                     remain.create (remain_cnt);
   10344      4325325 :                   for (unsigned i = 0; i < chain.length (); ++i)
   10345              :                     {
   10346      3026796 :                       stmt_vec_info stmt_info;
   10347      3026796 :                       if (chain[i].dt == vect_internal_def
   10348      3026796 :                           && ((stmt_info = bb_vinfo->lookup_def (chain[i].op)),
   10349      2938411 :                               gimple_get_lhs (stmt_info->stmt) == chain[i].op))
   10350      2938195 :                         stmts.quick_push (stmt_info);
   10351              :                       else
   10352        88601 :                         remain.quick_push (chain[i].op);
   10353              :                     }
   10354      1298529 :                   vec<stmt_vec_info> roots;
   10355      1298529 :                   roots.create (chain_stmts.length ());
   10356      4325325 :                   for (unsigned i = 0; i < chain_stmts.length (); ++i)
   10357      1728267 :                     roots.quick_push (bb_vinfo->lookup_stmt (chain_stmts[i]));
   10358      1298529 :                   bb_vinfo->roots.safe_push (slp_root (slp_inst_kind_bb_reduc,
   10359      1298529 :                                                        stmts, roots, remain));
   10360              :                 }
   10361              :             }
   10362      2140204 :         }
   10363              :     }
   10364      2285514 : }
   10365              : 
   10366              : /* Walk the grouped store chains and replace entries with their
   10367              :    pattern variant if any.  */
   10368              : 
   10369              : static void
   10370       661181 : vect_fixup_store_groups_with_patterns (vec_info *vinfo)
   10371              : {
   10372       661181 :   stmt_vec_info first_element;
   10373       661181 :   unsigned i;
   10374              : 
   10375      1571388 :   FOR_EACH_VEC_ELT (vinfo->grouped_stores, i, first_element)
   10376              :     {
   10377              :       /* We also have CTORs in this array.  */
   10378       910207 :       if (!STMT_VINFO_GROUPED_ACCESS (first_element))
   10379            0 :         continue;
   10380       910207 :       if (STMT_VINFO_IN_PATTERN_P (first_element))
   10381              :         {
   10382          252 :           stmt_vec_info orig = first_element;
   10383          252 :           first_element = STMT_VINFO_RELATED_STMT (first_element);
   10384          252 :           DR_GROUP_FIRST_ELEMENT (first_element) = first_element;
   10385          252 :           DR_GROUP_SIZE (first_element) = DR_GROUP_SIZE (orig);
   10386          252 :           DR_GROUP_GAP (first_element) = DR_GROUP_GAP (orig);
   10387          252 :           DR_GROUP_NEXT_ELEMENT (first_element) = DR_GROUP_NEXT_ELEMENT (orig);
   10388          252 :           vinfo->grouped_stores[i] = first_element;
   10389              :         }
   10390       910207 :       stmt_vec_info prev = first_element;
   10391      2559177 :       while (DR_GROUP_NEXT_ELEMENT (prev))
   10392              :         {
   10393      1648970 :           stmt_vec_info elt = DR_GROUP_NEXT_ELEMENT (prev);
   10394      1648970 :           if (STMT_VINFO_IN_PATTERN_P (elt))
   10395              :             {
   10396          849 :               stmt_vec_info orig = elt;
   10397          849 :               elt = STMT_VINFO_RELATED_STMT (elt);
   10398          849 :               DR_GROUP_NEXT_ELEMENT (prev) = elt;
   10399          849 :               DR_GROUP_GAP (elt) = DR_GROUP_GAP (orig);
   10400          849 :               DR_GROUP_NEXT_ELEMENT (elt) = DR_GROUP_NEXT_ELEMENT (orig);
   10401              :             }
   10402      1648970 :           DR_GROUP_FIRST_ELEMENT (elt) = first_element;
   10403      1648970 :           prev = elt;
   10404              :         }
   10405              :     }
   10406       661181 : }
   10407              : 
   10408              : /* Check if the region described by BB_VINFO can be vectorized, returning
   10409              :    true if so.  When returning false, set FATAL to true if the same failure
   10410              :    would prevent vectorization at other vector sizes, false if it is still
   10411              :    worth trying other sizes.  N_STMTS is the number of statements in the
   10412              :    region.  */
   10413              : 
   10414              : static bool
   10415      2285514 : vect_slp_analyze_bb_1 (bb_vec_info bb_vinfo, int n_stmts, bool &fatal,
   10416              :                        vec<int> *dataref_groups)
   10417              : {
   10418      2285514 :   DUMP_VECT_SCOPE ("vect_slp_analyze_bb");
   10419              : 
   10420      2285514 :   slp_instance instance;
   10421      2285514 :   int i;
   10422              : 
   10423              :   /* The first group of checks is independent of the vector size.  */
   10424      2285514 :   fatal = true;
   10425              : 
   10426              :   /* Analyze the data references.  */
   10427              : 
   10428      2285514 :   if (!vect_analyze_data_refs (bb_vinfo, NULL))
   10429              :     {
   10430            0 :       if (dump_enabled_p ())
   10431            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10432              :                          "not vectorized: unhandled data-ref in basic "
   10433              :                          "block.\n");
   10434              :       return false;
   10435              :     }
   10436              : 
   10437      2285514 :   if (!vect_analyze_data_ref_accesses (bb_vinfo, dataref_groups))
   10438              :     {
   10439            0 :      if (dump_enabled_p ())
   10440            0 :        dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10441              :                         "not vectorized: unhandled data access in "
   10442              :                         "basic block.\n");
   10443              :       return false;
   10444              :     }
   10445              : 
   10446      2285514 :   vect_slp_check_for_roots (bb_vinfo);
   10447              : 
   10448              :   /* If there are no grouped stores and no constructors in the region
   10449              :      there is no need to continue with pattern recog as vect_analyze_slp
   10450              :      will fail anyway.  */
   10451      2285514 :   if (bb_vinfo->grouped_stores.is_empty ()
   10452      1935187 :       && bb_vinfo->roots.is_empty ())
   10453              :     {
   10454      1624333 :       if (dump_enabled_p ())
   10455         1020 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10456              :                          "not vectorized: no grouped stores in "
   10457              :                          "basic block.\n");
   10458              :       return false;
   10459              :     }
   10460              : 
   10461              :   /* While the rest of the analysis below depends on it in some way.  */
   10462       661181 :   fatal = false;
   10463              : 
   10464       661181 :   vect_pattern_recog (bb_vinfo);
   10465              : 
   10466              :   /* Update store groups from pattern processing.  */
   10467       661181 :   vect_fixup_store_groups_with_patterns (bb_vinfo);
   10468              : 
   10469              :   /* Check the SLP opportunities in the basic block, analyze and build SLP
   10470              :      trees.  */
   10471       661181 :   if (!vect_analyze_slp (bb_vinfo, n_stmts, false))
   10472              :     {
   10473            0 :       if (dump_enabled_p ())
   10474              :         {
   10475            0 :           dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10476              :                            "Failed to SLP the basic block.\n");
   10477            0 :           dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10478              :                            "not vectorized: failed to find SLP opportunities "
   10479              :                            "in basic block.\n");
   10480              :         }
   10481              :       return false;
   10482              :     }
   10483              : 
   10484              :   /* Optimize permutations.  */
   10485       661181 :   vect_optimize_slp (bb_vinfo);
   10486              : 
   10487              :   /* Gather the loads reachable from the SLP graph entries.  */
   10488       661181 :   vect_gather_slp_loads (bb_vinfo);
   10489              : 
   10490       661181 :   vect_record_base_alignments (bb_vinfo);
   10491              : 
   10492              :   /* Analyze and verify the alignment of data references and the
   10493              :      dependence in the SLP instances.  */
   10494      2152951 :   for (i = 0; BB_VINFO_SLP_INSTANCES (bb_vinfo).iterate (i, &instance); )
   10495              :     {
   10496       830589 :       vect_location = instance->location ();
   10497       830589 :       if (! vect_slp_analyze_instance_alignment (bb_vinfo, instance)
   10498       830589 :           || ! vect_slp_analyze_instance_dependence (bb_vinfo, instance))
   10499              :         {
   10500         8709 :           slp_tree node = SLP_INSTANCE_TREE (instance);
   10501         8709 :           stmt_vec_info stmt_info = SLP_TREE_SCALAR_STMTS (node)[0];
   10502         8709 :           if (dump_enabled_p ())
   10503            4 :             dump_printf_loc (MSG_NOTE, vect_location,
   10504              :                              "removing SLP instance operations starting from: %G",
   10505              :                              stmt_info->stmt);
   10506         8709 :           vect_free_slp_instance (instance);
   10507         8709 :           BB_VINFO_SLP_INSTANCES (bb_vinfo).ordered_remove (i);
   10508         8709 :           continue;
   10509         8709 :         }
   10510              : 
   10511              :       /* Mark all the statements that we want to vectorize as relevant.  */
   10512       821880 :       vect_mark_slp_stmts_relevant (SLP_INSTANCE_TREE (instance));
   10513              : 
   10514       821880 :       i++;
   10515              :     }
   10516      2564985 :   if (! BB_VINFO_SLP_INSTANCES (bb_vinfo).length ())
   10517              :     return false;
   10518              : 
   10519       279471 :   if (!vect_slp_analyze_operations (bb_vinfo))
   10520              :     {
   10521        32149 :       if (dump_enabled_p ())
   10522           73 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10523              :                          "not vectorized: bad operation in basic block.\n");
   10524              :       return false;
   10525              :     }
   10526              : 
   10527              :   /* Compute vector stmt placement.  */
   10528       247322 :   if (!vect_schedule_slp (bb_vinfo, BB_VINFO_SLP_INSTANCES (bb_vinfo), true))
   10529              :     {
   10530            0 :       if (dump_enabled_p ())
   10531            0 :         dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10532              :                          "not vectorized: cannot schedule SLP graph\n");
   10533              :       return false;
   10534              :     }
   10535              : 
   10536              :   /* Mark all the statements that we vectorize.  */
   10537       247322 :   vect_bb_slp_mark_stmts_vectorized (bb_vinfo);
   10538              : 
   10539              :   /* Compute vectorizable live stmts.  */
   10540       247322 :   vect_bb_slp_mark_live_stmts (bb_vinfo);
   10541              : 
   10542       247322 :   vect_bb_partition_graph (bb_vinfo);
   10543              : 
   10544       247322 :   return true;
   10545              : }
   10546              : 
   10547              : /* Subroutine of vect_slp_bb.  Try to vectorize the statements for all
   10548              :    basic blocks in BBS, returning true on success.
   10549              :    The region has N_STMTS statements and has the datarefs given by DATAREFS.  */
   10550              : 
   10551              : static bool
   10552      1934395 : vect_slp_region (vec<basic_block> bbs, vec<data_reference_p> datarefs,
   10553              :                  vec<int> *dataref_groups, unsigned int n_stmts,
   10554              :                  loop_p orig_loop)
   10555              : {
   10556      1934395 :   bb_vec_info bb_vinfo;
   10557      1934395 :   auto_vector_modes vector_modes;
   10558              : 
   10559              :   /* Autodetect first vector size we try.  */
   10560      1934395 :   machine_mode next_vector_mode = VOIDmode;
   10561      1934395 :   targetm.vectorize.autovectorize_vector_modes (&vector_modes, false);
   10562      1934395 :   unsigned int mode_i = 0;
   10563              : 
   10564      1934395 :   vec_info_shared shared;
   10565              : 
   10566      1934395 :   machine_mode autodetected_vector_mode = VOIDmode;
   10567      2636633 :   while (1)
   10568              :     {
   10569      2285514 :       bool vectorized = false;
   10570      2285514 :       bool fatal = false;
   10571      2285514 :       bb_vinfo = new _bb_vec_info (bbs, &shared);
   10572              : 
   10573      2285514 :       bool first_time_p = shared.datarefs.is_empty ();
   10574      2285514 :       BB_VINFO_DATAREFS (bb_vinfo) = datarefs;
   10575      2285514 :       if (first_time_p)
   10576      1958803 :         bb_vinfo->shared->save_datarefs ();
   10577              :       else
   10578       326711 :         bb_vinfo->shared->check_datarefs ();
   10579      2285514 :       bb_vinfo->vector_mode = next_vector_mode;
   10580              : 
   10581      2285514 :       if (vect_slp_analyze_bb_1 (bb_vinfo, n_stmts, fatal, dataref_groups))
   10582              :         {
   10583       247322 :           if (dump_enabled_p ())
   10584              :             {
   10585         1664 :               dump_printf_loc (MSG_NOTE, vect_location,
   10586              :                                "***** Analysis succeeded with vector mode"
   10587          832 :                                " %s\n", GET_MODE_NAME (bb_vinfo->vector_mode));
   10588          832 :               dump_printf_loc (MSG_NOTE, vect_location, "SLPing BB part\n");
   10589              :             }
   10590              : 
   10591       247322 :           bb_vinfo->shared->check_datarefs ();
   10592              : 
   10593       247322 :           bool force_clear = false;
   10594       247322 :           auto_vec<slp_instance> profitable_subgraphs;
   10595      1459476 :           for (slp_instance instance : BB_VINFO_SLP_INSTANCES (bb_vinfo))
   10596              :             {
   10597       717510 :               if (instance->subgraph_entries.is_empty ())
   10598       222675 :                 continue;
   10599              : 
   10600       690562 :               dump_user_location_t saved_vect_location = vect_location;
   10601       690562 :               vect_location = instance->location ();
   10602       690562 :               if (!unlimited_cost_model (NULL)
   10603       686688 :                   && !param_vect_allow_possibly_not_worthwhile_vectorizations
   10604      1377241 :                   && !vect_bb_vectorization_profitable_p
   10605       686679 :                         (bb_vinfo, instance->subgraph_entries, orig_loop))
   10606              :                 {
   10607       195727 :                   if (dump_enabled_p ())
   10608           51 :                     dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10609              :                                      "not vectorized: vectorization is not "
   10610              :                                      "profitable.\n");
   10611       195727 :                   vect_location = saved_vect_location;
   10612       195727 :                   continue;
   10613              :                 }
   10614              : 
   10615       494835 :               vect_location = saved_vect_location;
   10616       494835 :               if (!dbg_cnt (vect_slp))
   10617              :                 {
   10618            0 :                   force_clear = true;
   10619            0 :                   continue;
   10620              :                 }
   10621              : 
   10622       494835 :               profitable_subgraphs.safe_push (instance);
   10623              :             }
   10624              : 
   10625              :           /* When we're vectorizing an if-converted loop body make sure
   10626              :              we vectorized all if-converted code.  */
   10627       411863 :           if ((!profitable_subgraphs.is_empty () || force_clear) && orig_loop)
   10628              :             {
   10629          159 :               gcc_assert (bb_vinfo->nbbs == 1);
   10630          318 :               for (gimple_stmt_iterator gsi = gsi_start_bb (bb_vinfo->bbs[0]);
   10631         6235 :                    !gsi_end_p (gsi); gsi_next (&gsi))
   10632              :                 {
   10633              :                   /* The costing above left us with DCEable vectorized scalar
   10634              :                      stmts having the visited flag set on profitable
   10635              :                      subgraphs.  Do the delayed clearing of the flag here.  */
   10636         6076 :                   if (gimple_visited_p (gsi_stmt (gsi)))
   10637              :                     {
   10638         1936 :                       gimple_set_visited (gsi_stmt (gsi), false);
   10639         1936 :                       continue;
   10640              :                     }
   10641         4140 :                   if (flag_vect_cost_model == VECT_COST_MODEL_UNLIMITED)
   10642          813 :                     continue;
   10643              : 
   10644         9115 :                   if (gassign *ass = dyn_cast <gassign *> (gsi_stmt (gsi)))
   10645         3773 :                     if (gimple_assign_rhs_code (ass) == COND_EXPR)
   10646              :                       {
   10647          175 :                         if (!profitable_subgraphs.is_empty ()
   10648           74 :                             && dump_enabled_p ())
   10649            0 :                           dump_printf_loc (MSG_NOTE, vect_location,
   10650              :                                            "not profitable because of "
   10651              :                                            "unprofitable if-converted scalar "
   10652              :                                            "code\n");
   10653          101 :                         profitable_subgraphs.truncate (0);
   10654              :                       }
   10655              :                 }
   10656              :             }
   10657              : 
   10658              :           /* Finally schedule the profitable subgraphs.  */
   10659      1071146 :           for (slp_instance instance : profitable_subgraphs)
   10660              :             {
   10661       494742 :               if (!vectorized && dump_enabled_p ())
   10662          793 :                 dump_printf_loc (MSG_NOTE, vect_location,
   10663              :                                  "Basic block will be vectorized "
   10664              :                                  "using SLP\n");
   10665       494742 :               vectorized = true;
   10666              : 
   10667              :               /* Dump before scheduling as store vectorization will remove
   10668              :                  the original stores and mess with the instance tree
   10669              :                  so querying its location will eventually ICE.  */
   10670       494742 :               if (flag_checking)
   10671      1991206 :                 for (slp_instance sub : instance->subgraph_entries)
   10672       506980 :                   gcc_assert (SLP_TREE_VECTYPE (SLP_INSTANCE_TREE (sub)));
   10673       494742 :               unsigned HOST_WIDE_INT bytes;
   10674       494742 :               if (dump_enabled_p ())
   10675         3853 :                 for (slp_instance sub : instance->subgraph_entries)
   10676              :                   {
   10677         1036 :                     tree vtype = SLP_TREE_VECTYPE (SLP_INSTANCE_TREE (sub));
   10678         2072 :                     if (GET_MODE_SIZE (TYPE_MODE (vtype)).is_constant (&bytes))
   10679         1036 :                       dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
   10680         1036 :                                        sub->location (),
   10681              :                                        "basic block part vectorized using %wu "
   10682              :                                        "byte vectors\n", bytes);
   10683              :                     else
   10684              :                       dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
   10685              :                                        sub->location (),
   10686              :                                        "basic block part vectorized using "
   10687              :                                        "variable length vectors\n");
   10688              :                   }
   10689              : 
   10690       494742 :               dump_user_location_t saved_vect_location = vect_location;
   10691       494742 :               vect_location = instance->location ();
   10692              : 
   10693       494742 :               vect_schedule_slp (bb_vinfo, instance->subgraph_entries, false);
   10694              : 
   10695       494742 :               vect_location = saved_vect_location;
   10696              :             }
   10697              : 
   10698              :           /* Generate the invariant statements.  */
   10699       247322 :           if (!gimple_seq_empty_p (bb_vinfo->inv_pattern_def_seq))
   10700              :             {
   10701           27 :               if (dump_enabled_p ())
   10702            0 :                 dump_printf_loc (MSG_NOTE, vect_location,
   10703              :                          "------>generating invariant statements\n");
   10704              : 
   10705           27 :               bb_vinfo->insert_seq_on_entry (NULL,
   10706              :                                              bb_vinfo->inv_pattern_def_seq);
   10707              :             }
   10708       247322 :         }
   10709              :       else
   10710              :         {
   10711      2038192 :           if (dump_enabled_p ())
   10712         1327 :             dump_printf_loc (MSG_NOTE, vect_location,
   10713              :                              "***** Analysis failed with vector mode %s\n",
   10714         1327 :                              GET_MODE_NAME (bb_vinfo->vector_mode));
   10715              :         }
   10716              : 
   10717      2285514 :       if (mode_i == 0)
   10718      1934395 :         autodetected_vector_mode = bb_vinfo->vector_mode;
   10719              : 
   10720      2285514 :       if (!fatal)
   10721      3302517 :         while (mode_i < vector_modes.length ()
   10722      1888361 :                && vect_chooses_same_modes_p (bb_vinfo, vector_modes[mode_i]))
   10723              :           {
   10724       355822 :             if (dump_enabled_p ())
   10725         1804 :               dump_printf_loc (MSG_NOTE, vect_location,
   10726              :                                "***** The result for vector mode %s would"
   10727              :                                " be the same\n",
   10728          902 :                                GET_MODE_NAME (vector_modes[mode_i]));
   10729       355822 :             mode_i += 1;
   10730              :           }
   10731              : 
   10732      2285514 :       delete bb_vinfo;
   10733              : 
   10734      2285514 :       if (mode_i < vector_modes.length ()
   10735      2092682 :           && VECTOR_MODE_P (autodetected_vector_mode)
   10736      2082764 :           && (related_vector_mode (vector_modes[mode_i],
   10737              :                                    GET_MODE_INNER (autodetected_vector_mode))
   10738      1041382 :               == autodetected_vector_mode)
   10739      4378196 :           && (related_vector_mode (autodetected_vector_mode,
   10740       525699 :                                    GET_MODE_INNER (vector_modes[mode_i]))
   10741      1051398 :               == vector_modes[mode_i]))
   10742              :         {
   10743       525699 :           if (dump_enabled_p ())
   10744          201 :             dump_printf_loc (MSG_NOTE, vect_location,
   10745              :                              "***** Skipping vector mode %s, which would"
   10746              :                              " repeat the analysis for %s\n",
   10747          201 :                              GET_MODE_NAME (vector_modes[mode_i]),
   10748          201 :                              GET_MODE_NAME (autodetected_vector_mode));
   10749       525699 :           mode_i += 1;
   10750              :         }
   10751              : 
   10752      2285514 :       if (vectorized
   10753      2121047 :           || mode_i == vector_modes.length ()
   10754      1928265 :           || autodetected_vector_mode == VOIDmode
   10755              :           /* If vect_slp_analyze_bb_1 signaled that analysis for all
   10756              :              vector sizes will fail do not bother iterating.  */
   10757      3162479 :           || fatal)
   10758      3868790 :         return vectorized;
   10759              : 
   10760              :       /* Try the next biggest vector size.  */
   10761       351119 :       next_vector_mode = vector_modes[mode_i++];
   10762       351119 :       if (dump_enabled_p ())
   10763          239 :         dump_printf_loc (MSG_NOTE, vect_location,
   10764              :                          "***** Re-trying analysis with vector mode %s\n",
   10765          239 :                          GET_MODE_NAME (next_vector_mode));
   10766       351119 :     }
   10767      1934395 : }
   10768              : 
   10769              : 
   10770              : /* Main entry for the BB vectorizer.  Analyze and transform BBS, returns
   10771              :    true if anything in the basic-block was vectorized.  */
   10772              : 
   10773              : static bool
   10774      1934395 : vect_slp_bbs (const vec<basic_block> &bbs, loop_p orig_loop)
   10775              : {
   10776      1934395 :   vec<data_reference_p> datarefs = vNULL;
   10777      1934395 :   auto_vec<int> dataref_groups;
   10778      1934395 :   int insns = 0;
   10779      1934395 :   int current_group = 0;
   10780              : 
   10781     12827877 :   for (unsigned i = 0; i < bbs.length (); i++)
   10782              :     {
   10783     10893482 :       basic_block bb = bbs[i];
   10784     95539218 :       for (gimple_stmt_iterator gsi = gsi_after_labels (bb); !gsi_end_p (gsi);
   10785     84645736 :            gsi_next (&gsi))
   10786              :         {
   10787     84645736 :           gimple *stmt = gsi_stmt (gsi);
   10788     84645736 :           if (is_gimple_debug (stmt))
   10789     53907894 :             continue;
   10790              : 
   10791     30737842 :           insns++;
   10792              : 
   10793     30737842 :           if (gimple_location (stmt) != UNKNOWN_LOCATION)
   10794     27574763 :             vect_location = stmt;
   10795              : 
   10796     30737842 :           if (!vect_find_stmt_data_reference (NULL, stmt, &datarefs,
   10797              :                                               &dataref_groups, current_group))
   10798      5242328 :             ++current_group;
   10799              :         }
   10800              :       /* New BBs always start a new DR group.  */
   10801     10893482 :       ++current_group;
   10802              :     }
   10803              : 
   10804      1934395 :   return vect_slp_region (bbs, datarefs, &dataref_groups, insns, orig_loop);
   10805      1934395 : }
   10806              : 
   10807              : /* Special entry for the BB vectorizer.  Analyze and transform a single
   10808              :    if-converted BB with ORIG_LOOPs body being the not if-converted
   10809              :    representation.  Returns true if anything in the basic-block was
   10810              :    vectorized.  */
   10811              : 
   10812              : bool
   10813        16800 : vect_slp_if_converted_bb (basic_block bb, loop_p orig_loop)
   10814              : {
   10815        16800 :   auto_vec<basic_block> bbs;
   10816        16800 :   bbs.safe_push (bb);
   10817        16800 :   return vect_slp_bbs (bbs, orig_loop);
   10818        16800 : }
   10819              : 
   10820              : /* Main entry for the BB vectorizer.  Analyze and transform BB, returns
   10821              :    true if anything in the basic-block was vectorized.  */
   10822              : 
   10823              : bool
   10824       927011 : vect_slp_function (function *fun)
   10825              : {
   10826       927011 :   bool r = false;
   10827       927011 :   int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (fun));
   10828       927011 :   auto_bitmap exit_bbs;
   10829       927011 :   bitmap_set_bit (exit_bbs, EXIT_BLOCK);
   10830       927011 :   edge entry = single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (fun));
   10831       927011 :   unsigned n = rev_post_order_and_mark_dfs_back_seme (fun, entry, exit_bbs,
   10832       927011 :                                                       true, rpo, NULL);
   10833              : 
   10834              :   /* For the moment split the function into pieces to avoid making
   10835              :      the iteration on the vector mode moot.  Split at points we know
   10836              :      to not handle well which is CFG merges (SLP discovery doesn't
   10837              :      handle non-loop-header PHIs) and loop exits.  Since pattern
   10838              :      recog requires reverse iteration to visit uses before defs
   10839              :      simply chop RPO into pieces.  */
   10840       927011 :   auto_vec<basic_block> bbs;
   10841     11830266 :   for (unsigned i = 0; i < n; i++)
   10842              :     {
   10843     10903255 :       basic_block bb = BASIC_BLOCK_FOR_FN (fun, rpo[i]);
   10844     10903255 :       bool split = false;
   10845              : 
   10846              :       /* Split when a BB is not dominated by the first block.  */
   10847     20569038 :       if (!bbs.is_empty ()
   10848      9665783 :           && !dominated_by_p (CDI_DOMINATORS, bb, bbs[0]))
   10849              :         {
   10850       696625 :           if (dump_enabled_p ())
   10851          146 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10852              :                              "splitting region at dominance boundary bb%d\n",
   10853              :                              bb->index);
   10854              :           split = true;
   10855              :         }
   10856              :       /* Split when the loop determined by the first block
   10857              :          is exited.  This is because we eventually insert
   10858              :          invariants at region begin.  */
   10859     19175788 :       else if (!bbs.is_empty ()
   10860      8969158 :                && bbs[0]->loop_father != bb->loop_father
   10861      2322007 :                && !flow_loop_nested_p (bbs[0]->loop_father, bb->loop_father))
   10862              :         {
   10863         3859 :           if (dump_enabled_p ())
   10864            3 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10865              :                              "splitting region at loop %d exit at bb%d\n",
   10866            3 :                              bbs[0]->loop_father->num, bb->index);
   10867              :           split = true;
   10868              :         }
   10869     10202771 :       else if (!bbs.is_empty ()
   10870      8965299 :                && bb->loop_father->header == bb
   10871       476740 :                && bb->loop_father->dont_vectorize)
   10872              :         {
   10873         6212 :           if (dump_enabled_p ())
   10874           72 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10875              :                              "splitting region at dont-vectorize loop %d "
   10876              :                              "entry at bb%d\n",
   10877              :                              bb->loop_father->num, bb->index);
   10878              :           split = true;
   10879              :         }
   10880              : 
   10881          221 :       if (split && !bbs.is_empty ())
   10882              :         {
   10883       706696 :           r |= vect_slp_bbs (bbs, NULL);
   10884       706696 :           bbs.truncate (0);
   10885              :         }
   10886              : 
   10887     10903255 :       if (bbs.is_empty ())
   10888              :         {
   10889              :           /* We need to be able to insert at the head of the region which
   10890              :              we cannot for region starting with a returns-twice call.  */
   10891      1944168 :           if (gcall *first = safe_dyn_cast <gcall *> (first_stmt (bb)))
   10892       409668 :             if (gimple_call_flags (first) & ECF_RETURNS_TWICE)
   10893              :               {
   10894          306 :                 if (dump_enabled_p ())
   10895            2 :                   dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10896              :                                    "skipping bb%d as start of region as it "
   10897              :                                    "starts with returns-twice call\n",
   10898              :                                    bb->index);
   10899        26573 :                 continue;
   10900              :               }
   10901              :           /* If the loop this BB belongs to is marked as not to be vectorized
   10902              :              honor that also for BB vectorization.  */
   10903      1943862 :           if (bb->loop_father->dont_vectorize)
   10904        26267 :             continue;
   10905              :         }
   10906              : 
   10907     10876682 :       bbs.safe_push (bb);
   10908              : 
   10909              :       /* When we have a stmt ending this block and defining a
   10910              :          value we have to insert on edges when inserting after it for
   10911              :          a vector containing its definition.  Avoid this for now.  */
   10912     21753364 :       if (gimple *last = *gsi_last_bb (bb))
   10913      8852161 :         if (gimple_get_lhs (last)
   10914      8852161 :             && is_ctrl_altering_stmt (last))
   10915              :           {
   10916       283895 :             if (dump_enabled_p ())
   10917            2 :               dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   10918              :                                "splitting region at control altering "
   10919              :                                "definition %G", last);
   10920       283895 :             r |= vect_slp_bbs (bbs, NULL);
   10921       283895 :             bbs.truncate (0);
   10922              :           }
   10923              :     }
   10924              : 
   10925       927011 :   if (!bbs.is_empty ())
   10926       927004 :     r |= vect_slp_bbs (bbs, NULL);
   10927              : 
   10928       927011 :   free (rpo);
   10929              : 
   10930       927011 :   return r;
   10931       927011 : }
   10932              : 
   10933              : /* Build a variable-length vector in which the elements in ELTS are repeated
   10934              :    to a fill NRESULTS vectors of type VECTOR_TYPE.  Store the vectors in
   10935              :    RESULTS and add any new instructions to SEQ.
   10936              : 
   10937              :    The approach we use is:
   10938              : 
   10939              :    (1) Find a vector mode VM with integer elements of mode IM.
   10940              : 
   10941              :    (2) Replace ELTS[0:NELTS] with ELTS'[0:NELTS'], where each element of
   10942              :        ELTS' has mode IM.  This involves creating NELTS' VIEW_CONVERT_EXPRs
   10943              :        from small vectors to IM.
   10944              : 
   10945              :    (3) Duplicate each ELTS'[I] into a vector of mode VM.
   10946              : 
   10947              :    (4) Use a tree of interleaving VEC_PERM_EXPRs to create VMs with the
   10948              :        correct byte contents.
   10949              : 
   10950              :    (5) Use VIEW_CONVERT_EXPR to cast the final VMs to the required type.
   10951              : 
   10952              :    We try to find the largest IM for which this sequence works, in order
   10953              :    to cut down on the number of interleaves.  */
   10954              : 
   10955              : void
   10956            0 : duplicate_and_interleave (vec_info *vinfo, gimple_seq *seq, tree vector_type,
   10957              :                           const vec<tree> &elts, unsigned int nresults,
   10958              :                           vec<tree> &results)
   10959              : {
   10960            0 :   unsigned int nelts = elts.length ();
   10961            0 :   tree element_type = TREE_TYPE (vector_type);
   10962              : 
   10963              :   /* (1) Find a vector mode VM with integer elements of mode IM.  */
   10964            0 :   unsigned int nvectors = 1;
   10965            0 :   tree new_vector_type;
   10966            0 :   tree permutes[2];
   10967            0 :   if (!can_duplicate_and_interleave_p (vinfo, nelts, element_type,
   10968              :                                        &nvectors, &new_vector_type,
   10969              :                                        permutes))
   10970            0 :     gcc_unreachable ();
   10971              : 
   10972              :   /* Get a vector type that holds ELTS[0:NELTS/NELTS'].  */
   10973            0 :   unsigned int partial_nelts = nelts / nvectors;
   10974            0 :   tree partial_vector_type = build_vector_type (element_type, partial_nelts);
   10975              : 
   10976            0 :   tree_vector_builder partial_elts;
   10977            0 :   auto_vec<tree, 32> pieces (nvectors * 2);
   10978            0 :   pieces.quick_grow_cleared (nvectors * 2);
   10979            0 :   for (unsigned int i = 0; i < nvectors; ++i)
   10980              :     {
   10981              :       /* (2) Replace ELTS[0:NELTS] with ELTS'[0:NELTS'], where each element of
   10982              :              ELTS' has mode IM.  */
   10983            0 :       partial_elts.new_vector (partial_vector_type, partial_nelts, 1);
   10984            0 :       for (unsigned int j = 0; j < partial_nelts; ++j)
   10985            0 :         partial_elts.quick_push (elts[i * partial_nelts + j]);
   10986            0 :       tree t = gimple_build_vector (seq, &partial_elts);
   10987            0 :       t = gimple_build (seq, VIEW_CONVERT_EXPR,
   10988            0 :                         TREE_TYPE (new_vector_type), t);
   10989              : 
   10990              :       /* (3) Duplicate each ELTS'[I] into a vector of mode VM.  */
   10991            0 :       pieces[i] = gimple_build_vector_from_val (seq, new_vector_type, t);
   10992              :     }
   10993              : 
   10994              :   /* (4) Use a tree of VEC_PERM_EXPRs to create a single VM with the
   10995              :          correct byte contents.
   10996              : 
   10997              :      Conceptually, we need to repeat the following operation log2(nvectors)
   10998              :      times, where hi_start = nvectors / 2:
   10999              : 
   11000              :         out[i * 2] = VEC_PERM_EXPR (in[i], in[i + hi_start], lo_permute);
   11001              :         out[i * 2 + 1] = VEC_PERM_EXPR (in[i], in[i + hi_start], hi_permute);
   11002              : 
   11003              :      However, if each input repeats every N elements and the VF is
   11004              :      a multiple of N * 2, the HI result is the same as the LO result.
   11005              :      This will be true for the first N1 iterations of the outer loop,
   11006              :      followed by N2 iterations for which both the LO and HI results
   11007              :      are needed.  I.e.:
   11008              : 
   11009              :         N1 + N2 = log2(nvectors)
   11010              : 
   11011              :      Each "N1 iteration" doubles the number of redundant vectors and the
   11012              :      effect of the process as a whole is to have a sequence of nvectors/2**N1
   11013              :      vectors that repeats 2**N1 times.  Rather than generate these redundant
   11014              :      vectors, we halve the number of vectors for each N1 iteration.  */
   11015              :   unsigned int in_start = 0;
   11016              :   unsigned int out_start = nvectors;
   11017              :   unsigned int new_nvectors = nvectors;
   11018            0 :   for (unsigned int in_repeat = 1; in_repeat < nvectors; in_repeat *= 2)
   11019              :     {
   11020            0 :       unsigned int hi_start = new_nvectors / 2;
   11021            0 :       unsigned int out_i = 0;
   11022            0 :       for (unsigned int in_i = 0; in_i < new_nvectors; ++in_i)
   11023              :         {
   11024            0 :           if ((in_i & 1) != 0
   11025            0 :               && multiple_p (TYPE_VECTOR_SUBPARTS (new_vector_type),
   11026              :                              2 * in_repeat))
   11027            0 :             continue;
   11028              : 
   11029            0 :           tree output = make_ssa_name (new_vector_type);
   11030            0 :           tree input1 = pieces[in_start + (in_i / 2)];
   11031            0 :           tree input2 = pieces[in_start + (in_i / 2) + hi_start];
   11032            0 :           gassign *stmt = gimple_build_assign (output, VEC_PERM_EXPR,
   11033              :                                                input1, input2,
   11034              :                                                permutes[in_i & 1]);
   11035            0 :           gimple_seq_add_stmt (seq, stmt);
   11036            0 :           pieces[out_start + out_i] = output;
   11037            0 :           out_i += 1;
   11038              :         }
   11039            0 :       std::swap (in_start, out_start);
   11040            0 :       new_nvectors = out_i;
   11041              :     }
   11042              : 
   11043              :   /* (5) Use VIEW_CONVERT_EXPR to cast the final VM to the required type.  */
   11044            0 :   results.reserve (nresults);
   11045            0 :   for (unsigned int i = 0; i < nresults; ++i)
   11046            0 :     if (i < new_nvectors)
   11047            0 :       results.quick_push (gimple_build (seq, VIEW_CONVERT_EXPR, vector_type,
   11048            0 :                                         pieces[in_start + i]));
   11049              :     else
   11050            0 :       results.quick_push (results[i - new_nvectors]);
   11051            0 : }
   11052              : 
   11053              : 
   11054              : /* For constant and loop invariant defs in OP_NODE this function creates
   11055              :    vector defs that will be used in the vectorized stmts and stores them
   11056              :    to SLP_TREE_VEC_DEFS of OP_NODE.  */
   11057              : 
   11058              : static void
   11059       502381 : vect_create_constant_vectors (vec_info *vinfo, slp_tree op_node)
   11060              : {
   11061       502381 :   unsigned HOST_WIDE_INT nunits;
   11062       502381 :   tree vec_cst;
   11063       502381 :   unsigned j, number_of_places_left_in_vector;
   11064       502381 :   tree vector_type;
   11065       502381 :   tree vop;
   11066       502381 :   int group_size = op_node->ops.length ();
   11067       502381 :   unsigned int vec_num, i;
   11068       502381 :   unsigned number_of_copies = 1;
   11069       502381 :   bool constant_p;
   11070       502381 :   gimple_seq ctor_seq = NULL;
   11071       502381 :   auto_vec<tree, 16> permute_results;
   11072              : 
   11073              :   /* We always want SLP_TREE_VECTYPE (op_node) here correctly set.  */
   11074       502381 :   vector_type = SLP_TREE_VECTYPE (op_node);
   11075              : 
   11076       502381 :   unsigned int number_of_vectors, excess_elts;
   11077       502381 :   bool res = vect_get_num_copies_for_invariant (vinfo, op_node,
   11078              :                                                 &number_of_vectors,
   11079              :                                                 &excess_elts);
   11080       502381 :   gcc_assert (res);
   11081       502381 :   SLP_TREE_VEC_DEFS (op_node).create (number_of_vectors);
   11082       502381 :   auto_vec<tree> voprnds (number_of_vectors);
   11083              : 
   11084              :   /* NUMBER_OF_COPIES is the number of times we need to use the same values in
   11085              :      created vectors. It is greater than 1 if unrolling is performed.
   11086              : 
   11087              :      For example, we have two scalar operands, s1 and s2 (e.g., group of
   11088              :      strided accesses of size two), while NUNITS is four (i.e., four scalars
   11089              :      of this type can be packed in a vector).  The output vector will contain
   11090              :      two copies of each scalar operand: {s1, s2, s1, s2}.  (NUMBER_OF_COPIES
   11091              :      will be 2).
   11092              : 
   11093              :      If GROUP_SIZE > NUNITS, the scalars will be split into several vectors
   11094              :      containing the operands.
   11095              : 
   11096              :      For example, NUNITS is four as before, and the group size is 8
   11097              :      (s1, s2, ..., s8).  We will create two vectors {s1, s2, s3, s4} and
   11098              :      {s5, s6, s7, s8}.  */
   11099              : 
   11100              :   /* When using duplicate_and_interleave, we just need one element for
   11101              :      each scalar statement.  */
   11102       502381 :   if (!TYPE_VECTOR_SUBPARTS (vector_type).is_constant (&nunits))
   11103              :     nunits = group_size;
   11104              : 
   11105       502381 :   number_of_copies = (nunits * number_of_vectors - excess_elts) / group_size;
   11106              : 
   11107       502381 :   constant_p = true;
   11108       502381 :   tree uniform_elt = NULL_TREE;
   11109       502381 :   tree_vector_builder elts (vector_type, nunits, 1);
   11110       502381 :   elts.quick_grow (nunits);
   11111              :   /* Zero-pad the last vector if necessary.  */
   11112       502381 :   number_of_places_left_in_vector = nunits - excess_elts;
   11113       502639 :   for (i = nunits; i > number_of_places_left_in_vector; --i)
   11114          258 :     elts[i-1] = build_zero_cst (TREE_TYPE (vector_type));
   11115              :   stmt_vec_info insert_after = NULL;
   11116      1489423 :   for (j = 0; j < number_of_copies; j++)
   11117              :     {
   11118       987042 :       tree op;
   11119      3794428 :       for (i = group_size - 1; op_node->ops.iterate (i, &op); i--)
   11120              :         {
   11121              :           /* Create 'vect_ = {op0,op1,...,opn}'.  */
   11122      1820344 :           tree orig_op = op;
   11123      1820344 :           if (number_of_places_left_in_vector == nunits)
   11124              :             uniform_elt = op;
   11125      1184866 :           else if (uniform_elt && operand_equal_p (uniform_elt, op))
   11126       749217 :             op = elts[number_of_places_left_in_vector];
   11127              :           else
   11128              :             uniform_elt = NULL_TREE;
   11129      1820344 :           number_of_places_left_in_vector--;
   11130      1820344 :           if (!types_compatible_p (TREE_TYPE (vector_type), TREE_TYPE (op)))
   11131              :             {
   11132       283395 :               if (CONSTANT_CLASS_P (op))
   11133              :                 {
   11134       102452 :                   if (VECTOR_BOOLEAN_TYPE_P (vector_type))
   11135              :                     {
   11136              :                       /* Can't use VIEW_CONVERT_EXPR for booleans because
   11137              :                          of possibly different sizes of scalar value and
   11138              :                          vector element.  */
   11139           66 :                       if (integer_zerop (op))
   11140           66 :                         op = build_int_cst (TREE_TYPE (vector_type), 0);
   11141            0 :                       else if (integer_onep (op))
   11142            0 :                         op = build_all_ones_cst (TREE_TYPE (vector_type));
   11143              :                       else
   11144            0 :                         gcc_unreachable ();
   11145              :                     }
   11146              :                   else
   11147       102386 :                     op = fold_unary (VIEW_CONVERT_EXPR,
   11148              :                                      TREE_TYPE (vector_type), op);
   11149       102452 :                   gcc_assert (op && CONSTANT_CLASS_P (op));
   11150              :                 }
   11151              :               else
   11152              :                 {
   11153       180943 :                   tree new_temp = make_ssa_name (TREE_TYPE (vector_type));
   11154       180943 :                   gimple *init_stmt;
   11155       180943 :                   if (VECTOR_BOOLEAN_TYPE_P (vector_type))
   11156              :                     {
   11157          427 :                       tree true_val
   11158          427 :                         = build_all_ones_cst (TREE_TYPE (vector_type));
   11159          427 :                       tree false_val
   11160          427 :                         = build_zero_cst (TREE_TYPE (vector_type));
   11161          427 :                       gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (op)));
   11162          427 :                       init_stmt = gimple_build_assign (new_temp, COND_EXPR,
   11163              :                                                        op, true_val,
   11164              :                                                        false_val);
   11165              :                     }
   11166              :                   else
   11167              :                     {
   11168       180516 :                       op = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (vector_type),
   11169              :                                    op);
   11170       180516 :                       init_stmt
   11171       180516 :                         = gimple_build_assign (new_temp, VIEW_CONVERT_EXPR,
   11172              :                                                op);
   11173              :                     }
   11174       180943 :                   gimple_seq_add_stmt (&ctor_seq, init_stmt);
   11175       180943 :                   op = new_temp;
   11176              :                 }
   11177              :             }
   11178      1820344 :           elts[number_of_places_left_in_vector] = op;
   11179      1820344 :           if (!CONSTANT_CLASS_P (op))
   11180       326988 :             constant_p = false;
   11181              :           /* For BB vectorization we have to compute an insert location
   11182              :              when a def is inside the analyzed region since we cannot
   11183              :              simply insert at the BB start in this case.  */
   11184      1820344 :           stmt_vec_info opdef;
   11185      1820344 :           if (TREE_CODE (orig_op) == SSA_NAME
   11186       189348 :               && !SSA_NAME_IS_DEFAULT_DEF (orig_op)
   11187       168990 :               && is_a <bb_vec_info> (vinfo)
   11188      1931555 :               && (opdef = vinfo->lookup_def (orig_op)))
   11189              :             {
   11190        91030 :               if (!insert_after)
   11191              :                 insert_after = opdef;
   11192              :               else
   11193        49939 :                 insert_after = get_later_stmt (insert_after, opdef);
   11194              :             }
   11195              : 
   11196      1820344 :           if (number_of_places_left_in_vector == 0)
   11197              :             {
   11198       635507 :               auto type_nunits = TYPE_VECTOR_SUBPARTS (vector_type);
   11199       635507 :               if (uniform_elt)
   11200       657920 :                 vec_cst = gimple_build_vector_from_val (&ctor_seq, vector_type,
   11201       328960 :                                                         elts[0]);
   11202       613094 :               else if (constant_p
   11203       613094 :                        ? multiple_p (type_nunits, nunits)
   11204       113958 :                        : known_eq (type_nunits, nunits))
   11205       306547 :                 vec_cst = gimple_build_vector (&ctor_seq, &elts);
   11206              :               else
   11207              :                 {
   11208            0 :                   if (permute_results.is_empty ())
   11209            0 :                     duplicate_and_interleave (vinfo, &ctor_seq, vector_type,
   11210              :                                               elts, number_of_vectors,
   11211              :                                               permute_results);
   11212            0 :                   vec_cst = permute_results[number_of_vectors - j - 1];
   11213              :                 }
   11214       635507 :               if (!gimple_seq_empty_p (ctor_seq))
   11215              :                 {
   11216       141908 :                   if (insert_after)
   11217              :                     {
   11218        41091 :                       gimple_stmt_iterator gsi;
   11219        41091 :                       if (gimple_code (insert_after->stmt) == GIMPLE_PHI)
   11220              :                         {
   11221          763 :                           gsi = gsi_after_labels (gimple_bb (insert_after->stmt));
   11222          763 :                           gsi_insert_seq_before (&gsi, ctor_seq,
   11223              :                                                  GSI_CONTINUE_LINKING);
   11224              :                         }
   11225        40328 :                       else if (!stmt_ends_bb_p (insert_after->stmt))
   11226              :                         {
   11227        40328 :                           gsi = gsi_for_stmt (insert_after->stmt);
   11228        40328 :                           gsi_insert_seq_after (&gsi, ctor_seq,
   11229              :                                                 GSI_CONTINUE_LINKING);
   11230              :                         }
   11231              :                       else
   11232              :                         {
   11233              :                           /* When we want to insert after a def where the
   11234              :                              defining stmt throws then insert on the fallthru
   11235              :                              edge.  */
   11236            0 :                           edge e = find_fallthru_edge
   11237            0 :                                      (gimple_bb (insert_after->stmt)->succs);
   11238            0 :                           basic_block new_bb
   11239            0 :                             = gsi_insert_seq_on_edge_immediate (e, ctor_seq);
   11240            0 :                           gcc_assert (!new_bb);
   11241              :                         }
   11242              :                     }
   11243              :                   else
   11244       100817 :                     vinfo->insert_seq_on_entry (NULL, ctor_seq);
   11245       141908 :                   ctor_seq = NULL;
   11246              :                 }
   11247       635507 :               voprnds.quick_push (vec_cst);
   11248       635507 :               insert_after = NULL;
   11249       635507 :               number_of_places_left_in_vector = nunits;
   11250       635507 :               constant_p = true;
   11251       635507 :               elts.new_vector (vector_type, nunits, 1);
   11252       635507 :               elts.quick_grow (nunits);
   11253              :             }
   11254              :         }
   11255              :     }
   11256              : 
   11257       502381 :   gcc_assert (number_of_places_left_in_vector == nunits);
   11258              : 
   11259              :   /* Since the vectors are created in the reverse order, we should invert
   11260              :      them.  */
   11261       502381 :   vec_num = voprnds.length ();
   11262       502381 :   gcc_checking_assert (vec_num > 0);
   11263              : 
   11264      1137888 :   for (j = vec_num; j != 0; j--)
   11265              :     {
   11266       635507 :       vop = voprnds[j - 1];
   11267       635507 :       SLP_TREE_VEC_DEFS (op_node).quick_push (vop);
   11268              :     }
   11269              : 
   11270              :   /* In case that VF is greater than the unrolling factor needed for the SLP
   11271              :      group of stmts, NUMBER_OF_VECTORS to be created is greater than
   11272              :      NUMBER_OF_SCALARS/NUNITS or NUNITS/NUMBER_OF_SCALARS, and hence we have
   11273              :      to replicate the vectors.  */
   11274      1004762 :   while (number_of_vectors > SLP_TREE_VEC_DEFS (op_node).length ())
   11275            0 :     for (i = 0; SLP_TREE_VEC_DEFS (op_node).iterate (i, &vop) && i < vec_num;
   11276              :          i++)
   11277            0 :       SLP_TREE_VEC_DEFS (op_node).quick_push (vop);
   11278       502381 : }
   11279              : 
   11280              : /* Get the scalar definition of the Nth lane from SLP_NODE or NULL_TREE
   11281              :    if there is no definition for it in the scalar IL or it is not known.  */
   11282              : 
   11283              : tree
   11284         2617 : vect_get_slp_scalar_def (slp_tree slp_node, unsigned n)
   11285              : {
   11286         2617 :   if (SLP_TREE_DEF_TYPE (slp_node) == vect_internal_def)
   11287              :     {
   11288         2605 :       if (!SLP_TREE_SCALAR_STMTS (slp_node).exists ())
   11289              :         return NULL_TREE;
   11290         2605 :       stmt_vec_info def = SLP_TREE_SCALAR_STMTS (slp_node)[n];
   11291         2605 :       if (!def)
   11292              :         return NULL_TREE;
   11293         2605 :       return gimple_get_lhs (STMT_VINFO_STMT (def));
   11294              :     }
   11295              :   else
   11296           12 :     return SLP_TREE_SCALAR_OPS (slp_node)[n];
   11297              : }
   11298              : 
   11299              : /* Get the Ith vectorized definition from SLP_NODE.  */
   11300              : 
   11301              : tree
   11302       148409 : vect_get_slp_vect_def (slp_tree slp_node, unsigned i)
   11303              : {
   11304       148409 :   return SLP_TREE_VEC_DEFS (slp_node)[i];
   11305              : }
   11306              : 
   11307              : /* Get the vectorized definitions of SLP_NODE in *VEC_DEFS.  */
   11308              : 
   11309              : void
   11310       957443 : vect_get_slp_defs (slp_tree slp_node, vec<tree> *vec_defs)
   11311              : {
   11312      1914886 :   vec_defs->create (SLP_TREE_VEC_DEFS (slp_node).length ());
   11313       957443 :   vec_defs->splice (SLP_TREE_VEC_DEFS (slp_node));
   11314       957443 : }
   11315              : 
   11316              : /* Get N vectorized definitions for SLP_NODE.  */
   11317              : 
   11318              : void
   11319         3051 : vect_get_slp_defs (vec_info *,
   11320              :                    slp_tree slp_node, vec<vec<tree> > *vec_oprnds, unsigned n)
   11321              : {
   11322         3051 :   if (n == -1U)
   11323         3051 :     n = SLP_TREE_CHILDREN (slp_node).length ();
   11324              : 
   11325        10920 :   for (unsigned i = 0; i < n; ++i)
   11326              :     {
   11327         7869 :       slp_tree child = SLP_TREE_CHILDREN (slp_node)[i];
   11328         7869 :       vec<tree> vec_defs = vNULL;
   11329         7869 :       vect_get_slp_defs (child, &vec_defs);
   11330         7869 :       vec_oprnds->quick_push (vec_defs);
   11331              :     }
   11332         3051 : }
   11333              : 
   11334              : /* A subroutine of vect_transform_slp_perm_load with two extra arguments:
   11335              :    - PERM gives the permutation that the caller wants to use for NODE,
   11336              :      which might be different from SLP_LOAD_PERMUTATION.
   11337              :    - DUMP_P controls whether the function dumps information.  */
   11338              : 
   11339              : static bool
   11340       138262 : vect_transform_slp_perm_load_1 (vec_info *vinfo, slp_tree node,
   11341              :                                 load_permutation_t &perm,
   11342              :                                 const vec<tree> &dr_chain,
   11343              :                                 gimple_stmt_iterator *gsi, poly_uint64 vf,
   11344              :                                 bool analyze_only, bool dump_p,
   11345              :                                 unsigned *n_perms, unsigned int *n_loads,
   11346              :                                 bool dce_chain)
   11347              : {
   11348       138262 :   stmt_vec_info stmt_info = SLP_TREE_SCALAR_STMTS (node)[0];
   11349       138262 :   int vec_index = 0;
   11350       138262 :   tree vectype = SLP_TREE_VECTYPE (node);
   11351       138262 :   unsigned int group_size = SLP_TREE_LANES (node);
   11352       138262 :   unsigned int mask_element;
   11353       138262 :   unsigned dr_group_size;
   11354       138262 :   machine_mode mode;
   11355              : 
   11356       138262 :   if (!STMT_VINFO_GROUPED_ACCESS (stmt_info))
   11357              :     {
   11358              :       /* We have both splats of the same non-grouped load and groups
   11359              :          of distinct invariant loads entering here.  */
   11360         1513 :       unsigned max_idx = 0;
   11361         8373 :       for (auto idx : perm)
   11362         3834 :         max_idx = idx > max_idx ? idx : max_idx;
   11363         1513 :       dr_group_size = max_idx + 1;
   11364              :     }
   11365              :   else
   11366              :     {
   11367       136749 :       stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
   11368       136749 :       dr_group_size = DR_GROUP_SIZE (stmt_info);
   11369              :     }
   11370              : 
   11371       138262 :   mode = TYPE_MODE (vectype);
   11372       138262 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
   11373       138262 :   unsigned int nstmts = vect_get_num_copies (vinfo, node);
   11374              : 
   11375              :   /* Initialize the vect stmts of NODE to properly insert the generated
   11376              :      stmts later.  */
   11377       138262 :   if (! analyze_only)
   11378        60758 :     for (unsigned i = SLP_TREE_VEC_DEFS (node).length (); i < nstmts; i++)
   11379        23310 :       SLP_TREE_VEC_DEFS (node).quick_push (NULL_TREE);
   11380              : 
   11381              :   /* Generate permutation masks for every NODE. Number of masks for each NODE
   11382              :      is equal to GROUP_SIZE.
   11383              :      E.g., we have a group of three nodes with three loads from the same
   11384              :      location in each node, and the vector size is 4. I.e., we have a
   11385              :      a0b0c0a1b1c1... sequence and we need to create the following vectors:
   11386              :      for a's: a0a0a0a1 a1a1a2a2 a2a3a3a3
   11387              :      for b's: b0b0b0b1 b1b1b2b2 b2b3b3b3
   11388              :      ...
   11389              : 
   11390              :      The masks for a's should be: {0,0,0,3} {3,3,6,6} {6,9,9,9}.
   11391              :      The last mask is illegal since we assume two operands for permute
   11392              :      operation, and the mask element values can't be outside that range.
   11393              :      Hence, the last mask must be converted into {2,5,5,5}.
   11394              :      For the first two permutations we need the first and the second input
   11395              :      vectors: {a0,b0,c0,a1} and {b1,c1,a2,b2}, and for the last permutation
   11396              :      we need the second and the third vectors: {b1,c1,a2,b2} and
   11397              :      {c2,a3,b3,c3}.  */
   11398              : 
   11399       138262 :   int vect_stmts_counter = 0;
   11400       138262 :   unsigned int index = 0;
   11401       138262 :   int first_vec_index = -1;
   11402       138262 :   int second_vec_index = -1;
   11403       138262 :   bool noop_p = true;
   11404       138262 :   *n_perms = 0;
   11405              : 
   11406       138262 :   vec_perm_builder mask;
   11407       138262 :   unsigned int nelts_to_build;
   11408       138262 :   unsigned int nvectors_per_build;
   11409       138262 :   unsigned int in_nlanes;
   11410       138262 :   bool repeating_p = (group_size == dr_group_size
   11411       174240 :                       && multiple_p (nunits, group_size));
   11412       138262 :   if (repeating_p)
   11413              :     {
   11414              :       /* A single vector contains a whole number of copies of the node, so:
   11415              :          (a) all permutes can use the same mask; and
   11416              :          (b) the permutes only need a single vector input.  */
   11417        33520 :       mask.new_vector (nunits, group_size, 3);
   11418        33520 :       nelts_to_build = mask.encoded_nelts ();
   11419              :       /* It's possible to obtain zero nstmts during analyze_only, so make
   11420              :          it at least one to ensure the later computation for n_perms
   11421              :          proceed.  */
   11422        33520 :       nvectors_per_build = nstmts > 0 ? nstmts : 1;
   11423        33520 :       in_nlanes = dr_group_size * 3;
   11424              :     }
   11425              :   else
   11426              :     {
   11427              :       /* We need to construct a separate mask for each vector statement.  */
   11428       104742 :       unsigned HOST_WIDE_INT const_nunits, const_vf;
   11429       104742 :       if (!nunits.is_constant (&const_nunits)
   11430       104742 :           || !vf.is_constant (&const_vf))
   11431              :         return false;
   11432       104742 :       mask.new_vector (const_nunits, const_nunits, 1);
   11433       104742 :       nelts_to_build = const_vf * group_size;
   11434       104742 :       nvectors_per_build = 1;
   11435       104742 :       in_nlanes = const_vf * dr_group_size;
   11436              :     }
   11437       138262 :   auto_sbitmap used_in_lanes (in_nlanes);
   11438       138262 :   bitmap_clear (used_in_lanes);
   11439       138262 :   auto_bitmap used_defs;
   11440              : 
   11441       138262 :   unsigned int count = mask.encoded_nelts ();
   11442       138262 :   mask.quick_grow (count);
   11443       138262 :   vec_perm_indices indices;
   11444              : 
   11445       727980 :   for (unsigned int j = 0; j < nelts_to_build; j++)
   11446              :     {
   11447       600549 :       unsigned int iter_num = j / group_size;
   11448       600549 :       unsigned int stmt_num = j % group_size;
   11449       600549 :       unsigned int i = (iter_num * dr_group_size + perm[stmt_num]);
   11450       600549 :       bitmap_set_bit (used_in_lanes, i);
   11451       600549 :       if (repeating_p)
   11452              :         {
   11453              :           first_vec_index = 0;
   11454              :           mask_element = i;
   11455              :         }
   11456              :       else
   11457              :         {
   11458              :           /* Enforced before the loop when !repeating_p.  */
   11459       382143 :           unsigned int const_nunits = nunits.to_constant ();
   11460       382143 :           vec_index = i / const_nunits;
   11461       382143 :           mask_element = i % const_nunits;
   11462       382143 :           if (vec_index == first_vec_index
   11463       382143 :               || first_vec_index == -1)
   11464              :             {
   11465              :               first_vec_index = vec_index;
   11466              :             }
   11467       153253 :           else if (vec_index == second_vec_index
   11468       153253 :                    || second_vec_index == -1)
   11469              :             {
   11470       146955 :               second_vec_index = vec_index;
   11471       146955 :               mask_element += const_nunits;
   11472              :             }
   11473              :           else
   11474              :             {
   11475         6298 :               if (dump_p)
   11476          280 :                 dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   11477              :                                  "permutation requires at "
   11478              :                                  "least three vectors %G",
   11479              :                                  stmt_info->stmt);
   11480         6298 :               gcc_assert (analyze_only);
   11481              :               return false;
   11482              :             }
   11483              : 
   11484       375845 :           gcc_assert (mask_element < 2 * const_nunits);
   11485              :         }
   11486              : 
   11487       594251 :       if (mask_element != index)
   11488       381914 :         noop_p = false;
   11489       594251 :       mask[index++] = mask_element;
   11490              : 
   11491       594251 :       if (index == count)
   11492              :         {
   11493       162838 :           if (!noop_p)
   11494              :             {
   11495       132750 :               indices.new_vector (mask, second_vec_index == -1 ? 1 : 2, nunits);
   11496       132750 :               if (!can_vec_perm_const_p (mode, mode, indices))
   11497              :                 {
   11498         4533 :                   if (dump_p)
   11499              :                     {
   11500           90 :                       dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   11501              :                                        "unsupported vect permute { ");
   11502          876 :                       for (i = 0; i < count; ++i)
   11503              :                         {
   11504          786 :                           dump_dec (MSG_MISSED_OPTIMIZATION, mask[i]);
   11505          786 :                           dump_printf (MSG_MISSED_OPTIMIZATION, " ");
   11506              :                         }
   11507           90 :                       dump_printf (MSG_MISSED_OPTIMIZATION, "}\n");
   11508              :                     }
   11509         4533 :                   gcc_assert (analyze_only);
   11510              :                   return false;
   11511              :                 }
   11512              : 
   11513       128217 :               tree mask_vec = NULL_TREE;
   11514       128217 :               if (!analyze_only)
   11515        21567 :                 mask_vec = vect_gen_perm_mask_checked (vectype, indices);
   11516              : 
   11517       128217 :               if (second_vec_index == -1)
   11518        36979 :                 second_vec_index = first_vec_index;
   11519              : 
   11520       259299 :               for (unsigned int ri = 0; ri < nvectors_per_build; ++ri)
   11521              :                 {
   11522       131082 :                   ++*n_perms;
   11523       131082 :                   if (analyze_only)
   11524       109232 :                     continue;
   11525              :                   /* Generate the permute statement if necessary.  */
   11526        21850 :                   tree first_vec = dr_chain[first_vec_index + ri];
   11527        21850 :                   tree second_vec = dr_chain[second_vec_index + ri];
   11528        21850 :                   gassign *stmt = as_a<gassign *> (stmt_info->stmt);
   11529        21850 :                   tree perm_dest
   11530        21850 :                     = vect_create_destination_var (gimple_assign_lhs (stmt),
   11531              :                                                    vectype);
   11532        21850 :                   perm_dest = make_ssa_name (perm_dest);
   11533        21850 :                   gimple *perm_stmt
   11534        21850 :                     = gimple_build_assign (perm_dest, VEC_PERM_EXPR, first_vec,
   11535              :                                            second_vec, mask_vec);
   11536        21850 :                   vect_finish_stmt_generation (vinfo, stmt_info, perm_stmt,
   11537              :                                                gsi);
   11538        21850 :                   if (dce_chain)
   11539              :                     {
   11540        20927 :                       bitmap_set_bit (used_defs, first_vec_index + ri);
   11541        20927 :                       bitmap_set_bit (used_defs, second_vec_index + ri);
   11542              :                     }
   11543              : 
   11544              :                   /* Store the vector statement in NODE.  */
   11545        21850 :                   SLP_TREE_VEC_DEFS (node)[vect_stmts_counter++] = perm_dest;
   11546              :                 }
   11547              :             }
   11548        30088 :           else if (!analyze_only)
   11549              :             {
   11550         2920 :               for (unsigned int ri = 0; ri < nvectors_per_build; ++ri)
   11551              :                 {
   11552         1460 :                   tree first_vec = dr_chain[first_vec_index + ri];
   11553              :                   /* If mask was NULL_TREE generate the requested
   11554              :                      identity transform.  */
   11555         1460 :                   if (dce_chain)
   11556         1453 :                     bitmap_set_bit (used_defs, first_vec_index + ri);
   11557              : 
   11558              :                   /* Store the vector statement in NODE.  */
   11559         1460 :                   SLP_TREE_VEC_DEFS (node)[vect_stmts_counter++] = first_vec;
   11560              :                 }
   11561              :             }
   11562              : 
   11563              :           index = 0;
   11564              :           first_vec_index = -1;
   11565              :           second_vec_index = -1;
   11566              :           noop_p = true;
   11567              :         }
   11568              :     }
   11569              : 
   11570       127431 :   if (n_loads)
   11571              :     {
   11572        89792 :       if (repeating_p)
   11573        10885 :         *n_loads = nstmts;
   11574              :       else
   11575              :         {
   11576              :           /* Enforced above when !repeating_p.  */
   11577        78907 :           unsigned int const_nunits = nunits.to_constant ();
   11578        78907 :           *n_loads = 0;
   11579        78907 :           bool load_seen = false;
   11580      1059222 :           for (unsigned i = 0; i < in_nlanes; ++i)
   11581              :             {
   11582       980315 :               if (i % const_nunits == 0)
   11583              :                 {
   11584       418979 :                   if (load_seen)
   11585       124751 :                     *n_loads += 1;
   11586              :                   load_seen = false;
   11587              :                 }
   11588       980315 :               if (bitmap_bit_p (used_in_lanes, i))
   11589       272643 :                 load_seen = true;
   11590              :             }
   11591        78907 :           if (load_seen)
   11592        52517 :             *n_loads += 1;
   11593              :         }
   11594              :     }
   11595              : 
   11596       127431 :   if (dce_chain)
   11597       214757 :     for (unsigned i = 0; i < dr_chain.length (); ++i)
   11598        76495 :       if (!bitmap_bit_p (used_defs, i))
   11599              :         {
   11600        41956 :           tree def = dr_chain[i];
   11601        42685 :           do
   11602              :             {
   11603        42685 :               gimple *stmt = SSA_NAME_DEF_STMT (def);
   11604        42685 :               if (is_gimple_assign (stmt)
   11605        42685 :                   && (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
   11606        42685 :                       || gimple_assign_rhs_code (stmt) == CONSTRUCTOR))
   11607         5330 :                 def = single_ssa_tree_operand (stmt, SSA_OP_USE);
   11608              :               else
   11609              :                 def = NULL;
   11610        42685 :               gimple_stmt_iterator rgsi = gsi_for_stmt (stmt);
   11611        42685 :               gsi_remove (&rgsi, true);
   11612        42685 :               release_defs (stmt);
   11613              :             }
   11614        42685 :           while (def);
   11615              :         }
   11616              : 
   11617              :   return true;
   11618       138262 : }
   11619              : 
   11620              : /* Generate vector permute statements from a list of loads in DR_CHAIN.
   11621              :    If ANALYZE_ONLY is TRUE, only check that it is possible to create valid
   11622              :    permute statements for the SLP node NODE.  Store the number of vector
   11623              :    permute instructions in *N_PERMS and the number of vector load
   11624              :    instructions in *N_LOADS.  If DCE_CHAIN is true, remove all definitions
   11625              :    that were not needed.  */
   11626              : 
   11627              : bool
   11628        99425 : vect_transform_slp_perm_load (vec_info *vinfo,
   11629              :                               slp_tree node, const vec<tree> &dr_chain,
   11630              :                               gimple_stmt_iterator *gsi, poly_uint64 vf,
   11631              :                               bool analyze_only, unsigned *n_perms,
   11632              :                               unsigned int *n_loads, bool dce_chain)
   11633              : {
   11634        99425 :   return vect_transform_slp_perm_load_1 (vinfo, node,
   11635        99425 :                                          SLP_TREE_LOAD_PERMUTATION (node),
   11636              :                                          dr_chain, gsi, vf, analyze_only,
   11637              :                                          dump_enabled_p (), n_perms, n_loads,
   11638        99425 :                                          dce_chain);
   11639              : }
   11640              : 
   11641              : /* Produce the next vector result for SLP permutation NODE by adding a vector
   11642              :    statement at GSI.  If MASK_VEC is nonnull, add:
   11643              : 
   11644              :       <new SSA name> = VEC_PERM_EXPR <FIRST_DEF, SECOND_DEF, MASK_VEC>
   11645              : 
   11646              :    otherwise add:
   11647              : 
   11648              :       <new SSA name> = VEC_PERM_EXPR <FIRST_DEF, SECOND_DEF,
   11649              :                                       { N, N+1, N+2, ... }>
   11650              : 
   11651              :    where N == IDENTITY_OFFSET which is either zero or equal to the
   11652              :    number of elements of the result.  */
   11653              : 
   11654              : static void
   11655        32492 : vect_add_slp_permutation (vec_info *vinfo, gimple_stmt_iterator *gsi,
   11656              :                           slp_tree node, tree first_def, tree second_def,
   11657              :                           tree mask_vec, poly_uint64 identity_offset)
   11658              : {
   11659        32492 :   tree vectype = SLP_TREE_VECTYPE (node);
   11660              : 
   11661              :   /* ???  We SLP match existing vector element extracts but
   11662              :      allow punning which we need to re-instantiate at uses
   11663              :      but have no good way of explicitly representing.  */
   11664        32492 :   if (operand_equal_p (TYPE_SIZE (TREE_TYPE (first_def)), TYPE_SIZE (vectype))
   11665        32492 :       && !types_compatible_p (TREE_TYPE (first_def), vectype))
   11666              :     {
   11667           20 :       gassign *conv_stmt
   11668           20 :         = gimple_build_assign (make_ssa_name (vectype),
   11669              :                                build1 (VIEW_CONVERT_EXPR, vectype, first_def));
   11670           20 :       vect_finish_stmt_generation (vinfo, NULL, conv_stmt, gsi);
   11671           20 :       first_def = gimple_assign_lhs (conv_stmt);
   11672              :     }
   11673        32492 :   gassign *perm_stmt;
   11674        32492 :   if (mask_vec)
   11675              :     {
   11676        28421 :       if (operand_equal_p (TYPE_SIZE (TREE_TYPE (first_def)),
   11677        28421 :                            TYPE_SIZE (vectype))
   11678        28421 :           && !types_compatible_p (TREE_TYPE (second_def), vectype))
   11679              :         {
   11680            8 :           gassign *conv_stmt
   11681            8 :             = gimple_build_assign (make_ssa_name (vectype),
   11682              :                                    build1 (VIEW_CONVERT_EXPR,
   11683              :                                            vectype, second_def));
   11684            8 :           vect_finish_stmt_generation (vinfo, NULL, conv_stmt, gsi);
   11685            8 :           second_def = gimple_assign_lhs (conv_stmt);
   11686              :         }
   11687        28421 :       tree perm_dest = make_ssa_name (vectype);
   11688        28421 :       perm_stmt = gimple_build_assign (perm_dest, VEC_PERM_EXPR,
   11689              :                                        first_def, second_def,
   11690              :                                        mask_vec);
   11691              :     }
   11692              :   else
   11693              :     {
   11694         4071 :       auto def_nunits = TYPE_VECTOR_SUBPARTS (TREE_TYPE (first_def));
   11695         4071 :       unsigned HOST_WIDE_INT vecno;
   11696         4071 :       poly_uint64 eltno;
   11697         4071 :       if (!can_div_trunc_p (poly_uint64 (identity_offset), def_nunits,
   11698              :                             &vecno, &eltno))
   11699              :         gcc_unreachable ();
   11700         4071 :       tree def = vecno & 1 ? second_def : first_def;
   11701         4071 :       if (!types_compatible_p (TREE_TYPE (def), vectype))
   11702              :         {
   11703              :           /* For identity permutes we still need to handle the case
   11704              :              of offsetted extracts or concats.  */
   11705          406 :           tree perm_dest = make_ssa_name (vectype);
   11706          406 :           unsigned HOST_WIDE_INT c;
   11707          406 :           if (known_le (TYPE_VECTOR_SUBPARTS (vectype), def_nunits))
   11708              :             {
   11709          402 :               unsigned HOST_WIDE_INT elsz
   11710          402 :                 = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (def))));
   11711          804 :               tree lowpart = build3 (BIT_FIELD_REF, vectype, def,
   11712          402 :                                      TYPE_SIZE (vectype),
   11713          402 :                                      bitsize_int (eltno * elsz));
   11714          402 :               perm_stmt = gimple_build_assign (perm_dest, lowpart);
   11715              :             }
   11716            4 :           else if (constant_multiple_p (TYPE_VECTOR_SUBPARTS (vectype),
   11717            4 :                                         def_nunits, &c) && c == 2)
   11718              :             {
   11719            4 :               gcc_assert (known_eq (identity_offset, 0U));
   11720            4 :               tree ctor = build_constructor_va (vectype, 2,
   11721              :                                                 NULL_TREE, first_def,
   11722              :                                                 NULL_TREE, second_def);
   11723            4 :               perm_stmt = gimple_build_assign (perm_dest, ctor);
   11724              :             }
   11725              :           else
   11726            0 :             gcc_unreachable ();
   11727              :         }
   11728              :       else
   11729              :         {
   11730         3665 :           gcc_assert (known_eq (eltno, 0U));
   11731         3665 :           node->push_vec_def (def);
   11732         3665 :           return;
   11733              :         }
   11734              :     }
   11735        28827 :   vect_finish_stmt_generation (vinfo, NULL, perm_stmt, gsi);
   11736              :   /* Store the vector statement in NODE.  */
   11737        28827 :   node->push_vec_def (perm_stmt);
   11738              : }
   11739              : 
   11740              : /* Subroutine of vectorizable_slp_permutation.  Check whether the target
   11741              :    can perform permutation PERM on the (1 or 2) input nodes in CHILDREN.
   11742              :    If GSI is nonnull, emit the permutation there.
   11743              : 
   11744              :    When GSI is null, the only purpose of NODE is to give properties
   11745              :    of the result, such as the vector type and number of SLP lanes.
   11746              :    The node does not need to be a VEC_PERM_EXPR.
   11747              : 
   11748              :    If the target supports the operation, return the number of individual
   11749              :    VEC_PERM_EXPRs needed, otherwise return -1.  Print information to the
   11750              :    dump file if DUMP_P is true.  */
   11751              : 
   11752              : static int
   11753       443593 : vectorizable_slp_permutation_1 (vec_info *vinfo, gimple_stmt_iterator *gsi,
   11754              :                                 slp_tree node, lane_permutation_t &perm,
   11755              :                                 vec<slp_tree> &children, bool dump_p)
   11756              : {
   11757       443593 :   tree vectype = SLP_TREE_VECTYPE (node);
   11758              : 
   11759              :   /* ???  We currently only support all same vector input types
   11760              :      while the SLP IL should really do a concat + select and thus accept
   11761              :      arbitrary mismatches.  */
   11762       443593 :   slp_tree child;
   11763       443593 :   unsigned i;
   11764       443593 :   poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
   11765       443593 :   bool repeating_p = multiple_p (nunits, SLP_TREE_LANES (node));
   11766              :   /* True if we're permuting a single input of 2N vectors down
   11767              :      to N vectors.  This case doesn't generalize beyond 2 since
   11768              :      VEC_PERM_EXPR only takes 2 inputs.  */
   11769       443593 :   bool pack_p = false;
   11770              :   /* If we're permuting inputs of N vectors each into X*N outputs,
   11771              :      this is the value of X, otherwise it is 1.  */
   11772       443593 :   unsigned int unpack_factor = 1;
   11773       443593 :   tree op_vectype = NULL_TREE;
   11774       445209 :   FOR_EACH_VEC_ELT (children, i, child)
   11775       445115 :     if (SLP_TREE_VECTYPE (child))
   11776              :       {
   11777              :         op_vectype = SLP_TREE_VECTYPE (child);
   11778              :         break;
   11779              :       }
   11780       443593 :   if (!op_vectype)
   11781           94 :     op_vectype = vectype;
   11782       932907 :   FOR_EACH_VEC_ELT (children, i, child)
   11783              :     {
   11784       489314 :       if ((SLP_TREE_DEF_TYPE (child) != vect_internal_def
   11785        17749 :            && !vect_maybe_update_slp_op_vectype (child, op_vectype))
   11786       489314 :           || !types_compatible_p (SLP_TREE_VECTYPE (child), op_vectype)
   11787       978628 :           || !types_compatible_p (TREE_TYPE (vectype), TREE_TYPE (op_vectype)))
   11788              :         {
   11789            0 :           if (dump_p)
   11790            0 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   11791              :                              "Unsupported vector types in lane permutation\n");
   11792       443593 :           return -1;
   11793              :         }
   11794       489314 :       auto op_nunits = TYPE_VECTOR_SUBPARTS (op_vectype);
   11795       489314 :       unsigned int this_unpack_factor;
   11796              :       /* Detect permutations of external, pre-existing vectors.  The external
   11797              :          node's SLP_TREE_LANES stores the total number of units in the vector,
   11798              :          or zero if the vector has variable length.
   11799              : 
   11800              :          We are expected to keep the original VEC_PERM_EXPR for such cases.
   11801              :          There is no repetition to model.  */
   11802       489314 :       if (SLP_TREE_DEF_TYPE (child) == vect_external_def
   11803       489314 :           && SLP_TREE_SCALAR_OPS (child).is_empty ())
   11804              :         repeating_p = false;
   11805              :       /* Check whether the input has twice as many lanes per vector.  */
   11806       474315 :       else if (children.length () == 1
   11807       474315 :                && known_eq (SLP_TREE_LANES (child) * nunits,
   11808              :                             SLP_TREE_LANES (node) * op_nunits * 2))
   11809              :         pack_p = true;
   11810              :       /* Check whether the output has N times as many lanes per vector.  */
   11811       489314 :       else if (constant_multiple_p (SLP_TREE_LANES (node) * op_nunits,
   11812       430135 :                                     SLP_TREE_LANES (child) * nunits,
   11813              :                                     &this_unpack_factor)
   11814       395196 :                && (i == 0 || unpack_factor == this_unpack_factor))
   11815              :         unpack_factor = this_unpack_factor;
   11816              :       else
   11817              :         repeating_p = false;
   11818              :     }
   11819              : 
   11820       887186 :   gcc_assert (perm.length () == SLP_TREE_LANES (node));
   11821              : 
   11822              :   /* Load-lanes permute.  This permute only acts as a forwarder to
   11823              :      select the correct vector def of the load-lanes load which
   11824              :      has the permuted vectors in its vector defs like
   11825              :      { v0, w0, r0, v1, w1, r1 ... } for a ld3.  All costs are
   11826              :      accounted for in the costing for the actual load so we
   11827              :      return zero here.  */
   11828       443593 :   if (node->ldst_lanes)
   11829              :     {
   11830            0 :       gcc_assert (children.length () == 1);
   11831            0 :       if (!gsi)
   11832              :         /* This is a trivial op always supported.  */
   11833              :         return 0;
   11834            0 :       slp_tree child = children[0];
   11835            0 :       unsigned vec_idx = (SLP_TREE_LANE_PERMUTATION (node)[0].second
   11836            0 :                           / SLP_TREE_LANES (node));
   11837            0 :       unsigned vec_num = SLP_TREE_LANES (child) / SLP_TREE_LANES (node);
   11838            0 :       unsigned nvectors = vect_get_num_copies (vinfo, node);
   11839            0 :       for (unsigned i = 0; i < nvectors; ++i)
   11840              :         {
   11841            0 :           tree def = SLP_TREE_VEC_DEFS (child)[i * vec_num  + vec_idx];
   11842            0 :           node->push_vec_def (def);
   11843              :         }
   11844              :       return 0;
   11845              :     }
   11846              : 
   11847              :   /* Set REPEATING_P to true if the permutations are cyclical wrt UNPACK_FACTOR
   11848              :      and if we can generate the vectors in a vector-length agnostic way.
   11849              :      This requires UNPACK_STEP == NUNITS / UNPACK_FACTOR to be known at
   11850              :      compile time.
   11851              : 
   11852              :      The significance of UNPACK_STEP is that, when PACK_P is false,
   11853              :      output vector I operates on a window of UNPACK_STEP elements from each
   11854              :      input, starting at lane UNPACK_STEP * (I % UNPACK_FACTOR).  For example,
   11855              :      when UNPACK_FACTOR is 2, the first output vector operates on lanes
   11856              :      [0, NUNITS / 2 - 1] of each input vector and the second output vector
   11857              :      operates on lanes [NUNITS / 2, NUNITS - 1] of each input vector.
   11858              : 
   11859              :      When REPEATING_P is true, NOUTPUTS holds the total number of outputs
   11860              :      that we actually need to generate.  */
   11861       443593 :   uint64_t noutputs = 0;
   11862       443593 :   poly_uint64 unpack_step = 0;
   11863       443593 :   loop_vec_info linfo = dyn_cast <loop_vec_info> (vinfo);
   11864       183554 :   if (!linfo
   11865       482734 :       || !multiple_p (nunits, unpack_factor, &unpack_step)
   11866       182604 :       || !constant_multiple_p (LOOP_VINFO_VECT_FACTOR (linfo)
   11867       182604 :                                * SLP_TREE_LANES (node), nunits, &noutputs))
   11868              :     repeating_p = false;
   11869              : 
   11870              :   /* We can handle the conditions described for REPEATING_P above for
   11871              :      both variable- and constant-length vectors.  The fallback requires
   11872              :      us to generate every element of every permute vector explicitly,
   11873              :      which is only possible for constant-length permute vectors.
   11874              : 
   11875              :      Set:
   11876              : 
   11877              :      - NPATTERNS and NELTS_PER_PATTERN to the encoding of the permute
   11878              :        mask vectors that we want to build.
   11879              : 
   11880              :      - NCOPIES to the number of copies of PERM that we need in order
   11881              :        to build the necessary permute mask vectors.  */
   11882       182604 :   uint64_t npatterns;
   11883       182604 :   unsigned nelts_per_pattern;
   11884       182604 :   uint64_t ncopies;
   11885       182604 :   if (repeating_p)
   11886              :     {
   11887              :       /* We need permute mask vectors that have the form:
   11888              : 
   11889              :            { X1, ..., Xn, X1 + n, ..., Xn + n, X1 + 2n, ..., Xn + 2n, ... }
   11890              : 
   11891              :          In other words, the original n-element permute in PERM is
   11892              :          "unrolled" to fill a full vector.  The stepped vector encoding
   11893              :          that we use for permutes requires 3n elements.  */
   11894       143463 :       npatterns = SLP_TREE_LANES (node);
   11895       143463 :       nelts_per_pattern = ncopies = 3;
   11896              :     }
   11897              :   else
   11898              :     {
   11899              :       /* Calculate every element of every permute mask vector explicitly,
   11900              :          instead of relying on the pattern described above.  */
   11901       300130 :       if (!nunits.is_constant (&npatterns)
   11902       300130 :           || !TYPE_VECTOR_SUBPARTS (op_vectype).is_constant ())
   11903              :         {
   11904              :           if (dump_p)
   11905              :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   11906              :                              "unsupported permutation %p on variable-length"
   11907              :                              " vectors\n", (void *) node);
   11908              :           return -1;
   11909              :         }
   11910       300130 :       nelts_per_pattern = ncopies = 1;
   11911       300130 :       if (linfo && !LOOP_VINFO_VECT_FACTOR (linfo).is_constant (&ncopies))
   11912              :         {
   11913              :           if (dump_p)
   11914              :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   11915              :                              "unsupported permutation %p for variable VF\n",
   11916              :                              (void *) node);
   11917              :           return -1;
   11918              :         }
   11919              :       pack_p = false;
   11920              :       unpack_factor = 1;
   11921              :     }
   11922       443593 :   unsigned olanes = unpack_factor * ncopies * SLP_TREE_LANES (node);
   11923       443593 :   gcc_assert (repeating_p || multiple_p (olanes, nunits));
   11924              : 
   11925              :   /* Compute the { { SLP operand, vector index}, lane } permutation sequence
   11926              :      from the { SLP operand, scalar lane } permutation as recorded in the
   11927              :      SLP node as intermediate step.  This part should already work
   11928              :      with SLP children with arbitrary number of lanes.  */
   11929       443593 :   auto_vec<std::pair<std::pair<unsigned, unsigned>, poly_uint64>> vperm;
   11930       443593 :   auto_vec<poly_uint64> active_lane;
   11931       443593 :   vperm.create (olanes);
   11932       443593 :   active_lane.safe_grow_cleared (children.length (), true);
   11933      1339292 :   for (unsigned int ui = 0; ui < unpack_factor; ++ui)
   11934              :     {
   11935      1916844 :       for (unsigned j = 0; j < children.length (); ++j)
   11936       506316 :         active_lane[j] = ui * unpack_step;
   11937      1306280 :       for (unsigned i = 0; i < ncopies; ++i)
   11938              :         {
   11939      5389330 :           for (unsigned pi = 0; pi < perm.length (); ++pi)
   11940              :             {
   11941      1840491 :               std::pair<unsigned, unsigned> p = perm[pi];
   11942      1840491 :               tree vtype = SLP_TREE_VECTYPE (children[p.first]);
   11943      1840491 :               if (repeating_p)
   11944       838959 :                 vperm.quick_push ({{p.first, 0},
   11945       838959 :                                    p.second + active_lane[p.first]});
   11946              :               else
   11947              :                 {
   11948              :                   /* We checked above that the vectors are constant-length.  */
   11949      1001532 :                   unsigned vnunits = TYPE_VECTOR_SUBPARTS (vtype)
   11950      1001532 :                     .to_constant ();
   11951      1001532 :                   unsigned lane = active_lane[p.first].to_constant ();
   11952      1001532 :                   unsigned vi = (lane + p.second) / vnunits;
   11953      1001532 :                   unsigned vl = (lane + p.second) % vnunits;
   11954      1001532 :                   vperm.quick_push ({{p.first, vi}, vl});
   11955              :                 }
   11956              :             }
   11957              :           /* Advance to the next group.  */
   11958      1828285 :           for (unsigned j = 0; j < children.length (); ++j)
   11959       974111 :             active_lane[j] += SLP_TREE_LANES (children[j]);
   11960              :         }
   11961              :     }
   11962              : 
   11963       443593 :   if (dump_p)
   11964              :     {
   11965         9032 :       dump_printf_loc (MSG_NOTE, vect_location,
   11966              :                        "vectorizing permutation %p", (void *)node);
   11967        32685 :       for (unsigned i = 0; i < perm.length (); ++i)
   11968        23653 :         dump_printf (MSG_NOTE, " op%u[%u]", perm[i].first, perm[i].second);
   11969         9032 :       if (repeating_p)
   11970         7574 :         dump_printf (MSG_NOTE, " (repeat %d)", SLP_TREE_LANES (node));
   11971         9032 :       dump_printf (MSG_NOTE, "\n");
   11972         9032 :       dump_printf_loc (MSG_NOTE, vect_location, "as");
   11973        90765 :       for (unsigned i = 0; i < vperm.length (); ++i)
   11974              :         {
   11975        81733 :           if (i != 0
   11976        81733 :               && (repeating_p
   11977        55351 :                   ? multiple_p (i, npatterns)
   11978        81733 :                   : multiple_p (i, TYPE_VECTOR_SUBPARTS (vectype))))
   11979        24385 :             dump_printf (MSG_NOTE, ",");
   11980        81733 :           dump_printf (MSG_NOTE, " vops%u[%u][",
   11981        81733 :                        vperm[i].first.first, vperm[i].first.second);
   11982        81733 :           dump_dec (MSG_NOTE, vperm[i].second);
   11983        81733 :           dump_printf (MSG_NOTE, "]");
   11984              :         }
   11985         9032 :       dump_printf (MSG_NOTE, "\n");
   11986              :     }
   11987              : 
   11988              :   /* We can only handle two-vector permutes, everything else should
   11989              :      be lowered on the SLP level.  The following is closely inspired
   11990              :      by vect_transform_slp_perm_load and is supposed to eventually
   11991              :      replace it.
   11992              :      ???   As intermediate step do code-gen in the SLP tree representation
   11993              :      somehow?  */
   11994       443593 :   std::pair<unsigned, unsigned> first_vec = std::make_pair (-1U, -1U);
   11995       443593 :   std::pair<unsigned, unsigned> second_vec = std::make_pair (-1U, -1U);
   11996       443593 :   unsigned int index = 0;
   11997       443593 :   poly_uint64 mask_element;
   11998       443593 :   vec_perm_builder mask;
   11999       443593 :   mask.new_vector (nunits, npatterns, nelts_per_pattern);
   12000       443593 :   unsigned int count = mask.encoded_nelts ();
   12001       443593 :   mask.quick_grow (count);
   12002       443593 :   vec_perm_indices indices;
   12003       443593 :   unsigned nperms = 0;
   12004              :   /* When REPEATING_P is true, we only have UNPACK_FACTOR unique permute
   12005              :      vectors to check during analysis, but we need to generate NOUTPUTS
   12006              :      vectors during transformation.  */
   12007       443593 :   unsigned total_nelts = olanes;
   12008       443593 :   unsigned process_nelts = olanes;
   12009       443593 :   if (repeating_p)
   12010              :     {
   12011       143463 :       total_nelts = (total_nelts / unpack_factor) * noutputs;
   12012       143463 :       if (gsi)
   12013         9917 :         process_nelts = total_nelts;
   12014              :     }
   12015       443593 :   unsigned last_ei = (total_nelts - 1) % process_nelts;
   12016      2288322 :   for (unsigned i = 0; i < process_nelts; ++i)
   12017              :     {
   12018              :       /* VI is the input vector index when generating code for REPEATING_P.  */
   12019      1854658 :       unsigned vi = i / olanes * (pack_p ? 2 : 1);
   12020      1854658 :       unsigned ei = i % olanes;
   12021      1854658 :       mask_element = vperm[ei].second;
   12022      1854658 :       if (pack_p)
   12023              :         {
   12024              :           /* In this case, we have N outputs and the single child provides 2N
   12025              :              inputs.  Output X permutes inputs 2X and 2X+1.
   12026              : 
   12027              :              The mask indices are taken directly from the SLP permutation node.
   12028              :              Index X selects from the first vector if (X / NUNITS) % 2 == 0;
   12029              :              X selects from the second vector otherwise.  These conditions
   12030              :              are only known at compile time for constant-length vectors.  */
   12031              :           first_vec = std::make_pair (0, 0);
   12032              :           second_vec = std::make_pair (0, 1);
   12033              :         }
   12034      1684924 :       else if (first_vec.first == -1U
   12035      1684924 :                || first_vec == vperm[ei].first)
   12036      1487033 :         first_vec = vperm[ei].first;
   12037       197891 :       else if (second_vec.first == -1U
   12038       197891 :                || second_vec == vperm[ei].first)
   12039              :         {
   12040       197487 :           second_vec = vperm[ei].first;
   12041       197487 :           mask_element += nunits;
   12042              :         }
   12043              :       else
   12044              :         {
   12045          404 :           if (dump_p)
   12046            7 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   12047              :                              "permutation requires at "
   12048              :                              "least three vectors\n");
   12049          404 :           gcc_assert (!gsi);
   12050              :           return -1;
   12051              :         }
   12052              : 
   12053      1854254 :       mask[index++] = mask_element;
   12054              : 
   12055      1854254 :       if (index == count)
   12056              :         {
   12057       588796 :           indices.new_vector (mask, second_vec.first == -1U ? 1 : 2,
   12058              :                               TYPE_VECTOR_SUBPARTS (op_vectype));
   12059       588796 :           bool identity_p = (indices.series_p (0, 1, mask[0], 1)
   12060       915521 :                              && constant_multiple_p (mask[0], nunits));
   12061       588796 :           machine_mode vmode = TYPE_MODE (vectype);
   12062       588796 :           machine_mode op_vmode = TYPE_MODE (op_vectype);
   12063       588796 :           unsigned HOST_WIDE_INT c;
   12064       588796 :           if ((!identity_p
   12065       539438 :                && !can_vec_perm_const_p (vmode, op_vmode, indices))
   12066       588796 :               || (identity_p
   12067        49358 :                   && !known_le (nunits,
   12068              :                                 TYPE_VECTOR_SUBPARTS (op_vectype))
   12069            8 :                   && (!constant_multiple_p (nunits,
   12070         9533 :                                             TYPE_VECTOR_SUBPARTS (op_vectype),
   12071            8 :                                             &c) || c != 2)))
   12072              :             {
   12073         9525 :               if (dump_p)
   12074              :                 {
   12075          154 :                   dump_printf_loc (MSG_MISSED_OPTIMIZATION,
   12076              :                                    vect_location,
   12077              :                                    "unsupported vect permute { ");
   12078         1596 :                   for (i = 0; i < count; ++i)
   12079              :                     {
   12080         1442 :                       dump_dec (MSG_MISSED_OPTIMIZATION, mask[i]);
   12081         1442 :                       dump_printf (MSG_MISSED_OPTIMIZATION, " ");
   12082              :                     }
   12083          154 :                   dump_printf (MSG_MISSED_OPTIMIZATION, "}\n");
   12084              :                 }
   12085         9525 :               gcc_assert (!gsi);
   12086       443593 :               return -1;
   12087              :             }
   12088              : 
   12089       579271 :           if (!identity_p)
   12090       529913 :             nperms += CEIL (total_nelts, process_nelts) - (ei > last_ei);
   12091       579271 :           if (gsi)
   12092              :             {
   12093        32492 :               if (second_vec.first == -1U)
   12094         7938 :                 second_vec = first_vec;
   12095              : 
   12096        32492 :               slp_tree
   12097        32492 :                 first_node = children[first_vec.first],
   12098        32492 :                 second_node = children[second_vec.first];
   12099              : 
   12100        32492 :               tree mask_vec = NULL_TREE;
   12101        32492 :               if (!identity_p)
   12102        28421 :                 mask_vec = vect_gen_perm_mask_checked (vectype, indices);
   12103              : 
   12104        32492 :               tree first_def
   12105        32492 :                 = vect_get_slp_vect_def (first_node, first_vec.second + vi);
   12106        32492 :               tree second_def
   12107        32492 :                 = vect_get_slp_vect_def (second_node, second_vec.second + vi);
   12108        32492 :               vect_add_slp_permutation (vinfo, gsi, node, first_def,
   12109        32492 :                                         second_def, mask_vec, mask[0]);
   12110              :             }
   12111              : 
   12112              :           index = 0;
   12113              :           first_vec = std::make_pair (-1U, -1U);
   12114              :           second_vec = std::make_pair (-1U, -1U);
   12115              :         }
   12116              :     }
   12117              : 
   12118       433664 :   return nperms;
   12119       443593 : }
   12120              : 
   12121              : /* Vectorize the SLP permutations in NODE as specified
   12122              :    in SLP_TREE_LANE_PERMUTATION which is a vector of pairs of SLP
   12123              :    child number and lane number.
   12124              :    Interleaving of two two-lane two-child SLP subtrees (not supported):
   12125              :      [ { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } ]
   12126              :    A blend of two four-lane two-child SLP subtrees:
   12127              :      [ { 0, 0 }, { 1, 1 }, { 0, 2 }, { 1, 3 } ]
   12128              :    Highpart of a four-lane one-child SLP subtree (not supported):
   12129              :      [ { 0, 2 }, { 0, 3 } ]
   12130              :    Where currently only a subset is supported by code generating below.  */
   12131              : 
   12132              : bool
   12133        99984 : vectorizable_slp_permutation (vec_info *vinfo, gimple_stmt_iterator *gsi,
   12134              :                               slp_tree node, stmt_vector_for_cost *cost_vec)
   12135              : {
   12136        99984 :   tree vectype = SLP_TREE_VECTYPE (node);
   12137        99984 :   lane_permutation_t &perm = SLP_TREE_LANE_PERMUTATION (node);
   12138        99984 :   int nperms = vectorizable_slp_permutation_1 (vinfo, gsi, node, perm,
   12139        99984 :                                                SLP_TREE_CHILDREN (node),
   12140              :                                                dump_enabled_p ());
   12141        99984 :   if (nperms < 0)
   12142              :     return false;
   12143              : 
   12144        98453 :   if (!gsi && nperms != 0)
   12145        74671 :     record_stmt_cost (cost_vec, nperms, vec_perm, node, vectype, 0, vect_body);
   12146              : 
   12147              :   return true;
   12148              : }
   12149              : 
   12150              : /* Vectorize SLP NODE.  Only compute the vector insertion places when
   12151              :    PLACE_ONLY is true.  When placing, return false if there is no possible
   12152              :    schedule.  */
   12153              : 
   12154              : static bool
   12155      3147937 : vect_schedule_slp_node (vec_info *vinfo,
   12156              :                         slp_tree node, slp_instance instance, bool place_only)
   12157              : {
   12158      3147937 :   int i;
   12159      3147937 :   slp_tree child;
   12160              : 
   12161              :   /* Vectorize externals and constants.  */
   12162      3147937 :   if (SLP_TREE_DEF_TYPE (node) == vect_constant_def
   12163      3147937 :       || SLP_TREE_DEF_TYPE (node) == vect_external_def)
   12164              :     {
   12165      1210071 :       if (place_only)
   12166              :         {
   12167       699320 :           if (SLP_TREE_DEF_TYPE (node) == vect_constant_def)
   12168              :             return true;
   12169       319147 :           gimple *last_stmt = NULL;
   12170       319147 :           vec<tree> &defs = (!SLP_TREE_SCALAR_OPS (node).is_empty ()
   12171              :                              ? SLP_TREE_SCALAR_OPS (node)
   12172       319147 :                              : SLP_TREE_VEC_DEFS (node));
   12173      1708352 :           for (tree def : defs)
   12174              :             /* If the stmt is not inside the region do not
   12175              :                use it as possible insertion point.  */
   12176       750911 :             if (auto stmt_info = vinfo->lookup_def (def))
   12177              :               {
   12178       388523 :                 gimple *stmt = stmt_info->stmt;
   12179       388523 :                 if (!last_stmt)
   12180              :                   last_stmt = stmt;
   12181       218502 :                 else if (vect_stmt_dominates_stmt_p (last_stmt, stmt))
   12182              :                   last_stmt = stmt;
   12183        65299 :                 else if (vect_stmt_dominates_stmt_p (stmt, last_stmt))
   12184              :                   ;
   12185              :                 else
   12186            0 :                   gcc_unreachable ();
   12187              :               }
   12188       319147 :           node->si = last_stmt;
   12189       319147 :           return true;
   12190              :         }
   12191              : 
   12192              :       /* ???  vectorizable_shift can end up using a scalar operand which is
   12193              :          currently denoted as !SLP_TREE_VECTYPE.  No need to vectorize the
   12194              :          node in this case.  */
   12195       510751 :       if (!SLP_TREE_VECTYPE (node))
   12196              :         return true;
   12197              : 
   12198              :       /* There are two reasons vector defs might already exist.  The first
   12199              :          is that we are vectorizing an existing vector def.  The second is
   12200              :          when performing BB vectorization shared constant/external nodes
   12201              :          are not split apart during partitioning so during the code-gen
   12202              :          DFS walk we can end up visiting them twice.  */
   12203       503327 :       if (! SLP_TREE_VEC_DEFS (node).exists ())
   12204       502381 :         vect_create_constant_vectors (vinfo, node);
   12205              :       return true;
   12206              :     }
   12207              : 
   12208      1937866 :   stmt_vec_info stmt_info = SLP_TREE_REPRESENTATIVE (node);
   12209              : 
   12210      1937866 :   gcc_assert (SLP_TREE_VEC_DEFS (node).is_empty ());
   12211      1937866 :   if (!place_only && SLP_TREE_VECTYPE (node))
   12212       998398 :     SLP_TREE_VEC_DEFS (node).create (vect_get_num_copies (vinfo, node));
   12213              : 
   12214      1937866 :   gimple *last_stmt;
   12215      1937866 :   gimple_stmt_iterator si;
   12216              :   /* ???  When !place_only we'd like to re-use place_only computed info,
   12217              :      but this is a bit awkward due to using gsi_insert_before and the
   12218              :      requirement to insert after vector defs.  So we compute last_stmt
   12219              :      during pre-scheduling and si during scheduling.  */
   12220      1937866 :   if (!SLP_TREE_PERMUTE_P (node) && STMT_VINFO_DATA_REF (stmt_info))
   12221              :     {
   12222              :       /* Vectorized loads go before the first scalar load to make it
   12223              :          ready early, vectorized stores go before the last scalar
   12224              :          stmt which is where all uses are ready.
   12225              :          In theory, if we delay dependence checking until after
   12226              :          placing, we can schedule at other points, but then
   12227              :          dependence checking would need to honor that.  On the
   12228              :          other hand dependence checking could request a different
   12229              :          scheduling point as well, if dependences require that.  */
   12230      1507947 :       stmt_vec_info last_stmt_info = NULL;
   12231      1507947 :       if (DR_IS_READ (STMT_VINFO_DATA_REF (stmt_info)))
   12232       284920 :         last_stmt_info = vect_find_first_scalar_stmt_in_slp (node);
   12233              :       else /* DR_IS_WRITE */
   12234              :         {
   12235      1223027 :           last_stmt_info = vect_find_last_scalar_stmt_in_slp (node);
   12236      1223027 :           if (place_only)
   12237      1331248 :             FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
   12238              :               {
   12239       665626 :                 if (child->si
   12240       665626 :                     && !vect_stmt_dominates_stmt_p (child->si,
   12241              :                                                     last_stmt_info->stmt))
   12242              :                   return false;
   12243              :               }
   12244              :         }
   12245      1507943 :       last_stmt = last_stmt_info->stmt;
   12246      1507943 :       si = gsi_for_stmt (last_stmt);
   12247      1507943 :     }
   12248       429919 :   else if (!SLP_TREE_PERMUTE_P (node)
   12249       408155 :            && (SLP_TREE_TYPE (node) == cycle_phi_info_type
   12250              :                || SLP_TREE_TYPE (node) == induc_vec_info_type
   12251              :                || SLP_TREE_TYPE (node) == phi_info_type))
   12252              :     {
   12253              :       /* For PHI node vectorization we do not use the insertion iterator.  */
   12254       108649 :       last_stmt = SLP_TREE_SCALAR_STMTS (node)[0]->stmt;
   12255       108649 :       if (place_only)
   12256       181872 :         FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
   12257              :           {
   12258       128703 :             if (child->si
   12259       224383 :                 && !dominated_by_p (CDI_DOMINATORS,
   12260              :                                     gimple_phi_arg_edge
   12261        95680 :                                       (as_a <gphi *> (last_stmt), i)->src,
   12262        95680 :                                     gimple_bb (child->si)))
   12263              :               return false;
   12264              :           }
   12265       108645 :       si = gsi_none ();
   12266              :     }
   12267              :   else
   12268              :     {
   12269              :       /* Emit other stmts after the children vectorized defs which is
   12270              :          earliest possible.  */
   12271              :       last_stmt = NULL;
   12272       888898 :       FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
   12273       567630 :         if (place_only)
   12274              :           {
   12275       187657 :             gimple *vstmt = child->si;
   12276       187657 :             if (!vstmt)
   12277              :               {
   12278              :                 /* vect_constant_def and defs at region boundary do not
   12279              :                    constrain placement.  */
   12280              :                 gcc_assert (SLP_TREE_DEF_TYPE (child) == vect_constant_def
   12281              :                             /* ???  Region boundary is not representated
   12282              :                                by a NULL stmt.  */
   12283              :                             || true);
   12284              :               }
   12285       146890 :             else if (!last_stmt)
   12286              :               last_stmt = vstmt;
   12287        42458 :             else if (vect_stmt_dominates_stmt_p (last_stmt, vstmt))
   12288              :               last_stmt = vstmt;
   12289        10854 :             else if (vect_stmt_dominates_stmt_p (vstmt, last_stmt))
   12290              :               ;
   12291              :             else
   12292              :               /* Non-trapping stmts from different BBs might be combined,
   12293              :                  and if we later CSE a low/high part we can run into this.  */
   12294              :               return false;
   12295              :           }
   12296       379973 :         else if (SLP_TREE_DEF_TYPE (child) == vect_internal_def)
   12297              :           {
   12298              :             /* For fold-left reductions we are retaining the scalar
   12299              :                reduction PHI but we still have SLP_TREE_NUM_VEC_STMTS
   12300              :                set so the representation isn't perfect.  Resort to the
   12301              :                last scalar def here.  */
   12302       303119 :             if (SLP_TREE_VEC_DEFS (child).is_empty ())
   12303              :               {
   12304          956 :                 gcc_assert (SLP_TREE_TYPE (child) == cycle_phi_info_type);
   12305          956 :                 gphi *phi = as_a <gphi *>
   12306          956 :                               (vect_find_last_scalar_stmt_in_slp (child)->stmt);
   12307          956 :                 if (!last_stmt)
   12308              :                   last_stmt = phi;
   12309          726 :                 else if (vect_stmt_dominates_stmt_p (last_stmt, phi))
   12310              :                   last_stmt = phi;
   12311          715 :                 else if (vect_stmt_dominates_stmt_p (phi, last_stmt))
   12312              :                   ;
   12313              :                 else
   12314            0 :                   gcc_unreachable ();
   12315              :               }
   12316              :             /* We are emitting all vectorized stmts in the same place and
   12317              :                the last one is the last.
   12318              :                ???  Unless we have a load permutation applied and that
   12319              :                figures to re-use an earlier generated load.  */
   12320       303119 :             unsigned j;
   12321       303119 :             tree vdef;
   12322       715127 :             FOR_EACH_VEC_ELT (SLP_TREE_VEC_DEFS (child), j, vdef)
   12323       412008 :               if (TREE_CODE (vdef) == SSA_NAME
   12324       412008 :                   && !SSA_NAME_IS_DEFAULT_DEF (vdef))
   12325              :                 {
   12326       411956 :                   gimple *vstmt = SSA_NAME_DEF_STMT (vdef);
   12327       411956 :                   if (!last_stmt)
   12328              :                     last_stmt = vstmt;
   12329       210319 :                   else if (vect_stmt_dominates_stmt_p (last_stmt, vstmt))
   12330              :                     last_stmt = vstmt;
   12331        47488 :                   else if (vect_stmt_dominates_stmt_p (vstmt, last_stmt))
   12332              :                     ;
   12333              :                   else
   12334            0 :                     gcc_unreachable ();
   12335              :                 }
   12336              :           }
   12337        76854 :         else if (!SLP_TREE_VECTYPE (child))
   12338              :           {
   12339              :             /* For externals we use unvectorized at all scalar defs.  */
   12340              :             unsigned j;
   12341              :             tree def;
   12342        16599 :             FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_OPS (child), j, def)
   12343              :               /* If the stmt is not inside the region do not
   12344              :                  use it as possible insertion point.  */
   12345         9803 :               if (auto stmt_info = vinfo->lookup_def (def))
   12346              :                 {
   12347          250 :                   gimple *stmt = stmt_info->stmt;
   12348          250 :                   if (!last_stmt)
   12349              :                     last_stmt = stmt;
   12350          230 :                   else if (vect_stmt_dominates_stmt_p (last_stmt, stmt))
   12351              :                     last_stmt = stmt;
   12352           26 :                   else if (vect_stmt_dominates_stmt_p (stmt, last_stmt))
   12353              :                     ;
   12354              :                   else
   12355            0 :                     gcc_unreachable ();
   12356              :                 }
   12357              :           }
   12358              :         else
   12359              :           {
   12360              :             /* For externals we have to look at all defs since their
   12361              :                insertion place is decided per vector.  But beware
   12362              :                of pre-existing vectors where we need to make sure
   12363              :                we do not insert before the region boundary.  */
   12364       139985 :             if (SLP_TREE_SCALAR_OPS (child).is_empty ()
   12365          716 :                 && !vinfo->lookup_def (SLP_TREE_VEC_DEFS (child)[0]))
   12366              :               ;
   12367              :             else
   12368              :               {
   12369              :                 unsigned j;
   12370              :                 tree vdef;
   12371       736032 :                 FOR_EACH_VEC_ELT (SLP_TREE_VEC_DEFS (child), j, vdef)
   12372        98477 :                   if (TREE_CODE (vdef) == SSA_NAME
   12373        98477 :                       && !SSA_NAME_IS_DEFAULT_DEF (vdef))
   12374              :                     {
   12375        22392 :                       gimple *vstmt = SSA_NAME_DEF_STMT (vdef);
   12376        22392 :                       if (!last_stmt)
   12377              :                         last_stmt = vstmt;
   12378        12175 :                       else if (vect_stmt_dominates_stmt_p (last_stmt, vstmt))
   12379              :                         last_stmt = vstmt;
   12380         9599 :                       else if (vect_stmt_dominates_stmt_p (vstmt, last_stmt))
   12381              :                         ;
   12382              :                       else
   12383            0 :                         gcc_unreachable ();
   12384              :                     }
   12385              :               }
   12386              :           }
   12387              : 
   12388              :       /* We split regions to vectorize at control altering stmts
   12389              :          with a definition so this can only be an external.  */
   12390       321268 :       gcc_checking_assert (!last_stmt
   12391              :                            || !is_ctrl_altering_stmt (last_stmt));
   12392              : 
   12393       321268 :       if (is_a <bb_vec_info> (vinfo)
   12394       130561 :           && !SLP_TREE_PERMUTE_P (node)
   12395       123942 :           && (!last_stmt
   12396       121093 :               || !dominated_by_p (CDI_DOMINATORS, gimple_bb (last_stmt),
   12397       121093 :                                   gimple_bb (stmt_info->stmt)))
   12398       346826 :           && gimple_could_trap_p (stmt_info->stmt))
   12399              :         {
   12400              :           /* We've constrained possibly trapping operations to all come
   12401              :              from the same basic-block, if vectorized defs would allow earlier
   12402              :              scheduling still force vectorized stmts to the original block.
   12403              :              This is only necessary for BB vectorization since for loop vect
   12404              :              all operations are in a single BB and scalar stmt based
   12405              :              placement doesn't play well with epilogue vectorization.  */
   12406          675 :           if (last_stmt
   12407         1258 :               && !dominated_by_p (CDI_DOMINATORS,
   12408          583 :                                   gimple_bb (stmt_info->stmt),
   12409          583 :                                   gimple_bb (last_stmt)))
   12410              :             {
   12411            4 :               gcc_assert (place_only);
   12412              :               return false;
   12413              :             }
   12414          671 :           si = gsi_after_labels (gimple_bb (stmt_info->stmt));
   12415          671 :           last_stmt = gsi_stmt (si);
   12416              :         }
   12417              :       /* When there is no in-region child def to guide placement, insert
   12418              :          at region boundary.  */
   12419       320593 :       else if (!last_stmt)
   12420              :         {
   12421         4642 :           si = gsi_after_labels (vinfo->bbs[0]);
   12422              :           /* last_stmt NULL marks the region start.  */
   12423              :         }
   12424       315951 :       else if (is_a <gphi *> (last_stmt))
   12425        31278 :         si = gsi_after_labels (gimple_bb (last_stmt));
   12426              :       else
   12427              :         {
   12428       284673 :           si = gsi_for_stmt (last_stmt);
   12429              :           /* We use gsi_insert_before, so when last_stmt is a vector
   12430              :              def we have to advance (or use gsi_insert_after).  */
   12431       284673 :           gsi_next (&si);
   12432              : 
   12433       284673 :           if (auto loop_vinfo = dyn_cast <loop_vec_info> (vinfo))
   12434              :             {
   12435              :               /* We'll have to fix this up for loop vect.  */
   12436       174775 :               gcc_assert (!place_only);
   12437              :               /* Avoid scheduling stmts to random places in the CFG, any
   12438              :                  stmt dominance check we performed is possibly wrong as UIDs
   12439              :                  are not initialized for all of the function for loop
   12440              :                  vectorization.  Instead append to the loop preheader.  */
   12441       174775 :               if ((LOOP_VINFO_LOOP (loop_vinfo)->header
   12442       174775 :                    != gimple_bb (last_stmt))
   12443       177729 :                   && dominated_by_p (CDI_DOMINATORS,
   12444              :                                      LOOP_VINFO_LOOP (loop_vinfo)->header,
   12445         2954 :                                      gimple_bb (last_stmt)))
   12446         1126 :                 si = gsi_end_bb (loop_preheader_edge
   12447          563 :                                    (LOOP_VINFO_LOOP (loop_vinfo))->src);
   12448              :               /* Avoid scheduling internal defs outside of the loop when
   12449              :                  we might have only implicitly tracked loop mask/len defs.  */
   12450           76 :               if (LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
   12451       174775 :                   || LOOP_VINFO_FULLY_WITH_LENGTH_P (loop_vinfo))
   12452              :                 {
   12453           76 :                   gimple_stmt_iterator si2
   12454           76 :                     = gsi_after_labels (LOOP_VINFO_LOOP (loop_vinfo)->header);
   12455           76 :                   if ((gsi_end_p (si2)
   12456            0 :                        && (LOOP_VINFO_LOOP (loop_vinfo)->header
   12457            0 :                            != gimple_bb (last_stmt))
   12458            0 :                        && dominated_by_p (CDI_DOMINATORS,
   12459              :                                           LOOP_VINFO_LOOP (loop_vinfo)->header,
   12460            0 :                                           gimple_bb (last_stmt)))
   12461           76 :                       || (!gsi_end_p (si2)
   12462           76 :                           && last_stmt != *si2
   12463           73 :                           && vect_stmt_dominates_stmt_p (last_stmt, *si2)))
   12464            3 :                     si = si2;
   12465              :                 }
   12466              :             }
   12467              :         }
   12468              :     }
   12469              : 
   12470      1937852 :   if (place_only)
   12471              :     {
   12472       939448 :       if (dump_enabled_p () && last_stmt)
   12473         3943 :         dump_printf_loc (MSG_NOTE, vect_location,
   12474              :                          "placing node %p at %G:", (void *)node, last_stmt);
   12475              :       /* Verify we either get a stmt anchor or region start.  */
   12476       939448 :       gcc_assert ((last_stmt && gimple_bb (last_stmt))
   12477              :                   || (!last_stmt && gsi_bb (si)));
   12478       939448 :       node->si = last_stmt;
   12479       939448 :       return true;
   12480              :     }
   12481              : 
   12482              :   /* ???  Asserting vect_stmt_dominates_stmt_p (gsi_stmt (si), node->si)
   12483              :      does not work because in some cases we advance si from last_stmt (as
   12484              :      we want to insert after vector stmts) and because vector stmts of
   12485              :      children have been inserted possibly at the same location constraint,
   12486              :      moving si even further.  */
   12487       998404 :   if (flag_checking && node->si && gimple_bb (node->si) && !gsi_end_p (si))
   12488              :     {
   12489       636587 :       auto gsi2 = si;
   12490       636587 :       while (1)
   12491              :         {
   12492       636587 :           if (vect_stmt_dominates_stmt_p (gsi_stmt (gsi2), node->si))
   12493              :             break;
   12494              :           /* As we have possibly advanced si it might now point to the
   12495              :              scalar stmt immediately following node->si.  That's OK.  */
   12496        30224 :           if (gsi_stmt (gsi2) != gsi_stmt (si)
   12497        30224 :               && gimple_uid (gsi_stmt (gsi2)) != 0)
   12498            0 :             gcc_unreachable ();
   12499        30224 :           gsi_prev (&gsi2);
   12500        30224 :           if (gsi_end_p (gsi2))
   12501              :             {
   12502          618 :               if (is_a <gphi *> (node->si)
   12503          618 :                   && gimple_bb (node->si) == gsi_bb (si))
   12504              :                 break;
   12505            0 :               gcc_unreachable ();
   12506              :             }
   12507              :         }
   12508              :     }
   12509              : 
   12510       998404 :   if (dump_enabled_p ())
   12511              :     {
   12512        72819 :       if (stmt_info)
   12513        69397 :         dump_printf_loc (MSG_NOTE, vect_location,
   12514              :                          "------>vectorizing SLP node starting from: %G",
   12515              :                          stmt_info->stmt);
   12516              :       else
   12517              :         {
   12518         3422 :           dump_printf_loc (MSG_NOTE, vect_location,
   12519              :                            "------>vectorizing SLP node:\n");
   12520         3422 :           vect_print_slp_tree (MSG_NOTE, vect_location, node);
   12521              :         }
   12522              :     }
   12523       998404 :   vect_transform_stmt (vinfo, stmt_info, &si, node, instance);
   12524       998404 :   return true;
   12525              : }
   12526              : 
   12527              : /* Replace scalar calls from SLP node NODE with setting of their lhs to zero.
   12528              :    For loop vectorization this is done in vectorizable_call, but for SLP
   12529              :    it needs to be deferred until end of vect_schedule_slp, because multiple
   12530              :    SLP instances may refer to the same scalar stmt.  */
   12531              : 
   12532              : static void
   12533       606036 : vect_remove_slp_scalar_calls (vec_info *vinfo,
   12534              :                               slp_tree node, hash_set<slp_tree> &visited)
   12535              : {
   12536       606036 :   gimple *new_stmt;
   12537       606036 :   gimple_stmt_iterator gsi;
   12538       606036 :   tree lhs;
   12539              : 
   12540       606036 :   if (!node || SLP_TREE_DEF_TYPE (node) != vect_internal_def)
   12541       189834 :     return;
   12542              : 
   12543       460138 :   if (visited.add (node))
   12544              :     return;
   12545              : 
   12546      1551417 :   for (auto child : SLP_TREE_CHILDREN (node))
   12547       515351 :     vect_remove_slp_scalar_calls (vinfo, child, visited);
   12548              : 
   12549      1729935 :   for (auto stmt_info : SLP_TREE_SCALAR_STMTS (node))
   12550              :     {
   12551       489939 :       if (!stmt_info)
   12552         4006 :         continue;
   12553       485933 :       stmt_info = vect_orig_stmt (stmt_info);
   12554       485933 :       gcall *stmt = dyn_cast <gcall *> (stmt_info->stmt);
   12555         5166 :       if (!stmt || gimple_bb (stmt) == NULL)
   12556       480809 :         continue;
   12557         5124 :       lhs = gimple_call_lhs (stmt);
   12558         5124 :       if (lhs)
   12559         4553 :         new_stmt = gimple_build_assign (lhs, build_zero_cst (TREE_TYPE (lhs)));
   12560              :       else
   12561          571 :         new_stmt = gimple_build_nop ();
   12562         5124 :       unlink_stmt_vdef (stmt_info->stmt);
   12563         5124 :       gsi = gsi_for_stmt (stmt);
   12564         5124 :       vinfo->replace_stmt (&gsi, stmt_info, new_stmt);
   12565         5124 :       if (lhs)
   12566         4553 :         SSA_NAME_DEF_STMT (lhs) = new_stmt;
   12567              :     }
   12568              : }
   12569              : 
   12570              : static void
   12571        90685 : vect_remove_slp_scalar_calls (vec_info *vinfo, slp_tree node)
   12572              : {
   12573        90685 :   hash_set<slp_tree> visited;
   12574        90685 :   vect_remove_slp_scalar_calls (vinfo, node, visited);
   12575        90685 : }
   12576              : 
   12577              : /* Vectorize the instance root.  */
   12578              : 
   12579              : void
   12580        14746 : vectorize_slp_instance_root_stmt (vec_info *vinfo, slp_tree node, slp_instance instance)
   12581              : {
   12582        14746 :   if (instance->kind == slp_inst_kind_ctor)
   12583              :     {
   12584         5661 :       tree new_def;
   12585         5661 :       if (SLP_TREE_VEC_DEFS (node).length () == 1)
   12586              :         {
   12587         5616 :           new_def = SLP_TREE_VEC_DEFS (node)[0];
   12588         5616 :           tree root_lhs = gimple_get_lhs (instance->root_stmts[0]->stmt);
   12589         5616 :           if (!useless_type_conversion_p (TREE_TYPE (root_lhs),
   12590         5616 :                                           TREE_TYPE (new_def)))
   12591            0 :             new_def = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (root_lhs),
   12592              :                                new_def);
   12593              :         }
   12594              :       else
   12595              :         {
   12596           45 :           gcc_assert (SLP_TREE_VEC_DEFS (node).length () > 1);
   12597           45 :           tree child_def;
   12598           45 :           int j;
   12599           45 :           vec<constructor_elt, va_gc> *v;
   12600           45 :           vec_alloc (v, SLP_TREE_VEC_DEFS (node).length ());
   12601              : 
   12602              :           /* A CTOR can handle V16HI composition from VNx8HI so we
   12603              :              do not need to convert vector elements if the types
   12604              :              do not match.  */
   12605          180 :           FOR_EACH_VEC_ELT (SLP_TREE_VEC_DEFS (node), j, child_def)
   12606           90 :             CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, child_def);
   12607           45 :           tree rtype
   12608           45 :             = TREE_TYPE (gimple_assign_rhs1 (instance->root_stmts[0]->stmt));
   12609           45 :           new_def = build_constructor (rtype, v);
   12610              :         }
   12611              : 
   12612         5661 :       gimple_stmt_iterator rgsi = gsi_for_stmt (instance->root_stmts[0]->stmt);
   12613         5661 :       gimple_assign_set_rhs_from_tree (&rgsi, new_def);
   12614         5661 :       update_stmt (gsi_stmt (rgsi));
   12615         5661 :       return;
   12616              :     }
   12617         9085 :   else if (instance->kind == slp_inst_kind_bb_reduc)
   12618              :     {
   12619              :       /* Largely inspired by reduction chain epilogue handling in
   12620              :          vect_create_epilog_for_reduction.  */
   12621         7457 :       vec<tree> vec_defs = vNULL;
   12622         7457 :       vect_get_slp_defs (node, &vec_defs);
   12623         7457 :       enum tree_code reduc_code
   12624         7457 :         = gimple_assign_rhs_code (instance->root_stmts[0]->stmt);
   12625              :       /* ???  We actually have to reflect signs somewhere.  */
   12626         7457 :       if (reduc_code == MINUS_EXPR)
   12627            0 :         reduc_code = PLUS_EXPR;
   12628         7457 :       gimple_seq epilogue = NULL;
   12629              :       /* We may end up with more than one vector result, reduce them
   12630              :          to one vector.  */
   12631         7457 :       tree vec_def = vec_defs[0];
   12632         7457 :       tree vectype = TREE_TYPE (vec_def);
   12633         7457 :       tree compute_vectype = vectype;
   12634         7457 :       bool pun_for_overflow_p = (ANY_INTEGRAL_TYPE_P (vectype)
   12635         6305 :                                  && TYPE_OVERFLOW_UNDEFINED (vectype)
   12636        11943 :                                  && operation_can_overflow (reduc_code));
   12637         3922 :       if (pun_for_overflow_p)
   12638              :         {
   12639         3922 :           compute_vectype = unsigned_type_for (vectype);
   12640         3922 :           vec_def = gimple_build (&epilogue, VIEW_CONVERT_EXPR,
   12641              :                                   compute_vectype, vec_def);
   12642              :         }
   12643        10764 :       for (unsigned i = 1; i < vec_defs.length (); ++i)
   12644              :         {
   12645         3307 :           tree def = vec_defs[i];
   12646         3307 :           if (pun_for_overflow_p)
   12647         3111 :             def = gimple_build (&epilogue, VIEW_CONVERT_EXPR,
   12648              :                                 compute_vectype, def);
   12649         3307 :           vec_def = gimple_build (&epilogue, reduc_code, compute_vectype,
   12650              :                                   vec_def, def);
   12651              :         }
   12652         7457 :       vec_defs.release ();
   12653              :       /* ???  Support other schemes than direct internal fn or two
   12654              :          element vectors.  */
   12655         7457 :       tree scalar_def;
   12656         7457 :       internal_fn reduc_fn;
   12657         9143 :       if (!reduction_fn_for_scalar_code (reduc_code, &reduc_fn)
   12658         7457 :           || reduc_fn == IFN_LAST
   12659        14914 :           || !direct_internal_fn_supported_p (reduc_fn, compute_vectype,
   12660              :                                               OPTIMIZE_FOR_BOTH))
   12661              :         {
   12662         1686 :           gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (compute_vectype), 2u));
   12663         1686 :           tree tem0 = gimple_build (&epilogue, BIT_FIELD_REF,
   12664         1686 :                                     TREE_TYPE (compute_vectype), vec_def,
   12665         1686 :                                     TYPE_SIZE (TREE_TYPE (compute_vectype)),
   12666         1686 :                                     bitsize_zero_node);
   12667         1686 :           tree tem1 = gimple_build (&epilogue, BIT_FIELD_REF,
   12668         1686 :                                     TREE_TYPE (compute_vectype), vec_def,
   12669         1686 :                                     TYPE_SIZE (TREE_TYPE (compute_vectype)),
   12670         1686 :                                     TYPE_SIZE (TREE_TYPE (compute_vectype)));
   12671         1686 :           scalar_def = gimple_build (&epilogue, reduc_code,
   12672         1686 :                                      TREE_TYPE (compute_vectype), tem0, tem1);
   12673              :         }
   12674              :       else
   12675         5771 :         scalar_def = gimple_build (&epilogue, as_combined_fn (reduc_fn),
   12676         5771 :                                    TREE_TYPE (compute_vectype), vec_def);
   12677         7457 :       if (!SLP_INSTANCE_REMAIN_DEFS (instance).is_empty ())
   12678              :         {
   12679         4352 :           tree rem_def = NULL_TREE;
   12680        17528 :           for (auto def : SLP_INSTANCE_REMAIN_DEFS (instance))
   12681              :             {
   12682        13176 :               def = gimple_convert (&epilogue, TREE_TYPE (scalar_def), def);
   12683        13176 :               if (!rem_def)
   12684              :                 rem_def = def;
   12685              :               else
   12686         8824 :                 rem_def = gimple_build (&epilogue, reduc_code,
   12687         8824 :                                         TREE_TYPE (scalar_def),
   12688              :                                         rem_def, def);
   12689              :             }
   12690         4352 :           scalar_def = gimple_build (&epilogue, reduc_code,
   12691         4352 :                                      TREE_TYPE (scalar_def),
   12692              :                                      scalar_def, rem_def);
   12693              :         }
   12694         7457 :       scalar_def = gimple_convert (&epilogue,
   12695         7457 :                                    TREE_TYPE (vectype), scalar_def);
   12696         7457 :       gimple_stmt_iterator rgsi = gsi_for_stmt (instance->root_stmts[0]->stmt);
   12697         7457 :       gsi_insert_seq_before (&rgsi, epilogue, GSI_SAME_STMT);
   12698         7457 :       gimple_assign_set_rhs_from_tree (&rgsi, scalar_def);
   12699         7457 :       update_stmt (gsi_stmt (rgsi));
   12700         7457 :       return;
   12701              :     }
   12702         1628 :   else if (instance->kind == slp_inst_kind_gcond)
   12703              :     {
   12704              :       /* Only support a single root for now as we can't codegen CFG yet and so we
   12705              :          can't support lane > 1 at this time.  */
   12706         1628 :       gcc_assert (instance->root_stmts.length () == 1);
   12707         1628 :       auto root_stmt_info = instance->root_stmts[0];
   12708         1628 :       auto last_stmt = STMT_VINFO_STMT (vect_orig_stmt (root_stmt_info));
   12709         1628 :       gimple_stmt_iterator rgsi = gsi_for_stmt (last_stmt);
   12710         1628 :       gcc_assert (!SLP_TREE_VEC_DEFS (node).is_empty ());
   12711         1628 :       bool res = vectorizable_early_exit (as_a <loop_vec_info> (vinfo),
   12712              :                                           root_stmt_info, &rgsi, node, NULL);
   12713         1628 :       gcc_assert (res);
   12714         1628 :       return;
   12715              :     }
   12716              :   else
   12717            0 :     gcc_unreachable ();
   12718              : }
   12719              : 
   12720              : struct slp_scc_info
   12721              : {
   12722              :   bool on_stack;
   12723              :   bool res;
   12724              :   int dfs;
   12725              :   int lowlink;
   12726              : };
   12727              : 
   12728              : /* Schedule the SLP INSTANCE doing a DFS walk and collecting SCCs.
   12729              :    When PLACE_ONLY, return false if there is no possible schedule.  */
   12730              : 
   12731              : static bool
   12732      3147937 : vect_schedule_scc (vec_info *vinfo, slp_tree node, slp_instance instance,
   12733              :                    hash_map<slp_tree, slp_scc_info> &scc_info,
   12734              :                    int &maxdfs, vec<slp_tree> &stack, bool place_only)
   12735              : {
   12736      3147937 :   bool existed_p;
   12737      3147937 :   slp_scc_info *info = &scc_info.get_or_insert (node, &existed_p);
   12738      3147937 :   gcc_assert (!existed_p);
   12739      3147937 :   info->dfs = maxdfs;
   12740      3147937 :   info->lowlink = maxdfs;
   12741      3147937 :   maxdfs++;
   12742              : 
   12743              :   /* Leaf.  */
   12744      3147937 :   if (SLP_TREE_DEF_TYPE (node) != vect_internal_def)
   12745              :     {
   12746      1210071 :       info->on_stack = false;
   12747      1210071 :       bool res = vect_schedule_slp_node (vinfo, node, instance, place_only);
   12748      1210071 :       gcc_assert (res);
   12749      1210071 :       info->res = res;
   12750      1210071 :       return res;
   12751              :     }
   12752              : 
   12753      1937866 :   info->on_stack = true;
   12754      1937866 :   info->res = true;
   12755      1937866 :   stack.safe_push (node);
   12756              : 
   12757      1937866 :   bool res = true;
   12758      1937866 :   unsigned i;
   12759      1937866 :   slp_tree child;
   12760              :   /* DFS recurse.  */
   12761      7570556 :   FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (node), i, child)
   12762              :     {
   12763      2042209 :       if (!child)
   12764        55726 :         continue;
   12765      1986483 :       slp_scc_info *child_info = scc_info.get (child);
   12766      1986483 :       if (!child_info)
   12767              :         {
   12768      1836604 :           res &= vect_schedule_scc (vinfo, child, instance, scc_info,
   12769              :                                     maxdfs, stack, place_only);
   12770              :           /* Recursion might have re-allocated the node.  */
   12771      1836604 :           info = scc_info.get (node);
   12772      1836604 :           child_info = scc_info.get (child);
   12773      1836604 :           info->lowlink = MIN (info->lowlink, child_info->lowlink);
   12774              :         }
   12775       149879 :       else if (child_info->on_stack)
   12776        35792 :         info->lowlink = MIN (info->lowlink, child_info->dfs);
   12777              :       else
   12778       114087 :         res &= child_info->res;
   12779              :     }
   12780      1937866 :   if (info->lowlink != info->dfs)
   12781              :     return res;
   12782              : 
   12783      1898230 :   auto_vec<slp_tree, 4> phis_to_fixup;
   12784              : 
   12785              :   /* Singleton.  */
   12786      1898230 :   if (stack.last () == node)
   12787              :     {
   12788      1869106 :       stack.pop ();
   12789      1869106 :       info->on_stack = false;
   12790      1869106 :       res &= vect_schedule_slp_node (vinfo, node, instance, place_only);
   12791      1869106 :       info->res = res;
   12792      1869106 :       if (!SLP_TREE_PERMUTE_P (node)
   12793      1869106 :           && is_a <gphi *> (SLP_TREE_REPRESENTATIVE (node)->stmt))
   12794        73579 :         phis_to_fixup.quick_push (node);
   12795              :     }
   12796              :   else
   12797              :     {
   12798              :       /* SCC.  */
   12799        29124 :       int last_idx = stack.length () - 1;
   12800        68760 :       while (stack[last_idx] != node)
   12801        39636 :         last_idx--;
   12802              :       /* We can break the cycle at PHIs who have at least one child
   12803              :          code generated.  Then we could re-start the DFS walk until
   12804              :          all nodes in the SCC are covered (we might have new entries
   12805              :          for only back-reachable nodes).  But it's simpler to just
   12806              :          iterate and schedule those that are ready.  */
   12807        29124 :       unsigned todo = stack.length () - last_idx;
   12808        29124 :       auto_vec<slp_tree, 4> saved_scc (todo);
   12809        87372 :       memcpy (saved_scc.address (), stack.address ()[last_idx + 1],
   12810              :               sizeof (slp_tree) * todo);
   12811        29959 :       do
   12812              :         {
   12813       132934 :           for (int idx = stack.length () - 1; idx >= last_idx; --idx)
   12814              :             {
   12815        73016 :               slp_tree entry = stack[idx];
   12816        73016 :               if (!entry)
   12817         2561 :                 continue;
   12818        70455 :               bool phi = (!SLP_TREE_PERMUTE_P (entry)
   12819        70455 :                           && is_a <gphi *> (SLP_TREE_REPRESENTATIVE (entry)->stmt));
   12820        70455 :               bool ready = !phi;
   12821       214280 :               FOR_EACH_VEC_ELT (SLP_TREE_CHILDREN (entry), i, child)
   12822       133586 :                 if (!child)
   12823              :                   {
   12824        23081 :                     gcc_assert (phi);
   12825              :                     ready = true;
   12826              :                     break;
   12827              :                   }
   12828       110505 :                 else if (scc_info.get (child)->on_stack)
   12829              :                   {
   12830        31008 :                     if (!phi)
   12831              :                       {
   12832              :                         ready = false;
   12833              :                         break;
   12834              :                       }
   12835              :                   }
   12836              :                 else
   12837              :                   {
   12838        79497 :                     if (phi)
   12839              :                       {
   12840              :                         ready = true;
   12841              :                         break;
   12842              :                       }
   12843              :                   }
   12844        47374 :               if (ready)
   12845              :                 {
   12846        68760 :                   res &= vect_schedule_slp_node (vinfo, entry, instance,
   12847              :                                                  place_only);
   12848        68760 :                   scc_info.get (entry)->on_stack = false;
   12849        68760 :                   stack[idx] = NULL;
   12850        68760 :                   todo--;
   12851        68760 :                   if (phi)
   12852        35628 :                     phis_to_fixup.safe_push (entry);
   12853              :                 }
   12854              :             }
   12855              :         }
   12856        29959 :       while (todo != 0);
   12857              : 
   12858              :       /* Push the scheduling result to all of the SCC.  */
   12859        87372 :       for (slp_tree entry : saved_scc)
   12860            0 :         scc_info.get (entry)->res = res;
   12861              : 
   12862              :       /* Pop the SCC.  */
   12863        29124 :       stack.truncate (last_idx);
   12864        29124 :     }
   12865              : 
   12866      1898230 :   if (place_only)
   12867              :     return res;
   12868              : 
   12869              :   /* Now fixup the backedge def of the vectorized PHIs in this SCC.  */
   12870              :   slp_tree phi_node;
   12871      1022381 :   FOR_EACH_VEC_ELT (phis_to_fixup, i, phi_node)
   12872              :     {
   12873        56034 :       gphi *phi = as_a <gphi *> (SLP_TREE_REPRESENTATIVE (phi_node)->stmt);
   12874        56034 :       edge_iterator ei;
   12875        56034 :       edge e;
   12876       176462 :       FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
   12877              :         {
   12878       120428 :           unsigned dest_idx = e->dest_idx;
   12879       120428 :           child = SLP_TREE_CHILDREN (phi_node)[dest_idx];
   12880       120428 :           if (!child || SLP_TREE_DEF_TYPE (child) != vect_internal_def)
   12881        67256 :             continue;
   12882        53172 :           unsigned n = SLP_TREE_VEC_DEFS (phi_node).length ();
   12883              :           /* Simply fill all args.  */
   12884        53172 :           if (STMT_VINFO_DEF_TYPE (SLP_TREE_REPRESENTATIVE (phi_node))
   12885              :               != vect_first_order_recurrence)
   12886       112342 :             for (unsigned i = 0; i < n; ++i)
   12887              :               {
   12888        59213 :                 tree phidef = SLP_TREE_VEC_DEFS (phi_node)[i];
   12889        59213 :                 gphi *phi = as_a <gphi *> (SSA_NAME_DEF_STMT (phidef));
   12890        59213 :                 add_phi_arg (phi, vect_get_slp_vect_def (child, i),
   12891              :                              e, gimple_phi_arg_location (phi, dest_idx));
   12892              :               }
   12893              :           else
   12894              :             {
   12895              :               /* Unless it is a first order recurrence which needs
   12896              :                  args filled in for both the PHI node and the permutes.  */
   12897           43 :               gimple *perm
   12898           43 :                 = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (phi_node)[0]);
   12899           43 :               gimple *rphi = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (perm));
   12900           43 :               add_phi_arg (as_a <gphi *> (rphi),
   12901              :                            vect_get_slp_vect_def (child, n - 1),
   12902              :                            e, gimple_phi_arg_location (phi, dest_idx));
   12903          166 :               for (unsigned i = 0; i < n; ++i)
   12904              :                 {
   12905           80 :                   gimple *perm
   12906           80 :                     = SSA_NAME_DEF_STMT (SLP_TREE_VEC_DEFS (phi_node)[i]);
   12907           80 :                   if (i > 0)
   12908           37 :                     gimple_assign_set_rhs1 (perm,
   12909              :                                             vect_get_slp_vect_def (child, i - 1));
   12910           80 :                   gimple_assign_set_rhs2 (perm,
   12911              :                                           vect_get_slp_vect_def (child, i));
   12912           80 :                   update_stmt (perm);
   12913              :                 }
   12914              :             }
   12915              :         }
   12916              :     }
   12917              : 
   12918       966347 :   gcc_assert (res);
   12919              :   return true;
   12920      1898230 : }
   12921              : 
   12922              : /* Generate vector code for SLP_INSTANCES in the loop/basic block.  Perform
   12923              :    vector stmt placement only when PLACE_ONLY is true, removing SLP graph
   12924              :    entries that cannot be scheduled.  If placing, return false if a schedule
   12925              :    cannot be computed for any entry.  */
   12926              : 
   12927              : bool
   12928       804364 : vect_schedule_slp (vec_info *vinfo, vec<slp_instance> &slp_instances,
   12929              :                    bool place_only)
   12930              : {
   12931       804364 :   slp_instance instance;
   12932       804364 :   unsigned int i;
   12933              : 
   12934       804364 :   hash_map<slp_tree, slp_scc_info> scc_info;
   12935       804364 :   int maxdfs = 0;
   12936      2119579 :   for (i = 0; slp_instances.iterate (i, &instance); )
   12937              :     {
   12938      1315215 :       slp_tree node = SLP_INSTANCE_TREE (instance);
   12939      1315215 :       if (!place_only && dump_enabled_p ())
   12940              :         {
   12941        16284 :           dump_printf_loc (MSG_NOTE, vect_location,
   12942              :                            "Vectorizing SLP tree:\n");
   12943              :           /* ???  Dump all?  */
   12944        16284 :           if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
   12945          522 :             dump_printf_loc (MSG_NOTE, vect_location, "Root stmt: %G",
   12946          522 :                          SLP_INSTANCE_ROOT_STMTS (instance)[0]->stmt);
   12947        16284 :           vect_print_slp_graph (MSG_NOTE, vect_location,
   12948              :                                 SLP_INSTANCE_TREE (instance));
   12949              :         }
   12950              :       /* Schedule the tree of INSTANCE, scheduling SCCs in a way to
   12951              :          have a PHI be the node breaking the cycle.  */
   12952      1315215 :       bool res;
   12953      1315215 :       if (slp_scc_info *info = scc_info.get (node))
   12954         3882 :         res = info->res;
   12955              :       else
   12956              :         {
   12957      1311333 :           auto_vec<slp_tree> stack;
   12958      1311333 :           res = vect_schedule_scc (vinfo, node, instance, scc_info,
   12959              :                                    maxdfs, stack, place_only);
   12960      1311333 :         }
   12961              : 
   12962      1315215 :       if (!SLP_INSTANCE_ROOT_STMTS (instance).is_empty ())
   12963              :         {
   12964        66670 :           if (place_only)
   12965              :             {
   12966        51924 :               gimple *root_stmt = instance->root_stmts[0]->stmt;
   12967        51924 :               res &= (!node->si
   12968              :                       /* As we instert after node->si it may not be the
   12969              :                          root_stmt itself.  */
   12970        51924 :                       || (node->si != root_stmt
   12971        51031 :                           && vect_stmt_dominates_stmt_p (node->si, root_stmt)));
   12972              :             }
   12973              :           else
   12974        14746 :             vectorize_slp_instance_root_stmt (vinfo, node, instance);
   12975              :         }
   12976              : 
   12977      1315215 :       if (!place_only && dump_enabled_p ())
   12978        16284 :         dump_printf_loc (MSG_NOTE, vect_location,
   12979              :                          "vectorizing stmts using SLP.\n");
   12980              : 
   12981      1315215 :       if (!res)
   12982              :         {
   12983           40 :           gcc_assert (place_only);
   12984           40 :           if (dump_enabled_p ())
   12985           26 :             dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
   12986              :                              "not vectorized: cannot schedule SLP graph "
   12987              :                              "entry %p\n", (void *)instance);
   12988           40 :           vect_free_slp_instance (instance);
   12989           40 :           slp_instances.ordered_remove (i);
   12990           40 :           continue;
   12991              :         }
   12992      1315175 :       ++i;
   12993              :     }
   12994              : 
   12995       804364 :   if (place_only)
   12996       494644 :     return !slp_instances.is_empty ();
   12997              : 
   12998      1959071 :   FOR_EACH_VEC_ELT (slp_instances, i, instance)
   12999              :     {
   13000       597665 :       slp_tree root = SLP_INSTANCE_TREE (instance);
   13001       597665 :       stmt_vec_info store_info;
   13002       597665 :       unsigned int j;
   13003              : 
   13004              :       /* Remove scalar call stmts.  Do not do this for basic-block
   13005              :          vectorization as not all uses may be vectorized.
   13006              :          ???  Why should this be necessary?  DCE should be able to
   13007              :          remove the stmts itself.
   13008              :          ???  For BB vectorization we can as well remove scalar
   13009              :          stmts starting from the SLP tree root if they have no
   13010              :          uses.  */
   13011       597665 :       if (is_a <loop_vec_info> (vinfo))
   13012        90685 :         vect_remove_slp_scalar_calls (vinfo, root);
   13013              : 
   13014              :       /* Remove vectorized stores original scalar stmts.  */
   13015      2661692 :       for (j = 0; SLP_TREE_SCALAR_STMTS (root).iterate (j, &store_info); j++)
   13016              :         {
   13017      1506626 :           if (!store_info
   13018      1506612 :               || !STMT_VINFO_DATA_REF (store_info)
   13019      1477029 :               || !DR_IS_WRITE (STMT_VINFO_DATA_REF (store_info)))
   13020              :             break;
   13021              : 
   13022      1466362 :           store_info = vect_orig_stmt (store_info);
   13023              :           /* Free the attached stmt_vec_info and remove the stmt.  */
   13024      1466362 :           vinfo->remove_stmt (store_info);
   13025              : 
   13026              :           /* Invalidate SLP_TREE_REPRESENTATIVE in case we released it
   13027              :              to not crash in vect_free_slp_tree later.  */
   13028      1466362 :           if (SLP_TREE_REPRESENTATIVE (root) == store_info)
   13029       557063 :             SLP_TREE_REPRESENTATIVE (root) = NULL;
   13030              :         }
   13031              :     }
   13032              : 
   13033              :   return true;
   13034       804364 : }
        

Generated by: LCOV version 2.4-beta

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