LCOV - code coverage report
Current view: top level - gcc - tree-ssa-loop-im.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 98.2 % 1681 1651
Test Date: 2026-12-05 16:10:02 Functions: 100.0 % 80 80
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Loop invariant motion.
       2              :    Copyright (C) 2003-2026 Free Software Foundation, Inc.
       3              : 
       4              : This file is part of GCC.
       5              : 
       6              : GCC is free software; you can redistribute it and/or modify it
       7              : under the terms of the GNU General Public License as published by the
       8              : Free Software Foundation; either version 3, or (at your option) any
       9              : later version.
      10              : 
      11              : GCC is distributed in the hope that it will be useful, but WITHOUT
      12              : ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
      13              : FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      14              : for more details.
      15              : 
      16              : You should have received a copy of the GNU General Public License
      17              : along with GCC; see the file COPYING3.  If not see
      18              : <http://www.gnu.org/licenses/>.  */
      19              : 
      20              : #include "config.h"
      21              : #include "system.h"
      22              : #include "coretypes.h"
      23              : #include "backend.h"
      24              : #include "tree.h"
      25              : #include "gimple.h"
      26              : #include "cfghooks.h"
      27              : #include "tree-pass.h"
      28              : #include "ssa.h"
      29              : #include "gimple-pretty-print.h"
      30              : #include "fold-const.h"
      31              : #include "cfganal.h"
      32              : #include "tree-eh.h"
      33              : #include "gimple-iterator.h"
      34              : #include "tree-cfg.h"
      35              : #include "tree-ssa-loop-manip.h"
      36              : #include "tree-ssa-loop.h"
      37              : #include "tree-into-ssa.h"
      38              : #include "cfgloop.h"
      39              : #include "tree-affine.h"
      40              : #include "tree-ssa-propagate.h"
      41              : #include "trans-mem.h"
      42              : #include "gimple-fold.h"
      43              : #include "tree-scalar-evolution.h"
      44              : #include "tree-ssa-loop-niter.h"
      45              : #include "alias.h"
      46              : #include "builtins.h"
      47              : #include "tree-dfa.h"
      48              : #include "tree-ssa.h"
      49              : #include "dbgcnt.h"
      50              : #include "insn-codes.h"
      51              : #include "optabs-tree.h"
      52              : 
      53              : /* TODO:  Support for predicated code motion.  I.e.
      54              : 
      55              :    while (1)
      56              :      {
      57              :        if (cond)
      58              :          {
      59              :            a = inv;
      60              :            something;
      61              :          }
      62              :      }
      63              : 
      64              :    Where COND and INV are invariants, but evaluating INV may trap or be
      65              :    invalid from some other reason if !COND.  This may be transformed to
      66              : 
      67              :    if (cond)
      68              :      a = inv;
      69              :    while (1)
      70              :      {
      71              :        if (cond)
      72              :          something;
      73              :      }  */
      74              : 
      75              : /* The auxiliary data kept for each statement.  */
      76              : 
      77              : struct lim_aux_data
      78              : {
      79              :   class loop *max_loop; /* The outermost loop in that the statement
      80              :                                    is invariant.  */
      81              : 
      82              :   class loop *tgt_loop; /* The loop out of that we want to move the
      83              :                                    invariant.  */
      84              : 
      85              :   class loop *always_executed_in;
      86              :                                 /* The outermost loop for that we are sure
      87              :                                    the statement is executed if the loop
      88              :                                    is entered.  */
      89              : 
      90              :   unsigned cost;                /* Cost of the computation performed by the
      91              :                                    statement.  */
      92              : 
      93              :   unsigned ref;                 /* The simple_mem_ref in this stmt or 0.  */
      94              : 
      95              :   vec<gimple *> depends;  /* Vector of statements that must be also
      96              :                                    hoisted out of the loop when this statement
      97              :                                    is hoisted; i.e. those that define the
      98              :                                    operands of the statement and are inside of
      99              :                                    the MAX_LOOP loop.  */
     100              : };
     101              : 
     102              : /* Maps statements to their lim_aux_data.  */
     103              : 
     104              : static hash_map<gimple *, lim_aux_data *> *lim_aux_data_map;
     105              : 
     106              : /* Description of a memory reference location.  */
     107              : 
     108              : struct mem_ref_loc
     109              : {
     110              :   tree *ref;                    /* The reference itself.  */
     111              :   gimple *stmt;                 /* The statement in that it occurs.  */
     112              : };
     113              : 
     114              : 
     115              : /* Description of a memory reference.  */
     116              : 
     117              : class im_mem_ref
     118              : {
     119              : public:
     120              :   unsigned id : 30;             /* ID assigned to the memory reference
     121              :                                    (its index in memory_accesses.refs_list)  */
     122              :   unsigned ref_canonical : 1;   /* Whether mem.ref was canonicalized.  */
     123              :   unsigned ref_decomposed : 1;  /* Whether the ref was hashed from mem.  */
     124              :   hashval_t hash;               /* Its hash value.  */
     125              : 
     126              :   /* The memory access itself and associated caching of alias-oracle
     127              :      query meta-data.  We are using mem.ref == error_mark_node for the
     128              :      case the reference is represented by its single access stmt
     129              :      in accesses_in_loop[0].  */
     130              :   ao_ref mem;
     131              : 
     132              :   bitmap stored;                /* The set of loops in that this memory location
     133              :                                    is stored to.  */
     134              :   bitmap loaded;                /* The set of loops in that this memory location
     135              :                                    is loaded from.  */
     136              :   vec<mem_ref_loc>                accesses_in_loop;
     137              :                                 /* The locations of the accesses.  */
     138              : 
     139              :   /* The following set is computed on demand.  */
     140              :   bitmap_head dep_loop;         /* The set of loops in that the memory
     141              :                                    reference is {in,}dependent in
     142              :                                    different modes.  */
     143              : };
     144              : 
     145              : static bool in_loop_pipeline;
     146              : 
     147              : /* We use six bits per loop in the ref->dep_loop bitmap to record
     148              :    the dep_kind x dep_state combinations.  */
     149              : 
     150              : enum dep_kind { lim_raw, sm_war, sm_waw };
     151              : enum dep_state { dep_unknown, dep_independent, dep_dependent };
     152              : 
     153              : /* coldest outermost loop for given loop.  */
     154              : vec<class loop *> coldest_outermost_loop;
     155              : /* hotter outer loop nearest to given loop.  */
     156              : vec<class loop *> hotter_than_inner_loop;
     157              : 
     158              : /* Populate the loop dependence cache of REF for LOOP, KIND with STATE.  */
     159              : 
     160              : static void
     161      1879615 : record_loop_dependence (class loop *loop, im_mem_ref *ref,
     162              :                         dep_kind kind, dep_state state)
     163              : {
     164      1879615 :   gcc_assert (state != dep_unknown);
     165      1879615 :   unsigned bit = 6 * loop->num + kind * 2 + (state == dep_dependent);
     166      1879615 :   bitmap_set_bit (&ref->dep_loop, bit);
     167      1879615 : }
     168              : 
     169              : /* Query the loop dependence cache of REF for LOOP, KIND.  */
     170              : 
     171              : static dep_state
     172       527727 : query_loop_dependence (class loop *loop, im_mem_ref *ref, dep_kind kind)
     173              : {
     174       527727 :   unsigned first_bit = 6 * loop->num + kind * 2;
     175       527727 :   if (bitmap_bit_p (&ref->dep_loop, first_bit))
     176              :     return dep_independent;
     177       514758 :   else if (bitmap_bit_p (&ref->dep_loop, first_bit + 1))
     178        52023 :     return dep_dependent;
     179              :   return dep_unknown;
     180              : }
     181              : 
     182              : /* Mem_ref hashtable helpers.  */
     183              : 
     184              : struct mem_ref_hasher : nofree_ptr_hash <im_mem_ref>
     185              : {
     186              :   typedef ao_ref *compare_type;
     187              :   static inline hashval_t hash (const im_mem_ref *);
     188              :   static inline bool equal (const im_mem_ref *, const ao_ref *);
     189              : };
     190              : 
     191              : /* A hash function for class im_mem_ref object OBJ.  */
     192              : 
     193              : inline hashval_t
     194     12020754 : mem_ref_hasher::hash (const im_mem_ref *mem)
     195              : {
     196     12020754 :   return mem->hash;
     197              : }
     198              : 
     199              : /* An equality function for class im_mem_ref object MEM1 with
     200              :    memory reference OBJ2.  */
     201              : 
     202              : inline bool
     203     53996285 : mem_ref_hasher::equal (const im_mem_ref *mem1, const ao_ref *obj2)
     204              : {
     205     53996285 :   if (!obj2->max_size_known_p ())
     206      1513645 :     return operand_equal_p (mem1->mem.ref, obj2->ref, 0);
     207              : 
     208     52482640 :   if (!mem1->ref_decomposed)
     209              :     return false;
     210              : 
     211              :   /* obj2 is now known decomposable and the hash is based on offset,
     212              :      size and base, matching gather_mem_refs_stmt.  */
     213     51791088 :   bool refs_equal
     214     51791088 :     = ((TREE_CODE (mem1->mem.base) == MEM_REF
     215      4900728 :         && TREE_CODE (obj2->base) == MEM_REF
     216      3312856 :         && operand_equal_p (TREE_OPERAND (mem1->mem.base, 0),
     217      3312856 :                             TREE_OPERAND (obj2->base, 0), 0)
     218      1994007 :         && known_eq (mem_ref_offset (mem1->mem.base) * BITS_PER_UNIT
     219              :                      + mem1->mem.offset,
     220              :                      mem_ref_offset (obj2->base) * BITS_PER_UNIT
     221              :                      + obj2->offset))
     222     56235374 :        || (operand_equal_p (mem1->mem.base, obj2->base, 0)
     223       831726 :            && known_eq (mem1->mem.offset, obj2->offset)));
     224              : 
     225     51791088 :   return (refs_equal
     226       948318 :           && known_eq (mem1->mem.size, obj2->size)
     227       945628 :           && known_eq (mem1->mem.max_size, obj2->max_size)
     228       945628 :           && mem1->mem.volatile_p == obj2->volatile_p
     229       945612 :           && (mem1->mem.ref_alias_set == obj2->ref_alias_set
     230              :               /* We are not canonicalizing alias-sets but for the
     231              :                  special-case we didn't canonicalize yet and the
     232              :                  incoming ref is a alias-set zero MEM we pick
     233              :                  the correct one already.  */
     234        15509 :               || (!mem1->ref_canonical
     235        13916 :                   && (TREE_CODE (obj2->ref) == MEM_REF
     236        13916 :                       || TREE_CODE (obj2->ref) == TARGET_MEM_REF)
     237         8717 :                   && obj2->ref_alias_set == 0)
     238              :               /* Likewise if there's a canonical ref with alias-set zero.  */
     239        12451 :               || (mem1->ref_canonical && mem1->mem.ref_alias_set == 0))
     240       934010 :           && types_compatible_p (TREE_TYPE (mem1->mem.ref),
     241       934010 :                                  TREE_TYPE (obj2->ref)));
     242              : }
     243              : 
     244              : 
     245              : /* Description of memory accesses in loops.  */
     246              : 
     247              : static struct
     248              : {
     249              :   /* The hash table of memory references accessed in loops.  */
     250              :   hash_table<mem_ref_hasher> *refs;
     251              : 
     252              :   /* The list of memory references.  */
     253              :   vec<im_mem_ref *> refs_list;
     254              : 
     255              :   /* The set of memory references accessed in each loop.  */
     256              :   vec<bitmap_head> refs_loaded_in_loop;
     257              : 
     258              :   /* The set of memory references stored in each loop.  */
     259              :   vec<bitmap_head> refs_stored_in_loop;
     260              : 
     261              :   /* The set of memory references stored in each loop, including subloops .  */
     262              :   vec<bitmap_head> all_refs_stored_in_loop;
     263              : 
     264              :   /* Cache for expanding memory addresses.  */
     265              :   hash_map<tree, name_expansion *> *ttae_cache;
     266              : } memory_accesses;
     267              : 
     268              : /* Obstack for the bitmaps in the above data structures.  */
     269              : static bitmap_obstack lim_bitmap_obstack;
     270              : static obstack mem_ref_obstack;
     271              : 
     272              : static bool ref_indep_loop_p (class loop *, im_mem_ref *, dep_kind);
     273              : static bool ref_always_stored_p (class loop *, im_mem_ref *);
     274              : static bool refs_independent_p (im_mem_ref *, im_mem_ref *, bool = true);
     275              : 
     276              : /* Minimum cost of an expensive expression.  */
     277              : #define LIM_EXPENSIVE ((unsigned) param_lim_expensive)
     278              : 
     279              : /* The outermost loop for which execution of the header guarantees that the
     280              :    block will be executed.  */
     281              : #define ALWAYS_EXECUTED_IN(BB) ((class loop *) (BB)->aux)
     282              : #define SET_ALWAYS_EXECUTED_IN(BB, VAL) ((BB)->aux = (void *) (VAL))
     283              : 
     284              : /* ID of the shared unanalyzable mem.  */
     285              : #define UNANALYZABLE_MEM_ID 0
     286              : 
     287              : /* Whether the reference was analyzable.  */
     288              : #define MEM_ANALYZABLE(REF) ((REF)->id != UNANALYZABLE_MEM_ID)
     289              : 
     290              : static struct lim_aux_data *
     291     18536632 : init_lim_data (gimple *stmt)
     292              : {
     293     18536632 :   lim_aux_data *p = XCNEW (struct lim_aux_data);
     294     18536632 :   lim_aux_data_map->put (stmt, p);
     295              : 
     296     18536632 :   return p;
     297              : }
     298              : 
     299              : static struct lim_aux_data *
     300     99807914 : get_lim_data (gimple *stmt)
     301              : {
     302     99807914 :   lim_aux_data **p = lim_aux_data_map->get (stmt);
     303     99807914 :   if (!p)
     304              :     return NULL;
     305              : 
     306     50437104 :   return *p;
     307              : }
     308              : 
     309              : /* Releases the memory occupied by DATA.  */
     310              : 
     311              : static void
     312     18536437 : free_lim_aux_data (struct lim_aux_data *data)
     313              : {
     314            0 :   data->depends.release ();
     315     18536437 :   free (data);
     316            0 : }
     317              : 
     318              : static void
     319     18536437 : clear_lim_data (gimple *stmt)
     320              : {
     321     18536437 :   lim_aux_data **p = lim_aux_data_map->get (stmt);
     322     18536437 :   if (!p)
     323              :     return;
     324              : 
     325     18536437 :   free_lim_aux_data (*p);
     326     18536437 :   *p = NULL;
     327              : }
     328              : 
     329              : 
     330              : /* The possibilities of statement movement.  */
     331              : enum move_pos
     332              :   {
     333              :     MOVE_IMPOSSIBLE,            /* No movement -- side effect expression.  */
     334              :     MOVE_PRESERVE_EXECUTION,    /* Must not cause the non-executed statement
     335              :                                    become executed -- memory accesses, ... */
     336              :     MOVE_POSSIBLE               /* Unlimited movement.  */
     337              :   };
     338              : 
     339              : 
     340              : /* If it is possible to hoist the statement STMT unconditionally,
     341              :    returns MOVE_POSSIBLE.
     342              :    If it is possible to hoist the statement STMT, but we must avoid making
     343              :    it executed if it would not be executed in the original program (e.g.
     344              :    because it may trap), return MOVE_PRESERVE_EXECUTION.
     345              :    Otherwise return MOVE_IMPOSSIBLE.  */
     346              : 
     347              : static enum move_pos
     348     49803101 : movement_possibility_1 (gimple *stmt)
     349              : {
     350     49803101 :   tree lhs;
     351     49803101 :   enum move_pos ret = MOVE_POSSIBLE;
     352              : 
     353     49803101 :   if (flag_unswitch_loops
     354     49803101 :       && gimple_code (stmt) == GIMPLE_COND)
     355              :     {
     356              :       /* If we perform unswitching, force the operands of the invariant
     357              :          condition to be moved out of the loop.  */
     358              :       return MOVE_POSSIBLE;
     359              :     }
     360              : 
     361     49419347 :   if (gimple_code (stmt) == GIMPLE_PHI
     362      2692308 :       && gimple_phi_num_args (stmt) <= 2
     363      5019774 :       && !virtual_operand_p (gimple_phi_result (stmt))
     364     50919626 :       && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt)))
     365              :     return MOVE_POSSIBLE;
     366              : 
     367     47919342 :   if (gimple_get_lhs (stmt) == NULL_TREE)
     368              :     return MOVE_IMPOSSIBLE;
     369              : 
     370     33015747 :   if (gimple_vdef (stmt))
     371              :     return MOVE_IMPOSSIBLE;
     372              : 
     373     13837026 :   if (stmt_ends_bb_p (stmt)
     374     12617080 :       || gimple_has_volatile_ops (stmt)
     375     13780927 :       || gimple_has_side_effects (stmt)
     376     27611461 :       || stmt_could_throw_p (cfun, stmt))
     377              :     return MOVE_IMPOSSIBLE;
     378              : 
     379     13376166 :   if (is_gimple_call (stmt))
     380              :     {
     381              :       /* While pure or const call is guaranteed to have no side effects, we
     382              :          cannot move it arbitrarily.  Consider code like
     383              : 
     384              :          char *s = something ();
     385              : 
     386              :          while (1)
     387              :            {
     388              :              if (s)
     389              :                t = strlen (s);
     390              :              else
     391              :                t = 0;
     392              :            }
     393              : 
     394              :          Here the strlen call cannot be moved out of the loop, even though
     395              :          s is invariant.  In addition to possibly creating a call with
     396              :          invalid arguments, moving out a function call that is not executed
     397              :          may cause performance regressions in case the call is costly and
     398              :          not executed at all.  */
     399       129646 :       ret = MOVE_PRESERVE_EXECUTION;
     400       129646 :       lhs = gimple_call_lhs (stmt);
     401              :     }
     402     13246520 :   else if (auto assign = dyn_cast<gassign *> (stmt))
     403     12054217 :     lhs = gimple_assign_lhs (assign);
     404              :   else
     405              :     return MOVE_IMPOSSIBLE;
     406              : 
     407     12183863 :   if (TREE_CODE (lhs) == SSA_NAME
     408     12183863 :       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
     409              :     return MOVE_IMPOSSIBLE;
     410              : 
     411     12183650 :   if (TREE_CODE (lhs) != SSA_NAME
     412     12183650 :       || gimple_could_trap_p (stmt))
     413              :     return MOVE_PRESERVE_EXECUTION;
     414              : 
     415      9714342 :   if (is_gimple_assign (stmt))
     416              :     {
     417      9592949 :       auto code = gimple_assign_rhs_code (stmt);
     418      9592949 :       tree type = TREE_TYPE (gimple_assign_rhs1 (stmt));
     419              :       /* A shift or rotate by a possibly out-of-bound count moves only where
     420              :          rewrite_to_defined_unconditional can reduce the count, and not at
     421              :          all when optimizing for size.  */
     422      9592949 :       if ((code == LSHIFT_EXPR
     423              :            || code == RSHIFT_EXPR
     424              :            || code == LROTATE_EXPR
     425      9592949 :            || code == RROTATE_EXPR)
     426       174000 :           && (TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST
     427              :               /* We cannot use ranges at 'stmt' here.  */
     428       129888 :               || wi::geu_p (wi::to_wide (gimple_assign_rhs2 (stmt)),
     429      9722837 :                             element_precision (type)))
     430      9637062 :           && (!gimple_needing_rewrite_undefined (stmt, true)
     431        42972 :               || optimize_loop_for_size_p (loop_containing_stmt (stmt))))
     432              :         ret = MOVE_PRESERVE_EXECUTION;
     433              :     }
     434              : 
     435              :   /* Non local loads in a transaction cannot be hoisted out.  Well,
     436              :      unless the load happens on every path out of the loop, but we
     437              :      don't take this into account yet.  */
     438      9714342 :   if (flag_tm
     439          434 :       && gimple_in_transaction (stmt)
     440      9714445 :       && gimple_assign_single_p (stmt))
     441              :     {
     442           21 :       tree rhs = gimple_assign_rhs1 (stmt);
     443           21 :       if (DECL_P (rhs) && is_global_var (rhs))
     444              :         {
     445           18 :           if (dump_file)
     446              :             {
     447            2 :               fprintf (dump_file, "Cannot hoist conditional load of ");
     448            2 :               print_generic_expr (dump_file, rhs, TDF_SLIM);
     449            2 :               fprintf (dump_file, " because it is in a transaction.\n");
     450              :             }
     451              :           return MOVE_IMPOSSIBLE;
     452              :         }
     453              :     }
     454              : 
     455              :   return ret;
     456              : }
     457              : 
     458              : static enum move_pos
     459     49803101 : movement_possibility (gimple *stmt)
     460              : {
     461     49803101 :   enum move_pos pos = movement_possibility_1 (stmt);
     462     49803101 :   if (pos == MOVE_POSSIBLE)
     463              :     {
     464     11474670 :       use_operand_p use_p;
     465     11474670 :       ssa_op_iter ssa_iter;
     466     37231045 :       FOR_EACH_PHI_OR_STMT_USE (use_p, stmt, ssa_iter, SSA_OP_USE)
     467     14301858 :         if (TREE_CODE (USE_FROM_PTR (use_p)) == SSA_NAME
     468     14301858 :             && ssa_name_maybe_undef_p (USE_FROM_PTR (use_p)))
     469        20153 :           return MOVE_PRESERVE_EXECUTION;
     470              :     }
     471              :   return pos;
     472              : }
     473              : 
     474              : 
     475              : /* Compare the profile count inequality of bb and loop's preheader, it is
     476              :    three-state as stated in profile-count.h, FALSE is returned if inequality
     477              :    cannot be decided.  */
     478              : bool
     479     14671104 : bb_colder_than_loop_preheader (basic_block bb, class loop *loop)
     480              : {
     481     14671104 :   gcc_assert (bb && loop);
     482     14671104 :   return bb->count < loop_preheader_edge (loop)->src->count;
     483              : }
     484              : 
     485              : /* Check coldest loop between OUTERMOST_LOOP and LOOP by comparing profile
     486              :    count.
     487              :   It does three steps check:
     488              :   1) Check whether CURR_BB is cold in it's own loop_father, if it is cold, just
     489              :   return NULL which means it should not be moved out at all;
     490              :   2) CURR_BB is NOT cold, check if pre-computed COLDEST_LOOP is outside of
     491              :   OUTERMOST_LOOP, if it is inside of OUTERMOST_LOOP, return the COLDEST_LOOP;
     492              :   3) If COLDEST_LOOP is outside of OUTERMOST_LOOP, check whether there is a
     493              :   hotter loop between OUTERMOST_LOOP and loop in pre-computed
     494              :   HOTTER_THAN_INNER_LOOP, return it's nested inner loop, otherwise return
     495              :   OUTERMOST_LOOP.
     496              :   At last, the coldest_loop is inside of OUTERMOST_LOOP, just return it as
     497              :   the hoist target.  */
     498              : 
     499              : static class loop *
     500     12977481 : get_coldest_out_loop (class loop *outermost_loop, class loop *loop,
     501              :                       basic_block curr_bb)
     502              : {
     503     12977481 :   gcc_assert (outermost_loop == loop
     504              :               || flow_loop_nested_p (outermost_loop, loop));
     505              : 
     506              :   /* If bb_colder_than_loop_preheader returns false due to three-state
     507              :     comparison, OUTERMOST_LOOP is returned finally to preserve the behavior.
     508              :     Otherwise, return the coldest loop between OUTERMOST_LOOP and LOOP.  */
     509     12977481 :   if (curr_bb && bb_colder_than_loop_preheader (curr_bb, loop))
     510              :     return NULL;
     511              : 
     512     11931007 :   class loop *coldest_loop = coldest_outermost_loop[loop->num];
     513     23862014 :   if (loop_depth (coldest_loop) < loop_depth (outermost_loop))
     514              :     {
     515       243685 :       class loop *hotter_loop = hotter_than_inner_loop[loop->num];
     516       243685 :       if (!hotter_loop
     517       250233 :           || loop_depth (hotter_loop) < loop_depth (outermost_loop))
     518              :         return outermost_loop;
     519              : 
     520              :       /*  hotter_loop is between OUTERMOST_LOOP and LOOP like:
     521              :         [loop tree root, ..., coldest_loop, ..., outermost_loop, ...,
     522              :         hotter_loop, second_coldest_loop, ..., loop]
     523              :         return second_coldest_loop to be the hoist target.  */
     524           38 :       class loop *aloop;
     525           38 :       for (aloop = hotter_loop->inner; aloop; aloop = aloop->next)
     526           38 :         if (aloop == loop || flow_loop_nested_p (aloop, loop))
     527              :           return aloop;
     528              :     }
     529              :   return coldest_loop;
     530              : }
     531              : 
     532              : /* Suppose that operand DEF is used inside the LOOP.  Returns the outermost
     533              :    loop to that we could move the expression using DEF if it did not have
     534              :    other operands, i.e. the outermost loop enclosing LOOP in that the value
     535              :    of DEF is invariant.  */
     536              : 
     537              : static class loop *
     538     20663422 : outermost_invariant_loop (tree def, class loop *loop)
     539              : {
     540     20663422 :   gimple *def_stmt;
     541     20663422 :   basic_block def_bb;
     542     20663422 :   class loop *max_loop;
     543     20663422 :   struct lim_aux_data *lim_data;
     544              : 
     545     20663422 :   if (!def)
     546       987009 :     return superloop_at_depth (loop, 1);
     547              : 
     548     19676413 :   if (TREE_CODE (def) != SSA_NAME)
     549              :     {
     550      4097956 :       gcc_assert (is_gimple_min_invariant (def));
     551      4097956 :       return superloop_at_depth (loop, 1);
     552              :     }
     553              : 
     554     15578457 :   def_stmt = SSA_NAME_DEF_STMT (def);
     555     15578457 :   def_bb = gimple_bb (def_stmt);
     556     15578457 :   if (!def_bb)
     557        77126 :     return superloop_at_depth (loop, 1);
     558              : 
     559     15501331 :   max_loop = find_common_loop (loop, def_bb->loop_father);
     560              : 
     561     15501331 :   lim_data = get_lim_data (def_stmt);
     562     15501331 :   if (lim_data != NULL && lim_data->max_loop != NULL)
     563       745299 :     max_loop = find_common_loop (max_loop,
     564              :                                  loop_outer (lim_data->max_loop));
     565     15501331 :   if (max_loop == loop)
     566              :     return NULL;
     567      1958603 :   max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
     568              : 
     569      1958603 :   return max_loop;
     570              : }
     571              : 
     572              : /* DATA is a structure containing information associated with a statement
     573              :    inside LOOP.  DEF is one of the operands of this statement.
     574              : 
     575              :    Find the outermost loop enclosing LOOP in that value of DEF is invariant
     576              :    and record this in DATA->max_loop field.  If DEF itself is defined inside
     577              :    this loop as well (i.e. we need to hoist it out of the loop if we want
     578              :    to hoist the statement represented by DATA), record the statement in that
     579              :    DEF is defined to the DATA->depends list.  Additionally if ADD_COST is true,
     580              :    add the cost of the computation of DEF to the DATA->cost.
     581              : 
     582              :    If DEF is not invariant in LOOP, return false.  Otherwise return TRUE.  */
     583              : 
     584              : static bool
     585     12140044 : add_dependency (tree def, struct lim_aux_data *data, class loop *loop,
     586              :                 bool add_cost)
     587              : {
     588     12140044 :   gimple *def_stmt = SSA_NAME_DEF_STMT (def);
     589     12140044 :   basic_block def_bb = gimple_bb (def_stmt);
     590     12140044 :   class loop *max_loop;
     591     12140044 :   struct lim_aux_data *def_data;
     592              : 
     593     12140044 :   if (!def_bb)
     594              :     return true;
     595              : 
     596     11764871 :   max_loop = outermost_invariant_loop (def, loop);
     597     11764871 :   if (!max_loop)
     598              :     return false;
     599              : 
     600      1476228 :   if (flow_loop_nested_p (data->max_loop, max_loop))
     601       443402 :     data->max_loop = max_loop;
     602              : 
     603      1476228 :   def_data = get_lim_data (def_stmt);
     604      1476228 :   if (!def_data)
     605              :     return true;
     606              : 
     607       735413 :   if (add_cost
     608              :       /* Only add the cost if the statement defining DEF is inside LOOP,
     609              :          i.e. if it is likely that by moving the invariants dependent
     610              :          on it, we will be able to avoid creating a new register for
     611              :          it (since it will be only used in these dependent invariants).  */
     612       709534 :       && def_bb->loop_father == loop)
     613       504802 :     data->cost += def_data->cost;
     614              : 
     615       735413 :   data->depends.safe_push (def_stmt);
     616              : 
     617       735413 :   return true;
     618              : }
     619              : 
     620              : /* Returns an estimate for a cost of statement STMT.  The values here
     621              :    are just ad-hoc constants, similar to costs for inlining.  */
     622              : 
     623              : static unsigned
     624       841987 : stmt_cost (gimple *stmt)
     625              : {
     626              :   /* Always try to create possibilities for unswitching.  */
     627       841987 :   if (gimple_code (stmt) == GIMPLE_COND
     628       841987 :       || gimple_code (stmt) == GIMPLE_PHI)
     629        16954 :     return LIM_EXPENSIVE;
     630              : 
     631              :   /* We should be hoisting calls if possible.  */
     632       825033 :   if (is_gimple_call (stmt))
     633              :     {
     634          912 :       tree fndecl;
     635              : 
     636              :       /* Unless the call is a builtin_constant_p; this always folds to a
     637              :          constant, so moving it is useless.  */
     638          912 :       fndecl = gimple_call_fndecl (stmt);
     639          912 :       if (fndecl && fndecl_built_in_p (fndecl, BUILT_IN_CONSTANT_P))
     640              :         return 0;
     641              : 
     642          912 :       return LIM_EXPENSIVE;
     643              :     }
     644              : 
     645              :   /* Hoisting memory references out should almost surely be a win.  */
     646       824121 :   if (gimple_references_memory_p (stmt))
     647        70618 :     return LIM_EXPENSIVE;
     648              : 
     649       753503 :   auto assign = dyn_cast<gassign *> (stmt);
     650       753503 :   if (!assign)
     651              :     return 1;
     652              : 
     653       753503 :   enum tree_code code = gimple_assign_rhs_code (assign);
     654       753503 :   switch (code)
     655              :     {
     656       124512 :     case MULT_EXPR:
     657       124512 :     case WIDEN_MULT_EXPR:
     658       124512 :     case WIDEN_MULT_PLUS_EXPR:
     659       124512 :     case WIDEN_MULT_MINUS_EXPR:
     660       124512 :     case DOT_PROD_EXPR:
     661       124512 :     case TRUNC_DIV_EXPR:
     662       124512 :     case CEIL_DIV_EXPR:
     663       124512 :     case FLOOR_DIV_EXPR:
     664       124512 :     case ROUND_DIV_EXPR:
     665       124512 :     case EXACT_DIV_EXPR:
     666       124512 :     case CEIL_MOD_EXPR:
     667       124512 :     case FLOOR_MOD_EXPR:
     668       124512 :     case ROUND_MOD_EXPR:
     669       124512 :     case TRUNC_MOD_EXPR:
     670       124512 :     case RDIV_EXPR:
     671              :       /* Division and multiplication are usually expensive.  */
     672       124512 :       return LIM_EXPENSIVE;
     673              : 
     674         9200 :     case LSHIFT_EXPR:
     675         9200 :     case RSHIFT_EXPR:
     676         9200 :     case WIDEN_LSHIFT_EXPR:
     677         9200 :     case LROTATE_EXPR:
     678         9200 :     case RROTATE_EXPR:
     679              :       /* Shifts and rotates are usually expensive.  */
     680         9200 :       return LIM_EXPENSIVE;
     681              : 
     682          547 :     case COND_EXPR:
     683          547 :     case VEC_COND_EXPR:
     684              :       /* Conditionals are expensive.  */
     685          547 :       return LIM_EXPENSIVE;
     686              : 
     687         1554 :     case CONSTRUCTOR:
     688              :       /* Make vector construction cost proportional to the number
     689              :          of elements.  */
     690         1554 :       return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (assign));
     691              : 
     692              :     case SSA_NAME:
     693              :     case PAREN_EXPR:
     694              :       /* Whether or not something is wrapped inside a PAREN_EXPR
     695              :          should not change move cost.  Nor should an intermediate
     696              :          unpropagated SSA name copy.  */
     697              :       return 0;
     698              : 
     699       580244 :     default:
     700              :       /* Comparisons are usually expensive.  */
     701       580244 :       if (TREE_CODE_CLASS (code) == tcc_comparison)
     702         9046 :         return LIM_EXPENSIVE;
     703              :       return 1;
     704              :     }
     705              : }
     706              : 
     707              : /* Finds the outermost loop between OUTER and LOOP in that the memory reference
     708              :    REF is independent.  If REF is not independent in LOOP, NULL is returned
     709              :    instead.  */
     710              : 
     711              : static class loop *
     712       808262 : outermost_indep_loop (class loop *outer, class loop *loop, im_mem_ref *ref)
     713              : {
     714       808262 :   class loop *aloop;
     715              : 
     716       808262 :   if (ref->stored && bitmap_bit_p (ref->stored, loop->num))
     717              :     return NULL;
     718              : 
     719        88628 :   for (aloop = outer;
     720       728122 :        aloop != loop;
     721        88628 :        aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
     722        10520 :     if ((!ref->stored || !bitmap_bit_p (ref->stored, aloop->num))
     723       106398 :         && ref_indep_loop_p (aloop, ref, lim_raw))
     724              :       return aloop;
     725              : 
     726       623567 :   if (ref_indep_loop_p (loop, ref, lim_raw))
     727              :     return loop;
     728              :   else
     729       568876 :     return NULL;
     730              : }
     731              : 
     732              : /* If there is a simple load or store to a memory reference in STMT, returns
     733              :    the location of the memory reference, and sets IS_STORE according to whether
     734              :    it is a store or load.  Otherwise, returns NULL.  */
     735              : 
     736              : static tree *
     737      7373834 : simple_mem_ref_in_stmt (gimple *stmt, bool *is_store)
     738              : {
     739      7373834 :   tree *lhs, *rhs;
     740              : 
     741              :   /* Recognize SSA_NAME = MEM and MEM = (SSA_NAME | invariant) patterns.  */
     742      7373834 :   if (!gimple_assign_single_p (stmt))
     743              :     return NULL;
     744              : 
     745      6074489 :   lhs = gimple_assign_lhs_ptr (stmt);
     746      6074489 :   rhs = gimple_assign_rhs1_ptr (stmt);
     747              : 
     748      9392756 :   if (TREE_CODE (*lhs) == SSA_NAME && gimple_vuse (stmt))
     749              :     {
     750      3318267 :       *is_store = false;
     751      3318267 :       return rhs;
     752              :     }
     753      2756222 :   else if (gimple_vdef (stmt)
     754      2756222 :            && (TREE_CODE (*rhs) == SSA_NAME || is_gimple_min_invariant (*rhs)))
     755              :     {
     756      2281774 :       *is_store = true;
     757      2281774 :       return lhs;
     758              :     }
     759              :   else
     760              :     return NULL;
     761              : }
     762              : 
     763              : /* From a controlling predicate in DOM determine the arguments from
     764              :    the PHI node PHI that are chosen if the predicate evaluates to
     765              :    true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
     766              :    they are non-NULL.  Returns true if the arguments can be determined,
     767              :    else return false.  */
     768              : 
     769              : static bool
     770        14272 : extract_true_false_args_from_phi (basic_block dom, gphi *phi,
     771              :                                   tree *true_arg_p, tree *false_arg_p)
     772              : {
     773        14272 :   edge te, fe;
     774        14272 :   if (! extract_true_false_controlled_edges (dom, gimple_bb (phi),
     775              :                                              &te, &fe))
     776              :     return false;
     777              : 
     778        13367 :   if (true_arg_p)
     779         1488 :     *true_arg_p = PHI_ARG_DEF (phi, te->dest_idx);
     780        13367 :   if (false_arg_p)
     781         1488 :     *false_arg_p = PHI_ARG_DEF (phi, fe->dest_idx);
     782              : 
     783              :   return true;
     784              : }
     785              : 
     786              : /* Return true if STMT is a shift or rotate whose count would have to be
     787              :    masked when moved out of LOOP, because STMT is not always executed
     788              :    when LOOP is entered.  An out-of-range constant count folds instead.  */
     789              : 
     790              : static bool
     791       230321 : shift_needs_mask_p (gimple *stmt, class loop *loop)
     792              : {
     793       230321 :   if (!is_gimple_assign (stmt)
     794       230321 :       || !gimple_needing_rewrite_undefined (stmt, true))
     795              :     return false;
     796        27000 :   enum tree_code code = gimple_assign_rhs_code (stmt);
     797        27000 :   if ((code != LSHIFT_EXPR
     798              :        && code != RSHIFT_EXPR
     799              :        && code != LROTATE_EXPR
     800        27000 :        && code != RROTATE_EXPR)
     801        27000 :       || TREE_CODE (gimple_assign_rhs2 (stmt)) == INTEGER_CST)
     802              :     return false;
     803          767 :   class loop *always = get_lim_data (stmt)->always_executed_in;
     804          767 :   return !always || !(always == loop || flow_loop_nested_p (always, loop));
     805              : }
     806              : 
     807              : /* Determine the outermost loop to that it is possible to hoist a statement
     808              :    STMT and store it to LIM_DATA (STMT)->max_loop.  To do this we determine
     809              :    the outermost loop in that the value computed by STMT is invariant.
     810              :    If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
     811              :    we preserve the fact whether STMT is executed.  It also fills other related
     812              :    information to LIM_DATA (STMT).
     813              : 
     814              :    The function returns false if STMT cannot be hoisted outside of the loop it
     815              :    is defined in, and true otherwise.  */
     816              : 
     817              : static bool
     818     12930008 : determine_max_movement (gimple *stmt, bool must_preserve_exec)
     819              : {
     820     12930008 :   basic_block bb = gimple_bb (stmt);
     821     12930008 :   class loop *loop = bb->loop_father;
     822     12930008 :   class loop *level;
     823     12930008 :   struct lim_aux_data *lim_data = get_lim_data (stmt);
     824     12930008 :   tree val;
     825     12930008 :   ssa_op_iter iter;
     826              : 
     827     12930008 :   if (must_preserve_exec)
     828      1469407 :     level = ALWAYS_EXECUTED_IN (bb);
     829              :   else
     830     11460601 :     level = superloop_at_depth (loop, 1);
     831     12930008 :   lim_data->max_loop = get_coldest_out_loop (level, loop, bb);
     832     12930008 :   if (!lim_data->max_loop)
     833              :     return false;
     834              : 
     835     11885276 :   if (gphi *phi = dyn_cast <gphi *> (stmt))
     836              :     {
     837      1442606 :       use_operand_p use_p;
     838      1442606 :       unsigned min_cost = UINT_MAX;
     839      1442606 :       unsigned total_cost = 0;
     840      1442606 :       struct lim_aux_data *def_data;
     841              : 
     842              :       /* We will end up promoting dependencies to be unconditionally
     843              :          evaluated.  For this reason the PHI cost (and thus the
     844              :          cost we remove from the loop by doing the invariant motion)
     845              :          is that of the cheapest PHI argument dependency chain.  */
     846      1664294 :       FOR_EACH_PHI_ARG (use_p, phi, iter, SSA_OP_USE)
     847              :         {
     848      1636603 :           val = USE_FROM_PTR (use_p);
     849              : 
     850      1636603 :           if (TREE_CODE (val) != SSA_NAME)
     851              :             {
     852              :               /* Assign const 1 to constants.  */
     853       137957 :               min_cost = MIN (min_cost, 1);
     854       137957 :               total_cost += 1;
     855       137957 :               continue;
     856              :             }
     857      1498646 :           if (!add_dependency (val, lim_data, loop, false))
     858              :             return false;
     859              : 
     860        83731 :           gimple *def_stmt = SSA_NAME_DEF_STMT (val);
     861        83731 :           if (gimple_bb (def_stmt)
     862        83731 :               && gimple_bb (def_stmt)->loop_father == loop)
     863              :             {
     864         3192 :               def_data = get_lim_data (def_stmt);
     865         3192 :               if (def_data)
     866              :                 {
     867         3192 :                   min_cost = MIN (min_cost, def_data->cost);
     868         3192 :                   total_cost += def_data->cost;
     869              :                 }
     870              :             }
     871              :         }
     872              : 
     873        27691 :       min_cost = MIN (min_cost, total_cost);
     874        27691 :       lim_data->cost += min_cost;
     875              : 
     876        27691 :       if (gimple_phi_num_args (phi) > 1)
     877              :         {
     878        27440 :           basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
     879        27440 :           gimple *cond;
     880        54880 :           if (gsi_end_p (gsi_last_bb (dom)))
     881              :             return false;
     882        18408 :           cond = gsi_stmt (gsi_last_bb (dom));
     883        18408 :           if (gimple_code (cond) != GIMPLE_COND)
     884              :             return false;
     885              :           /* Verify that this is an extended form of a diamond and
     886              :              the PHI arguments are completely controlled by the
     887              :              predicate in DOM.  */
     888        12784 :           if (!extract_true_false_args_from_phi (dom, phi, NULL, NULL))
     889              :             return false;
     890              : 
     891              :         /* Check if one of the dependent statement is a vector compare whether
     892              :            the target supports it,  otherwise it's invalid to hoist it out of
     893              :            the gcond it belonged to.  */
     894        11879 :         if (VECTOR_TYPE_P (TREE_TYPE (gimple_cond_lhs (cond))))
     895              :           {
     896            5 :             tree type = TREE_TYPE (gimple_cond_lhs (cond));
     897            5 :             auto code = gimple_cond_code (cond);
     898            5 :             if (!target_supports_op_p (type, code, optab_vector))
     899              :               return false;
     900              :           }
     901              : 
     902              :           /* Fold in dependencies and cost of the condition.  */
     903        15352 :           FOR_EACH_SSA_TREE_OPERAND (val, cond, iter, SSA_OP_USE)
     904              :             {
     905        12681 :               if (!add_dependency (val, lim_data, loop, false))
     906              :                 return false;
     907         3478 :               def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
     908         3478 :               if (def_data)
     909         2057 :                 lim_data->cost += def_data->cost;
     910              :             }
     911              : 
     912              :           /* We want to avoid unconditionally executing very expensive
     913              :              operations.  As costs for our dependencies cannot be
     914              :              negative just claim we are not invariand for this case.
     915              :              We also are not sure whether the control-flow inside the
     916              :              loop will vanish.  */
     917         2671 :           if (total_cost - min_cost >= 2 * LIM_EXPENSIVE
     918         1233 :               && !(min_cost != 0
     919         1233 :                    && total_cost / min_cost <= 2))
     920              :             return false;
     921              : 
     922              :           /* Assume that the control-flow in the loop will vanish.
     923              :              ???  We should verify this and not artificially increase
     924              :              the cost if that is not the case.  */
     925         1488 :           lim_data->cost += stmt_cost (stmt);
     926              :         }
     927              : 
     928              :       return true;
     929              :     }
     930              : 
     931              :   /* A stmt that receives abnormal edges cannot be hoisted.  */
     932     10442670 :   if (is_a <gcall *> (stmt)
     933     10442670 :       && (gimple_call_flags (stmt) & ECF_RETURNS_TWICE))
     934              :     return false;
     935              : 
     936     12206835 :   FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
     937     10627624 :     if (!add_dependency (val, lim_data, loop, true))
     938              :       return false;
     939              : 
     940      3142956 :   if (gimple_vuse (stmt))
     941              :     {
     942       809355 :       im_mem_ref *ref
     943       809355 :         = lim_data ? memory_accesses.refs_list[lim_data->ref] : NULL;
     944       809355 :       if (ref
     945       809355 :           && MEM_ANALYZABLE (ref))
     946              :         {
     947       808262 :           lim_data->max_loop = outermost_indep_loop (lim_data->max_loop,
     948              :                                                      loop, ref);
     949       808262 :           if (!lim_data->max_loop)
     950              :             return false;
     951              :         }
     952         1093 :       else if (! add_dependency (gimple_vuse (stmt), lim_data, loop, false))
     953              :         return false;
     954              :     }
     955              : 
     956              :   /* A shift that needs its count masked is not worth moving on its own.  */
     957       840499 :   unsigned cost = stmt_cost (stmt);
     958       840499 :   if (cost >= LIM_EXPENSIVE && shift_needs_mask_p (stmt, lim_data->max_loop))
     959              :     cost = 1;
     960       840499 :   lim_data->cost += cost;
     961              : 
     962       840499 :   return true;
     963              : }
     964              : 
     965              : /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
     966              :    and that one of the operands of this statement is computed by STMT.
     967              :    Ensure that STMT (together with all the statements that define its
     968              :    operands) is hoisted at least out of the loop LEVEL.  */
     969              : 
     970              : static void
     971       773499 : set_level (gimple *stmt, class loop *orig_loop, class loop *level)
     972              : {
     973       773499 :   class loop *stmt_loop = gimple_bb (stmt)->loop_father;
     974       773499 :   struct lim_aux_data *lim_data;
     975       773499 :   gimple *dep_stmt;
     976       773499 :   unsigned i;
     977              : 
     978       773499 :   stmt_loop = find_common_loop (orig_loop, stmt_loop);
     979       773499 :   lim_data = get_lim_data (stmt);
     980       773499 :   if (lim_data != NULL && lim_data->tgt_loop != NULL)
     981       200587 :     stmt_loop = find_common_loop (stmt_loop,
     982              :                                   loop_outer (lim_data->tgt_loop));
     983       773499 :   if (flow_loop_nested_p (stmt_loop, level))
     984       773499 :     return;
     985              : 
     986       510075 :   gcc_assert (level == lim_data->max_loop
     987              :               || flow_loop_nested_p (lim_data->max_loop, level));
     988              : 
     989       510075 :   lim_data->tgt_loop = level;
     990       886507 :   FOR_EACH_VEC_ELT (lim_data->depends, i, dep_stmt)
     991       376432 :     set_level (dep_stmt, orig_loop, level);
     992              : }
     993              : 
     994              : /* Determines an outermost loop from that we want to hoist the statement STMT.
     995              :    For now we chose the outermost possible loop.  TODO -- use profiling
     996              :    information to set it more sanely.  */
     997              : 
     998              : static void
     999       332857 : set_profitable_level (gimple *stmt)
    1000              : {
    1001       332857 :   set_level (stmt, gimple_bb (stmt)->loop_father, get_lim_data (stmt)->max_loop);
    1002       332857 : }
    1003              : 
    1004              : /* Returns true if STMT is a call that has side effects.  */
    1005              : 
    1006              : static bool
    1007     76674375 : nonpure_call_p (gimple *stmt)
    1008              : {
    1009            0 :   if (gimple_code (stmt) != GIMPLE_CALL)
    1010              :     return false;
    1011              : 
    1012      2345655 :   return gimple_has_side_effects (stmt);
    1013              : }
    1014              : 
    1015              : /* Rewrite a/b to a*(1/b).  Return the invariant stmt to process.  */
    1016              : 
    1017              : static gimple *
    1018           35 : rewrite_reciprocal (gimple_stmt_iterator *bsi)
    1019              : {
    1020           35 :   gassign *stmt, *stmt1, *stmt2;
    1021           35 :   tree name, lhs, type;
    1022           35 :   tree real_one;
    1023           35 :   gimple_stmt_iterator gsi;
    1024              : 
    1025           35 :   stmt = as_a <gassign *> (gsi_stmt (*bsi));
    1026           35 :   lhs = gimple_assign_lhs (stmt);
    1027           35 :   type = TREE_TYPE (lhs);
    1028              : 
    1029           35 :   real_one = build_one_cst (type);
    1030              : 
    1031           35 :   name = make_temp_ssa_name (type, NULL, "reciptmp");
    1032           70 :   stmt1 = gimple_build_assign (name, RDIV_EXPR, real_one,
    1033              :                                gimple_assign_rhs2 (stmt));
    1034           35 :   stmt2 = gimple_build_assign (lhs, MULT_EXPR, name,
    1035              :                                gimple_assign_rhs1 (stmt));
    1036              : 
    1037              :   /* Replace division stmt with reciprocal and multiply stmts.
    1038              :      The multiply stmt is not invariant, so update iterator
    1039              :      and avoid rescanning.  */
    1040           35 :   gsi = *bsi;
    1041           35 :   gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
    1042           35 :   gsi_replace (&gsi, stmt2, true);
    1043              : 
    1044              :   /* Continue processing with invariant reciprocal statement.  */
    1045           35 :   return stmt1;
    1046              : }
    1047              : 
    1048              : /* Check if the pattern at *BSI is a bittest of the form
    1049              :    (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0.  */
    1050              : 
    1051              : static gimple *
    1052         9942 : rewrite_bittest (gimple_stmt_iterator *bsi)
    1053              : {
    1054         9942 :   gassign *stmt;
    1055         9942 :   gassign *stmt1;
    1056         9942 :   gassign *stmt2;
    1057         9942 :   gimple *use_stmt;
    1058         9942 :   gcond *cond_stmt;
    1059         9942 :   tree lhs, name, t, a, b;
    1060         9942 :   use_operand_p use;
    1061              : 
    1062         9942 :   stmt = as_a <gassign *> (gsi_stmt (*bsi));
    1063         9942 :   lhs = gimple_assign_lhs (stmt);
    1064              : 
    1065              :   /* Verify that the single use of lhs is a comparison against zero.  */
    1066         9942 :   if (TREE_CODE (lhs) != SSA_NAME
    1067         9942 :       || !single_imm_use (lhs, &use, &use_stmt))
    1068              :     return stmt;
    1069         9451 :   cond_stmt = dyn_cast <gcond *> (use_stmt);
    1070         5514 :   if (!cond_stmt)
    1071              :     return stmt;
    1072         5514 :   if (gimple_cond_lhs (cond_stmt) != lhs
    1073         5336 :       || (gimple_cond_code (cond_stmt) != NE_EXPR
    1074         2226 :           && gimple_cond_code (cond_stmt) != EQ_EXPR)
    1075        10850 :       || !integer_zerop (gimple_cond_rhs (cond_stmt)))
    1076              :     return stmt;
    1077              : 
    1078              :   /* Get at the operands of the shift.  The rhs is TMP1 & 1.  */
    1079         5298 :   stmt1 = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt)));
    1080         5200 :   if (!stmt1)
    1081              :     return stmt;
    1082              : 
    1083              :   /* There is a conversion in between possibly inserted by fold.  */
    1084         5962 :   if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1)))
    1085              :     {
    1086          223 :       t = gimple_assign_rhs1 (stmt1);
    1087          223 :       if (TREE_CODE (t) != SSA_NAME
    1088          223 :           || !has_single_use (t))
    1089              :         return stmt;
    1090          153 :       stmt1 = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (t));
    1091              :       if (!stmt1)
    1092              :         return stmt;
    1093              :     }
    1094              : 
    1095              :   /* Verify that B is loop invariant but A is not.  Verify that with
    1096              :      all the stmt walking we are still in the same loop.  */
    1097         5088 :   if (gimple_assign_rhs_code (stmt1) != RSHIFT_EXPR
    1098        11552 :       || loop_containing_stmt (stmt1) != loop_containing_stmt (stmt))
    1099              :     return stmt;
    1100              : 
    1101         3232 :   a = gimple_assign_rhs1 (stmt1);
    1102         3232 :   b = gimple_assign_rhs2 (stmt1);
    1103              : 
    1104         3232 :   if (outermost_invariant_loop (b, loop_containing_stmt (stmt1)) != NULL
    1105         3261 :       && outermost_invariant_loop (a, loop_containing_stmt (stmt1)) == NULL)
    1106              :     {
    1107           29 :       gimple_stmt_iterator rsi;
    1108              : 
    1109              :       /* 1 << B */
    1110           29 :       t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
    1111              :                        build_int_cst (TREE_TYPE (a), 1), b);
    1112           29 :       name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
    1113           29 :       stmt1 = gimple_build_assign (name, t);
    1114              : 
    1115              :       /* A & (1 << B) */
    1116           29 :       t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
    1117           29 :       name = make_temp_ssa_name (TREE_TYPE (a), NULL, "shifttmp");
    1118           29 :       stmt2 = gimple_build_assign (name, t);
    1119              : 
    1120              :       /* Replace the SSA_NAME we compare against zero.  Adjust
    1121              :          the type of zero accordingly.  */
    1122           29 :       SET_USE (use, name);
    1123           29 :       gimple_cond_set_rhs (cond_stmt,
    1124           29 :                            build_int_cst_type (TREE_TYPE (name),
    1125              :                                                0));
    1126              : 
    1127              :       /* Don't use gsi_replace here, none of the new assignments sets
    1128              :          the variable originally set in stmt.  Move bsi to stmt1, and
    1129              :          then remove the original stmt, so that we get a chance to
    1130              :          retain debug info for it.  */
    1131           29 :       rsi = *bsi;
    1132           29 :       gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
    1133           29 :       gsi_insert_before (&rsi, stmt2, GSI_SAME_STMT);
    1134           29 :       gimple *to_release = gsi_stmt (rsi);
    1135           29 :       gsi_remove (&rsi, true);
    1136           29 :       release_defs (to_release);
    1137              : 
    1138           29 :       return stmt1;
    1139              :     }
    1140              : 
    1141              :   return stmt;
    1142              : }
    1143              : 
    1144              : /* Determine the outermost loops in that statements in basic block BB are
    1145              :    invariant, and record them to the LIM_DATA associated with the
    1146              :    statements.  */
    1147              : 
    1148              : static void
    1149     14879454 : compute_invariantness (basic_block bb)
    1150              : {
    1151     14879454 :   enum move_pos pos;
    1152     14879454 :   gimple_stmt_iterator bsi;
    1153     14879454 :   gimple *stmt;
    1154     14879454 :   bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
    1155     14879454 :   class loop *outermost = ALWAYS_EXECUTED_IN (bb);
    1156     14879454 :   struct lim_aux_data *lim_data;
    1157              : 
    1158     14879454 :   if (!loop_outer (bb->loop_father))
    1159      8585878 :     return;
    1160              : 
    1161      6293576 :   if (dump_file && (dump_flags & TDF_DETAILS))
    1162          602 :     fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
    1163          602 :              bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
    1164              : 
    1165              :   /* Look at PHI nodes, but only if there is at most two.
    1166              :      ???  We could relax this further by post-processing the inserted
    1167              :      code and transforming adjacent cond-exprs with the same predicate
    1168              :      to control flow again.  */
    1169      6293576 :   bsi = gsi_start_phis (bb);
    1170      6293576 :   if (!gsi_end_p (bsi)
    1171      6293576 :       && ((gsi_next (&bsi), gsi_end_p (bsi))
    1172      1434190 :           || (gsi_next (&bsi), gsi_end_p (bsi))))
    1173      4464893 :     for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
    1174              :       {
    1175      2692308 :         stmt = gsi_stmt (bsi);
    1176              : 
    1177      2692308 :         pos = movement_possibility (stmt);
    1178      2692308 :         if (pos == MOVE_IMPOSSIBLE)
    1179      1192303 :           continue;
    1180              : 
    1181      1500005 :         lim_data = get_lim_data (stmt);
    1182      1500005 :         if (! lim_data)
    1183      1500005 :           lim_data = init_lim_data (stmt);
    1184      1500005 :         lim_data->always_executed_in = outermost;
    1185              : 
    1186      1500005 :         if (!determine_max_movement (stmt, false))
    1187              :           {
    1188      1498266 :             lim_data->max_loop = NULL;
    1189      1498266 :             continue;
    1190              :           }
    1191              : 
    1192         1739 :         if (dump_file && (dump_flags & TDF_DETAILS))
    1193              :           {
    1194            2 :             print_gimple_stmt (dump_file, stmt, 2);
    1195            2 :             fprintf (dump_file, "  invariant up to level %d, cost %d.\n\n",
    1196            2 :                      loop_depth (lim_data->max_loop),
    1197              :                      lim_data->cost);
    1198              :           }
    1199              : 
    1200         1739 :         if (lim_data->cost >= LIM_EXPENSIVE)
    1201         1500 :           set_profitable_level (stmt);
    1202              :       }
    1203              : 
    1204     59697945 :   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
    1205              :     {
    1206     47110793 :       stmt = gsi_stmt (bsi);
    1207              : 
    1208     47110793 :       pos = movement_possibility (stmt);
    1209     47110793 :       if (pos == MOVE_IMPOSSIBLE)
    1210              :         {
    1211     35772888 :           if (nonpure_call_p (stmt))
    1212              :             {
    1213              :               maybe_never = true;
    1214              :               outermost = NULL;
    1215              :             }
    1216              :           /* Make sure to note always_executed_in for stores to make
    1217              :              store-motion work.  */
    1218     33319239 :           else if (stmt_makes_single_store (stmt))
    1219              :             {
    1220      2628478 :               struct lim_aux_data *lim_data = get_lim_data (stmt);
    1221      2628478 :               if (! lim_data)
    1222            0 :                 lim_data = init_lim_data (stmt);
    1223      2628478 :               lim_data->always_executed_in = outermost;
    1224              :             }
    1225     34543407 :           continue;
    1226     34543407 :         }
    1227              : 
    1228     12567386 :       if (is_gimple_assign (stmt)
    1229     12567386 :           && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
    1230              :               == GIMPLE_BINARY_RHS))
    1231              :         {
    1232      6066462 :           tree op0 = gimple_assign_rhs1 (stmt);
    1233      6066462 :           tree op1 = gimple_assign_rhs2 (stmt);
    1234     12132924 :           class loop *ol1 = outermost_invariant_loop (op1,
    1235              :                                         loop_containing_stmt (stmt));
    1236              : 
    1237              :           /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
    1238              :              to be hoisted out of loop, saving expensive divide.  */
    1239      6066462 :           if (pos == MOVE_POSSIBLE
    1240      5621207 :               && gimple_assign_rhs_code (stmt) == RDIV_EXPR
    1241          992 :               && flag_unsafe_math_optimizations
    1242          432 :               && !flag_trapping_math
    1243          432 :               && ol1 != NULL
    1244      6066500 :               && outermost_invariant_loop (op0, ol1) == NULL)
    1245           35 :             stmt = rewrite_reciprocal (&bsi);
    1246              : 
    1247              :           /* If the shift count is invariant, convert (A >> B) & 1 to
    1248              :              A & (1 << B) allowing the bit mask to be hoisted out of the loop
    1249              :              saving an expensive shift.  */
    1250      6066462 :           if (pos == MOVE_POSSIBLE
    1251      5621207 :               && gimple_assign_rhs_code (stmt) == BIT_AND_EXPR
    1252       204019 :               && integer_onep (op1)
    1253        20301 :               && TREE_CODE (op0) == SSA_NAME
    1254      6086763 :               && has_single_use (op0))
    1255         9942 :             stmt = rewrite_bittest (&bsi);
    1256              :         }
    1257              : 
    1258     12567386 :       lim_data = get_lim_data (stmt);
    1259     12567386 :       if (! lim_data)
    1260      9617763 :         lim_data = init_lim_data (stmt);
    1261     12567386 :       lim_data->always_executed_in = outermost;
    1262              : 
    1263     12567386 :       if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
    1264      1137383 :         continue;
    1265              : 
    1266     11430003 :       if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
    1267              :         {
    1268     10589504 :           lim_data->max_loop = NULL;
    1269     10589504 :           continue;
    1270              :         }
    1271              : 
    1272       840499 :       if (dump_file && (dump_flags & TDF_DETAILS))
    1273              :         {
    1274          318 :           print_gimple_stmt (dump_file, stmt, 2);
    1275          318 :           fprintf (dump_file, "  invariant up to level %d, cost %d.\n\n",
    1276          318 :                    loop_depth (lim_data->max_loop),
    1277              :                    lim_data->cost);
    1278              :         }
    1279              : 
    1280       840499 :       if (lim_data->cost >= LIM_EXPENSIVE)
    1281       331357 :         set_profitable_level (stmt);
    1282              :       /* When we run before PRE and PRE is active hoist all expressions
    1283              :          to the always executed loop since PRE would do so anyway
    1284              :          and we can preserve range info while PRE cannot.  */
    1285       509142 :       else if (flag_tree_pre && !in_loop_pipeline
    1286       106346 :                && outermost)
    1287              :         {
    1288        61207 :           class loop *mloop = lim_data->max_loop;
    1289       183621 :           if (loop_depth (outermost) > loop_depth (mloop))
    1290              :             {
    1291         8577 :               mloop = outermost;
    1292         8577 :               if (dump_file && (dump_flags & TDF_DETAILS))
    1293            1 :                 fprintf (dump_file, "  constraining to loop depth %d\n\n\n",
    1294              :                          loop_depth (mloop));
    1295              :             }
    1296        61207 :           set_level (stmt, bb->loop_father, mloop);
    1297              :         }
    1298              :     }
    1299              : }
    1300              : 
    1301              : /* Hoist the statements in basic block BB out of the loops prescribed by
    1302              :    data stored in LIM_DATA structures associated with each statement.  Callback
    1303              :    for walk_dominator_tree.  */
    1304              : 
    1305              : unsigned int
    1306     14921608 : move_computations_worker (basic_block bb)
    1307              : {
    1308     14921608 :   class loop *level;
    1309     14921608 :   unsigned cost = 0;
    1310     14921608 :   struct lim_aux_data *lim_data;
    1311     14921608 :   unsigned int todo = 0;
    1312              : 
    1313     14921608 :   if (!loop_outer (bb->loop_father))
    1314              :     return todo;
    1315              : 
    1316     11041964 :   for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi); )
    1317              :     {
    1318      4740935 :       gassign *new_stmt;
    1319      4740935 :       gphi *stmt = bsi.phi ();
    1320              : 
    1321      4740935 :       lim_data = get_lim_data (stmt);
    1322      4740935 :       if (lim_data == NULL)
    1323              :         {
    1324      3240930 :           gsi_next (&bsi);
    1325      3240930 :           continue;
    1326              :         }
    1327              : 
    1328      1500005 :       cost = lim_data->cost;
    1329      1500005 :       level = lim_data->tgt_loop;
    1330      1500005 :       clear_lim_data (stmt);
    1331              : 
    1332      1500005 :       if (!level)
    1333              :         {
    1334      1498493 :           gsi_next (&bsi);
    1335      1498493 :           continue;
    1336              :         }
    1337              : 
    1338         1512 :       if (dump_file && (dump_flags & TDF_DETAILS))
    1339              :         {
    1340            2 :           fprintf (dump_file, "Moving PHI node\n");
    1341            2 :           print_gimple_stmt (dump_file, stmt, 0);
    1342            2 :           fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
    1343              :                    cost, level->num);
    1344              :         }
    1345              : 
    1346         1512 :       if (gimple_phi_num_args (stmt) == 1)
    1347              :         {
    1348           24 :           tree arg = PHI_ARG_DEF (stmt, 0);
    1349           24 :           new_stmt = gimple_build_assign (gimple_phi_result (stmt),
    1350           24 :                                           TREE_CODE (arg), arg);
    1351              :         }
    1352              :       else
    1353              :         {
    1354         1488 :           basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
    1355         1488 :           gimple *cond = gsi_stmt (gsi_last_bb (dom));
    1356         1488 :           tree arg0 = NULL_TREE, arg1 = NULL_TREE, t;
    1357              :           /* Get the PHI arguments corresponding to the true and false
    1358              :              edges of COND.  */
    1359         1488 :           extract_true_false_args_from_phi (dom, stmt, &arg0, &arg1);
    1360         1488 :           gcc_assert (arg0 && arg1);
    1361              :           /* For `bool_val != 0`, reuse bool_val. */
    1362         1488 :           if (gimple_cond_code (cond) == NE_EXPR
    1363          682 :               && integer_zerop (gimple_cond_rhs (cond))
    1364         2095 :               && types_compatible_p (TREE_TYPE (gimple_cond_lhs (cond)),
    1365              :                                      boolean_type_node))
    1366              :             {
    1367           90 :               t = gimple_cond_lhs (cond);
    1368              :             }
    1369              :           else
    1370              :             {
    1371         1398 :               t = make_ssa_name (boolean_type_node);
    1372         1398 :               new_stmt = gimple_build_assign (t, gimple_cond_code (cond),
    1373              :                                               gimple_cond_lhs (cond),
    1374              :                                               gimple_cond_rhs (cond));
    1375         1398 :               gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
    1376              :             }
    1377         1488 :           new_stmt = gimple_build_assign (gimple_phi_result (stmt),
    1378              :                                           COND_EXPR, t, arg0, arg1);
    1379         1488 :           todo |= TODO_cleanup_cfg;
    1380              :         }
    1381         1512 :       if (!ALWAYS_EXECUTED_IN (bb)
    1382         1512 :           || (ALWAYS_EXECUTED_IN (bb) != level
    1383          104 :               && !flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level)))
    1384          918 :         reset_flow_sensitive_info (gimple_assign_lhs (new_stmt));
    1385         1512 :       gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
    1386         1512 :       remove_phi_node (&bsi, false);
    1387              :     }
    1388              : 
    1389     59782609 :   for (gimple_stmt_iterator bsi = gsi_start_bb (bb); !gsi_end_p (bsi); )
    1390              :     {
    1391     47180551 :       edge e;
    1392              : 
    1393     47180551 :       gimple *stmt = gsi_stmt (bsi);
    1394              : 
    1395     47180551 :       lim_data = get_lim_data (stmt);
    1396     47180551 :       if (lim_data == NULL)
    1397              :         {
    1398     30144119 :           gsi_next (&bsi);
    1399     30144119 :           continue;
    1400              :         }
    1401              : 
    1402     17036432 :       cost = lim_data->cost;
    1403     17036432 :       level = lim_data->tgt_loop;
    1404     17036432 :       clear_lim_data (stmt);
    1405              : 
    1406     17036432 :       if (!level)
    1407              :         {
    1408     16485957 :           gsi_next (&bsi);
    1409     16485957 :           continue;
    1410              :         }
    1411              : 
    1412              :       /* We do not really want to move conditionals out of the loop; we just
    1413              :          placed it here to force its operands to be moved if necessary.  */
    1414       550475 :       if (gimple_code (stmt) == GIMPLE_COND)
    1415              :         {
    1416        15466 :           gsi_next (&bsi);
    1417        15466 :           continue;
    1418              :         }
    1419              : 
    1420       535009 :       if (dump_file && (dump_flags & TDF_DETAILS))
    1421              :         {
    1422          389 :           fprintf (dump_file, "Moving statement ");
    1423          389 :           print_gimple_stmt (dump_file, stmt, 0);
    1424          389 :           fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
    1425              :                    cost, level->num);
    1426              :         }
    1427              : 
    1428       535009 :       e = loop_preheader_edge (level);
    1429      1070018 :       gcc_assert (!gimple_vdef (stmt));
    1430      1070018 :       if (gimple_vuse (stmt))
    1431              :         {
    1432              :           /* The new VUSE is the one from the virtual PHI in the loop
    1433              :              header or the one already present.  */
    1434        89495 :           gphi_iterator gsi2;
    1435        89495 :           for (gsi2 = gsi_start_phis (e->dest);
    1436       213778 :                !gsi_end_p (gsi2); gsi_next (&gsi2))
    1437              :             {
    1438       194592 :               gphi *phi = gsi2.phi ();
    1439       389184 :               if (virtual_operand_p (gimple_phi_result (phi)))
    1440              :                 {
    1441        70309 :                   SET_USE (gimple_vuse_op (stmt),
    1442              :                            PHI_ARG_DEF_FROM_EDGE (phi, e));
    1443        70309 :                   break;
    1444              :                 }
    1445              :             }
    1446              :         }
    1447       535009 :       gsi_remove (&bsi, false);
    1448       535009 :       if (gimple_has_lhs (stmt)
    1449       535009 :           && TREE_CODE (gimple_get_lhs (stmt)) == SSA_NAME
    1450       490891 :           && (!ALWAYS_EXECUTED_IN (bb)
    1451       397522 :               || !(ALWAYS_EXECUTED_IN (bb) == level
    1452        98314 :                    || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
    1453       233330 :         reset_flow_sensitive_info (gimple_get_lhs (stmt));
    1454              :       /* In case this is a stmt that is not unconditionally executed
    1455              :          when the target loop header is executed and the stmt may
    1456              :          invoke undefined integer or pointer overflow rewrite it to
    1457              :          unsigned arithmetic.  */
    1458       535009 :       if (gimple_needing_rewrite_undefined (stmt, true)
    1459       535009 :           && (!ALWAYS_EXECUTED_IN (bb)
    1460        76631 :               || !(ALWAYS_EXECUTED_IN (bb) == level
    1461        19633 :                    || flow_loop_nested_p (ALWAYS_EXECUTED_IN (bb), level))))
    1462        20629 :         gsi_insert_seq_on_edge (e, rewrite_to_defined_unconditional (stmt));
    1463              :       else
    1464       514380 :         gsi_insert_on_edge (e, stmt);
    1465              :     }
    1466              : 
    1467      6301029 :   return todo;
    1468              : }
    1469              : 
    1470              : /* Checks whether the statement defining variable *INDEX can be hoisted
    1471              :    out of the loop passed in DATA.  Callback for for_each_index.  */
    1472              : 
    1473              : static bool
    1474      1838946 : may_move_till (tree ref, tree *index, void *data)
    1475              : {
    1476      1838946 :   class loop *loop = (class loop *) data, *max_loop;
    1477              : 
    1478              :   /* If REF is an array reference, check also that the step and the lower
    1479              :      bound is invariant in LOOP.  */
    1480      1838946 :   if (TREE_CODE (ref) == ARRAY_REF)
    1481              :     {
    1482       494922 :       tree step = TREE_OPERAND (ref, 3);
    1483       494922 :       tree lbound = TREE_OPERAND (ref, 2);
    1484              : 
    1485       494922 :       max_loop = outermost_invariant_loop (step, loop);
    1486       494922 :       if (!max_loop)
    1487              :         return false;
    1488              : 
    1489       494922 :       max_loop = outermost_invariant_loop (lbound, loop);
    1490       494922 :       if (!max_loop)
    1491              :         return false;
    1492              :     }
    1493              : 
    1494      1838946 :   max_loop = outermost_invariant_loop (*index, loop);
    1495      1838946 :   if (!max_loop)
    1496      1180176 :     return false;
    1497              : 
    1498              :   return true;
    1499              : }
    1500              : 
    1501              : /* If OP is SSA NAME, force the statement that defines it to be
    1502              :    moved out of the LOOP.  ORIG_LOOP is the loop in that EXPR is used.  */
    1503              : 
    1504              : static void
    1505        41099 : force_move_till_op (tree op, class loop *orig_loop, class loop *loop)
    1506              : {
    1507        41099 :   gimple *stmt;
    1508              : 
    1509        41099 :   if (!op
    1510        41099 :       || is_gimple_min_invariant (op))
    1511              :     return;
    1512              : 
    1513         4604 :   gcc_assert (TREE_CODE (op) == SSA_NAME);
    1514              : 
    1515         4604 :   stmt = SSA_NAME_DEF_STMT (op);
    1516         4604 :   if (gimple_nop_p (stmt))
    1517              :     return;
    1518              : 
    1519         3003 :   set_level (stmt, orig_loop, loop);
    1520              : }
    1521              : 
    1522              : /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
    1523              :    the LOOP.  The reference REF is used in the loop ORIG_LOOP.  Callback for
    1524              :    for_each_index.  */
    1525              : 
    1526              : struct fmt_data
    1527              : {
    1528              :   class loop *loop;
    1529              :   class loop *orig_loop;
    1530              : };
    1531              : 
    1532              : static bool
    1533        21387 : force_move_till (tree ref, tree *index, void *data)
    1534              : {
    1535        21387 :   struct fmt_data *fmt_data = (struct fmt_data *) data;
    1536              : 
    1537        21387 :   if (TREE_CODE (ref) == ARRAY_REF)
    1538              :     {
    1539         9856 :       tree step = TREE_OPERAND (ref, 3);
    1540         9856 :       tree lbound = TREE_OPERAND (ref, 2);
    1541              : 
    1542         9856 :       force_move_till_op (step, fmt_data->orig_loop, fmt_data->loop);
    1543         9856 :       force_move_till_op (lbound, fmt_data->orig_loop, fmt_data->loop);
    1544              :     }
    1545              : 
    1546        21387 :   force_move_till_op (*index, fmt_data->orig_loop, fmt_data->loop);
    1547              : 
    1548        21387 :   return true;
    1549              : }
    1550              : 
    1551              : /* A function to free the mem_ref object OBJ.  */
    1552              : 
    1553              : static void
    1554      5580807 : memref_free (class im_mem_ref *mem)
    1555              : {
    1556            0 :   mem->accesses_in_loop.release ();
    1557            0 : }
    1558              : 
    1559              : /* Allocates and returns a memory reference description for MEM whose hash
    1560              :    value is HASH and id is ID.  */
    1561              : 
    1562              : static im_mem_ref *
    1563      5580807 : mem_ref_alloc (ao_ref *mem, unsigned hash, unsigned id)
    1564              : {
    1565      5580807 :   im_mem_ref *ref = XOBNEW (&mem_ref_obstack, class im_mem_ref);
    1566      5580807 :   if (mem)
    1567      4600329 :     ref->mem = *mem;
    1568              :   else
    1569       980478 :     ao_ref_init (&ref->mem, error_mark_node);
    1570      5580807 :   ref->id = id;
    1571      5580807 :   ref->ref_canonical = false;
    1572      5580807 :   ref->ref_decomposed = false;
    1573      5580807 :   ref->hash = hash;
    1574      5580807 :   ref->stored = NULL;
    1575      5580807 :   ref->loaded = NULL;
    1576      5580807 :   bitmap_initialize (&ref->dep_loop, &lim_bitmap_obstack);
    1577      5580807 :   ref->accesses_in_loop.create (1);
    1578              : 
    1579      5580807 :   return ref;
    1580              : }
    1581              : 
    1582              : /* Records memory reference location *LOC in LOOP to the memory reference
    1583              :    description REF.  The reference occurs in statement STMT.  */
    1584              : 
    1585              : static void
    1586      6074489 : record_mem_ref_loc (im_mem_ref *ref, gimple *stmt, tree *loc)
    1587              : {
    1588      6074489 :   mem_ref_loc aref;
    1589      6074489 :   aref.stmt = stmt;
    1590      6074489 :   aref.ref = loc;
    1591            0 :   ref->accesses_in_loop.safe_push (aref);
    1592            0 : }
    1593              : 
    1594              : /* Set the LOOP bit in REF stored bitmap and allocate that if
    1595              :    necessary.  Return whether a bit was changed.  */
    1596              : 
    1597              : static bool
    1598      4749866 : set_ref_stored_in_loop (im_mem_ref *ref, class loop *loop)
    1599              : {
    1600      4749866 :   if (!ref->stored)
    1601      2745068 :     ref->stored = BITMAP_ALLOC (&lim_bitmap_obstack);
    1602      4749866 :   return bitmap_set_bit (ref->stored, loop->num);
    1603              : }
    1604              : 
    1605              : /* Marks reference REF as stored in LOOP.  */
    1606              : 
    1607              : static void
    1608      3975052 : mark_ref_stored (im_mem_ref *ref, class loop *loop)
    1609              : {
    1610      3975052 :   while (loop != current_loops->tree_root
    1611      7666814 :          && set_ref_stored_in_loop (ref, loop))
    1612      3691762 :     loop = loop_outer (loop);
    1613      3975052 : }
    1614              : 
    1615              : /* Set the LOOP bit in REF loaded bitmap and allocate that if
    1616              :    necessary.  Return whether a bit was changed.  */
    1617              : 
    1618              : static bool
    1619      6408798 : set_ref_loaded_in_loop (im_mem_ref *ref, class loop *loop)
    1620              : {
    1621      6408798 :   if (!ref->loaded)
    1622      3498509 :     ref->loaded = BITMAP_ALLOC (&lim_bitmap_obstack);
    1623      6408798 :   return bitmap_set_bit (ref->loaded, loop->num);
    1624              : }
    1625              : 
    1626              : /* Marks reference REF as loaded in LOOP.  */
    1627              : 
    1628              : static void
    1629      5092060 : mark_ref_loaded (im_mem_ref *ref, class loop *loop)
    1630              : {
    1631      5092060 :   while (loop != current_loops->tree_root
    1632     10134159 :          && set_ref_loaded_in_loop (ref, loop))
    1633      5042099 :     loop = loop_outer (loop);
    1634      5092060 : }
    1635              : 
    1636              : /* Gathers memory references in statement STMT in LOOP, storing the
    1637              :    information about them in the memory_accesses structure.  Marks
    1638              :    the vops accessed through unrecognized statements there as
    1639              :    well.  */
    1640              : 
    1641              : static void
    1642     47110729 : gather_mem_refs_stmt (class loop *loop, gimple *stmt)
    1643              : {
    1644     47110729 :   tree *mem = NULL;
    1645     47110729 :   hashval_t hash;
    1646     47110729 :   im_mem_ref **slot;
    1647     47110729 :   im_mem_ref *ref;
    1648     47110729 :   bool is_stored;
    1649     47110729 :   unsigned id;
    1650              : 
    1651     63742697 :   if (!gimple_vuse (stmt))
    1652              :     return;
    1653              : 
    1654      7373834 :   mem = simple_mem_ref_in_stmt (stmt, &is_stored);
    1655      7373834 :   if (!mem && is_gimple_assign (stmt))
    1656              :     {
    1657              :       /* For aggregate copies record distinct references but use them
    1658              :          only for disambiguation purposes.  */
    1659       474448 :       id = memory_accesses.refs_list.length ();
    1660       474448 :       ref = mem_ref_alloc (NULL, 0, id);
    1661       474448 :       memory_accesses.refs_list.safe_push (ref);
    1662       474448 :       if (dump_file && (dump_flags & TDF_DETAILS))
    1663              :         {
    1664           30 :           fprintf (dump_file, "Unhandled memory reference %u: ", id);
    1665           30 :           print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
    1666              :         }
    1667       474448 :       record_mem_ref_loc (ref, stmt, mem);
    1668       948896 :       is_stored = gimple_vdef (stmt);
    1669              :     }
    1670      6899386 :   else if (!mem)
    1671              :     {
    1672              :       /* We use the shared mem_ref for all unanalyzable refs.  */
    1673      1299345 :       id = UNANALYZABLE_MEM_ID;
    1674      1299345 :       ref = memory_accesses.refs_list[id];
    1675      1299345 :       if (dump_file && (dump_flags & TDF_DETAILS))
    1676              :         {
    1677           21 :           fprintf (dump_file, "Unanalyzed memory reference %u: ", id);
    1678           21 :           print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
    1679              :         }
    1680      2598690 :       is_stored = gimple_vdef (stmt);
    1681              :     }
    1682              :   else
    1683              :     {
    1684              :       /* We are looking for equal refs that might differ in structure
    1685              :          such as a.b vs. MEM[&a + 4].  So we key off the ao_ref but
    1686              :          make sure we can canonicalize the ref in the hashtable if
    1687              :          non-operand_equal_p refs are found.  For the lookup we mark
    1688              :          the case we want strict equality with aor.max_size == -1.  */
    1689      5600041 :       ao_ref aor;
    1690      5600041 :       ao_ref_init (&aor, *mem);
    1691      5600041 :       ao_ref_base (&aor);
    1692      5600041 :       ao_ref_alias_set (&aor);
    1693      5600041 :       HOST_WIDE_INT offset, size, max_size;
    1694      5600041 :       poly_int64 saved_maxsize = aor.max_size, mem_off;
    1695      5600041 :       tree mem_base;
    1696      5600041 :       bool ref_decomposed;
    1697      5600041 :       if (aor.max_size_known_p ()
    1698      5410969 :           && aor.offset.is_constant (&offset)
    1699      5410969 :           && aor.size.is_constant (&size)
    1700      5410969 :           && aor.max_size.is_constant (&max_size)
    1701      5410969 :           && size == max_size
    1702      4796982 :           && (size % BITS_PER_UNIT) == 0
    1703              :           /* We're canonicalizing to a MEM where TYPE_SIZE specifies the
    1704              :              size.  Make sure this is consistent with the extraction.  */
    1705      4785375 :           && poly_int_tree_p (TYPE_SIZE (TREE_TYPE (*mem)))
    1706      4785375 :           && known_eq (wi::to_poly_offset (TYPE_SIZE (TREE_TYPE (*mem))),
    1707              :                        aor.size)
    1708     10385324 :           && (mem_base = get_addr_base_and_unit_offset (aor.ref, &mem_off)))
    1709              :         {
    1710      4784131 :           ref_decomposed = true;
    1711      4784131 :           tree base = ao_ref_base (&aor);
    1712      4784131 :           poly_int64 moffset;
    1713      4784131 :           HOST_WIDE_INT mcoffset;
    1714      4784131 :           if (TREE_CODE (base) == MEM_REF
    1715      4784131 :               && (mem_ref_offset (base) * BITS_PER_UNIT + offset).to_shwi (&moffset)
    1716      4784131 :               && moffset.is_constant (&mcoffset))
    1717              :             {
    1718      2130890 :               hash = iterative_hash_expr (TREE_OPERAND (base, 0), 0);
    1719      2130890 :               hash = iterative_hash_host_wide_int (mcoffset, hash);
    1720              :             }
    1721              :           else
    1722              :             {
    1723      2653241 :               hash = iterative_hash_expr (base, 0);
    1724      2653241 :               hash = iterative_hash_host_wide_int (offset, hash);
    1725              :             }
    1726      4784131 :           hash = iterative_hash_host_wide_int (size, hash);
    1727              :         }
    1728              :       else
    1729              :         {
    1730       815910 :           ref_decomposed = false;
    1731       815910 :           hash = iterative_hash_expr (aor.ref, 0);
    1732       815910 :           aor.max_size = -1;
    1733              :         }
    1734      5600041 :       slot = memory_accesses.refs->find_slot_with_hash (&aor, hash, INSERT);
    1735      5600041 :       aor.max_size = saved_maxsize;
    1736      5600041 :       if (*slot)
    1737              :         {
    1738       999712 :           if (!(*slot)->ref_canonical
    1739       999712 :               && !operand_equal_p (*mem, (*slot)->mem.ref, 0))
    1740              :             {
    1741              :               /* If we didn't yet canonicalize the hashtable ref (which
    1742              :                  we'll end up using for code insertion) and hit a second
    1743              :                  equal ref that is not structurally equivalent create
    1744              :                  a canonical ref which is a bare MEM_REF.  */
    1745        57243 :               if (TREE_CODE (*mem) == MEM_REF
    1746        57243 :                   || TREE_CODE (*mem) == TARGET_MEM_REF)
    1747        16468 :                 (*slot)->mem = aor;
    1748              :               else
    1749              :                 {
    1750        40775 :                   tree ref_alias_type = reference_alias_ptr_type (*mem);
    1751        40775 :                   unsigned int ref_align = get_object_alignment (*mem);
    1752        40775 :                   tree ref_type = TREE_TYPE (*mem);
    1753        40775 :                   tree tmp = build1 (ADDR_EXPR, ptr_type_node,
    1754              :                                      unshare_expr (mem_base));
    1755        40775 :                   if (TYPE_ALIGN (ref_type) != ref_align)
    1756        11227 :                     ref_type = build_aligned_type (ref_type, ref_align);
    1757        40775 :                   tree new_ref
    1758        40775 :                     = fold_build2 (MEM_REF, ref_type, tmp,
    1759              :                                    build_int_cst (ref_alias_type, mem_off));
    1760        40775 :                   if ((*slot)->mem.volatile_p)
    1761           14 :                     TREE_THIS_VOLATILE (new_ref) = 1;
    1762        40775 :                   if (reverse_storage_order_for_component_p (*mem))
    1763            7 :                     REF_REVERSE_STORAGE_ORDER (new_ref) = 1;
    1764        40775 :                   (*slot)->mem.ref = new_ref;
    1765              :                   /* Make sure the recorded base and offset are consistent
    1766              :                      with the newly built ref.  */
    1767        40775 :                   if (TREE_CODE (TREE_OPERAND (new_ref, 0)) == ADDR_EXPR)
    1768              :                     ;
    1769              :                   else
    1770              :                     {
    1771        22501 :                       (*slot)->mem.base = new_ref;
    1772        22501 :                       (*slot)->mem.offset = 0;
    1773              :                     }
    1774        40775 :                   gcc_checking_assert (TREE_CODE ((*slot)->mem.ref) == MEM_REF
    1775              :                                        && is_gimple_mem_ref_addr
    1776              :                                             (TREE_OPERAND ((*slot)->mem.ref,
    1777              :                                                            0)));
    1778        40775 :                   (*slot)->mem.base_alias_set = (*slot)->mem.ref_alias_set;
    1779              :                 }
    1780        57243 :               (*slot)->ref_canonical = true;
    1781              :             }
    1782       999712 :           ref = *slot;
    1783       999712 :           id = ref->id;
    1784              :         }
    1785              :       else
    1786              :         {
    1787      4600329 :           id = memory_accesses.refs_list.length ();
    1788      4600329 :           ref = mem_ref_alloc (&aor, hash, id);
    1789      4600329 :           ref->ref_decomposed = ref_decomposed;
    1790      4600329 :           memory_accesses.refs_list.safe_push (ref);
    1791      4600329 :           *slot = ref;
    1792              : 
    1793      4600329 :           if (dump_file && (dump_flags & TDF_DETAILS))
    1794              :             {
    1795          560 :               fprintf (dump_file, "Memory reference %u: ", id);
    1796          560 :               print_generic_expr (dump_file, ref->mem.ref, TDF_SLIM);
    1797          560 :               fprintf (dump_file, "\n");
    1798              :             }
    1799              :         }
    1800              : 
    1801      5600041 :       record_mem_ref_loc (ref, stmt, mem);
    1802              :     }
    1803      7373834 :   if (is_stored)
    1804              :     {
    1805      3975052 :       bitmap_set_bit (&memory_accesses.refs_stored_in_loop[loop->num], ref->id);
    1806      3975052 :       mark_ref_stored (ref, loop);
    1807              :     }
    1808              :   /* A not simple memory op is also a read when it is a write.  */
    1809      7373834 :   if (!is_stored || id == UNANALYZABLE_MEM_ID
    1810      2756222 :       || ref->mem.ref == error_mark_node)
    1811              :     {
    1812      5092060 :       bitmap_set_bit (&memory_accesses.refs_loaded_in_loop[loop->num], ref->id);
    1813      5092060 :       mark_ref_loaded (ref, loop);
    1814              :     }
    1815      7373834 :   init_lim_data (stmt)->ref = ref->id;
    1816      7373834 :   return;
    1817              : }
    1818              : 
    1819              : static unsigned *bb_loop_postorder;
    1820              : 
    1821              : /* qsort sort function to sort blocks after their loop fathers postorder.  */
    1822              : 
    1823              : static int
    1824    163541928 : sort_bbs_in_loop_postorder_cmp (const void *bb1_, const void *bb2_,
    1825              :                                 void *bb_loop_postorder_)
    1826              : {
    1827    163541928 :   unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
    1828    163541928 :   basic_block bb1 = *(const basic_block *)bb1_;
    1829    163541928 :   basic_block bb2 = *(const basic_block *)bb2_;
    1830    163541928 :   class loop *loop1 = bb1->loop_father;
    1831    163541928 :   class loop *loop2 = bb2->loop_father;
    1832    163541928 :   if (loop1->num == loop2->num)
    1833     77128837 :     return bb1->index - bb2->index;
    1834     86413091 :   return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
    1835              : }
    1836              : 
    1837              : /* qsort sort function to sort ref locs after their loop fathers postorder.  */
    1838              : 
    1839              : static int
    1840       999697 : sort_locs_in_loop_postorder_cmp (const void *loc1_, const void *loc2_,
    1841              :                                  void *bb_loop_postorder_)
    1842              : {
    1843       999697 :   unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
    1844       999697 :   const mem_ref_loc *loc1 = (const mem_ref_loc *)loc1_;
    1845       999697 :   const mem_ref_loc *loc2 = (const mem_ref_loc *)loc2_;
    1846       999697 :   class loop *loop1 = gimple_bb (loc1->stmt)->loop_father;
    1847       999697 :   class loop *loop2 = gimple_bb (loc2->stmt)->loop_father;
    1848       999697 :   if (loop1->num == loop2->num)
    1849              :     return 0;
    1850       149885 :   return bb_loop_postorder[loop1->num] < bb_loop_postorder[loop2->num] ? -1 : 1;
    1851              : }
    1852              : 
    1853              : /* Gathers memory references in loops.  */
    1854              : 
    1855              : static void
    1856       506030 : analyze_memory_references (bool store_motion)
    1857              : {
    1858       506030 :   gimple_stmt_iterator bsi;
    1859       506030 :   basic_block bb, *bbs;
    1860       506030 :   class loop *outer;
    1861       506030 :   unsigned i, n;
    1862              : 
    1863              :   /* Collect all basic-blocks in loops and sort them after their
    1864              :      loops postorder.  */
    1865       506030 :   i = 0;
    1866       506030 :   bbs = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS);
    1867     15385484 :   FOR_EACH_BB_FN (bb, cfun)
    1868     14879454 :     if (bb->loop_father != current_loops->tree_root)
    1869      6293576 :       bbs[i++] = bb;
    1870       506030 :   n = i;
    1871       506030 :   gcc_sort_r (bbs, n, sizeof (basic_block), sort_bbs_in_loop_postorder_cmp,
    1872              :               bb_loop_postorder);
    1873              : 
    1874              :   /* Visit blocks in loop postorder and assign mem-ref IDs in that order.
    1875              :      That results in better locality for all the bitmaps.  It also
    1876              :      automatically sorts the location list of gathered memory references
    1877              :      after their loop postorder number allowing to binary-search it.  */
    1878      7305636 :   for (i = 0; i < n; ++i)
    1879              :     {
    1880      6293576 :       basic_block bb = bbs[i];
    1881     59697881 :       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
    1882     47110729 :         gather_mem_refs_stmt (bb->loop_father, gsi_stmt (bsi));
    1883              :     }
    1884              : 
    1885              :   /* Verify the list of gathered memory references is sorted after their
    1886              :      loop postorder number.  */
    1887       506030 :   if (flag_checking)
    1888              :     {
    1889              :       im_mem_ref *ref;
    1890     11667566 :       FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
    1891      6580472 :         for (unsigned j = 1; j < ref->accesses_in_loop.length (); ++j)
    1892       999697 :           gcc_assert (sort_locs_in_loop_postorder_cmp
    1893              :                         (&ref->accesses_in_loop[j-1], &ref->accesses_in_loop[j],
    1894              :                          bb_loop_postorder) <= 0);
    1895              :     }
    1896              : 
    1897       506030 :   free (bbs);
    1898              : 
    1899       506030 :   if (!store_motion)
    1900       506030 :     return;
    1901              : 
    1902              :   /* Propagate the information about accessed memory references up
    1903              :      the loop hierarchy.  */
    1904      2878191 :   for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
    1905              :     {
    1906              :       /* Finalize the overall touched references (including subloops).  */
    1907      1364748 :       bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[loop->num],
    1908      1364748 :                        &memory_accesses.refs_stored_in_loop[loop->num]);
    1909              : 
    1910              :       /* Propagate the information about accessed memory references up
    1911              :          the loop hierarchy.  */
    1912      1364748 :       outer = loop_outer (loop);
    1913      1364748 :       if (outer == current_loops->tree_root)
    1914      1050828 :         continue;
    1915              : 
    1916       313920 :       bitmap_ior_into (&memory_accesses.all_refs_stored_in_loop[outer->num],
    1917       313920 :                        &memory_accesses.all_refs_stored_in_loop[loop->num]);
    1918       504481 :     }
    1919              : }
    1920              : 
    1921              : /* Returns true if MEM1 and MEM2 may alias.  TTAE_CACHE is used as a cache in
    1922              :    tree_to_aff_combination_expand.  */
    1923              : 
    1924              : static bool
    1925       497434 : mem_refs_may_alias_p (im_mem_ref *mem1, im_mem_ref *mem2,
    1926              :                       hash_map<tree, name_expansion *> **ttae_cache,
    1927              :                       bool tbaa_p)
    1928              : {
    1929       497434 :   gcc_checking_assert (mem1->mem.ref != error_mark_node
    1930              :                        && mem2->mem.ref != error_mark_node);
    1931              : 
    1932              :   /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
    1933              :      object and their offset differ in such a way that the locations cannot
    1934              :      overlap, then they cannot alias.  */
    1935       497434 :   poly_widest_int size1, size2;
    1936       994868 :   aff_tree off1, off2;
    1937              : 
    1938              :   /* Perform basic offset and type-based disambiguation.  */
    1939       497434 :   if (!refs_may_alias_p_1 (&mem1->mem, &mem2->mem, tbaa_p))
    1940              :     return false;
    1941              : 
    1942              :   /* The expansion of addresses may be a bit expensive, thus we only do
    1943              :      the check at -O2 and higher optimization levels.  */
    1944        59259 :   if (optimize < 2)
    1945              :     return true;
    1946              : 
    1947        51049 :   get_inner_reference_aff (mem1->mem.ref, &off1, &size1);
    1948        51049 :   get_inner_reference_aff (mem2->mem.ref, &off2, &size2);
    1949        51049 :   aff_combination_expand (&off1, ttae_cache);
    1950        51049 :   aff_combination_expand (&off2, ttae_cache);
    1951        51049 :   aff_combination_scale (&off1, -1);
    1952        51049 :   aff_combination_add (&off2, &off1);
    1953              : 
    1954        51049 :   if (aff_comb_cannot_overlap_p (&off2, size1, size2))
    1955         2983 :     return false;
    1956              : 
    1957              :   return true;
    1958       497434 : }
    1959              : 
    1960              : /* Compare function for bsearch searching for reference locations
    1961              :    in a loop.  */
    1962              : 
    1963              : static int
    1964       297530 : find_ref_loc_in_loop_cmp (const void *loop_, const void *loc_,
    1965              :                           void *bb_loop_postorder_)
    1966              : {
    1967       297530 :   unsigned *bb_loop_postorder = (unsigned *)bb_loop_postorder_;
    1968       297530 :   class loop *loop = (class loop *)const_cast<void *>(loop_);
    1969       297530 :   mem_ref_loc *loc = (mem_ref_loc *)const_cast<void *>(loc_);
    1970       297530 :   class loop *loc_loop = gimple_bb (loc->stmt)->loop_father;
    1971       297530 :   if (loop->num  == loc_loop->num
    1972       297530 :       || flow_loop_nested_p (loop, loc_loop))
    1973              :     return 0;
    1974        71724 :   return (bb_loop_postorder[loop->num] < bb_loop_postorder[loc_loop->num]
    1975        71724 :           ? -1 : 1);
    1976              : }
    1977              : 
    1978              : /* Iterates over all locations of REF in LOOP and its subloops calling
    1979              :    fn.operator() with the location as argument.  When that operator
    1980              :    returns true the iteration is stopped and true is returned.
    1981              :    Otherwise false is returned.  */
    1982              : 
    1983              : template <typename FN>
    1984              : static bool
    1985       225806 : for_all_locs_in_loop (class loop *loop, im_mem_ref *ref, FN fn)
    1986              : {
    1987              :   unsigned i;
    1988              :   mem_ref_loc *loc;
    1989              : 
    1990              :   /* Search for the cluster of locs in the accesses_in_loop vector
    1991              :      which is sorted after postorder index of the loop father.  */
    1992       225806 :   loc = ref->accesses_in_loop.bsearch (loop, find_ref_loc_in_loop_cmp,
    1993              :                                        bb_loop_postorder);
    1994       225806 :   if (!loc)
    1995              :     return false;
    1996              : 
    1997              :   /* We have found one location inside loop or its sub-loops.  Iterate
    1998              :      both forward and backward to cover the whole cluster.  */
    1999       225806 :   i = loc - ref->accesses_in_loop.address ();
    2000       319601 :   while (i > 0)
    2001              :     {
    2002       157662 :       --i;
    2003       157662 :       mem_ref_loc *l = &ref->accesses_in_loop[i];
    2004       157662 :       if (!flow_bb_inside_loop_p (loop, gimple_bb (l->stmt)))
    2005              :         break;
    2006       130358 :       if (fn (l))
    2007              :         return true;
    2008              :     }
    2009       520557 :   for (i = loc - ref->accesses_in_loop.address ();
    2010       331314 :        i < ref->accesses_in_loop.length (); ++i)
    2011              :     {
    2012       248186 :       mem_ref_loc *l = &ref->accesses_in_loop[i];
    2013       248186 :       if (!flow_bb_inside_loop_p (loop, gimple_bb (l->stmt)))
    2014              :         break;
    2015       226941 :       if (fn (l))
    2016              :         return true;
    2017              :     }
    2018              : 
    2019              :   return false;
    2020              : }
    2021              : 
    2022              : /* Rewrites location LOC by TMP_VAR.  */
    2023              : 
    2024              : class rewrite_mem_ref_loc
    2025              : {
    2026              : public:
    2027        37977 :   rewrite_mem_ref_loc (tree tmp_var_) : tmp_var (tmp_var_) {}
    2028              :   bool operator () (mem_ref_loc *loc);
    2029              :   tree tmp_var;
    2030              : };
    2031              : 
    2032              : bool
    2033        59573 : rewrite_mem_ref_loc::operator () (mem_ref_loc *loc)
    2034              : {
    2035        59573 :   *loc->ref = tmp_var;
    2036        59573 :   update_stmt (loc->stmt);
    2037        59573 :   return false;
    2038              : }
    2039              : 
    2040              : /* Rewrites all references to REF in LOOP by variable TMP_VAR.  */
    2041              : 
    2042              : static void
    2043        37977 : rewrite_mem_refs (class loop *loop, im_mem_ref *ref, tree tmp_var)
    2044              : {
    2045            0 :   for_all_locs_in_loop (loop, ref, rewrite_mem_ref_loc (tmp_var));
    2046            0 : }
    2047              : 
    2048              : /* Stores the first reference location in LOCP.  */
    2049              : 
    2050              : class first_mem_ref_loc_1
    2051              : {
    2052              : public:
    2053        37977 :   first_mem_ref_loc_1 (mem_ref_loc **locp_) : locp (locp_) {}
    2054              :   bool operator () (mem_ref_loc *loc);
    2055              :   mem_ref_loc **locp;
    2056              : };
    2057              : 
    2058              : bool
    2059        37977 : first_mem_ref_loc_1::operator () (mem_ref_loc *loc)
    2060              : {
    2061        37977 :   *locp = loc;
    2062        37977 :   return true;
    2063              : }
    2064              : 
    2065              : /* Returns the first reference location to REF in LOOP.  */
    2066              : 
    2067              : static mem_ref_loc *
    2068        37977 : first_mem_ref_loc (class loop *loop, im_mem_ref *ref)
    2069              : {
    2070        37977 :   mem_ref_loc *locp = NULL;
    2071            0 :   for_all_locs_in_loop (loop, ref, first_mem_ref_loc_1 (&locp));
    2072        37977 :   return locp;
    2073              : }
    2074              : 
    2075              : /* Helper function for execute_sm.  Emit code to store TMP_VAR into
    2076              :    MEM along edge EX.
    2077              : 
    2078              :    The store is only done if MEM has changed.  We do this so no
    2079              :    changes to MEM occur on code paths that did not originally store
    2080              :    into it.
    2081              : 
    2082              :    The common case for execute_sm will transform:
    2083              : 
    2084              :      for (...) {
    2085              :        if (foo)
    2086              :          stuff;
    2087              :        else
    2088              :          MEM = TMP_VAR;
    2089              :      }
    2090              : 
    2091              :    into:
    2092              : 
    2093              :      lsm = MEM;
    2094              :      for (...) {
    2095              :        if (foo)
    2096              :          stuff;
    2097              :        else
    2098              :          lsm = TMP_VAR;
    2099              :      }
    2100              :      MEM = lsm;
    2101              : 
    2102              :   This function will generate:
    2103              : 
    2104              :      lsm = MEM;
    2105              : 
    2106              :      lsm_flag = false;
    2107              :      ...
    2108              :      for (...) {
    2109              :        if (foo)
    2110              :          stuff;
    2111              :        else {
    2112              :          lsm = TMP_VAR;
    2113              :          lsm_flag = true;
    2114              :        }
    2115              :      }
    2116              :      if (lsm_flag)      <--
    2117              :        MEM = lsm;       <-- (X)
    2118              : 
    2119              :   In case MEM and TMP_VAR are NULL the function will return the then
    2120              :   block so the caller can insert (X) and other related stmts.
    2121              : */
    2122              : 
    2123              : static basic_block
    2124        12235 : execute_sm_if_changed (edge ex, tree mem, tree tmp_var, tree flag,
    2125              :                        edge preheader, hash_set <basic_block> *flag_bbs,
    2126              :                        edge &append_cond_position, edge &last_cond_fallthru)
    2127              : {
    2128        12235 :   basic_block new_bb, then_bb, old_dest;
    2129        12235 :   bool loop_has_only_one_exit;
    2130        12235 :   edge then_old_edge;
    2131        12235 :   gimple_stmt_iterator gsi;
    2132        12235 :   gimple *stmt;
    2133        12235 :   bool irr = ex->flags & EDGE_IRREDUCIBLE_LOOP;
    2134              : 
    2135        12235 :   profile_count count_sum = profile_count::zero ();
    2136        12235 :   int nbbs = 0, ncount = 0;
    2137        12235 :   profile_probability flag_probability = profile_probability::uninitialized ();
    2138              : 
    2139              :   /* Flag is set in FLAG_BBS. Determine probability that flag will be true
    2140              :      at loop exit.
    2141              : 
    2142              :      This code may look fancy, but it cannot update profile very realistically
    2143              :      because we do not know the probability that flag will be true at given
    2144              :      loop exit.
    2145              : 
    2146              :      We look for two interesting extremes
    2147              :        - when exit is dominated by block setting the flag, we know it will
    2148              :          always be true.  This is a common case.
    2149              :        - when all blocks setting the flag have very low frequency we know
    2150              :          it will likely be false.
    2151              :      In all other cases we default to 2/3 for flag being true.  */
    2152              : 
    2153        12235 :   for (hash_set<basic_block>::iterator it = flag_bbs->begin ();
    2154        27465 :        it != flag_bbs->end (); ++it)
    2155              :     {
    2156        15230 :        if ((*it)->count.initialized_p ())
    2157        15217 :          count_sum += (*it)->count, ncount ++;
    2158        15230 :        if (dominated_by_p (CDI_DOMINATORS, ex->src, *it))
    2159         2544 :          flag_probability = profile_probability::always ();
    2160        15230 :        nbbs++;
    2161              :     }
    2162              : 
    2163        12235 :   profile_probability cap
    2164        12235 :           = profile_probability::guessed_always ().apply_scale (2, 3);
    2165              : 
    2166        12235 :   if (flag_probability.initialized_p ())
    2167              :     ;
    2168         9797 :   else if (ncount == nbbs
    2169        19861 :            && preheader->count () >= count_sum && preheader->count ().nonzero_p ())
    2170              :     {
    2171          172 :       flag_probability = count_sum.probability_in (preheader->count ());
    2172          172 :       if (flag_probability > cap)
    2173           77 :         flag_probability = cap;
    2174              :     }
    2175              : 
    2176        12235 :   if (!flag_probability.initialized_p ())
    2177         9625 :     flag_probability = cap;
    2178              : 
    2179              :   /* ?? Insert store after previous store if applicable.  See note
    2180              :      below.  */
    2181        12235 :   if (append_cond_position)
    2182         4135 :     ex = append_cond_position;
    2183              : 
    2184        12235 :   loop_has_only_one_exit = single_pred_p (ex->dest);
    2185              : 
    2186        12235 :   if (loop_has_only_one_exit)
    2187         5185 :     ex = split_block_after_labels (ex->dest);
    2188              :   else
    2189              :     {
    2190         7050 :       for (gphi_iterator gpi = gsi_start_phis (ex->dest);
    2191        10762 :            !gsi_end_p (gpi); gsi_next (&gpi))
    2192              :         {
    2193         4692 :           gphi *phi = gpi.phi ();
    2194         9384 :           if (virtual_operand_p (gimple_phi_result (phi)))
    2195         3712 :             continue;
    2196              : 
    2197              :           /* When the destination has a non-virtual PHI node with multiple
    2198              :              predecessors make sure we preserve the PHI structure by
    2199              :              forcing a forwarder block so that hoisting of that PHI will
    2200              :              still work.  */
    2201          980 :           split_edge (ex);
    2202          980 :           break;
    2203              :         }
    2204              :     }
    2205              : 
    2206        12235 :   old_dest = ex->dest;
    2207        12235 :   new_bb = split_edge (ex);
    2208        12235 :   if (append_cond_position)
    2209         4135 :     new_bb->count += last_cond_fallthru->count ();
    2210        12235 :   then_bb = create_empty_bb (new_bb);
    2211        12235 :   then_bb->count = new_bb->count.apply_probability (flag_probability);
    2212        12235 :   if (irr)
    2213           51 :     then_bb->flags = BB_IRREDUCIBLE_LOOP;
    2214        12235 :   add_bb_to_loop (then_bb, new_bb->loop_father);
    2215              : 
    2216        12235 :   gsi = gsi_start_bb (new_bb);
    2217        12235 :   stmt = gimple_build_cond (NE_EXPR, flag, boolean_false_node,
    2218              :                             NULL_TREE, NULL_TREE);
    2219        12235 :   gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
    2220              : 
    2221              :   /* Insert actual store.  */
    2222        12235 :   if (mem)
    2223              :     {
    2224         9758 :       gsi = gsi_start_bb (then_bb);
    2225         9758 :       stmt = gimple_build_assign (unshare_expr (mem), tmp_var);
    2226         9758 :       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
    2227              :     }
    2228              : 
    2229        12235 :   edge e1 = single_succ_edge (new_bb);
    2230        24419 :   edge e2 = make_edge (new_bb, then_bb,
    2231              :                        EDGE_TRUE_VALUE | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
    2232        12235 :   e2->probability = flag_probability;
    2233              : 
    2234        12235 :   e1->flags |= EDGE_FALSE_VALUE | (irr ? EDGE_IRREDUCIBLE_LOOP : 0);
    2235        12235 :   e1->flags &= ~EDGE_FALLTHRU;
    2236              : 
    2237        12235 :   e1->probability = flag_probability.invert ();
    2238              : 
    2239        24419 :   then_old_edge = make_single_succ_edge (then_bb, old_dest,
    2240              :                              EDGE_FALLTHRU | (irr ? EDGE_IRREDUCIBLE_LOOP : 0));
    2241              : 
    2242        12235 :   set_immediate_dominator (CDI_DOMINATORS, then_bb, new_bb);
    2243              : 
    2244        12235 :   if (append_cond_position)
    2245              :     {
    2246         4135 :       basic_block prevbb = last_cond_fallthru->src;
    2247         4135 :       redirect_edge_succ (last_cond_fallthru, new_bb);
    2248         4135 :       set_immediate_dominator (CDI_DOMINATORS, new_bb, prevbb);
    2249         4135 :       set_immediate_dominator (CDI_DOMINATORS, old_dest,
    2250              :                                recompute_dominator (CDI_DOMINATORS, old_dest));
    2251              :     }
    2252              : 
    2253              :   /* ?? Because stores may alias, they must happen in the exact
    2254              :      sequence they originally happened.  Save the position right after
    2255              :      the (_lsm) store we just created so we can continue appending after
    2256              :      it and maintain the original order.  */
    2257        12235 :   append_cond_position = then_old_edge;
    2258        12235 :   last_cond_fallthru = find_edge (new_bb, old_dest);
    2259              : 
    2260        12235 :   if (!loop_has_only_one_exit)
    2261         7050 :     for (gphi_iterator gpi = gsi_start_phis (old_dest);
    2262        10594 :          !gsi_end_p (gpi); gsi_next (&gpi))
    2263              :       {
    2264         3544 :         gphi *phi = gpi.phi ();
    2265         3544 :         unsigned i;
    2266              : 
    2267        23483 :         for (i = 0; i < gimple_phi_num_args (phi); i++)
    2268        16395 :           if (gimple_phi_arg_edge (phi, i)->src == new_bb)
    2269              :             {
    2270         3544 :               tree arg = gimple_phi_arg_def (phi, i);
    2271         3544 :               add_phi_arg (phi, arg, then_old_edge, UNKNOWN_LOCATION);
    2272         3544 :               update_stmt (phi);
    2273              :             }
    2274              :       }
    2275              : 
    2276        12235 :   return then_bb;
    2277              : }
    2278              : 
    2279              : /* When REF is set on the location, set flag indicating the store.  */
    2280              : 
    2281              : class sm_set_flag_if_changed
    2282              : {
    2283              : public:
    2284         7053 :   sm_set_flag_if_changed (tree flag_, hash_set <basic_block> *bbs_)
    2285         7053 :          : flag (flag_), bbs (bbs_) {}
    2286              :   bool operator () (mem_ref_loc *loc);
    2287              :   tree flag;
    2288              :   hash_set <basic_block> *bbs;
    2289              : };
    2290              : 
    2291              : bool
    2292        13078 : sm_set_flag_if_changed::operator () (mem_ref_loc *loc)
    2293              : {
    2294              :   /* Only set the flag for writes.  */
    2295        13078 :   if (is_gimple_assign (loc->stmt)
    2296        13078 :       && gimple_assign_lhs_ptr (loc->stmt) == loc->ref)
    2297              :     {
    2298         8105 :       gimple_stmt_iterator gsi = gsi_for_stmt (loc->stmt);
    2299         8105 :       gimple *stmt = gimple_build_assign (flag, boolean_true_node);
    2300         8105 :       gsi_insert_after (&gsi, stmt, GSI_CONTINUE_LINKING);
    2301         8105 :       bbs->add (gimple_bb (stmt));
    2302              :     }
    2303        13078 :   return false;
    2304              : }
    2305              : 
    2306              : /* Helper function for execute_sm.  On every location where REF is
    2307              :    set, set an appropriate flag indicating the store.  */
    2308              : 
    2309              : static tree
    2310         7053 : execute_sm_if_changed_flag_set (class loop *loop, im_mem_ref *ref,
    2311              :                                 hash_set <basic_block> *bbs)
    2312              : {
    2313         7053 :   tree flag;
    2314         7053 :   char *str = get_lsm_tmp_name (ref->mem.ref, ~0, "_flag");
    2315         7053 :   flag = create_tmp_reg (boolean_type_node, str);
    2316         7053 :   for_all_locs_in_loop (loop, ref, sm_set_flag_if_changed (flag, bbs));
    2317         7053 :   return flag;
    2318              : }
    2319              : 
    2320        37977 : struct sm_aux
    2321              : {
    2322              :   tree tmp_var;
    2323              :   tree store_flag;
    2324              :   hash_set <basic_block> flag_bbs;
    2325              : };
    2326              : 
    2327              : /* Executes store motion of memory reference REF from LOOP.
    2328              :    Exits from the LOOP are stored in EXITS.  The initialization of the
    2329              :    temporary variable is put to the preheader of the loop, and assignments
    2330              :    to the reference from the temporary variable are emitted to exits.  */
    2331              : 
    2332              : static sm_aux *
    2333        37977 : execute_sm (class loop *loop, im_mem_ref *ref,
    2334              :             hash_map<im_mem_ref *, sm_aux *> &aux_map, bool maybe_mt,
    2335              :             bool use_other_flag_var)
    2336              : {
    2337        37977 :   gassign *load;
    2338        37977 :   struct fmt_data fmt_data;
    2339        37977 :   struct lim_aux_data *lim_data;
    2340        37977 :   bool multi_threaded_model_p = false;
    2341        37977 :   gimple_stmt_iterator gsi;
    2342        37977 :   sm_aux *aux = new sm_aux;
    2343              : 
    2344        37977 :   if (dump_file && (dump_flags & TDF_DETAILS))
    2345              :     {
    2346           84 :       fprintf (dump_file, "Executing store motion of ");
    2347           84 :       print_generic_expr (dump_file, ref->mem.ref);
    2348           84 :       fprintf (dump_file, " from loop %d\n", loop->num);
    2349              :     }
    2350              : 
    2351        37977 :   aux->tmp_var = create_tmp_reg (TREE_TYPE (ref->mem.ref),
    2352        37977 :                                  get_lsm_tmp_name (ref->mem.ref, ~0));
    2353              : 
    2354        37977 :   fmt_data.loop = loop;
    2355        37977 :   fmt_data.orig_loop = loop;
    2356        37977 :   for_each_index (&ref->mem.ref, force_move_till, &fmt_data);
    2357              : 
    2358        75954 :   bool always_stored = ref_always_stored_p (loop, ref);
    2359        37977 :   if (maybe_mt
    2360        11335 :       && (bb_in_transaction (loop_preheader_edge (loop)->src)
    2361        11334 :           || (ref_can_have_store_data_races (ref->mem.ref) && ! always_stored)
    2362              :           /* Do not speculate a load/store when that's not a noop, either
    2363              :              because the mode cannot be transferred or because there's
    2364              :              UB involved for out-of-bound values.  */
    2365         4015 :           || !mode_can_transfer_bits (TYPE_MODE (TREE_TYPE (ref->mem.ref)))
    2366         4015 :           || TREE_CODE (TREE_TYPE (ref->mem.ref)) == BOOLEAN_TYPE
    2367         4004 :           || (TREE_CODE (ref->mem.ref) == COMPONENT_REF
    2368          884 :               && DECL_BIT_FIELD (TREE_OPERAND (ref->mem.ref, 1)))))
    2369              :     multi_threaded_model_p = true;
    2370              : 
    2371        37977 :   if (multi_threaded_model_p && !use_other_flag_var)
    2372         7053 :     aux->store_flag
    2373         7053 :       = execute_sm_if_changed_flag_set (loop, ref, &aux->flag_bbs);
    2374              :   else
    2375              :     aux->store_flag = NULL_TREE;
    2376              : 
    2377              :   /* Remember variable setup.  */
    2378        37977 :   aux_map.put (ref, aux);
    2379              : 
    2380        37977 :   rewrite_mem_refs (loop, ref, aux->tmp_var);
    2381              : 
    2382              :   /* Emit the load code on a random exit edge or into the latch if
    2383              :      the loop does not exit, so that we are sure it will be processed
    2384              :      by move_computations after all dependencies.  */
    2385        37977 :   gsi = gsi_for_stmt (first_mem_ref_loc (loop, ref)->stmt);
    2386              : 
    2387              :   /* Avoid doing a load if there was no load of the ref in the loop.
    2388              :      Esp. when the ref is not always stored we cannot optimize it
    2389              :      away later.  But when it is not always stored we must use a conditional
    2390              :      store then.  */
    2391        37977 :   if ((!always_stored && !multi_threaded_model_p)
    2392        37977 :       || (ref->loaded && bitmap_bit_p (ref->loaded, loop->num)))
    2393        19073 :     load = gimple_build_assign (aux->tmp_var, unshare_expr (ref->mem.ref));
    2394              :   else
    2395              :     {
    2396              :       /* If not emitting a load mark the uninitialized state on the
    2397              :          loop entry as not to be warned for.  */
    2398        18904 :       tree uninit = create_tmp_reg (TREE_TYPE (aux->tmp_var));
    2399        18904 :       suppress_warning (uninit, OPT_Wuninitialized);
    2400        18904 :       uninit = get_or_create_ssa_default_def (cfun, uninit);
    2401        18904 :       load = gimple_build_assign (aux->tmp_var, uninit);
    2402              :     }
    2403        37977 :   lim_data = init_lim_data (load);
    2404        37977 :   lim_data->max_loop = loop;
    2405        37977 :   lim_data->tgt_loop = loop;
    2406        37977 :   gsi_insert_before (&gsi, load, GSI_SAME_STMT);
    2407              : 
    2408        37977 :   if (aux->store_flag)
    2409              :     {
    2410         7053 :       load = gimple_build_assign (aux->store_flag, boolean_false_node);
    2411         7053 :       lim_data = init_lim_data (load);
    2412         7053 :       lim_data->max_loop = loop;
    2413         7053 :       lim_data->tgt_loop = loop;
    2414         7053 :       gsi_insert_before (&gsi, load, GSI_SAME_STMT);
    2415              :     }
    2416              : 
    2417        37977 :   return aux;
    2418              : }
    2419              : 
    2420              : /* sm_ord is used for ordinary stores we can retain order with respect
    2421              :        to other stores
    2422              :    sm_unord is used for conditional executed stores which need to be
    2423              :        able to execute in arbitrary order with respect to other stores
    2424              :    sm_other is used for stores we do not try to apply store motion to.  */
    2425              : enum sm_kind { sm_ord, sm_unord, sm_other };
    2426              : struct seq_entry
    2427              : {
    2428              :   seq_entry () = default;
    2429        56675 :   seq_entry (unsigned f, sm_kind k, tree fr = NULL)
    2430        56675 :     : first (f), second (k), from (fr) {}
    2431              :   unsigned first;
    2432              :   sm_kind second;
    2433              :   tree from;
    2434              : };
    2435              : 
    2436              : static void
    2437        34906 : execute_sm_exit (class loop *loop, edge ex, vec<seq_entry> &seq,
    2438              :                  hash_map<im_mem_ref *, sm_aux *> &aux_map, sm_kind kind,
    2439              :                  edge &append_cond_position, edge &last_cond_fallthru,
    2440              :                  bitmap clobbers_to_prune)
    2441              : {
    2442              :   /* Sink the stores to exit from the loop.  */
    2443       122100 :   for (unsigned i = seq.length (); i > 0; --i)
    2444              :     {
    2445        52288 :       im_mem_ref *ref = memory_accesses.refs_list[seq[i-1].first];
    2446        52288 :       if (seq[i-1].second == sm_other)
    2447              :         {
    2448         5571 :           gcc_assert (kind == sm_ord && seq[i-1].from != NULL_TREE);
    2449         5571 :           gassign *store;
    2450         5571 :           if (ref->mem.ref == error_mark_node)
    2451              :             {
    2452          195 :               tree lhs = gimple_assign_lhs (ref->accesses_in_loop[0].stmt);
    2453          195 :               if (dump_file && (dump_flags & TDF_DETAILS))
    2454              :                 {
    2455            3 :                   fprintf (dump_file, "Re-issuing dependent ");
    2456            3 :                   print_generic_expr (dump_file, unshare_expr (seq[i-1].from));
    2457            3 :                   fprintf (dump_file, " of ");
    2458            3 :                   print_generic_expr (dump_file, lhs);
    2459            3 :                   fprintf (dump_file, " from loop %d on exit %d -> %d\n",
    2460            3 :                            loop->num, ex->src->index, ex->dest->index);
    2461              :                 }
    2462          195 :               store = gimple_build_assign (unshare_expr (lhs),
    2463          195 :                                            unshare_expr (seq[i-1].from));
    2464          195 :               bitmap_set_bit (clobbers_to_prune, seq[i-1].first);
    2465              :             }
    2466              :           else
    2467              :             {
    2468         5376 :               if (dump_file && (dump_flags & TDF_DETAILS))
    2469              :                 {
    2470            2 :                   fprintf (dump_file, "Re-issuing dependent store of ");
    2471            2 :                   print_generic_expr (dump_file, ref->mem.ref);
    2472            2 :                   fprintf (dump_file, " from loop %d on exit %d -> %d\n",
    2473            2 :                            loop->num, ex->src->index, ex->dest->index);
    2474              :                 }
    2475         5376 :               store = gimple_build_assign (unshare_expr (ref->mem.ref),
    2476         5376 :                                            seq[i-1].from);
    2477              :             }
    2478         5571 :           gsi_insert_on_edge (ex, store);
    2479              :         }
    2480              :       else
    2481              :         {
    2482        46717 :           sm_aux *aux = *aux_map.get (ref);
    2483        46717 :           if (!aux->store_flag || kind == sm_ord)
    2484              :             {
    2485        36959 :               gassign *store;
    2486        36959 :               store = gimple_build_assign (unshare_expr (ref->mem.ref),
    2487              :                                            aux->tmp_var);
    2488        36959 :               gsi_insert_on_edge (ex, store);
    2489        36959 :             }
    2490              :           else
    2491         9758 :             execute_sm_if_changed (ex, ref->mem.ref, aux->tmp_var,
    2492              :                                    aux->store_flag,
    2493              :                                    loop_preheader_edge (loop), &aux->flag_bbs,
    2494              :                                    append_cond_position, last_cond_fallthru);
    2495              :         }
    2496              :     }
    2497        34906 : }
    2498              : 
    2499              : /* Push the SM candidate at index PTR in the sequence SEQ down until
    2500              :    we hit the next SM candidate.  Return true if that went OK and
    2501              :    false if we could not disambiguate against another unrelated ref.
    2502              :    Update *AT to the index where the candidate now resides.  */
    2503              : 
    2504              : static bool
    2505        42363 : sm_seq_push_down (vec<seq_entry> &seq, unsigned ptr, unsigned *at)
    2506              : {
    2507        42363 :   *at = ptr;
    2508        43181 :   for (; ptr > 0; --ptr)
    2509              :     {
    2510        19989 :       seq_entry &new_cand = seq[ptr];
    2511        19989 :       seq_entry &against = seq[ptr-1];
    2512        19989 :       if (against.second == sm_ord
    2513         6665 :           || (against.second == sm_other && against.from != NULL_TREE))
    2514              :         /* Found the tail of the sequence.  */
    2515              :         break;
    2516              :       /* We may not ignore self-dependences here.  */
    2517         1125 :       if (new_cand.first == against.first
    2518              :           /* ???  We could actually handle clobbers here, but not easily
    2519              :              with LIMs dependence analysis.  */
    2520          903 :           || (memory_accesses.refs_list[new_cand.first]->mem.ref
    2521          903 :               == error_mark_node)
    2522          898 :           || (memory_accesses.refs_list[against.first]->mem.ref
    2523              :               == error_mark_node)
    2524         1999 :           || !refs_independent_p (memory_accesses.refs_list[new_cand.first],
    2525          874 :                                   memory_accesses.refs_list[against.first],
    2526              :                                   false))
    2527              :         /* ???  Prune new_cand from the list of refs to apply SM to.  */
    2528              :         return false;
    2529          818 :       std::swap (new_cand, against);
    2530          818 :       *at = ptr - 1;
    2531              :     }
    2532              :   return true;
    2533              : }
    2534              : 
    2535              : /* Computes the sequence of stores from candidates in REFS_NOT_IN_SEQ to SEQ
    2536              :    walking backwards from VDEF (or the end of BB if VDEF is NULL).  */
    2537              : 
    2538              : static int
    2539        33747 : sm_seq_valid_bb (class loop *loop, basic_block bb, tree vdef,
    2540              :                  vec<seq_entry> &seq, bitmap refs_not_in_seq,
    2541              :                  bitmap refs_not_supported, bool forked,
    2542              :                  bitmap fully_visited)
    2543              : {
    2544        38831 :   if (!vdef)
    2545       158513 :     for (gimple_stmt_iterator gsi = gsi_last_bb (bb); !gsi_end_p (gsi);
    2546       100961 :          gsi_prev (&gsi))
    2547              :       {
    2548       159825 :         vdef = gimple_vdef (gsi_stmt (gsi));
    2549        58864 :         if (vdef)
    2550              :           break;
    2551              :       }
    2552        28776 :   if (!vdef)
    2553              :     {
    2554         8497 :       gphi *vphi = get_virtual_phi (bb);
    2555         8497 :       if (vphi)
    2556         4447 :         vdef = gimple_phi_result (vphi);
    2557              :     }
    2558        38831 :   if (!vdef)
    2559              :     {
    2560         4050 :       if (single_pred_p (bb))
    2561              :         /* This handles the perfect nest case.  */
    2562         3254 :         return sm_seq_valid_bb (loop, single_pred (bb), vdef,
    2563              :                                 seq, refs_not_in_seq, refs_not_supported,
    2564         3254 :                                 forked, fully_visited);
    2565              :       return 0;
    2566              :     }
    2567        87849 :   do
    2568              :     {
    2569        61315 :       gimple *def = SSA_NAME_DEF_STMT (vdef);
    2570        61315 :       if (gimple_bb (def) != bb)
    2571              :         {
    2572              :           /* If we forked by processing a PHI do not allow our walk to
    2573              :              merge again until we handle that robustly.  */
    2574         3064 :           if (forked)
    2575              :             {
    2576              :               /* Mark refs_not_in_seq as unsupported.  */
    2577         1317 :               bitmap_ior_into (refs_not_supported, refs_not_in_seq);
    2578         1317 :               return 1;
    2579              :             }
    2580              :           /* Otherwise it doesn't really matter if we end up in different
    2581              :              BBs.  */
    2582              :           bb = gimple_bb (def);
    2583              :         }
    2584        59998 :       if (gphi *phi = dyn_cast <gphi *> (def))
    2585              :         {
    2586              :           /* Handle CFG merges.  Until we handle forks (gimple_bb (def) != bb)
    2587              :              this is still linear.
    2588              :              Eventually we want to cache intermediate results per BB
    2589              :              (but we can't easily cache for different exits?).  */
    2590              :           /* Stop at PHIs with possible backedges.  */
    2591        11784 :           if (bb == bb->loop_father->header
    2592         6014 :               || bb->flags & BB_IRREDUCIBLE_LOOP)
    2593              :             {
    2594              :               /* Mark refs_not_in_seq as unsupported.  */
    2595         5775 :               bitmap_ior_into (refs_not_supported, refs_not_in_seq);
    2596         5775 :               return 1;
    2597              :             }
    2598         6009 :           if (gimple_phi_num_args (phi) == 1)
    2599         1830 :             return sm_seq_valid_bb (loop, gimple_phi_arg_edge (phi, 0)->src,
    2600              :                                     gimple_phi_arg_def (phi, 0), seq,
    2601              :                                     refs_not_in_seq, refs_not_supported,
    2602         1830 :                                     false, fully_visited);
    2603         8358 :           if (bitmap_bit_p (fully_visited,
    2604         4179 :                             SSA_NAME_VERSION (gimple_phi_result (phi))))
    2605              :             return 1;
    2606         4075 :           auto_vec<seq_entry> first_edge_seq;
    2607         4075 :           auto_bitmap tem_refs_not_in_seq (&lim_bitmap_obstack);
    2608         4075 :           int eret;
    2609         4075 :           bitmap_copy (tem_refs_not_in_seq, refs_not_in_seq);
    2610         4075 :           eret = sm_seq_valid_bb (loop, gimple_phi_arg_edge (phi, 0)->src,
    2611              :                                   gimple_phi_arg_def (phi, 0),
    2612              :                                   first_edge_seq,
    2613              :                                   tem_refs_not_in_seq, refs_not_supported,
    2614              :                                   true, fully_visited);
    2615         4075 :           if (eret != 1)
    2616              :             return -1;
    2617              :           /* Simplify our lives by pruning the sequence of !sm_ord.  */
    2618         3938 :           while (!first_edge_seq.is_empty ()
    2619         9302 :                  && first_edge_seq.last ().second != sm_ord)
    2620         1289 :             first_edge_seq.pop ();
    2621         8225 :           for (unsigned int i = 1; i < gimple_phi_num_args (phi); ++i)
    2622              :             {
    2623         6387 :               tree vuse = gimple_phi_arg_def (phi, i);
    2624         6387 :               edge e = gimple_phi_arg_edge (phi, i);
    2625         6387 :               auto_vec<seq_entry> edge_seq;
    2626         6387 :               bitmap_and_compl (tem_refs_not_in_seq,
    2627              :                                 refs_not_in_seq, refs_not_supported);
    2628              :               /* If we've marked all refs we search for as unsupported
    2629              :                  we can stop processing and use the sequence as before
    2630              :                  the PHI.  */
    2631         6387 :               if (bitmap_empty_p (tem_refs_not_in_seq))
    2632              :                 return 1;
    2633         4150 :               eret = sm_seq_valid_bb (loop, e->src, vuse, edge_seq,
    2634              :                                       tem_refs_not_in_seq, refs_not_supported,
    2635              :                                       true, fully_visited);
    2636         4150 :               if (eret != 1)
    2637              :                 return -1;
    2638              :               /* Simplify our lives by pruning the sequence of !sm_ord.  */
    2639         3444 :               while (!edge_seq.is_empty ()
    2640         8664 :                      && edge_seq.last ().second != sm_ord)
    2641         1070 :                 edge_seq.pop ();
    2642         8300 :               unsigned min_len = MIN(first_edge_seq.length (),
    2643              :                                      edge_seq.length ());
    2644              :               /* Incrementally merge seqs into first_edge_seq.  */
    2645         4150 :               int first_uneq = -1;
    2646         4150 :               auto_vec<seq_entry, 2> extra_refs;
    2647         6572 :               for (unsigned int i = 0; i < min_len; ++i)
    2648              :                 {
    2649              :                   /* ???  We can more intelligently merge when we face different
    2650              :                      order by additional sinking operations in one sequence.
    2651              :                      For now we simply mark them as to be processed by the
    2652              :                      not order-preserving SM code.  */
    2653         2422 :                   if (first_edge_seq[i].first != edge_seq[i].first)
    2654              :                     {
    2655           34 :                       if (first_edge_seq[i].second == sm_ord)
    2656           21 :                         bitmap_set_bit (refs_not_supported,
    2657           21 :                                         first_edge_seq[i].first);
    2658           34 :                       if (edge_seq[i].second == sm_ord)
    2659           26 :                         bitmap_set_bit (refs_not_supported, edge_seq[i].first);
    2660           34 :                       first_edge_seq[i].second = sm_other;
    2661           34 :                       first_edge_seq[i].from = NULL_TREE;
    2662              :                       /* Record the dropped refs for later processing.  */
    2663           34 :                       if (first_uneq == -1)
    2664           32 :                         first_uneq = i;
    2665           68 :                       extra_refs.safe_push (seq_entry (edge_seq[i].first,
    2666           34 :                                                        sm_other, NULL_TREE));
    2667              :                     }
    2668              :                   /* sm_other prevails.  */
    2669         2388 :                   else if (first_edge_seq[i].second != edge_seq[i].second)
    2670              :                     {
    2671              :                       /* Make sure the ref is marked as not supported.  */
    2672            0 :                       bitmap_set_bit (refs_not_supported,
    2673            0 :                                       first_edge_seq[i].first);
    2674            0 :                       first_edge_seq[i].second = sm_other;
    2675            0 :                       first_edge_seq[i].from = NULL_TREE;
    2676              :                     }
    2677         2388 :                   else if (first_edge_seq[i].second == sm_other
    2678            4 :                            && first_edge_seq[i].from != NULL_TREE
    2679         2392 :                            && (edge_seq[i].from == NULL_TREE
    2680            4 :                                || !operand_equal_p (first_edge_seq[i].from,
    2681            4 :                                                     edge_seq[i].from, 0)))
    2682            4 :                     first_edge_seq[i].from = NULL_TREE;
    2683              :                 }
    2684              :               /* Any excess elements become sm_other since they are now
    2685              :                  coonditionally executed.  */
    2686        11266 :               if (first_edge_seq.length () > edge_seq.length ())
    2687              :                 {
    2688         7441 :                   for (unsigned i = edge_seq.length ();
    2689         9582 :                        i < first_edge_seq.length (); ++i)
    2690              :                     {
    2691         7441 :                       if (first_edge_seq[i].second == sm_ord)
    2692         3931 :                         bitmap_set_bit (refs_not_supported,
    2693         3931 :                                         first_edge_seq[i].first);
    2694         7441 :                       first_edge_seq[i].second = sm_other;
    2695              :                     }
    2696              :                 }
    2697         2009 :               else if (edge_seq.length () > first_edge_seq.length ())
    2698              :                 {
    2699            5 :                   if (first_uneq == -1)
    2700            0 :                     first_uneq = first_edge_seq.length ();
    2701            5 :                   for (unsigned i = first_edge_seq.length ();
    2702           20 :                        i < edge_seq.length (); ++i)
    2703              :                     {
    2704           15 :                       if (edge_seq[i].second == sm_ord)
    2705            5 :                         bitmap_set_bit (refs_not_supported, edge_seq[i].first);
    2706           30 :                       extra_refs.safe_push (seq_entry (edge_seq[i].first,
    2707           15 :                                                        sm_other, NULL_TREE));
    2708              :                     }
    2709              :                 }
    2710              :               /* Put unmerged refs at first_uneq to force dependence checking
    2711              :                  on them.  */
    2712         4150 :               if (first_uneq != -1)
    2713              :                 {
    2714              :                   /* Missing ordered_splice_at.  */
    2715           64 :                   if ((unsigned)first_uneq == first_edge_seq.length ())
    2716            0 :                     first_edge_seq.safe_splice (extra_refs);
    2717              :                   else
    2718              :                     {
    2719           32 :                       unsigned fes_length = first_edge_seq.length ();
    2720           32 :                       first_edge_seq.safe_grow (fes_length
    2721           32 :                                                 + extra_refs.length ());
    2722           32 :                       memmove (&first_edge_seq[first_uneq + extra_refs.length ()],
    2723           32 :                                &first_edge_seq[first_uneq],
    2724           32 :                                (fes_length - first_uneq) * sizeof (seq_entry));
    2725           64 :                       memcpy (&first_edge_seq[first_uneq],
    2726           32 :                               extra_refs.address (),
    2727           32 :                               extra_refs.length () * sizeof (seq_entry));
    2728              :                     }
    2729              :                 }
    2730         6387 :             }
    2731              :           /* Use the sequence from the first edge and push SMs down.  */
    2732         5042 :           for (unsigned i = 0; i < first_edge_seq.length (); ++i)
    2733              :             {
    2734         3204 :               unsigned id = first_edge_seq[i].first;
    2735         3204 :               seq.safe_push (first_edge_seq[i]);
    2736         3204 :               unsigned new_idx;
    2737         3204 :               if ((first_edge_seq[i].second == sm_ord
    2738         2321 :                    || (first_edge_seq[i].second == sm_other
    2739         2321 :                        && first_edge_seq[i].from != NULL_TREE))
    2740         4483 :                   && !sm_seq_push_down (seq, seq.length () - 1, &new_idx))
    2741              :                 {
    2742          125 :                   if (first_edge_seq[i].second == sm_ord)
    2743            0 :                     bitmap_set_bit (refs_not_supported, id);
    2744              :                   /* Mark it sm_other.  */
    2745          125 :                   seq[new_idx].second = sm_other;
    2746          125 :                   seq[new_idx].from = NULL_TREE;
    2747              :                 }
    2748              :             }
    2749         1838 :           bitmap_set_bit (fully_visited,
    2750         1838 :                           SSA_NAME_VERSION (gimple_phi_result (phi)));
    2751         1838 :           return 1;
    2752         4075 :         }
    2753        48214 :       lim_aux_data *data = get_lim_data (def);
    2754        48214 :       im_mem_ref *ref = memory_accesses.refs_list[data->ref];
    2755        48214 :       if (data->ref == UNANALYZABLE_MEM_ID)
    2756              :         return -1;
    2757              :       /* Stop at memory references which we can't move.  */
    2758        48214 :       else if ((ref->mem.ref == error_mark_node
    2759              :                 /* We can move end-of-storage/object down.  */
    2760          393 :                 && !gimple_clobber_p (ref->accesses_in_loop[0].stmt,
    2761              :                                       CLOBBER_STORAGE_END)
    2762          246 :                 && !gimple_clobber_p (ref->accesses_in_loop[0].stmt,
    2763              :                                       CLOBBER_OBJECT_END))
    2764        48517 :                || TREE_THIS_VOLATILE (ref->mem.ref))
    2765              :         {
    2766              :           /* Mark refs_not_in_seq as unsupported.  */
    2767          122 :           bitmap_ior_into (refs_not_supported, refs_not_in_seq);
    2768          122 :           return 1;
    2769              :         }
    2770              :       /* One of the stores we want to apply SM to and we've not yet seen.  */
    2771        48092 :       else if (bitmap_clear_bit (refs_not_in_seq, data->ref))
    2772              :         {
    2773        37876 :           seq.safe_push (seq_entry (data->ref, sm_ord));
    2774              : 
    2775              :           /* 1) push it down the queue until a SMed
    2776              :              and not ignored ref is reached, skipping all not SMed refs
    2777              :              and ignored refs via non-TBAA disambiguation.  */
    2778        37876 :           unsigned new_idx;
    2779        75752 :           if (!sm_seq_push_down (seq, seq.length () - 1, &new_idx)
    2780              :               /* If that fails but we did not fork yet continue, we'll see
    2781              :                  to re-materialize all of the stores in the sequence then.
    2782              :                  Further stores will only be pushed up to this one.  */
    2783        37876 :               && forked)
    2784              :             {
    2785            0 :               bitmap_set_bit (refs_not_supported, data->ref);
    2786              :               /* Mark it sm_other.  */
    2787            0 :               seq[new_idx].second = sm_other;
    2788              :             }
    2789              : 
    2790              :           /* 2) check whether we've seen all refs we want to SM and if so
    2791              :              declare success for the active exit  */
    2792        37876 :           if (bitmap_empty_p (refs_not_in_seq))
    2793        21558 :             return 1;
    2794              :         }
    2795              :       else
    2796              :         /* Another store not part of the final sequence.  Simply push it.  */
    2797        10216 :         seq.safe_push (seq_entry (data->ref, sm_other,
    2798        10216 :                                   gimple_assign_rhs1 (def)));
    2799              : 
    2800        26534 :       vdef = gimple_vuse (def);
    2801        26534 :     }
    2802              :   while (1);
    2803              : }
    2804              : 
    2805              : /* Hoists memory references MEM_REFS out of LOOP.  EXITS is the list of exit
    2806              :    edges of the LOOP.  */
    2807              : 
    2808              : static void
    2809        23895 : hoist_memory_references (class loop *loop, bitmap mem_refs,
    2810              :                          const vec<edge> &exits)
    2811              : {
    2812        23895 :   im_mem_ref *ref;
    2813        23895 :   unsigned  i;
    2814        23895 :   bitmap_iterator bi;
    2815              : 
    2816              :   /* There's a special case we can use ordered re-materialization for
    2817              :      conditionally executed stores which is when all stores in the loop
    2818              :      happen in the same basic-block.  In that case we know we'll reach
    2819              :      all stores and thus can simply process that BB and emit a single
    2820              :      conditional block of ordered materializations.  See PR102436.  */
    2821        23895 :   basic_block single_store_bb = NULL;
    2822        34728 :   EXECUTE_IF_SET_IN_BITMAP (&memory_accesses.all_refs_stored_in_loop[loop->num],
    2823              :                             0, i, bi)
    2824              :     {
    2825        32367 :       bool fail = false;
    2826        32367 :       ref = memory_accesses.refs_list[i];
    2827       147942 :       for (auto loc : ref->accesses_in_loop)
    2828       158830 :         if (!gimple_vdef (loc.stmt))
    2829              :           ;
    2830        35614 :         else if (!single_store_bb)
    2831              :           {
    2832        23895 :             single_store_bb = gimple_bb (loc.stmt);
    2833        23895 :             bool conditional = false;
    2834        86459 :             for (edge e : exits)
    2835        25621 :               if (!dominated_by_p (CDI_DOMINATORS, e->src, single_store_bb))
    2836              :                 {
    2837              :                   /* Conditional as seen from e.  */
    2838              :                   conditional = true;
    2839              :                   break;
    2840              :                 }
    2841        23895 :             if (!conditional)
    2842              :               {
    2843              :                 fail = true;
    2844              :                 break;
    2845              :               }
    2846              :           }
    2847        11719 :         else if (single_store_bb != gimple_bb (loc.stmt))
    2848              :           {
    2849              :             fail = true;
    2850              :             break;
    2851              :           }
    2852        32367 :       if (fail)
    2853              :         {
    2854              :           single_store_bb = NULL;
    2855              :           break;
    2856              :         }
    2857              :     }
    2858        23895 :   if (single_store_bb)
    2859              :     {
    2860              :       /* Analyze the single block with stores.  */
    2861         2361 :       auto_bitmap fully_visited;
    2862         2361 :       auto_bitmap refs_not_supported;
    2863         2361 :       auto_bitmap refs_not_in_seq;
    2864         2361 :       auto_vec<seq_entry> seq;
    2865         2361 :       bitmap_copy (refs_not_in_seq, mem_refs);
    2866         2361 :       int res = sm_seq_valid_bb (loop, single_store_bb, NULL_TREE,
    2867              :                                  seq, refs_not_in_seq, refs_not_supported,
    2868              :                                  false, fully_visited);
    2869         2361 :       if (res != 1)
    2870              :         {
    2871              :           /* Unhandled refs can still fail this.  */
    2872            0 :           bitmap_clear (mem_refs);
    2873            0 :           return;
    2874              :         }
    2875              : 
    2876              :       /* We cannot handle sm_other since we neither remember the
    2877              :          stored location nor the value at the point we execute them.  */
    2878         5698 :       for (unsigned i = 0; i < seq.length (); ++i)
    2879              :         {
    2880         3337 :           unsigned new_i;
    2881         3337 :           if (seq[i].second == sm_other
    2882         3337 :               && seq[i].from != NULL_TREE)
    2883          467 :             seq[i].from = NULL_TREE;
    2884         2870 :           else if ((seq[i].second == sm_ord
    2885            0 :                     || (seq[i].second == sm_other
    2886            0 :                         && seq[i].from != NULL_TREE))
    2887         2870 :                    && !sm_seq_push_down (seq, i, &new_i))
    2888              :             {
    2889           69 :               bitmap_set_bit (refs_not_supported, seq[new_i].first);
    2890           69 :               seq[new_i].second = sm_other;
    2891           69 :               seq[new_i].from = NULL_TREE;
    2892              :             }
    2893              :         }
    2894         2361 :       bitmap_and_compl_into (mem_refs, refs_not_supported);
    2895         2361 :       if (bitmap_empty_p (mem_refs))
    2896              :         return;
    2897              : 
    2898              :       /* Prune seq.  */
    2899         2734 :       while (seq.last ().second == sm_other
    2900         2734 :              && seq.last ().from == NULL_TREE)
    2901          425 :         seq.pop ();
    2902              : 
    2903         2309 :       hash_map<im_mem_ref *, sm_aux *> aux_map;
    2904              : 
    2905              :       /* Execute SM but delay the store materialization for ordered
    2906              :          sequences on exit.  Remember a created flag var and make
    2907              :          sure to re-use it.  */
    2908         2309 :       sm_aux *flag_var_aux = nullptr;
    2909         5110 :       EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
    2910              :         {
    2911         2801 :           ref = memory_accesses.refs_list[i];
    2912         2801 :           sm_aux *aux = execute_sm (loop, ref, aux_map, true,
    2913              :                                     flag_var_aux != nullptr);
    2914         2801 :           if (aux->store_flag)
    2915         1597 :             flag_var_aux = aux;
    2916              :         }
    2917              : 
    2918              :       /* Materialize ordered store sequences on exits.  */
    2919         2309 :       edge e;
    2920         2309 :       auto_bitmap clobbers_to_prune;
    2921         6214 :       FOR_EACH_VEC_ELT (exits, i, e)
    2922              :         {
    2923         3905 :           edge append_cond_position = NULL;
    2924         3905 :           edge last_cond_fallthru = NULL;
    2925         3905 :           edge insert_e = e;
    2926              :           /* Construct the single flag variable control flow and insert
    2927              :              the ordered seq of stores in the then block.  With
    2928              :              -fstore-data-races we can do the stores unconditionally.  */
    2929         3905 :           if (flag_var_aux)
    2930         2477 :             insert_e
    2931              :               = single_pred_edge
    2932         2477 :                   (execute_sm_if_changed (e, NULL_TREE, NULL_TREE,
    2933              :                                           flag_var_aux->store_flag,
    2934              :                                           loop_preheader_edge (loop),
    2935              :                                           &flag_var_aux->flag_bbs,
    2936              :                                           append_cond_position,
    2937              :                                           last_cond_fallthru));
    2938         3905 :           execute_sm_exit (loop, insert_e, seq, aux_map, sm_ord,
    2939              :                            append_cond_position, last_cond_fallthru,
    2940              :                            clobbers_to_prune);
    2941         3905 :           gsi_commit_one_edge_insert (insert_e, NULL);
    2942              :         }
    2943              : 
    2944              :       /* Remove clobbers inside the loop we re-materialized on exits.  */
    2945         2309 :       EXECUTE_IF_SET_IN_BITMAP (clobbers_to_prune, 0, i, bi)
    2946              :         {
    2947            0 :           gimple *stmt = memory_accesses.refs_list[i]->accesses_in_loop[0].stmt;
    2948            0 :           gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
    2949            0 :           unlink_stmt_vdef (stmt);
    2950            0 :           release_defs (stmt);
    2951            0 :           gimple_set_vdef (stmt, NULL_TREE);
    2952            0 :           gsi_remove (&gsi, true);
    2953              :         }
    2954              : 
    2955         5110 :       for (hash_map<im_mem_ref *, sm_aux *>::iterator iter = aux_map.begin ();
    2956         5110 :            iter != aux_map.end (); ++iter)
    2957         5602 :         delete (*iter).second;
    2958              : 
    2959         2309 :       return;
    2960         4670 :     }
    2961              : 
    2962              :   /* To address PR57359 before actually applying store-motion check
    2963              :      the candidates found for validity with regards to reordering
    2964              :      relative to other stores which we until here disambiguated using
    2965              :      TBAA which isn't valid.
    2966              :      What matters is the order of the last stores to the mem_refs
    2967              :      with respect to the other stores of the loop at the point of the
    2968              :      loop exits.  */
    2969              : 
    2970              :   /* For each exit compute the store order, pruning from mem_refs
    2971              :      on the fly.  */
    2972              :   /* The complexity of this is at least
    2973              :      O(number of exits * number of SM refs) but more approaching
    2974              :      O(number of exits * number of SM refs * number of stores).  */
    2975              :   /* ???  Somehow do this in a single sweep over the loop body.  */
    2976        21534 :   auto_vec<std::pair<edge, vec<seq_entry> > > sms;
    2977        21534 :   auto_bitmap refs_not_supported (&lim_bitmap_obstack);
    2978        21534 :   edge e;
    2979        43899 :   FOR_EACH_VEC_ELT (exits, i, e)
    2980              :     {
    2981        24309 :       vec<seq_entry> seq;
    2982        24309 :       seq.create (4);
    2983        24309 :       auto_bitmap refs_not_in_seq (&lim_bitmap_obstack);
    2984        24309 :       bitmap_and_compl (refs_not_in_seq, mem_refs, refs_not_supported);
    2985        24309 :       if (bitmap_empty_p (refs_not_in_seq))
    2986              :         {
    2987         1148 :           seq.release ();
    2988         1148 :           break;
    2989              :         }
    2990        23161 :       auto_bitmap fully_visited;
    2991        23161 :       int res = sm_seq_valid_bb (loop, e->src, NULL_TREE,
    2992              :                                  seq, refs_not_in_seq,
    2993              :                                  refs_not_supported, false,
    2994              :                                  fully_visited);
    2995        23161 :       if (res != 1)
    2996              :         {
    2997          796 :           bitmap_copy (refs_not_supported, mem_refs);
    2998          796 :           seq.release ();
    2999          796 :           break;
    3000              :         }
    3001        22365 :       sms.safe_push (std::make_pair (e, seq));
    3002        25105 :     }
    3003              : 
    3004              :   /* Prune pruned mem_refs from earlier processed exits.  */
    3005        21534 :   bool changed = !bitmap_empty_p (refs_not_supported);
    3006        21534 :   while (changed)
    3007              :     {
    3008         6277 :       changed = false;
    3009         6277 :       std::pair<edge, vec<seq_entry> > *seq;
    3010        43183 :       FOR_EACH_VEC_ELT (sms, i, seq)
    3011              :         {
    3012              :           bool need_to_push = false;
    3013        14124 :           for (unsigned i = 0; i < seq->second.length (); ++i)
    3014              :             {
    3015         6438 :               sm_kind kind = seq->second[i].second;
    3016         6438 :               if (kind == sm_other && seq->second[i].from == NULL_TREE)
    3017              :                 break;
    3018         5461 :               unsigned id = seq->second[i].first;
    3019         5461 :               unsigned new_idx;
    3020         5461 :               if (kind == sm_ord
    3021         5461 :                   && bitmap_bit_p (refs_not_supported, id))
    3022              :                 {
    3023         2658 :                   seq->second[i].second = sm_other;
    3024         2658 :                   gcc_assert (seq->second[i].from == NULL_TREE);
    3025              :                   need_to_push = true;
    3026              :                 }
    3027         2803 :               else if (need_to_push
    3028         2803 :                        && !sm_seq_push_down (seq->second, i, &new_idx))
    3029              :                 {
    3030              :                   /* We need to push down both sm_ord and sm_other
    3031              :                      but for the latter we need to disqualify all
    3032              :                      following refs.  */
    3033          113 :                   if (kind == sm_ord)
    3034              :                     {
    3035            7 :                       if (bitmap_set_bit (refs_not_supported, id))
    3036            7 :                         changed = true;
    3037            7 :                       seq->second[new_idx].second = sm_other;
    3038              :                     }
    3039              :                   else
    3040              :                     {
    3041          411 :                       for (unsigned j = seq->second.length () - 1;
    3042          305 :                            j > new_idx; --j)
    3043          199 :                         if (seq->second[j].second == sm_ord
    3044          321 :                             && bitmap_set_bit (refs_not_supported,
    3045          122 :                                                seq->second[j].first))
    3046              :                           changed = true;
    3047          106 :                       seq->second.truncate (new_idx);
    3048          106 :                       break;
    3049              :                     }
    3050              :                 }
    3051              :             }
    3052              :         }
    3053              :     }
    3054        21534 :   std::pair<edge, vec<seq_entry> > *seq;
    3055        66264 :   FOR_EACH_VEC_ELT (sms, i, seq)
    3056              :     {
    3057              :       /* Prune sm_other from the end.  */
    3058        70747 :       while (!seq->second.is_empty ()
    3059        48382 :              && seq->second.last ().second == sm_other)
    3060         5126 :         seq->second.pop ();
    3061              :       /* Prune duplicates from the start.  */
    3062        22365 :       auto_bitmap seen (&lim_bitmap_obstack);
    3063        22365 :       unsigned j, k;
    3064        53897 :       for (j = k = 0; j < seq->second.length (); ++j)
    3065        31532 :         if (bitmap_set_bit (seen, seq->second[j].first))
    3066              :           {
    3067        31423 :             if (k != j)
    3068           77 :               seq->second[k] = seq->second[j];
    3069        31423 :             ++k;
    3070              :           }
    3071        22365 :       seq->second.truncate (k);
    3072              :       /* And verify.  */
    3073        22365 :       seq_entry *e;
    3074        98518 :       FOR_EACH_VEC_ELT (seq->second, j, e)
    3075        31423 :         gcc_assert (e->second == sm_ord
    3076              :                     || (e->second == sm_other && e->from != NULL_TREE));
    3077        22365 :     }
    3078              : 
    3079              :   /* Verify dependence for refs we cannot handle with the order preserving
    3080              :      code (refs_not_supported) or prune them from mem_refs.  */
    3081        21534 :   auto_vec<seq_entry> unord_refs;
    3082        37751 :   EXECUTE_IF_SET_IN_BITMAP (refs_not_supported, 0, i, bi)
    3083              :     {
    3084        16217 :       ref = memory_accesses.refs_list[i];
    3085        16217 :       if (!ref_indep_loop_p (loop, ref, sm_waw))
    3086         7683 :         bitmap_clear_bit (mem_refs, i);
    3087              :       /* We've now verified store order for ref with respect to all other
    3088              :          stores in the loop does not matter.  */
    3089              :       else
    3090         8534 :         unord_refs.safe_push (seq_entry (i, sm_unord));
    3091              :     }
    3092              : 
    3093        21534 :   hash_map<im_mem_ref *, sm_aux *> aux_map;
    3094              : 
    3095              :   /* Execute SM but delay the store materialization for ordered
    3096              :      sequences on exit.  */
    3097        56710 :   EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
    3098              :     {
    3099        35176 :       ref = memory_accesses.refs_list[i];
    3100        35176 :       execute_sm (loop, ref, aux_map, bitmap_bit_p (refs_not_supported, i),
    3101              :                   false);
    3102              :     }
    3103              : 
    3104              :   /* Materialize ordered store sequences on exits.  */
    3105        21534 :   auto_bitmap clobbers_to_prune;
    3106        46973 :   FOR_EACH_VEC_ELT (exits, i, e)
    3107              :     {
    3108        25439 :       edge append_cond_position = NULL;
    3109        25439 :       edge last_cond_fallthru = NULL;
    3110        25439 :       if (i < sms.length ())
    3111              :         {
    3112        22365 :           gcc_assert (sms[i].first == e);
    3113        22365 :           execute_sm_exit (loop, e, sms[i].second, aux_map, sm_ord,
    3114              :                            append_cond_position, last_cond_fallthru,
    3115              :                            clobbers_to_prune);
    3116        22365 :           sms[i].second.release ();
    3117              :         }
    3118        25439 :       if (!unord_refs.is_empty ())
    3119         8636 :         execute_sm_exit (loop, e, unord_refs, aux_map, sm_unord,
    3120              :                          append_cond_position, last_cond_fallthru,
    3121              :                          clobbers_to_prune);
    3122              :       /* Commit edge inserts here to preserve the order of stores
    3123              :          when an exit exits multiple loops.  */
    3124        25439 :       gsi_commit_one_edge_insert (e, NULL);
    3125              :     }
    3126              : 
    3127              :   /* Remove clobbers inside the loop we re-materialized on exits.  */
    3128        21729 :   EXECUTE_IF_SET_IN_BITMAP (clobbers_to_prune, 0, i, bi)
    3129              :     {
    3130          195 :       gimple *stmt = memory_accesses.refs_list[i]->accesses_in_loop[0].stmt;
    3131          195 :       gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
    3132          195 :       unlink_stmt_vdef (stmt);
    3133          195 :       release_defs (stmt);
    3134          195 :       gimple_set_vdef (stmt, NULL_TREE);
    3135          195 :       gsi_remove (&gsi, true);
    3136              :     }
    3137              : 
    3138        56710 :   for (hash_map<im_mem_ref *, sm_aux *>::iterator iter = aux_map.begin ();
    3139        78244 :        iter != aux_map.end (); ++iter)
    3140        70352 :     delete (*iter).second;
    3141        21534 : }
    3142              : 
    3143              : class ref_always_stored
    3144              : {
    3145              : public:
    3146        96043 :   ref_always_stored (class loop *loop_)
    3147        96043 :       : loop (loop_) {}
    3148              :   bool operator () (mem_ref_loc *loc);
    3149              :   class loop *loop;
    3150              : };
    3151              : 
    3152              : bool
    3153       199198 : ref_always_stored::operator () (mem_ref_loc *loc)
    3154              : {
    3155              :   /* Make sure the statement is a store.  */
    3156       199198 :   tree lhs = gimple_get_lhs (loc->stmt);
    3157       199198 :   if (!lhs
    3158       199198 :       || !(DECL_P (lhs) || REFERENCE_CLASS_P (lhs)))
    3159              :     return false;
    3160              : 
    3161       120985 :   struct lim_aux_data *lim_data = get_lim_data (loc->stmt);
    3162       120985 :   if (!lim_data)
    3163              :     return false;
    3164              : 
    3165       120985 :   class loop *must_exec = lim_data->always_executed_in;
    3166       120985 :   if (!must_exec)
    3167              :     return false;
    3168              : 
    3169        41670 :   if (must_exec == loop
    3170        41670 :       || flow_loop_nested_p (must_exec, loop))
    3171        37725 :     return true;
    3172              : 
    3173              :   return false;
    3174              : }
    3175              : 
    3176              : /* Returns true if REF is always stored in LOOP.  */
    3177              : 
    3178              : static bool
    3179        96043 : ref_always_stored_p (class loop *loop, im_mem_ref *ref)
    3180              : {
    3181        96043 :   return for_all_locs_in_loop (loop, ref, ref_always_stored (loop));
    3182              : }
    3183              : 
    3184              : /* Returns true if LOAD_REF and STORE_REF form a "self write" pattern
    3185              :    where the stored value comes from the loaded value via SSA.
    3186              :    Example: a[i] = a[0] is safe to hoist a[0] even when i==0.  */
    3187              : 
    3188              : static bool
    3189       292213 : is_self_write (im_mem_ref *load_ref, im_mem_ref *store_ref)
    3190              : {
    3191              :   /* Only handle the simple case with a single access per ref.
    3192              :      Bail out on multiple accesses to be conservative.  */
    3193       292213 :   if (load_ref->accesses_in_loop.length () != 1
    3194       381137 :       || store_ref->accesses_in_loop.length () != 1)
    3195              :     return false;
    3196              : 
    3197        88941 :   gimple *load_stmt = load_ref->accesses_in_loop[0].stmt;
    3198        88941 :   gimple *store_stmt = store_ref->accesses_in_loop[0].stmt;
    3199              : 
    3200        88941 :   if (!is_gimple_assign (load_stmt) || !is_gimple_assign (store_stmt))
    3201              :     return false;
    3202              : 
    3203        88941 :   tree loaded_val = gimple_assign_lhs (load_stmt);
    3204        88941 :   tree stored_val = gimple_assign_rhs1 (store_stmt);
    3205              : 
    3206        88941 :   if (TREE_CODE (loaded_val) != SSA_NAME || TREE_CODE (stored_val) != SSA_NAME)
    3207              :     return false;
    3208              : 
    3209              :   /* Self write: stored value is the loaded value.  */
    3210        66075 :   if (stored_val != loaded_val)
    3211              :     return false;
    3212              : 
    3213              : 
    3214              :   /* TODO: Try to factor this out with mem_ref_hasher::equal
    3215              :      into im_compare_access_position_and_size
    3216              :      or a similar helper to centralize this delicate handling
    3217              :      complete for MEM_REF offsets and base pointer equality.
    3218              : 
    3219              :      TODO: Also ensure max_size_known_p agrees or resort to
    3220              :      alignment considerations to rule out partial overlaps.
    3221              : 
    3222              :      See:
    3223              :      https://gcc.gnu.org/pipermail/gcc-patches/2025-December/704155.html
    3224              :      For more context on TODOs above.  */
    3225              : 
    3226              :   /* They may alias.  Verify exact same location.  */
    3227         1669 :   return (operand_equal_p (load_ref->mem.base, store_ref->mem.base, 0)
    3228           46 :           && known_eq (load_ref->mem.size, store_ref->mem.size)
    3229         1715 :           && known_eq (load_ref->mem.offset, store_ref->mem.offset));
    3230              : 
    3231              : }
    3232              : 
    3233              : /* Returns true if REF1 and REF2 are independent.  */
    3234              : 
    3235              : static bool
    3236       557483 : refs_independent_p (im_mem_ref *ref1, im_mem_ref *ref2, bool tbaa_p)
    3237              : {
    3238       557483 :   if (ref1 == ref2)
    3239              :     return true;
    3240              : 
    3241       497434 :   if (dump_file && (dump_flags & TDF_DETAILS))
    3242         3043 :     fprintf (dump_file, "Querying dependency of refs %u and %u: ",
    3243         3043 :              ref1->id, ref2->id);
    3244              : 
    3245       497434 :   if (mem_refs_may_alias_p (ref1, ref2, &memory_accesses.ttae_cache, tbaa_p))
    3246              :     {
    3247        56276 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3248           97 :         fprintf (dump_file, "dependent.\n");
    3249              :       return false;
    3250              :     }
    3251              :   else
    3252              :     {
    3253       441158 :       if (dump_file && (dump_flags & TDF_DETAILS))
    3254         2946 :         fprintf (dump_file, "independent.\n");
    3255              :       return true;
    3256              :     }
    3257              : }
    3258              : 
    3259              : /* Returns true if REF is independent on all other accessess in LOOP.
    3260              :    KIND specifies the kind of dependence to consider.
    3261              :      lim_raw assumes REF is not stored in LOOP and disambiguates RAW
    3262              :              dependences so if true REF can be hoisted out of LOOP
    3263              :      sm_war disambiguates a store REF against all other loads to see
    3264              :             whether the store can be sunk across loads out of LOOP
    3265              :      sm_waw disambiguates a store REF against all other stores to see
    3266              :             whether the store can be sunk across stores out of LOOP.  */
    3267              : 
    3268              : static bool
    3269      1944607 : ref_indep_loop_p (class loop *loop, im_mem_ref *ref, dep_kind kind)
    3270              : {
    3271      1944607 :   bool indep_p = true;
    3272      1944607 :   bitmap refs_to_check;
    3273              : 
    3274      1944607 :   if (kind == sm_war)
    3275       957847 :     refs_to_check = &memory_accesses.refs_loaded_in_loop[loop->num];
    3276              :   else
    3277       986760 :     refs_to_check = &memory_accesses.refs_stored_in_loop[loop->num];
    3278              : 
    3279      1944607 :   if (bitmap_bit_p (refs_to_check, UNANALYZABLE_MEM_ID)
    3280      1944607 :       || ref->mem.ref == error_mark_node)
    3281              :     indep_p = false;
    3282              :   else
    3283              :     {
    3284              :       /* tri-state, { unknown, independent, dependent }  */
    3285       527727 :       dep_state state = query_loop_dependence (loop, ref, kind);
    3286       527727 :       if (state != dep_unknown)
    3287        64992 :         return state == dep_independent;
    3288              : 
    3289       462735 :       class loop *inner = loop->inner;
    3290       600603 :       while (inner)
    3291              :         {
    3292       265998 :           if (!ref_indep_loop_p (inner, ref, kind))
    3293              :             {
    3294              :               indep_p = false;
    3295              :               break;
    3296              :             }
    3297       137868 :           inner = inner->next;
    3298              :         }
    3299              : 
    3300       462735 :       if (indep_p)
    3301              :         {
    3302       334605 :           unsigned i;
    3303       334605 :           bitmap_iterator bi;
    3304       853319 :           EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
    3305              :             {
    3306       578883 :               im_mem_ref *aref = memory_accesses.refs_list[i];
    3307       578883 :               if (aref->mem.ref == error_mark_node)
    3308              :                 {
    3309        22257 :                   gimple *stmt = aref->accesses_in_loop[0].stmt;
    3310        22257 :                   if ((kind == sm_war
    3311         7376 :                        && ref_maybe_used_by_stmt_p (stmt, &ref->mem,
    3312              :                                                     kind != sm_waw))
    3313        29030 :                       || stmt_may_clobber_ref_p_1 (stmt, &ref->mem,
    3314              :                                                    kind != sm_waw))
    3315              :                     {
    3316              :                       indep_p = false;
    3317              :                       break;
    3318              :                     }
    3319              :                 }
    3320              :               /* For hoisting loads (lim_raw), allow "self write": the store
    3321              :                  writes back the loaded value.  Example: a[i] = a[0]
    3322              :                  is safe even when i==0 causes aliasing.  */
    3323       556626 :               else if (kind == lim_raw
    3324       292213 :                        && ref->loaded && aref->stored
    3325       848839 :                        && is_self_write (ref, aref))
    3326              :                 {
    3327           17 :                   if (dump_file && (dump_flags & TDF_DETAILS))
    3328            2 :                     fprintf (dump_file,
    3329              :                              "Dependency of refs %u and %u: "
    3330              :                              "independent (self write).\n",
    3331            2 :                              ref->id, aref->id);
    3332              :                 }
    3333              : 
    3334       556609 :               else if (!refs_independent_p (ref, aref, kind != sm_waw))
    3335              :                 {
    3336              :                   indep_p = false;
    3337              :                   break;
    3338              :                 }
    3339              :             }
    3340              :         }
    3341              :     }
    3342              : 
    3343      1879615 :   if (dump_file && (dump_flags & TDF_DETAILS))
    3344          777 :     fprintf (dump_file, "Querying %s dependencies of ref %u in loop %d: %s\n",
    3345              :              kind == lim_raw ? "RAW" : (kind == sm_war ? "SM WAR" : "SM WAW"),
    3346          378 :              ref->id, loop->num, indep_p ? "independent" : "dependent");
    3347              : 
    3348              :   /* Record the computed result in the cache.  */
    3349      1879615 :   record_loop_dependence (loop, ref, kind,
    3350              :                           indep_p ? dep_independent : dep_dependent);
    3351              : 
    3352      1879615 :   return indep_p;
    3353              : }
    3354              : 
    3355              : class ref_in_loop_hot_body
    3356              : {
    3357              : public:
    3358        46756 :   ref_in_loop_hot_body (class loop *loop_) : l (loop_) {}
    3359              :   bool operator () (mem_ref_loc *loc);
    3360              :   class loop *l;
    3361              : };
    3362              : 
    3363              : /* Check the coldest loop between loop L and innermost loop.  If there is one
    3364              :    cold loop between L and INNER_LOOP, store motion can be performed, otherwise
    3365              :    no cold loop means no store motion.  get_coldest_out_loop also handles cases
    3366              :    when l is inner_loop.  */
    3367              : bool
    3368        47473 : ref_in_loop_hot_body::operator () (mem_ref_loc *loc)
    3369              : {
    3370        47473 :   basic_block curr_bb = gimple_bb (loc->stmt);
    3371        47473 :   class loop *inner_loop = curr_bb->loop_father;
    3372        47473 :   return get_coldest_out_loop (l, inner_loop, curr_bb);
    3373              : }
    3374              : 
    3375              : 
    3376              : /* Returns true if we can perform store motion of REF from LOOP.  */
    3377              : 
    3378              : static bool
    3379      3121838 : can_sm_ref_p (class loop *loop, im_mem_ref *ref)
    3380              : {
    3381      3121838 :   bool store_could_trap;
    3382              : 
    3383              :   /* Can't hoist unanalyzable refs.  */
    3384      3121838 :   if (!MEM_ANALYZABLE (ref))
    3385              :     return false;
    3386              : 
    3387              :   /* Can't hoist/sink aggregate copies.  */
    3388      2755397 :   if (ref->mem.ref == error_mark_node)
    3389              :     return false;
    3390              : 
    3391              :   /* It should be movable.  */
    3392      2306279 :   if (!is_gimple_reg_type (TREE_TYPE (ref->mem.ref))
    3393      2305993 :       || TREE_THIS_VOLATILE (ref->mem.ref)
    3394      4476082 :       || !for_each_index (&ref->mem.ref, may_move_till, loop))
    3395              :     return false;
    3396              : 
    3397       989627 :   store_could_trap = lhs_could_trap_p (ref->mem.ref);
    3398              : 
    3399              :   /* Do not move a load or store that can throw.  Store motion does not
    3400              :      update EH information.  */
    3401       989627 :   if (tree_could_throw_p (ref->mem.ref)
    3402       989627 :       || (flag_exceptions
    3403       694695 :           && cfun->can_throw_non_call_exceptions
    3404       540163 :           && store_could_trap))
    3405              :     return false;
    3406              : 
    3407              :   /* If a store can trap, it must be always executed in LOOP.  */
    3408       966163 :   if (store_could_trap
    3409              :       /* ???  We can at least use false here, allowing loads?  We
    3410              :          are forcing conditional stores if the ref is not always
    3411              :          stored to later anyway.  So this would only guard
    3412              :          the load we need to emit.  Thus when the ref is not
    3413              :          loaded we can elide this completely?  */
    3414      1024229 :       && !ref_always_stored_p (loop, ref))
    3415              :     return false;
    3416              : 
    3417              :   /* Verify all loads of ref can be hoisted.  */
    3418       919318 :   if (ref->loaded
    3419        97655 :       && bitmap_bit_p (ref->loaded, loop->num)
    3420      1010863 :       && !ref_indep_loop_p (loop, ref, lim_raw))
    3421              :     return false;
    3422              : 
    3423              :   /* Verify the candidate can be disambiguated against all loads,
    3424              :      that is, we can elide all in-loop stores.  Disambiguation
    3425              :      against stores is done later when we cannot guarantee preserving
    3426              :      the order of stores.  */
    3427       851402 :   if (!ref_indep_loop_p (loop, ref, sm_war))
    3428              :     return false;
    3429              : 
    3430              :   /* Verify whether the candidate is hot for LOOP.  Only do store motion if the
    3431              :     candidate's profile count is hot.  Statement in cold BB shouldn't be moved
    3432              :     out of it's loop_father.  */
    3433        46756 :   if (!for_all_locs_in_loop (loop, ref, ref_in_loop_hot_body (loop)))
    3434              :     return false;
    3435              : 
    3436              :   return true;
    3437              : }
    3438              : 
    3439              : /* Marks the references in LOOP for that store motion should be performed
    3440              :    in REFS_TO_SM.  SM_EXECUTED is the set of references for that store
    3441              :    motion was performed in one of the outer loops.  */
    3442              : 
    3443              : static void
    3444      1320874 : find_refs_for_sm (class loop *loop, bitmap sm_executed, bitmap refs_to_sm)
    3445              : {
    3446      1320874 :   bitmap refs = &memory_accesses.all_refs_stored_in_loop[loop->num];
    3447      1320874 :   unsigned i;
    3448      1320874 :   bitmap_iterator bi;
    3449      1320874 :   im_mem_ref *ref;
    3450              : 
    3451      4442712 :   EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
    3452              :     {
    3453      3121838 :       ref = memory_accesses.refs_list[i];
    3454      3121838 :       if (can_sm_ref_p (loop, ref) && dbg_cnt (lim))
    3455        45731 :         bitmap_set_bit (refs_to_sm, i);
    3456              :     }
    3457      1320874 : }
    3458              : 
    3459              : /* Checks whether LOOP (with exits stored in EXITS array) is suitable
    3460              :    for a store motion optimization (i.e. whether we can insert statement
    3461              :    on its exits).  */
    3462              : 
    3463              : static bool
    3464      1364748 : loop_suitable_for_sm (class loop *loop ATTRIBUTE_UNUSED,
    3465              :                       const vec<edge> &exits)
    3466              : {
    3467      1364748 :   unsigned i;
    3468      1364748 :   edge ex;
    3469              : 
    3470      3526840 :   FOR_EACH_VEC_ELT (exits, i, ex)
    3471      2205966 :     if (ex->flags & (EDGE_ABNORMAL | EDGE_EH))
    3472              :       return false;
    3473              : 
    3474              :   return true;
    3475              : }
    3476              : 
    3477              : /* Try to perform store motion for all memory references modified inside
    3478              :    LOOP.  SM_EXECUTED is the bitmap of the memory references for that
    3479              :    store motion was executed in one of the outer loops.  */
    3480              : 
    3481              : static void
    3482      1364748 : store_motion_loop (class loop *loop, bitmap sm_executed)
    3483              : {
    3484      1364748 :   auto_vec<edge> exits = get_loop_exit_edges (loop);
    3485      1364748 :   class loop *subloop;
    3486      1364748 :   bitmap sm_in_loop = BITMAP_ALLOC (&lim_bitmap_obstack);
    3487              : 
    3488      1364748 :   if (loop_suitable_for_sm (loop, exits))
    3489              :     {
    3490      1320874 :       find_refs_for_sm (loop, sm_executed, sm_in_loop);
    3491      1320874 :       if (!bitmap_empty_p (sm_in_loop))
    3492        23895 :         hoist_memory_references (loop, sm_in_loop, exits);
    3493              :     }
    3494              : 
    3495      1364748 :   bitmap_ior_into (sm_executed, sm_in_loop);
    3496      1678668 :   for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
    3497       313920 :     store_motion_loop (subloop, sm_executed);
    3498      1364748 :   bitmap_and_compl_into (sm_executed, sm_in_loop);
    3499      1364748 :   BITMAP_FREE (sm_in_loop);
    3500      1364748 : }
    3501              : 
    3502              : /* Try to perform store motion for all memory references modified inside
    3503              :    loops.  */
    3504              : 
    3505              : static void
    3506       504481 : do_store_motion (void)
    3507              : {
    3508       504481 :   class loop *loop;
    3509       504481 :   bitmap sm_executed = BITMAP_ALLOC (&lim_bitmap_obstack);
    3510              : 
    3511      1555309 :   for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
    3512      1050828 :     store_motion_loop (loop, sm_executed);
    3513              : 
    3514       504481 :   BITMAP_FREE (sm_executed);
    3515       504481 : }
    3516              : 
    3517              : /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
    3518              :    for each such basic block bb records the outermost loop for that execution
    3519              :    of its header implies execution of bb.  CONTAINS_CALL is the bitmap of
    3520              :    blocks that contain a nonpure call.  */
    3521              : 
    3522              : static void
    3523      1372266 : fill_always_executed_in_1 (class loop *loop, sbitmap contains_call)
    3524              : {
    3525      1372266 :   basic_block bb = NULL, last = NULL;
    3526      1372266 :   edge e;
    3527      1372266 :   class loop *inn_loop = loop;
    3528              : 
    3529      1688619 :   for (class loop *inner = loop->inner; inner; inner = inner->next)
    3530       316353 :     fill_always_executed_in_1 (inner, contains_call);
    3531              : 
    3532      1372266 :   auto_vec<basic_block, 64> worklist;
    3533      1372266 :   worklist.reserve_exact (loop->num_nodes);
    3534      1372266 :   worklist.quick_push (loop->header);
    3535      3076271 :   do
    3536              :     {
    3537      3076271 :       edge_iterator ei;
    3538      3076271 :       bb = worklist.pop ();
    3539              : 
    3540      3076271 :       if (!flow_bb_inside_loop_p (inn_loop, bb))
    3541              :         {
    3542              :           /* When we are leaving a possibly infinite inner loop
    3543              :              we have to stop processing.  */
    3544       192690 :           if (!finite_loop_p (inn_loop))
    3545              :             break;
    3546              :           /* If the loop was finite we can continue with processing
    3547              :              the loop we exited to.  */
    3548       183182 :           inn_loop = bb->loop_father;
    3549              :         }
    3550              : 
    3551      3066763 :       if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
    3552      1770036 :         last = bb;
    3553              : 
    3554      3066763 :       if (bitmap_bit_p (contains_call, bb->index))
    3555              :         break;
    3556              : 
    3557              :       /* If LOOP exits from this BB stop processing.  */
    3558      5941833 :       FOR_EACH_EDGE (e, ei, bb->succs)
    3559      4226983 :         if (!flow_bb_inside_loop_p (loop, e->dest))
    3560              :           break;
    3561      2720339 :       if (e)
    3562              :         break;
    3563              : 
    3564              :       /* A loop might be infinite (TODO use simple loop analysis
    3565              :          to disprove this if possible).  */
    3566      1714850 :       if (bb->flags & BB_IRREDUCIBLE_LOOP)
    3567              :         break;
    3568              : 
    3569      1714722 :       if (bb->loop_father->header == bb)
    3570              :         /* Record that we enter into a subloop since it might not
    3571              :            be finite.  */
    3572              :         /* ???  Entering into a not always executed subloop makes
    3573              :            fill_always_executed_in quadratic in loop depth since
    3574              :            we walk those loops N times.  This is not a problem
    3575              :            in practice though, see PR102253 for a worst-case testcase.  */
    3576       640946 :         inn_loop = bb->loop_father;
    3577              : 
    3578              :       /* Walk the body of LOOP sorted by dominance relation.  Additionally,
    3579              :          if a basic block S dominates the latch, then only blocks dominated
    3580              :          by S are after it.
    3581              :          This is get_loop_body_in_dom_order using a worklist algorithm and
    3582              :          stopping once we are no longer interested in visiting further
    3583              :          blocks.  */
    3584      1714722 :       unsigned old_len = worklist.length ();
    3585      1714722 :       unsigned postpone = 0;
    3586      1714722 :       for (basic_block son = first_dom_son (CDI_DOMINATORS, bb);
    3587      3712554 :            son;
    3588      1997832 :            son = next_dom_son (CDI_DOMINATORS, son))
    3589              :         {
    3590      1997832 :           if (!flow_bb_inside_loop_p (loop, son))
    3591        22018 :             continue;
    3592      1975814 :           if (dominated_by_p (CDI_DOMINATORS, loop->latch, son))
    3593       544535 :             postpone = worklist.length ();
    3594      1975814 :           worklist.quick_push (son);
    3595              :         }
    3596      1714722 :       if (postpone)
    3597              :         /* Postponing the block that dominates the latch means
    3598              :            processing it last and thus putting it earliest in the
    3599              :            worklist.  */
    3600        90019 :         std::swap (worklist[old_len], worklist[postpone]);
    3601              :     }
    3602      3429444 :   while (!worklist.is_empty ());
    3603              : 
    3604      2167806 :   while (1)
    3605              :     {
    3606      1770036 :       if (last->loop_father == loop
    3607      1770036 :           || (ALWAYS_EXECUTED_IN (last)
    3608       162104 :               && loop_outer (ALWAYS_EXECUTED_IN (last)) == loop))
    3609              :         {
    3610      1769360 :           if (dump_enabled_p ())
    3611         2487 :             dump_printf (MSG_NOTE, "BB %d is always executed in loop %d\n",
    3612              :                          last->index, loop->num);
    3613      1769360 :           SET_ALWAYS_EXECUTED_IN (last, loop);
    3614              :         }
    3615      1770036 :       if (last == loop->header)
    3616              :         break;
    3617       397770 :       last = get_immediate_dominator (CDI_DOMINATORS, last);
    3618              :     }
    3619      1372266 : }
    3620              : 
    3621              : /* Fills ALWAYS_EXECUTED_IN information for basic blocks, i.e.
    3622              :    for each such basic block bb records the outermost loop for that execution
    3623              :    of its header implies execution of bb.  */
    3624              : 
    3625              : static void
    3626       506030 : fill_always_executed_in (void)
    3627              : {
    3628       506030 :   basic_block bb;
    3629       506030 :   class loop *loop;
    3630              : 
    3631       506030 :   auto_sbitmap contains_call (last_basic_block_for_fn (cfun));
    3632       506030 :   bitmap_clear (contains_call);
    3633     15385484 :   FOR_EACH_BB_FN (bb, cfun)
    3634              :     {
    3635     14879454 :       if (loop_depth (bb->loop_father) == 0)
    3636              :         {
    3637              :           /* Outside of loops we can skip scanning all stmts.  */
    3638      8585878 :           bitmap_set_bit (contains_call, bb->index);
    3639      8585878 :           continue;
    3640              :         }
    3641      6293576 :       gimple_stmt_iterator gsi;
    3642     53726448 :       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
    3643              :         {
    3644     43247142 :           if (nonpure_call_p (gsi_stmt (gsi)))
    3645              :             break;
    3646              :         }
    3647              : 
    3648      6293576 :       if (!gsi_end_p (gsi))
    3649       991672 :         bitmap_set_bit (contains_call, bb->index);
    3650              :     }
    3651              : 
    3652      1561943 :   for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
    3653      1055913 :     fill_always_executed_in_1 (loop, contains_call);
    3654       506030 : }
    3655              : 
    3656              : /* Find the coldest loop preheader for LOOP, also find the nearest hotter loop
    3657              :    to LOOP.  Then recursively iterate each inner loop.  */
    3658              : 
    3659              : void
    3660      1372266 : fill_coldest_and_hotter_out_loop (class loop *coldest_loop,
    3661              :                                   class loop *hotter_loop, class loop *loop)
    3662              : {
    3663      1372266 :   if (bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
    3664              :                                      coldest_loop))
    3665        29464 :     coldest_loop = loop;
    3666              : 
    3667      1372266 :   coldest_outermost_loop[loop->num] = coldest_loop;
    3668              : 
    3669      1372266 :   hotter_than_inner_loop[loop->num] = NULL;
    3670      1372266 :   class loop *outer_loop = loop_outer (loop);
    3671      1372266 :   if (hotter_loop
    3672      1372266 :       && bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
    3673              :                                         hotter_loop))
    3674         2582 :     hotter_than_inner_loop[loop->num] = hotter_loop;
    3675              : 
    3676      1372266 :   if (outer_loop && outer_loop != current_loops->tree_root
    3677      1688619 :       && bb_colder_than_loop_preheader (loop_preheader_edge (loop)->src,
    3678              :                                         outer_loop))
    3679        35895 :     hotter_than_inner_loop[loop->num] = outer_loop;
    3680              : 
    3681      1372266 :   if (dump_enabled_p ())
    3682              :     {
    3683         1954 :       dump_printf (MSG_NOTE, "loop %d's coldest_outermost_loop is %d, ",
    3684              :                    loop->num, coldest_loop->num);
    3685         1954 :       if (hotter_than_inner_loop[loop->num])
    3686          319 :         dump_printf (MSG_NOTE, "hotter_than_inner_loop is %d\n",
    3687          319 :                      hotter_than_inner_loop[loop->num]->num);
    3688              :       else
    3689         1635 :         dump_printf (MSG_NOTE, "hotter_than_inner_loop is NULL\n");
    3690              :     }
    3691              : 
    3692      1372266 :   class loop *inner_loop;
    3693      1688619 :   for (inner_loop = loop->inner; inner_loop; inner_loop = inner_loop->next)
    3694       632706 :     fill_coldest_and_hotter_out_loop (coldest_loop,
    3695       316353 :                                       hotter_than_inner_loop[loop->num],
    3696              :                                       inner_loop);
    3697      1372266 : }
    3698              : 
    3699              : /* Compute the global information needed by the loop invariant motion pass.  */
    3700              : 
    3701              : static void
    3702       506030 : tree_ssa_lim_initialize (bool store_motion)
    3703              : {
    3704       506030 :   unsigned i;
    3705              : 
    3706       506030 :   bitmap_obstack_initialize (&lim_bitmap_obstack);
    3707       506030 :   gcc_obstack_init (&mem_ref_obstack);
    3708       506030 :   lim_aux_data_map = new hash_map<gimple *, lim_aux_data *>;
    3709              : 
    3710       506030 :   if (flag_tm)
    3711          104 :     compute_transaction_bits ();
    3712              : 
    3713       506030 :   memory_accesses.refs = new hash_table<mem_ref_hasher> (100);
    3714       506030 :   memory_accesses.refs_list.create (100);
    3715              :   /* Allocate a special, unanalyzable mem-ref with ID zero.  */
    3716       506030 :   memory_accesses.refs_list.quick_push
    3717       506030 :     (mem_ref_alloc (NULL, 0, UNANALYZABLE_MEM_ID));
    3718              : 
    3719      1012060 :   memory_accesses.refs_loaded_in_loop.create (number_of_loops (cfun));
    3720      1012060 :   memory_accesses.refs_loaded_in_loop.quick_grow_cleared (number_of_loops (cfun));
    3721      1012060 :   memory_accesses.refs_stored_in_loop.create (number_of_loops (cfun));
    3722      1012060 :   memory_accesses.refs_stored_in_loop.quick_grow_cleared (number_of_loops (cfun));
    3723       506030 :   if (store_motion)
    3724              :     {
    3725      1008962 :       memory_accesses.all_refs_stored_in_loop.create (number_of_loops (cfun));
    3726       504481 :       memory_accesses.all_refs_stored_in_loop.quick_grow_cleared
    3727      1008962 :                                                       (number_of_loops (cfun));
    3728              :     }
    3729              : 
    3730      6269628 :   for (i = 0; i < number_of_loops (cfun); i++)
    3731              :     {
    3732      2628784 :       bitmap_initialize (&memory_accesses.refs_loaded_in_loop[i],
    3733              :                          &lim_bitmap_obstack);
    3734      2628784 :       bitmap_initialize (&memory_accesses.refs_stored_in_loop[i],
    3735              :                          &lim_bitmap_obstack);
    3736      2628784 :       if (store_motion)
    3737      2616197 :         bitmap_initialize (&memory_accesses.all_refs_stored_in_loop[i],
    3738              :                            &lim_bitmap_obstack);
    3739              :     }
    3740              : 
    3741       506030 :   memory_accesses.ttae_cache = NULL;
    3742              : 
    3743              :   /* Initialize bb_loop_postorder with a mapping from loop->num to
    3744              :      its postorder index.  */
    3745       506030 :   i = 0;
    3746      1012060 :   bb_loop_postorder = XNEWVEC (unsigned, number_of_loops (cfun));
    3747      2890356 :   for (auto loop : loops_list (cfun, LI_FROM_INNERMOST))
    3748      1372266 :     bb_loop_postorder[loop->num] = i++;
    3749       506030 : }
    3750              : 
    3751              : /* Cleans up after the invariant motion pass.  */
    3752              : 
    3753              : static void
    3754       506030 : tree_ssa_lim_finalize (void)
    3755              : {
    3756       506030 :   basic_block bb;
    3757       506030 :   unsigned i;
    3758       506030 :   im_mem_ref *ref;
    3759              : 
    3760     15427638 :   FOR_EACH_BB_FN (bb, cfun)
    3761     14921608 :     SET_ALWAYS_EXECUTED_IN (bb, NULL);
    3762              : 
    3763       506030 :   bitmap_obstack_release (&lim_bitmap_obstack);
    3764      1012060 :   delete lim_aux_data_map;
    3765              : 
    3766       506030 :   delete memory_accesses.refs;
    3767       506030 :   memory_accesses.refs = NULL;
    3768              : 
    3769      6086837 :   FOR_EACH_VEC_ELT (memory_accesses.refs_list, i, ref)
    3770      5580807 :     memref_free (ref);
    3771       506030 :   memory_accesses.refs_list.release ();
    3772       506030 :   obstack_free (&mem_ref_obstack, NULL);
    3773              : 
    3774       506030 :   memory_accesses.refs_loaded_in_loop.release ();
    3775       506030 :   memory_accesses.refs_stored_in_loop.release ();
    3776       506030 :   memory_accesses.all_refs_stored_in_loop.release ();
    3777              : 
    3778       506030 :   if (memory_accesses.ttae_cache)
    3779         5061 :     free_affine_expand_cache (&memory_accesses.ttae_cache);
    3780              : 
    3781       506030 :   free (bb_loop_postorder);
    3782              : 
    3783       506030 :   coldest_outermost_loop.release ();
    3784       506030 :   hotter_than_inner_loop.release ();
    3785       506030 : }
    3786              : 
    3787              : /* Moves invariants from loops.  Only "expensive" invariants are moved out --
    3788              :    i.e. those that are likely to be win regardless of the register pressure.
    3789              :    Only perform store motion if STORE_MOTION is true.  */
    3790              : 
    3791              : unsigned int
    3792       506030 : loop_invariant_motion_in_fun (function *fun, bool store_motion)
    3793              : {
    3794       506030 :   unsigned int todo = 0;
    3795              : 
    3796       506030 :   tree_ssa_lim_initialize (store_motion);
    3797              : 
    3798       506030 :   mark_ssa_maybe_undefs ();
    3799              : 
    3800              :   /* Gathers information about memory accesses in the loops.  */
    3801       506030 :   analyze_memory_references (store_motion);
    3802              : 
    3803              :   /* Fills ALWAYS_EXECUTED_IN information for basic blocks.  */
    3804       506030 :   fill_always_executed_in ();
    3805              : 
    3806              :   /* Pre-compute coldest outermost loop and nearest hotter loop of each loop.
    3807              :    */
    3808       506030 :   class loop *loop;
    3809      1012060 :   coldest_outermost_loop.create (number_of_loops (cfun));
    3810      1012060 :   coldest_outermost_loop.safe_grow_cleared (number_of_loops (cfun));
    3811      1012060 :   hotter_than_inner_loop.create (number_of_loops (cfun));
    3812      1012060 :   hotter_than_inner_loop.safe_grow_cleared (number_of_loops (cfun));
    3813      1561943 :   for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
    3814      1055913 :     fill_coldest_and_hotter_out_loop (loop, NULL, loop);
    3815              : 
    3816       506030 :   int *rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
    3817       506030 :   int n = pre_and_rev_post_order_compute_fn (fun, NULL, rpo, false);
    3818              : 
    3819              :   /* For each statement determine the outermost loop in that it is
    3820              :      invariant and cost for computing the invariant.  */
    3821     15891514 :   for (int i = 0; i < n; ++i)
    3822     14879454 :     compute_invariantness (BASIC_BLOCK_FOR_FN (fun, rpo[i]));
    3823              : 
    3824              :   /* Execute store motion.  Force the necessary invariants to be moved
    3825              :      out of the loops as well.  */
    3826       506030 :   if (store_motion)
    3827       504481 :     do_store_motion ();
    3828              : 
    3829       506030 :   free (rpo);
    3830       506030 :   rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
    3831       506030 :   n = pre_and_rev_post_order_compute_fn (fun, NULL, rpo, false);
    3832              : 
    3833              :   /* Move the expressions that are expensive enough.  */
    3834     15933668 :   for (int i = 0; i < n; ++i)
    3835     14921608 :     todo |= move_computations_worker (BASIC_BLOCK_FOR_FN (fun, rpo[i]));
    3836              : 
    3837       506030 :   free (rpo);
    3838              : 
    3839       506030 :   gsi_commit_edge_inserts ();
    3840       506030 :   if (need_ssa_update_p (fun))
    3841        15810 :     rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
    3842              : 
    3843       506030 :   tree_ssa_lim_finalize ();
    3844              : 
    3845       506030 :   return todo;
    3846              : }
    3847              : 
    3848              : /* Loop invariant motion pass.  */
    3849              : 
    3850              : namespace {
    3851              : 
    3852              : const pass_data pass_data_lim =
    3853              : {
    3854              :   GIMPLE_PASS, /* type */
    3855              :   "lim", /* name */
    3856              :   OPTGROUP_LOOP, /* optinfo_flags */
    3857              :   TV_LIM, /* tv_id */
    3858              :   PROP_cfg, /* properties_required */
    3859              :   0, /* properties_provided */
    3860              :   0, /* properties_destroyed */
    3861              :   0, /* todo_flags_start */
    3862              :   0, /* todo_flags_finish */
    3863              : };
    3864              : 
    3865              : class pass_lim : public gimple_opt_pass
    3866              : {
    3867              : public:
    3868      1211940 :   pass_lim (gcc::context *ctxt)
    3869      2423880 :     : gimple_opt_pass (pass_data_lim, ctxt)
    3870              :   {}
    3871              : 
    3872              :   /* opt_pass methods: */
    3873       908955 :   opt_pass * clone () final override { return new pass_lim (m_ctxt); }
    3874      1321537 :   bool gate (function *) final override { return flag_tree_loop_im != 0; }
    3875              :   unsigned int execute (function *) final override;
    3876              : 
    3877              : }; // class pass_lim
    3878              : 
    3879              : unsigned int
    3880      1321117 : pass_lim::execute (function *fun)
    3881              : {
    3882      1321117 :   in_loop_pipeline = scev_initialized_p ();
    3883      1321117 :   if (!in_loop_pipeline)
    3884      1069077 :     loop_optimizer_init (LOOPS_NORMAL | LOOPS_HAVE_RECORDED_EXITS);
    3885              : 
    3886      2642234 :   if (number_of_loops (fun) <= 1)
    3887              :     return 0;
    3888       504515 :   unsigned int todo = loop_invariant_motion_in_fun (fun, flag_move_loop_stores);
    3889              : 
    3890       504515 :   if (!in_loop_pipeline)
    3891       252475 :     loop_optimizer_finalize ();
    3892              :   else
    3893       252040 :     scev_reset ();
    3894              :   return todo;
    3895              : }
    3896              : 
    3897              : } // anon namespace
    3898              : 
    3899              : gimple_opt_pass *
    3900       302985 : make_pass_lim (gcc::context *ctxt)
    3901              : {
    3902       302985 :   return new pass_lim (ctxt);
    3903              : }
    3904              : 
        

Generated by: LCOV version 2.6-beta

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