]> git.ipfire.org Git - thirdparty/gcc.git/blobdiff - gcc/tree-loop-distribution.c
Correct a function pre/postcondition [PR102403].
[thirdparty/gcc.git] / gcc / tree-loop-distribution.c
index 3db3d6ec21ef4c0a784edd684a6b3a2a977247e5..2df762c8aa88d84eaf615f4a6e67f7f23f6cdbfe 100644 (file)
@@ -1,5 +1,5 @@
 /* Loop distribution.
-   Copyright (C) 2006-2017 Free Software Foundation, Inc.
+   Copyright (C) 2006-2021 Free Software Foundation, Inc.
    Contributed by Georges-Andre Silber <Georges-Andre.Silber@ensmp.fr>
    and Sebastian Pop <sebastian.pop@amd.com>.
 
@@ -83,8 +83,8 @@ along with GCC; see the file COPYING3.  If not see
        loops and recover to the original one.
 
    TODO:
-     1) We only distribute innermost loops now.  This pass should handle loop
-       nests in the future.
+     1) We only distribute innermost two-level loop nest now.  We should
+       extend it for arbitrary loop nests in the future.
      2) We only fuse partitions in SCC now.  A better fusion algorithm is
        desired to minimize loop overhead, maximize parallelism and maximize
        data reuse.  */
@@ -106,17 +106,25 @@ along with GCC; see the file COPYING3.  If not see
 #include "stor-layout.h"
 #include "tree-cfg.h"
 #include "tree-ssa-loop-manip.h"
+#include "tree-ssa-loop-ivopts.h"
 #include "tree-ssa-loop.h"
 #include "tree-into-ssa.h"
 #include "tree-ssa.h"
 #include "cfgloop.h"
 #include "tree-scalar-evolution.h"
-#include "params.h"
 #include "tree-vectorizer.h"
+#include "tree-eh.h"
+#include "gimple-fold.h"
+#include "tree-affine.h"
 
 
 #define MAX_DATAREFS_NUM \
-       ((unsigned) PARAM_VALUE (PARAM_LOOP_MAX_DATAREFS_FOR_DATADEPS))
+       ((unsigned) param_loop_max_datarefs_for_datadeps)
+
+/* Threshold controlling number of distributed partitions.  Given it may
+   be unnecessary if a memory stream cost model is invented in the future,
+   we define it as a temporary macro, rather than a parameter.  */
+#define NUM_PARTITION_THRESHOLD (4)
 
 /* Hashtable helpers.  */
 
@@ -147,18 +155,10 @@ ddr_hasher::equal (const data_dependence_relation *ddr1,
   return (DDR_A (ddr1) == DDR_A (ddr2) && DDR_B (ddr1) == DDR_B (ddr2));
 }
 
-/* The loop (nest) to be distributed.  */
-static vec<loop_p> loop_nest;
 
-/* Vector of data references in the loop to be distributed.  */
-static vec<data_reference_p> datarefs_vec;
 
-/* Store index of data reference in aux field.  */
 #define DR_INDEX(dr)      ((uintptr_t) (dr)->aux)
 
-/* Hash table for data dependence relation in the loop to be distributed.  */
-static hash_table<ddr_hasher> *ddrs_table;
-
 /* A Reduced Dependence Graph (RDG) vertex representing a statement.  */
 struct rdg_vertex
 {
@@ -205,6 +205,83 @@ struct rdg_edge
 
 #define RDGE_TYPE(E)        ((struct rdg_edge *) ((E)->data))->type
 
+/* Kind of distributed loop.  */
+enum partition_kind {
+    PKIND_NORMAL,
+    /* Partial memset stands for a paritition can be distributed into a loop
+       of memset calls, rather than a single memset call.  It's handled just
+       like a normal parition, i.e, distributed as separate loop, no memset
+       call is generated.
+
+       Note: This is a hacking fix trying to distribute ZERO-ing stmt in a
+       loop nest as deep as possible.  As a result, parloop achieves better
+       parallelization by parallelizing deeper loop nest.  This hack should
+       be unnecessary and removed once distributed memset can be understood
+       and analyzed in data reference analysis.  See PR82604 for more.  */
+    PKIND_PARTIAL_MEMSET,
+    PKIND_MEMSET, PKIND_MEMCPY, PKIND_MEMMOVE
+};
+
+/* Type of distributed loop.  */
+enum partition_type {
+    /* The distributed loop can be executed parallelly.  */
+    PTYPE_PARALLEL = 0,
+    /* The distributed loop has to be executed sequentially.  */
+    PTYPE_SEQUENTIAL
+};
+
+/* Builtin info for loop distribution.  */
+struct builtin_info
+{
+  /* data-references a kind != PKIND_NORMAL partition is about.  */
+  data_reference_p dst_dr;
+  data_reference_p src_dr;
+  /* Base address and size of memory objects operated by the builtin.  Note
+     both dest and source memory objects must have the same size.  */
+  tree dst_base;
+  tree src_base;
+  tree size;
+  /* Base and offset part of dst_base after stripping constant offset.  This
+     is only used in memset builtin distribution for now.  */
+  tree dst_base_base;
+  unsigned HOST_WIDE_INT dst_base_offset;
+};
+
+/* Partition for loop distribution.  */
+struct partition
+{
+  /* Statements of the partition.  */
+  bitmap stmts;
+  /* True if the partition defines variable which is used outside of loop.  */
+  bool reduction_p;
+  location_t loc;
+  enum partition_kind kind;
+  enum partition_type type;
+  /* Data references in the partition.  */
+  bitmap datarefs;
+  /* Information of builtin parition.  */
+  struct builtin_info *builtin;
+};
+
+/* Partitions are fused because of different reasons.  */
+enum fuse_type
+{
+  FUSE_NON_BUILTIN = 0,
+  FUSE_REDUCTION = 1,
+  FUSE_SHARE_REF = 2,
+  FUSE_SAME_SCC = 3,
+  FUSE_FINALIZE = 4
+};
+
+/* Description on different fusing reason.  */
+static const char *fuse_message[] = {
+  "they are non-builtins",
+  "they have reductions",
+  "they have shared memory refs",
+  "they are in the same dependence scc",
+  "there is no point to distribute loop"};
+
+
 /* Dump vertex I in RDG to FILE.  */
 
 static void
@@ -425,11 +502,207 @@ create_rdg_cd_edges (struct graph *rdg, control_dependences *cd, loop_p loop)
     }
 }
 
-/* Build the vertices of the reduced dependence graph RDG.  Return false
-   if that failed.  */
 
-static bool
-create_rdg_vertices (struct graph *rdg, vec<gimple *> stmts, loop_p loop)
+class loop_distribution
+{
+  private:
+  /* The loop (nest) to be distributed.  */
+  vec<loop_p> loop_nest;
+
+  /* Vector of data references in the loop to be distributed.  */
+  vec<data_reference_p> datarefs_vec;
+
+  /* If there is nonaddressable data reference in above vector.  */
+  bool has_nonaddressable_dataref_p;
+
+  /* Store index of data reference in aux field.  */
+
+  /* Hash table for data dependence relation in the loop to be distributed.  */
+  hash_table<ddr_hasher> *ddrs_table;
+
+  /* Array mapping basic block's index to its topological order.  */
+  int *bb_top_order_index;
+  /* And size of the array.  */
+  int bb_top_order_index_size;
+
+  /* Build the vertices of the reduced dependence graph RDG.  Return false
+     if that failed.  */
+  bool create_rdg_vertices (struct graph *rdg, const vec<gimple *> &stmts,
+                           loop_p loop);
+
+  /* Initialize STMTS with all the statements of LOOP.  We use topological
+     order to discover all statements.  The order is important because
+     generate_loops_for_partition is using the same traversal for identifying
+     statements in loop copies.  */
+  void stmts_from_loop (class loop *loop, vec<gimple *> *stmts);
+
+
+  /* Build the Reduced Dependence Graph (RDG) with one vertex per statement of
+     LOOP, and one edge per flow dependence or control dependence from control
+     dependence CD.  During visiting each statement, data references are also
+     collected and recorded in global data DATAREFS_VEC.  */
+  struct graph * build_rdg (class loop *loop, control_dependences *cd);
+
+/* Merge PARTITION into the partition DEST.  RDG is the reduced dependence
+   graph and we update type for result partition if it is non-NULL.  */
+  void partition_merge_into (struct graph *rdg,
+                            partition *dest, partition *partition,
+                            enum fuse_type ft);
+
+
+  /* Return data dependence relation for data references A and B.  The two
+     data references must be in lexicographic order wrto reduced dependence
+     graph RDG.  We firstly try to find ddr from global ddr hash table.  If
+     it doesn't exist, compute the ddr and cache it.  */
+  data_dependence_relation * get_data_dependence (struct graph *rdg,
+                                                 data_reference_p a,
+                                                 data_reference_p b);
+
+
+  /* In reduced dependence graph RDG for loop distribution, return true if
+     dependence between references DR1 and DR2 leads to a dependence cycle
+     and such dependence cycle can't be resolved by runtime alias check.  */
+  bool data_dep_in_cycle_p (struct graph *rdg, data_reference_p dr1,
+                           data_reference_p dr2);
+
+
+  /* Given reduced dependence graph RDG, PARTITION1 and PARTITION2, update
+     PARTITION1's type after merging PARTITION2 into PARTITION1.  */
+  void update_type_for_merge (struct graph *rdg,
+                             partition *partition1, partition *partition2);
+
+
+  /* Returns a partition with all the statements needed for computing
+     the vertex V of the RDG, also including the loop exit conditions.  */
+  partition *build_rdg_partition_for_vertex (struct graph *rdg, int v);
+
+  /* Given data references DST_DR and SRC_DR in loop nest LOOP and RDG, classify
+     if it forms builtin memcpy or memmove call.  */
+  void classify_builtin_ldst (loop_p loop, struct graph *rdg, partition *partition,
+                             data_reference_p dst_dr, data_reference_p src_dr);
+
+  /* Classifies the builtin kind we can generate for PARTITION of RDG and LOOP.
+     For the moment we detect memset, memcpy and memmove patterns.  Bitmap
+     STMT_IN_ALL_PARTITIONS contains statements belonging to all partitions.
+     Returns true if there is a reduction in all partitions and we
+     possibly did not mark PARTITION as having one for this reason.  */
+
+  bool
+  classify_partition (loop_p loop,
+                     struct graph *rdg, partition *partition,
+                     bitmap stmt_in_all_partitions);
+
+
+  /* Returns true when PARTITION1 and PARTITION2 access the same memory
+     object in RDG.  */
+  bool share_memory_accesses (struct graph *rdg,
+                             partition *partition1, partition *partition2);
+
+  /* For each seed statement in STARTING_STMTS, this function builds
+     partition for it by adding depended statements according to RDG.
+     All partitions are recorded in PARTITIONS.  */
+  void rdg_build_partitions (struct graph *rdg,
+                            vec<gimple *> starting_stmts,
+                            vec<partition *> *partitions);
+
+  /* Compute partition dependence created by the data references in DRS1
+     and DRS2, modify and return DIR according to that.  IF ALIAS_DDR is
+     not NULL, we record dependence introduced by possible alias between
+     two data references in ALIAS_DDRS; otherwise, we simply ignore such
+     dependence as if it doesn't exist at all.  */
+  int pg_add_dependence_edges (struct graph *rdg, int dir, bitmap drs1,
+                              bitmap drs2, vec<ddr_p> *alias_ddrs);
+
+
+  /* Build and return partition dependence graph for PARTITIONS.  RDG is
+     reduced dependence graph for the loop to be distributed.  If IGNORE_ALIAS_P
+     is true, data dependence caused by possible alias between references
+     is ignored, as if it doesn't exist at all; otherwise all depdendences
+     are considered.  */
+  struct graph *build_partition_graph (struct graph *rdg,
+                                      vec<struct partition *> *partitions,
+                                      bool ignore_alias_p);
+
+  /* Given reduced dependence graph RDG merge strong connected components
+     of PARTITIONS.  If IGNORE_ALIAS_P is true, data dependence caused by
+     possible alias between references is ignored, as if it doesn't exist
+     at all; otherwise all depdendences are considered.  */
+  void merge_dep_scc_partitions (struct graph *rdg, vec<struct partition *>
+                                *partitions, bool ignore_alias_p);
+
+/* This is the main function breaking strong conected components in
+   PARTITIONS giving reduced depdendence graph RDG.  Store data dependence
+   relations for runtime alias check in ALIAS_DDRS.  */
+  void break_alias_scc_partitions (struct graph *rdg, vec<struct partition *>
+                                  *partitions, vec<ddr_p> *alias_ddrs);
+
+
+  /* Fuse PARTITIONS of LOOP if necessary before finalizing distribution.
+     ALIAS_DDRS contains ddrs which need runtime alias check.  */
+  void finalize_partitions (class loop *loop, vec<struct partition *>
+                           *partitions, vec<ddr_p> *alias_ddrs);
+
+  /* Distributes the code from LOOP in such a way that producer statements
+     are placed before consumer statements.  Tries to separate only the
+     statements from STMTS into separate loops.  Returns the number of
+     distributed loops.  Set NB_CALLS to number of generated builtin calls.
+     Set *DESTROY_P to whether LOOP needs to be destroyed.  */
+  int distribute_loop (class loop *loop, const vec<gimple *> &stmts,
+                      control_dependences *cd, int *nb_calls, bool *destroy_p,
+                      bool only_patterns_p);
+
+  /* Compute topological order for basic blocks.  Topological order is
+     needed because data dependence is computed for data references in
+     lexicographical order.  */
+  void bb_top_order_init (void);
+
+  void bb_top_order_destroy (void);
+
+  public:
+
+  /* Getter for bb_top_order.  */
+
+  inline int get_bb_top_order_index_size (void)
+    {
+      return bb_top_order_index_size;
+    }
+
+  inline int get_bb_top_order_index (int i)
+    {
+      return bb_top_order_index[i];
+    }
+
+  unsigned int execute (function *fun);
+};
+
+
+/* If X has a smaller topological sort number than Y, returns -1;
+   if greater, returns 1.  */
+static int
+bb_top_order_cmp_r (const void *x, const void *y, void *loop)
+{
+  loop_distribution *_loop =
+    (loop_distribution *) loop;
+
+  basic_block bb1 = *(const basic_block *) x;
+  basic_block bb2 = *(const basic_block *) y;
+
+  int bb_top_order_index_size = _loop->get_bb_top_order_index_size ();
+
+  gcc_assert (bb1->index < bb_top_order_index_size
+             && bb2->index < bb_top_order_index_size);
+  gcc_assert (bb1 == bb2
+             || _loop->get_bb_top_order_index(bb1->index)
+                != _loop->get_bb_top_order_index(bb2->index));
+
+  return (_loop->get_bb_top_order_index(bb1->index) - 
+         _loop->get_bb_top_order_index(bb2->index));
+}
+
+bool
+loop_distribution::create_rdg_vertices (struct graph *rdg,
+                                       const vec<gimple *> &stmts,
+                                       loop_p loop)
 {
   int i;
   gimple *stmt;
@@ -460,44 +733,17 @@ create_rdg_vertices (struct graph *rdg, vec<gimple *> stmts, loop_p loop)
          else
            RDGV_HAS_MEM_WRITE (v) = true;
          RDGV_DATAREFS (v).safe_push (dr);
+         has_nonaddressable_dataref_p |= may_be_nonaddressable_p (dr->ref);
        }
     }
   return true;
 }
 
-/* Array mapping basic block's index to its topological order.  */
-static int *bb_top_order_index;
-/* And size of the array.  */
-static int bb_top_order_index_size;
-
-/* If X has a smaller topological sort number than Y, returns -1;
-   if greater, returns 1.  */
-
-static int
-bb_top_order_cmp (const void *x, const void *y)
-{
-  basic_block bb1 = *(const basic_block *) x;
-  basic_block bb2 = *(const basic_block *) y;
-
-  gcc_assert (bb1->index < bb_top_order_index_size
-             && bb2->index < bb_top_order_index_size);
-  gcc_assert (bb1 == bb2
-             || bb_top_order_index[bb1->index]
-                != bb_top_order_index[bb2->index]);
-
-  return (bb_top_order_index[bb1->index] - bb_top_order_index[bb2->index]);
-}
-
-/* Initialize STMTS with all the statements of LOOP.  We use topological
-   order to discover all statements.  The order is important because
-   generate_loops_for_partition is using the same traversal for identifying
-   statements in loop copies.  */
-
-static void
-stmts_from_loop (struct loop *loop, vec<gimple *> *stmts)
+void
+loop_distribution::stmts_from_loop (class loop *loop, vec<gimple *> *stmts)
 {
   unsigned int i;
-  basic_block *bbs = get_loop_body_in_custom_order (loop, bb_top_order_cmp);
+  basic_block *bbs = get_loop_body_in_custom_order (loop, this, bb_top_order_cmp_r);
 
   for (i = 0; i < loop->num_nodes; i++)
     {
@@ -546,13 +792,8 @@ free_rdg (struct graph *rdg)
   free_graph (rdg);
 }
 
-/* Build the Reduced Dependence Graph (RDG) with one vertex per statement of
-   LOOP, and one edge per flow dependence or control dependence from control
-   dependence CD.  During visiting each statement, data references are also
-   collected and recorded in global data DATAREFS_VEC.  */
-
-static struct graph *
-build_rdg (struct loop *loop, control_dependences *cd)
+struct graph *
+loop_distribution::build_rdg (class loop *loop, control_dependences *cd)
 {
   struct graph *rdg;
 
@@ -575,41 +816,6 @@ build_rdg (struct loop *loop, control_dependences *cd)
 }
 
 
-/* Kind of distributed loop.  */
-enum partition_kind {
-    PKIND_NORMAL, PKIND_MEMSET, PKIND_MEMCPY, PKIND_MEMMOVE
-};
-
-/* Type of distributed loop.  */
-enum partition_type {
-    /* The distributed loop can be executed parallelly.  */
-    PTYPE_PARALLEL = 0,
-    /* The distributed loop has to be executed sequentially.  */
-    PTYPE_SEQUENTIAL
-};
-
-/* Partition for loop distribution.  */
-struct partition
-{
-  /* Statements of the partition.  */
-  bitmap stmts;
-  /* True if the partition defines variable which is used outside of loop.  */
-  bool reduction_p;
-  /* For builtin partition, true if it executes one iteration more than
-     number of loop (latch) iterations.  */
-  bool plus_one;
-  enum partition_kind kind;
-  enum partition_type type;
-  /* data-references a kind != PKIND_NORMAL partition is about.  */
-  data_reference_p main_dr;
-  data_reference_p secondary_dr;
-  /* Number of loop (latch) iterations.  */
-  tree niter;
-  /* Data references in the partition.  */
-  bitmap datarefs;
-};
-
-
 /* Allocate and initialize a partition from BITMAP.  */
 
 static partition *
@@ -618,7 +824,9 @@ partition_alloc (void)
   partition *partition = XCNEW (struct partition);
   partition->stmts = BITMAP_ALLOC (NULL);
   partition->reduction_p = false;
+  partition->loc = UNKNOWN_LOCATION;
   partition->kind = PKIND_NORMAL;
+  partition->type = PTYPE_PARALLEL;
   partition->datarefs = BITMAP_ALLOC (NULL);
   return partition;
 }
@@ -630,6 +838,9 @@ partition_free (partition *partition)
 {
   BITMAP_FREE (partition->stmts);
   BITMAP_FREE (partition->datarefs);
+  if (partition->builtin)
+    free (partition->builtin);
+
   free (partition);
 }
 
@@ -638,7 +849,7 @@ partition_free (partition *partition)
 static bool
 partition_builtin_p (partition *partition)
 {
-  return partition->kind != PKIND_NORMAL;
+  return partition->kind > PKIND_PARTIAL_MEMSET;
 }
 
 /* Returns true if the partition contains a reduction.  */
@@ -649,33 +860,9 @@ partition_reduction_p (partition *partition)
   return partition->reduction_p;
 }
 
-/* Partitions are fused because of different reasons.  */
-enum fuse_type
-{
-  FUSE_NON_BUILTIN = 0,
-  FUSE_REDUCTION = 1,
-  FUSE_SHARE_REF = 2,
-  FUSE_SAME_SCC = 3,
-  FUSE_FINALIZE = 4
-};
-
-/* Description on different fusing reason.  */
-static const char *fuse_message[] = {
-  "they are non-builtins",
-  "they have reductions",
-  "they have shared memory refs",
-  "they are in the same dependence scc",
-  "there is no point to distribute loop"};
-
-static void
-update_type_for_merge (struct graph *, partition *, partition *);
-
-/* Merge PARTITION into the partition DEST.  RDG is the reduced dependence
-   graph and we update type for result partition if it is non-NULL.  */
-
-static void
-partition_merge_into (struct graph *rdg, partition *dest,
-                     partition *partition, enum fuse_type ft)
+void
+loop_distribution::partition_merge_into (struct graph *rdg,
+                     partition *dest, partition *partition, enum fuse_type ft)
 {
   if (dump_file && (dump_flags & TDF_DETAILS))
     {
@@ -714,9 +901,11 @@ ssa_name_has_uses_outside_loop_p (tree def, loop_p loop)
 
   FOR_EACH_IMM_USE_FAST (use_p, imm_iter, def)
     {
-      gimple *use_stmt = USE_STMT (use_p);
-      if (!is_gimple_debug (use_stmt)
-         && loop != loop_containing_stmt (use_stmt))
+      if (is_gimple_debug (USE_STMT (use_p)))
+       continue;
+
+      basic_block use_bb = gimple_bb (USE_STMT (use_p));
+      if (!flow_bb_inside_loop_p (loop, use_bb))
        return true;
     }
 
@@ -744,10 +933,10 @@ stmt_has_scalar_dependences_outside_loop (loop_p loop, gimple *stmt)
 
 /* Return a copy of LOOP placed before LOOP.  */
 
-static struct loop *
-copy_loop_before (struct loop *loop)
+static class loop *
+copy_loop_before (class loop *loop)
 {
-  struct loop *res;
+  class loop *res;
   edge preheader = loop_preheader_edge (loop);
 
   initialize_original_copy_tables ();
@@ -762,7 +951,7 @@ copy_loop_before (struct loop *loop)
 /* Creates an empty basic block after LOOP.  */
 
 static void
-create_bb_after_loop (struct loop *loop)
+create_bb_after_loop (class loop *loop)
 {
   edge exit = single_exit (loop);
 
@@ -779,7 +968,7 @@ create_bb_after_loop (struct loop *loop)
    basic blocks of a loop are taken in dom order.  */
 
 static void
-generate_loops_for_partition (struct loop *loop, partition *partition,
+generate_loops_for_partition (class loop *loop, partition *partition,
                              bool copy_p)
 {
   unsigned i;
@@ -803,7 +992,7 @@ generate_loops_for_partition (struct loop *loop, partition *partition,
   /* Remove stmts not in the PARTITION bitmap.  */
   bbs = get_loop_body_in_dom_order (loop);
 
-  if (MAY_HAVE_DEBUG_STMTS)
+  if (MAY_HAVE_DEBUG_BIND_STMTS)
     for (i = 0; i < loop->num_nodes; i++)
       {
        basic_block bb = bbs[i];
@@ -830,6 +1019,10 @@ generate_loops_for_partition (struct loop *loop, partition *partition,
   for (i = 0; i < loop->num_nodes; i++)
     {
       basic_block bb = bbs[i];
+      edge inner_exit = NULL;
+
+      if (loop != bb->loop_father)
+       inner_exit = single_exit (bb->loop_father);
 
       for (gphi_iterator bsi = gsi_start_phis (bb); !gsi_end_p (bsi);)
        {
@@ -848,11 +1041,17 @@ generate_loops_for_partition (struct loop *loop, partition *partition,
              && !is_gimple_debug (stmt)
              && !bitmap_bit_p (partition->stmts, gimple_uid (stmt)))
            {
-             /* Choose an arbitrary path through the empty CFG part
-                that this unnecessary control stmt controls.  */
+             /* In distribution of loop nest, if bb is inner loop's exit_bb,
+                we choose its exit edge/path in order to avoid generating
+                infinite loop.  For all other cases, we choose an arbitrary
+                path through the empty CFG part that this unnecessary
+                control stmt controls.  */
              if (gcond *cond_stmt = dyn_cast <gcond *> (stmt))
                {
-                 gimple_cond_make_false (cond_stmt);
+                 if (inner_exit && inner_exit->flags & EDGE_TRUE_VALUE)
+                   gimple_cond_make_true (cond_stmt);
+                 else
+                   gimple_cond_make_false (cond_stmt);
                  update_stmt (stmt);
                }
              else if (gimple_code (stmt) == GIMPLE_SWITCH)
@@ -877,43 +1076,6 @@ generate_loops_for_partition (struct loop *loop, partition *partition,
   free (bbs);
 }
 
-/* Build the size argument for a memory operation call.  */
-
-static tree
-build_size_arg_loc (location_t loc, data_reference_p dr, tree nb_iter,
-                   bool plus_one)
-{
-  tree size = fold_convert_loc (loc, sizetype, nb_iter);
-  if (plus_one)
-    size = size_binop (PLUS_EXPR, size, size_one_node);
-  size = fold_build2_loc (loc, MULT_EXPR, sizetype, size,
-                         TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr))));
-  size = fold_convert_loc (loc, size_type_node, size);
-  return size;
-}
-
-/* Build an address argument for a memory operation call.  */
-
-static tree
-build_addr_arg_loc (location_t loc, data_reference_p dr, tree nb_bytes)
-{
-  tree addr_base;
-
-  addr_base = size_binop_loc (loc, PLUS_EXPR, DR_OFFSET (dr), DR_INIT (dr));
-  addr_base = fold_convert_loc (loc, sizetype, addr_base);
-
-  /* Test for a negative stride, iterating over every element.  */
-  if (tree_int_cst_sgn (DR_STEP (dr)) == -1)
-    {
-      addr_base = size_binop_loc (loc, MINUS_EXPR, addr_base,
-                                 fold_convert_loc (loc, sizetype, nb_bytes));
-      addr_base = size_binop_loc (loc, PLUS_EXPR, addr_base,
-                                 TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr))));
-    }
-
-  return fold_build_pointer_plus_loc (loc, DR_BASE_ADDRESS (dr), addr_base);
-}
-
 /* If VAL memory representation contains the same value in all bytes,
    return that value, otherwise return -1.
    E.g. for 0x24242424 return 0x24, for IEEE double
@@ -948,13 +1110,16 @@ const_with_all_bytes_same (tree val)
            return 0;
          break;
        case VECTOR_CST:
-         unsigned int j;
-         for (j = 0; j < VECTOR_CST_NELTS (val); ++j)
-           if (const_with_all_bytes_same (VECTOR_CST_ELT (val, j)))
-             break;
-         if (j == VECTOR_CST_NELTS (val))
-           return 0;
-         break;
+         {
+           unsigned int count = vector_cst_encoded_nelts (val);
+           unsigned int j;
+           for (j = 0; j < count; ++j)
+             if (const_with_all_bytes_same (VECTOR_CST_ENCODED_ELT (val, j)))
+               break;
+           if (j == count)
+             return 0;
+           break;
+         }
        default:
          break;
        }
@@ -975,30 +1140,26 @@ const_with_all_bytes_same (tree val)
 /* Generate a call to memset for PARTITION in LOOP.  */
 
 static void
-generate_memset_builtin (struct loop *loop, partition *partition)
+generate_memset_builtin (class loop *loop, partition *partition)
 {
   gimple_stmt_iterator gsi;
-  gimple *stmt, *fn_call;
   tree mem, fn, nb_bytes;
-  location_t loc;
   tree val;
-
-  stmt = DR_STMT (partition->main_dr);
-  loc = gimple_location (stmt);
+  struct builtin_info *builtin = partition->builtin;
+  gimple *fn_call;
 
   /* The new statements will be placed before LOOP.  */
   gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
 
-  nb_bytes = build_size_arg_loc (loc, partition->main_dr, partition->niter,
-                                partition->plus_one);
+  nb_bytes = rewrite_to_non_trapping_overflow (builtin->size);
   nb_bytes = force_gimple_operand_gsi (&gsi, nb_bytes, true, NULL_TREE,
                                       false, GSI_CONTINUE_LINKING);
-  mem = build_addr_arg_loc (loc, partition->main_dr, nb_bytes);
+  mem = rewrite_to_non_trapping_overflow (builtin->dst_base);
   mem = force_gimple_operand_gsi (&gsi, mem, true, NULL_TREE,
                                  false, GSI_CONTINUE_LINKING);
 
   /* This exactly matches the pattern recognition in classify_partition.  */
-  val = gimple_assign_rhs1 (stmt);
+  val = gimple_assign_rhs1 (DR_STMT (builtin->dst_dr));
   /* Handle constants like 0x15151515 and similarly
      floating point constants etc. where all bytes are the same.  */
   int bytev = const_with_all_bytes_same (val);
@@ -1016,7 +1177,9 @@ generate_memset_builtin (struct loop *loop, partition *partition)
 
   fn = build_fold_addr_expr (builtin_decl_implicit (BUILT_IN_MEMSET));
   fn_call = gimple_build_call (fn, 3, mem, val, nb_bytes);
+  gimple_set_location (fn_call, partition->loc);
   gsi_insert_after (&gsi, fn_call, GSI_CONTINUE_LINKING);
+  fold_stmt (&gsi);
 
   if (dump_file && (dump_flags & TDF_DETAILS))
     {
@@ -1031,31 +1194,39 @@ generate_memset_builtin (struct loop *loop, partition *partition)
 /* Generate a call to memcpy for PARTITION in LOOP.  */
 
 static void
-generate_memcpy_builtin (struct loop *loop, partition *partition)
+generate_memcpy_builtin (class loop *loop, partition *partition)
 {
   gimple_stmt_iterator gsi;
-  gimple *stmt, *fn_call;
+  gimple *fn_call;
   tree dest, src, fn, nb_bytes;
-  location_t loc;
   enum built_in_function kind;
-
-  stmt = DR_STMT (partition->main_dr);
-  loc = gimple_location (stmt);
+  struct builtin_info *builtin = partition->builtin;
 
   /* The new statements will be placed before LOOP.  */
   gsi = gsi_last_bb (loop_preheader_edge (loop)->src);
 
-  nb_bytes = build_size_arg_loc (loc, partition->main_dr, partition->niter,
-                                partition->plus_one);
+  nb_bytes = rewrite_to_non_trapping_overflow (builtin->size);
   nb_bytes = force_gimple_operand_gsi (&gsi, nb_bytes, true, NULL_TREE,
                                       false, GSI_CONTINUE_LINKING);
-  dest = build_addr_arg_loc (loc, partition->main_dr, nb_bytes);
-  src = build_addr_arg_loc (loc, partition->secondary_dr, nb_bytes);
+  dest = rewrite_to_non_trapping_overflow (builtin->dst_base);
+  src = rewrite_to_non_trapping_overflow (builtin->src_base);
   if (partition->kind == PKIND_MEMCPY
       || ! ptr_derefs_may_alias_p (dest, src))
     kind = BUILT_IN_MEMCPY;
   else
     kind = BUILT_IN_MEMMOVE;
+  /* Try harder if we're copying a constant size.  */
+  if (kind == BUILT_IN_MEMMOVE && poly_int_tree_p (nb_bytes))
+    {
+      aff_tree asrc, adest;
+      tree_to_aff_combination (src, ptr_type_node, &asrc);
+      tree_to_aff_combination (dest, ptr_type_node, &adest);
+      aff_combination_scale (&adest, -1);
+      aff_combination_add (&asrc, &adest);
+      if (aff_comb_cannot_overlap_p (&asrc, wi::to_poly_widest (nb_bytes),
+                                    wi::to_poly_widest (nb_bytes)))
+       kind = BUILT_IN_MEMCPY;
+    }
 
   dest = force_gimple_operand_gsi (&gsi, dest, true, NULL_TREE,
                                   false, GSI_CONTINUE_LINKING);
@@ -1063,7 +1234,9 @@ generate_memcpy_builtin (struct loop *loop, partition *partition)
                                  false, GSI_CONTINUE_LINKING);
   fn = build_fold_addr_expr (builtin_decl_implicit (kind));
   fn_call = gimple_build_call (fn, 3, dest, src, nb_bytes);
+  gimple_set_location (fn_call, partition->loc);
   gsi_insert_after (&gsi, fn_call, GSI_CONTINUE_LINKING);
+  fold_stmt (&gsi);
 
   if (dump_file && (dump_flags & TDF_DETAILS))
     {
@@ -1077,7 +1250,7 @@ generate_memcpy_builtin (struct loop *loop, partition *partition)
 /* Remove and destroy the loop LOOP.  */
 
 static void
-destroy_loop (struct loop *loop)
+destroy_loop (class loop *loop)
 {
   unsigned nbbs = loop->num_nodes;
   edge exit = single_exit (loop);
@@ -1087,21 +1260,15 @@ destroy_loop (struct loop *loop)
 
   bbs = get_loop_body_in_dom_order (loop);
 
-  redirect_edge_pred (exit, src);
-  exit->flags &= ~(EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
-  exit->flags |= EDGE_FALLTHRU;
-  cancel_loop_tree (loop);
-  rescan_loop_exit (exit, false, true);
-
-  i = nbbs;
-  do
+  gimple_stmt_iterator dst_gsi = gsi_after_labels (exit->dest);
+  bool safe_p = single_pred_p (exit->dest);
+  for (unsigned i = 0; i < nbbs; ++i)
     {
       /* We have made sure to not leave any dangling uses of SSA
          names defined in the loop.  With the exception of virtuals.
         Make sure we replace all uses of virtual defs that will remain
         outside of the loop with the bare symbol as delete_basic_block
         will release them.  */
-      --i;
       for (gphi_iterator gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi);
           gsi_next (&gsi))
        {
@@ -1109,14 +1276,44 @@ destroy_loop (struct loop *loop)
          if (virtual_operand_p (gimple_phi_result (phi)))
            mark_virtual_phi_result_for_renaming (phi);
        }
-      for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]); !gsi_end_p (gsi);
-          gsi_next (&gsi))
+      for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]); !gsi_end_p (gsi);)
        {
          gimple *stmt = gsi_stmt (gsi);
          tree vdef = gimple_vdef (stmt);
          if (vdef && TREE_CODE (vdef) == SSA_NAME)
            mark_virtual_operand_for_renaming (vdef);
+         /* Also move and eventually reset debug stmts.  We can leave
+            constant values in place in case the stmt dominates the exit.
+            ???  Non-constant values from the last iteration can be
+            replaced with final values if we can compute them.  */
+         if (gimple_debug_bind_p (stmt))
+           {
+             tree val = gimple_debug_bind_get_value (stmt);
+             gsi_move_before (&gsi, &dst_gsi);
+             if (val
+                 && (!safe_p
+                     || !is_gimple_min_invariant (val)
+                     || !dominated_by_p (CDI_DOMINATORS, exit->src, bbs[i])))
+               {
+                 gimple_debug_bind_reset_value (stmt);
+                 update_stmt (stmt);
+               }
+           }
+         else
+           gsi_next (&gsi);
        }
+    }
+
+  redirect_edge_pred (exit, src);
+  exit->flags &= ~(EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
+  exit->flags |= EDGE_FALLTHRU;
+  cancel_loop_tree (loop);
+  rescan_loop_exit (exit, false, true);
+
+  i = nbbs;
+  do
+    {
+      --i;
       delete_basic_block (bbs[i]);
     }
   while (i != 0);
@@ -1130,12 +1327,13 @@ destroy_loop (struct loop *loop)
 /* Generates code for PARTITION.  Return whether LOOP needs to be destroyed.  */
 
 static bool 
-generate_code_for_partition (struct loop *loop,
+generate_code_for_partition (class loop *loop,
                             partition *partition, bool copy_p)
 {
   switch (partition->kind)
     {
     case PKIND_NORMAL:
+    case PKIND_PARTIAL_MEMSET:
       /* Reductions all have to be in the last partition.  */
       gcc_assert (!partition_reduction_p (partition)
                  || !copy_p);
@@ -1162,13 +1360,9 @@ generate_code_for_partition (struct loop *loop,
   return false;
 }
 
-/* Return data dependence relation for data references A and B.  The two
-   data references must be in lexicographic order wrto reduced dependence
-   graph RDG.  We firstly try to find ddr from global ddr hash table.  If
-   it doesn't exist, compute the ddr and cache it.  */
-
-static data_dependence_relation *
-get_data_dependence (struct graph *rdg, data_reference_p a, data_reference_p b)
+data_dependence_relation *
+loop_distribution::get_data_dependence (struct graph *rdg, data_reference_p a,
+                                       data_reference_p b)
 {
   struct data_dependence_relation ent, **slot;
   struct data_dependence_relation *ddr;
@@ -1189,13 +1383,10 @@ get_data_dependence (struct graph *rdg, data_reference_p a, data_reference_p b)
   return *slot;
 }
 
-/* In reduced dependence graph RDG for loop distribution, return true if
-   dependence between references DR1 and DR2 leads to a dependence cycle
-   and such dependence cycle can't be resolved by runtime alias check.  */
-
-static bool
-data_dep_in_cycle_p (struct graph *rdg,
-                    data_reference_p dr1, data_reference_p dr2)
+bool
+loop_distribution::data_dep_in_cycle_p (struct graph *rdg,
+                                       data_reference_p dr1,
+                                       data_reference_p dr2)
 {
   struct data_dependence_relation *ddr;
 
@@ -1225,12 +1416,10 @@ data_dep_in_cycle_p (struct graph *rdg,
   return true;
 }
 
-/* Given reduced dependence graph RDG, PARTITION1 and PARTITION2, update
-   PARTITION1's type after merging PARTITION2 into PARTITION1.  */
-
-static void
-update_type_for_merge (struct graph *rdg,
-                      partition *partition1, partition *partition2)
+void
+loop_distribution::update_type_for_merge (struct graph *rdg,
+                                          partition *partition1,
+                                          partition *partition2)
 {
   unsigned i, j;
   bitmap_iterator bi, bj;
@@ -1258,11 +1447,8 @@ update_type_for_merge (struct graph *rdg,
     }
 }
 
-/* Returns a partition with all the statements needed for computing
-   the vertex V of the RDG, also including the loop exit conditions.  */
-
-static partition *
-build_rdg_partition_for_vertex (struct graph *rdg, int v)
+partition *
+loop_distribution::build_rdg_partition_for_vertex (struct graph *rdg, int v)
 {
   partition *partition = partition_alloc ();
   auto_vec<int, 3> nodes;
@@ -1301,69 +1487,22 @@ build_rdg_partition_for_vertex (struct graph *rdg, int v)
   return partition;
 }
 
-/* Classifies the builtin kind we can generate for PARTITION of RDG and LOOP.
-   For the moment we detect memset, memcpy and memmove patterns.  Bitmap
-   STMT_IN_ALL_PARTITIONS contains statements belonging to all partitions.  */
+/* Given PARTITION of LOOP and RDG, record single load/store data references
+   for builtin partition in SRC_DR/DST_DR, return false if there is no such
+   data references.  */
 
-static void
-classify_partition (loop_p loop, struct graph *rdg, partition *partition,
-                   bitmap stmt_in_all_partitions)
+static bool
+find_single_drs (class loop *loop, struct graph *rdg, partition *partition,
+                data_reference_p *dst_dr, data_reference_p *src_dr)
 {
-  bitmap_iterator bi;
   unsigned i;
-  tree nb_iter;
-  data_reference_p single_load, single_store;
-  bool volatiles_p = false, plus_one = false, has_reduction = false;
-
-  partition->kind = PKIND_NORMAL;
-  partition->main_dr = NULL;
-  partition->secondary_dr = NULL;
-  partition->niter = NULL_TREE;
-  partition->plus_one = false;
-
-  EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, bi)
-    {
-      gimple *stmt = RDG_STMT (rdg, i);
-
-      if (gimple_has_volatile_ops (stmt))
-       volatiles_p = true;
-
-      /* If the stmt is not included by all partitions and there is uses
-        outside of the loop, then mark the partition as reduction.  */
-      if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
-       {
-         /* Due to limitation in the transform phase we have to fuse all
-            reduction partitions.  As a result, this could cancel valid
-            loop distribution especially for loop that induction variable
-            is used outside of loop.  To workaround this issue, we skip
-            marking partition as reudction if the reduction stmt belongs
-            to all partitions.  In such case, reduction will be computed
-            correctly no matter how partitions are fused/distributed.  */
-         if (!bitmap_bit_p (stmt_in_all_partitions, i))
-           {
-             partition->reduction_p = true;
-             return;
-           }
-         has_reduction = true;
-       }
-    }
-
-  /* Perform general partition disqualification for builtins.  */
-  if (volatiles_p
-      /* Simple workaround to prevent classifying the partition as builtin
-        if it contains any use outside of loop.  */
-      || has_reduction
-      || !flag_tree_loop_distribute_patterns)
-    return;
+  data_reference_p single_ld = NULL, single_st = NULL;
+  bitmap_iterator bi;
 
-  /* Detect memset and memcpy.  */
-  single_load = NULL;
-  single_store = NULL;
   EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, bi)
     {
       gimple *stmt = RDG_STMT (rdg, i);
       data_reference_p dr;
-      unsigned j;
 
       if (gimple_code (stmt) == GIMPLE_PHI)
        continue;
@@ -1374,114 +1513,360 @@ classify_partition (loop_p loop, struct graph *rdg, partition *partition,
 
       /* Otherwise just regular loads/stores.  */
       if (!gimple_assign_single_p (stmt))
-       return;
+       return false;
 
       /* But exactly one store and/or load.  */
-      for (j = 0; RDG_DATAREFS (rdg, i).iterate (j, &dr); ++j)
+      for (unsigned j = 0; RDG_DATAREFS (rdg, i).iterate (j, &dr); ++j)
        {
          tree type = TREE_TYPE (DR_REF (dr));
 
          /* The memset, memcpy and memmove library calls are only
             able to deal with generic address space.  */
          if (!ADDR_SPACE_GENERIC_P (TYPE_ADDR_SPACE (type)))
-           return;
+           return false;
 
          if (DR_IS_READ (dr))
            {
-             if (single_load != NULL)
-               return;
-             single_load = dr;
+             if (single_ld != NULL)
+               return false;
+             single_ld = dr;
            }
          else
            {
-             if (single_store != NULL)
-               return;
-             single_store = dr;
+             if (single_st != NULL)
+               return false;
+             single_st = dr;
            }
        }
     }
 
-  if (!single_store)
-    return;
+  if (!single_st)
+    return false;
+
+  /* Bail out if this is a bitfield memory reference.  */
+  if (TREE_CODE (DR_REF (single_st)) == COMPONENT_REF
+      && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (single_st), 1)))
+    return false;
+
+  /* Data reference must be executed exactly once per iteration of each
+     loop in the loop nest.  We only need to check dominance information
+     against the outermost one in a perfect loop nest because a bb can't
+     dominate outermost loop's latch without dominating inner loop's.  */
+  basic_block bb_st = gimple_bb (DR_STMT (single_st));
+  if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb_st))
+    return false;
+
+  if (single_ld)
+    {
+      gimple *store = DR_STMT (single_st), *load = DR_STMT (single_ld);
+      /* Direct aggregate copy or via an SSA name temporary.  */
+      if (load != store
+         && gimple_assign_lhs (load) != gimple_assign_rhs1 (store))
+       return false;
+
+      /* Bail out if this is a bitfield memory reference.  */
+      if (TREE_CODE (DR_REF (single_ld)) == COMPONENT_REF
+         && DECL_BIT_FIELD (TREE_OPERAND (DR_REF (single_ld), 1)))
+       return false;
+
+      /* Load and store must be in the same loop nest.  */
+      basic_block bb_ld = gimple_bb (DR_STMT (single_ld));
+      if (bb_st->loop_father != bb_ld->loop_father)
+       return false;
+
+      /* Data reference must be executed exactly once per iteration.
+        Same as single_st, we only need to check against the outermost
+        loop.  */
+      if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb_ld))
+       return false;
+
+      edge e = single_exit (bb_st->loop_father);
+      bool dom_ld = dominated_by_p (CDI_DOMINATORS, e->src, bb_ld);
+      bool dom_st = dominated_by_p (CDI_DOMINATORS, e->src, bb_st);
+      if (dom_ld != dom_st)
+       return false;
+    }
+
+  *src_dr = single_ld;
+  *dst_dr = single_st;
+  return true;
+}
+
+/* Given data reference DR in LOOP_NEST, this function checks the enclosing
+   loops from inner to outer to see if loop's step equals to access size at
+   each level of loop.  Return 2 if we can prove this at all level loops;
+   record access base and size in BASE and SIZE; save loop's step at each
+   level of loop in STEPS if it is not null.  For example:
+
+     int arr[100][100][100];
+     for (i = 0; i < 100; i++)       ;steps[2] = 40000
+       for (j = 100; j > 0; j--)     ;steps[1] = -400
+        for (k = 0; k < 100; k++)   ;steps[0] = 4
+          arr[i][j - 1][k] = 0;     ;base = &arr, size = 4000000
+
+   Return 1 if we can prove the equality at the innermost loop, but not all
+   level loops.  In this case, no information is recorded.
+
+   Return 0 if no equality can be proven at any level loops.  */
+
+static int
+compute_access_range (loop_p loop_nest, data_reference_p dr, tree *base,
+                     tree *size, vec<tree> *steps = NULL)
+{
+  location_t loc = gimple_location (DR_STMT (dr));
+  basic_block bb = gimple_bb (DR_STMT (dr));
+  class loop *loop = bb->loop_father;
+  tree ref = DR_REF (dr);
+  tree access_base = build_fold_addr_expr (ref);
+  tree access_size = TYPE_SIZE_UNIT (TREE_TYPE (ref));
+  int res = 0;
+
+  do {
+      tree scev_fn = analyze_scalar_evolution (loop, access_base);
+      if (TREE_CODE (scev_fn) != POLYNOMIAL_CHREC)
+       return res;
+
+      access_base = CHREC_LEFT (scev_fn);
+      if (tree_contains_chrecs (access_base, NULL))
+       return res;
+
+      tree scev_step = CHREC_RIGHT (scev_fn);
+      /* Only support constant steps.  */
+      if (TREE_CODE (scev_step) != INTEGER_CST)
+       return res;
+
+      enum ev_direction access_dir = scev_direction (scev_fn);
+      if (access_dir == EV_DIR_UNKNOWN)
+       return res;
+
+      if (steps != NULL)
+       steps->safe_push (scev_step);
+
+      scev_step = fold_convert_loc (loc, sizetype, scev_step);
+      /* Compute absolute value of scev step.  */
+      if (access_dir == EV_DIR_DECREASES)
+       scev_step = fold_build1_loc (loc, NEGATE_EXPR, sizetype, scev_step);
+
+      /* At each level of loop, scev step must equal to access size.  In other
+        words, DR must access consecutive memory between loop iterations.  */
+      if (!operand_equal_p (scev_step, access_size, 0))
+       return res;
+
+      /* Access stride can be computed for data reference at least for the
+        innermost loop.  */
+      res = 1;
+
+      /* Compute DR's execution times in loop.  */
+      tree niters = number_of_latch_executions (loop);
+      niters = fold_convert_loc (loc, sizetype, niters);
+      if (dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src, bb))
+       niters = size_binop_loc (loc, PLUS_EXPR, niters, size_one_node);
+
+      /* Compute DR's overall access size in loop.  */
+      access_size = fold_build2_loc (loc, MULT_EXPR, sizetype,
+                                    niters, scev_step);
+      /* Adjust base address in case of negative step.  */
+      if (access_dir == EV_DIR_DECREASES)
+       {
+         tree adj = fold_build2_loc (loc, MINUS_EXPR, sizetype,
+                                     scev_step, access_size);
+         access_base = fold_build_pointer_plus_loc (loc, access_base, adj);
+       }
+  } while (loop != loop_nest && (loop = loop_outer (loop)) != NULL);
+
+  *base = access_base;
+  *size = access_size;
+  /* Access stride can be computed for data reference at each level loop.  */
+  return 2;
+}
+
+/* Allocate and return builtin struct.  Record information like DST_DR,
+   SRC_DR, DST_BASE, SRC_BASE and SIZE in the allocated struct.  */
+
+static struct builtin_info *
+alloc_builtin (data_reference_p dst_dr, data_reference_p src_dr,
+              tree dst_base, tree src_base, tree size)
+{
+  struct builtin_info *builtin = XNEW (struct builtin_info);
+  builtin->dst_dr = dst_dr;
+  builtin->src_dr = src_dr;
+  builtin->dst_base = dst_base;
+  builtin->src_base = src_base;
+  builtin->size = size;
+  return builtin;
+}
+
+/* Given data reference DR in loop nest LOOP, classify if it forms builtin
+   memset call.  */
+
+static void
+classify_builtin_st (loop_p loop, partition *partition, data_reference_p dr)
+{
+  gimple *stmt = DR_STMT (dr);
+  tree base, size, rhs = gimple_assign_rhs1 (stmt);
+
+  if (const_with_all_bytes_same (rhs) == -1
+      && (!INTEGRAL_TYPE_P (TREE_TYPE (rhs))
+         || (TYPE_MODE (TREE_TYPE (rhs))
+             != TYPE_MODE (unsigned_char_type_node))))
+    return;
+
+  if (TREE_CODE (rhs) == SSA_NAME
+      && !SSA_NAME_IS_DEFAULT_DEF (rhs)
+      && flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (rhs))))
+    return;
+
+  int res = compute_access_range (loop, dr, &base, &size);
+  if (res == 0)
+    return;
+  if (res == 1)
+    {
+      partition->kind = PKIND_PARTIAL_MEMSET;
+      return;
+    }
+
+  poly_uint64 base_offset;
+  unsigned HOST_WIDE_INT const_base_offset;
+  tree base_base = strip_offset (base, &base_offset);
+  if (!base_offset.is_constant (&const_base_offset))
+    return;
+
+  struct builtin_info *builtin;
+  builtin = alloc_builtin (dr, NULL, base, NULL_TREE, size);
+  builtin->dst_base_base = base_base;
+  builtin->dst_base_offset = const_base_offset;
+  partition->builtin = builtin;
+  partition->kind = PKIND_MEMSET;
+}
+
+/* Given data references DST_DR and SRC_DR in loop nest LOOP and RDG, classify
+   if it forms builtin memcpy or memmove call.  */
+
+void
+loop_distribution::classify_builtin_ldst (loop_p loop, struct graph *rdg,
+                                         partition *partition,
+                                         data_reference_p dst_dr,
+                                         data_reference_p src_dr)
+{
+  tree base, size, src_base, src_size;
+  auto_vec<tree> dst_steps, src_steps;
+
+  /* Compute access range of both load and store.  */
+  int res = compute_access_range (loop, dst_dr, &base, &size, &dst_steps);
+  if (res != 2)
+    return;
+  res = compute_access_range (loop, src_dr, &src_base, &src_size, &src_steps);
+  if (res != 2)
+    return;
+
+  /* They much have the same access size.  */
+  if (!operand_equal_p (size, src_size, 0))
+    return;
+
+  /* Load and store in loop nest must access memory in the same way, i.e,
+     their must have the same steps in each loop of the nest.  */
+  if (dst_steps.length () != src_steps.length ())
+    return;
+  for (unsigned i = 0; i < dst_steps.length (); ++i)
+    if (!operand_equal_p (dst_steps[i], src_steps[i], 0))
+      return;
+
+  /* Now check that if there is a dependence.  */
+  ddr_p ddr = get_data_dependence (rdg, src_dr, dst_dr);
+
+  /* Classify as memmove if no dependence between load and store.  */
+  if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
+    {
+      partition->builtin = alloc_builtin (dst_dr, src_dr, base, src_base, size);
+      partition->kind = PKIND_MEMMOVE;
+      return;
+    }
+
+  /* Can't do memmove in case of unknown dependence or dependence without
+     classical distance vector.  */
+  if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know
+      || DDR_NUM_DIST_VECTS (ddr) == 0)
+    return;
+
+  unsigned i;
+  lambda_vector dist_v;
+  int num_lev = (DDR_LOOP_NEST (ddr)).length ();
+  FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
+    {
+      unsigned dep_lev = dependence_level (dist_v, num_lev);
+      /* Can't do memmove if load depends on store.  */
+      if (dep_lev > 0 && dist_v[dep_lev - 1] > 0 && !DDR_REVERSED_P (ddr))
+       return;
+    }
+
+  partition->builtin = alloc_builtin (dst_dr, src_dr, base, src_base, size);
+  partition->kind = PKIND_MEMMOVE;
+  return;
+}
+
+bool
+loop_distribution::classify_partition (loop_p loop,
+                                      struct graph *rdg, partition *partition,
+                                      bitmap stmt_in_all_partitions)
+{
+  bitmap_iterator bi;
+  unsigned i;
+  data_reference_p single_ld = NULL, single_st = NULL;
+  bool volatiles_p = false, has_reduction = false;
+
+  EXECUTE_IF_SET_IN_BITMAP (partition->stmts, 0, i, bi)
+    {
+      gimple *stmt = RDG_STMT (rdg, i);
+
+      if (gimple_has_volatile_ops (stmt))
+       volatiles_p = true;
+
+      /* If the stmt is not included by all partitions and there is uses
+        outside of the loop, then mark the partition as reduction.  */
+      if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
+       {
+         /* Due to limitation in the transform phase we have to fuse all
+            reduction partitions.  As a result, this could cancel valid
+            loop distribution especially for loop that induction variable
+            is used outside of loop.  To workaround this issue, we skip
+            marking partition as reudction if the reduction stmt belongs
+            to all partitions.  In such case, reduction will be computed
+            correctly no matter how partitions are fused/distributed.  */
+         if (!bitmap_bit_p (stmt_in_all_partitions, i))
+           partition->reduction_p = true;
+         else
+           has_reduction = true;
+       }
+    }
+
+  /* Simple workaround to prevent classifying the partition as builtin
+     if it contains any use outside of loop.  For the case where all
+     partitions have the reduction this simple workaround is delayed
+     to only affect the last partition.  */
+  if (partition->reduction_p)
+     return has_reduction;
 
-  nb_iter = number_of_latch_executions (loop);
-  gcc_assert (nb_iter && nb_iter != chrec_dont_know);
-  if (dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src,
-                     gimple_bb (DR_STMT (single_store))))
-    plus_one = true;
+  /* Perform general partition disqualification for builtins.  */
+  if (volatiles_p
+      || !flag_tree_loop_distribute_patterns)
+    return has_reduction;
 
-  if (single_store && !single_load)
-    {
-      gimple *stmt = DR_STMT (single_store);
-      tree rhs = gimple_assign_rhs1 (stmt);
-      if (const_with_all_bytes_same (rhs) == -1
-         && (!INTEGRAL_TYPE_P (TREE_TYPE (rhs))
-             || (TYPE_MODE (TREE_TYPE (rhs))
-                 != TYPE_MODE (unsigned_char_type_node))))
-       return;
-      if (TREE_CODE (rhs) == SSA_NAME
-         && !SSA_NAME_IS_DEFAULT_DEF (rhs)
-         && flow_bb_inside_loop_p (loop, gimple_bb (SSA_NAME_DEF_STMT (rhs))))
-       return;
-      if (!adjacent_dr_p (single_store)
-         || !dominated_by_p (CDI_DOMINATORS,
-                             loop->latch, gimple_bb (stmt)))
-       return;
-      partition->kind = PKIND_MEMSET;
-      partition->main_dr = single_store;
-      partition->niter = nb_iter;
-      partition->plus_one = plus_one;
-    }
-  else if (single_store && single_load)
-    {
-      gimple *store = DR_STMT (single_store);
-      gimple *load = DR_STMT (single_load);
-      /* Direct aggregate copy or via an SSA name temporary.  */
-      if (load != store
-         && gimple_assign_lhs (load) != gimple_assign_rhs1 (store))
-       return;
-      if (!adjacent_dr_p (single_store)
-         || !adjacent_dr_p (single_load)
-         || !operand_equal_p (DR_STEP (single_store),
-                              DR_STEP (single_load), 0)
-         || !dominated_by_p (CDI_DOMINATORS,
-                             loop->latch, gimple_bb (store)))
-       return;
-      /* Now check that if there is a dependence this dependence is
-         of a suitable form for memmove.  */
-      ddr_p ddr = get_data_dependence (rdg, single_load, single_store);
-      if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
-       return;
+  /* Find single load/store data references for builtin partition.  */
+  if (!find_single_drs (loop, rdg, partition, &single_st, &single_ld))
+    return has_reduction;
 
-      if (DDR_ARE_DEPENDENT (ddr) != chrec_known)
-       {
-         if (DDR_NUM_DIST_VECTS (ddr) == 0)
-           return;
+  partition->loc = gimple_location (DR_STMT (single_st));
 
-         lambda_vector dist_v;
-         FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
-           {
-             int dist = dist_v[index_in_loop_nest (loop->num,
-                                                   DDR_LOOP_NEST (ddr))];
-             if (dist > 0 && !DDR_REVERSED_P (ddr))
-               return;
-           }
-         partition->kind = PKIND_MEMMOVE;
-       }
-      else
-       partition->kind = PKIND_MEMCPY;
-      partition->main_dr = single_store;
-      partition->secondary_dr = single_load;
-      partition->niter = nb_iter;
-      partition->plus_one = plus_one;
-    }
+  /* Classify the builtin kind.  */
+  if (single_ld == NULL)
+    classify_builtin_st (loop, partition, single_st);
+  else
+    classify_builtin_ldst (loop, rdg, partition, single_st, single_ld);
+  return has_reduction;
 }
 
-/* Returns true when PARTITION1 and PARTITION2 access the same memory
-   object in RDG.  */
-
-static bool
-share_memory_accesses (struct graph *rdg,
+bool
+loop_distribution::share_memory_accesses (struct graph *rdg,
                       partition *partition1, partition *partition2)
 {
   unsigned i, j;
@@ -1528,10 +1913,10 @@ share_memory_accesses (struct graph *rdg,
    partition for it by adding depended statements according to RDG.
    All partitions are recorded in PARTITIONS.  */
 
-static void
-rdg_build_partitions (struct graph *rdg,
-                     vec<gimple *> starting_stmts,
-                     vec<partition *> *partitions)
+void
+loop_distribution::rdg_build_partitions (struct graph *rdg,
+                                        vec<gimple *> starting_stmts,
+                                        vec<partition *> *partitions)
 {
   auto_bitmap processed;
   int i;
@@ -1570,7 +1955,7 @@ rdg_build_partitions (struct graph *rdg,
 /* Dump to FILE the PARTITIONS.  */
 
 static void
-dump_rdg_partitions (FILE *file, vec<partition *> partitions)
+dump_rdg_partitions (FILE *file, const vec<partition *> &partitions)
 {
   int i;
   partition *partition;
@@ -1580,10 +1965,10 @@ dump_rdg_partitions (FILE *file, vec<partition *> partitions)
 }
 
 /* Debug PARTITIONS.  */
-extern void debug_rdg_partitions (vec<partition *> );
+extern void debug_rdg_partitions (const vec<partition *> &);
 
 DEBUG_FUNCTION void
-debug_rdg_partitions (vec<partition *> partitions)
+debug_rdg_partitions (const vec<partition *> &partitions)
 {
   dump_rdg_partitions (stderr, partitions);
 }
@@ -1634,7 +2019,7 @@ number_of_rw_in_partition (struct graph *rdg, partition *partition)
 
 static bool
 partition_contains_all_rw (struct graph *rdg,
-                          vec<partition *> partitions)
+                          const vec<partition *> &partitions)
 {
   int i;
   partition *partition;
@@ -1647,14 +2032,8 @@ partition_contains_all_rw (struct graph *rdg,
   return false;
 }
 
-/* Compute partition dependence created by the data references in DRS1
-   and DRS2, modify and return DIR according to that.  IF ALIAS_DDR is
-   not NULL, we record dependence introduced by possible alias between
-   two data references in ALIAS_DDRS; otherwise, we simply ignore such
-   dependence as if it doesn't exist at all.  */
-
-static int
-pg_add_dependence_edges (struct graph *rdg, int dir,
+int
+loop_distribution::pg_add_dependence_edges (struct graph *rdg, int dir,
                         bitmap drs1, bitmap drs2, vec<ddr_p> *alias_ddrs)
 {
   unsigned i, j;
@@ -1695,7 +2074,7 @@ pg_add_dependence_edges (struct graph *rdg, int dir,
              /* Be conservative.  If data references are not well analyzed,
                 or the two data references have the same base address and
                 offset, add dependence and consider it alias to each other.
-                In other words, the dependence can not be resolved by
+                In other words, the dependence cannot be resolved by
                 runtime alias check.  */
              if (!DR_BASE_ADDRESS (dr1) || !DR_BASE_ADDRESS (dr2)
                  || !DR_OFFSET (dr1) || !DR_OFFSET (dr2)
@@ -1716,11 +2095,13 @@ pg_add_dependence_edges (struct graph *rdg, int dir,
                this_dir = -this_dir;
 
              /* Known dependences can still be unordered througout the
-                iteration space, see gcc.dg/tree-ssa/ldist-16.c.  */
+                iteration space, see gcc.dg/tree-ssa/ldist-16.c and
+                gcc.dg/tree-ssa/pr94969.c.  */
              if (DDR_NUM_DIST_VECTS (ddr) != 1)
                this_dir = 2;
              /* If the overlap is exact preserve stmt order.  */
-             else if (lambda_vector_zerop (DDR_DIST_VECT (ddr, 0), 1))
+             else if (lambda_vector_zerop (DDR_DIST_VECT (ddr, 0),
+                                           DDR_NB_LOOPS (ddr)))
                ;
              /* Else as the distance vector is lexicographic positive swap
                 the dependence direction.  */
@@ -1779,6 +2160,8 @@ struct pg_edge_callback_data
   bitmap sccs_to_merge;
   /* Array constains component information for all vertices.  */
   int *vertices_component;
+  /* Array constains postorder information for all vertices.  */
+  int *vertices_post;
   /* Vector to record all data dependence relations which are needed
      to break strong connected components by runtime alias checks.  */
   vec<ddr_p> *alias_ddrs;
@@ -1869,10 +2252,10 @@ free_partition_graph_vdata (struct graph *pg)
    is ignored, as if it doesn't exist at all; otherwise all depdendences
    are considered.  */
 
-static struct graph *
-build_partition_graph (struct graph *rdg,
-                      vec<struct partition *> *partitions,
-                      bool ignore_alias_p)
+struct graph *
+loop_distribution::build_partition_graph (struct graph *rdg,
+                                         vec<struct partition *> *partitions,
+                                         bool ignore_alias_p)
 {
   int i, j;
   struct partition *partition1, *partition2;
@@ -1907,7 +2290,7 @@ build_partition_graph (struct graph *rdg,
 
          /* Add edge to partition graph if there exists dependence.  There
             are two types of edges.  One type edge is caused by compilation
-            time known dependence, this type can not be resolved by runtime
+            time known dependence, this type cannot be resolved by runtime
             alias check.  The other type can be resolved by runtime alias
             check.  */
          if (dir == 1 || dir == 2
@@ -1933,7 +2316,8 @@ build_partition_graph (struct graph *rdg,
   return pg;
 }
 
-/* Sort partitions in PG by post order and store them in PARTITIONS.  */
+/* Sort partitions in PG in descending post order and store them in
+   PARTITIONS.  */
 
 static void
 sort_partitions_by_post_order (struct graph *pg,
@@ -1942,7 +2326,7 @@ sort_partitions_by_post_order (struct graph *pg,
   int i;
   struct pg_vdata *data;
 
-  /* Now order the remaining nodes in postorder.  */
+  /* Now order the remaining nodes in descending postorder.  */
   qsort (pg->vertices, pg->n_vertices, sizeof (vertex), pgcmp);
   partitions->truncate (0);
   for (i = 0; i < pg->n_vertices; ++i)
@@ -1953,17 +2337,14 @@ sort_partitions_by_post_order (struct graph *pg,
     }
 }
 
-/* Given reduced dependence graph RDG merge strong connected components
-   of PARTITIONS.  In this function, data dependence caused by possible
-   alias between references is ignored, as if it doesn't exist at all.  */
-
-static void
-merge_dep_scc_partitions (struct graph *rdg,
-                         vec<struct partition *> *partitions)
+void
+loop_distribution::merge_dep_scc_partitions (struct graph *rdg,
+                                            vec<struct partition *> *partitions,
+                                            bool ignore_alias_p)
 {
   struct partition *partition1, *partition2;
   struct pg_vdata *data;
-  graph *pg = build_partition_graph (rdg, partitions, true);
+  graph *pg = build_partition_graph (rdg, partitions, ignore_alias_p);
   int i, j, num_sccs = graphds_scc (pg, NULL);
 
   /* Strong connected compoenent means dependence cycle, we cannot distribute
@@ -1992,6 +2373,7 @@ merge_dep_scc_partitions (struct graph *rdg,
   sort_partitions_by_post_order (pg, partitions);
   gcc_assert (partitions->length () == (unsigned)num_sccs);
   free_partition_graph_vdata (pg);
+  for_each_edge (pg, free_partition_graph_edata_cb, NULL);
   free_graph (pg);
 }
 
@@ -2032,13 +2414,12 @@ pg_collect_alias_ddrs (struct graph *g, struct graph_edge *e, void *data)
 /* This is the main function breaking strong conected components in
    PARTITIONS giving reduced depdendence graph RDG.  Store data dependence
    relations for runtime alias check in ALIAS_DDRS.  */
-
-static void
-break_alias_scc_partitions (struct graph *rdg,
-                           vec<struct partition *> *partitions,
-                           vec<ddr_p> *alias_ddrs)
+void
+loop_distribution::break_alias_scc_partitions (struct graph *rdg,
+                                              vec<struct partition *> *partitions,
+                                              vec<ddr_p> *alias_ddrs)
 {
-  int i, j, num_sccs, num_sccs_no_alias;
+  int i, j, k, num_sccs, num_sccs_no_alias = 0;
   /* Build partition dependence graph.  */
   graph *pg = build_partition_graph (rdg, partitions, false);
 
@@ -2055,7 +2436,7 @@ break_alias_scc_partitions (struct graph *rdg,
       auto_vec<enum partition_type> scc_types;
       struct partition *partition, *first;
 
-      /* If all paritions in a SCC has the same type, we can simply merge the
+      /* If all partitions in a SCC have the same type, we can simply merge the
         SCC.  This loop finds out such SCCS and record them in bitmap.  */
       bitmap_set_range (sccs_to_merge, 0, (unsigned) num_sccs);
       for (i = 0; i < num_sccs; ++i)
@@ -2063,6 +2444,8 @@ break_alias_scc_partitions (struct graph *rdg,
          for (j = 0; partitions->iterate (j, &first); ++j)
            if (pg->vertices[j].component == i)
              break;
+
+         bool same_type = true, all_builtins = partition_builtin_p (first);
          for (++j; partitions->iterate (j, &partition); ++j)
            {
              if (pg->vertices[j].component != i)
@@ -2070,16 +2453,24 @@ break_alias_scc_partitions (struct graph *rdg,
 
              if (first->type != partition->type)
                {
-                 bitmap_clear_bit (sccs_to_merge, i);
+                 same_type = false;
                  break;
                }
+             all_builtins &= partition_builtin_p (partition);
            }
+         /* Merge SCC if all partitions in SCC have the same type, though the
+            result partition is sequential, because vectorizer can do better
+            runtime alias check.  One expecption is all partitions in SCC are
+            builtins.  */
+         if (!same_type || all_builtins)
+           bitmap_clear_bit (sccs_to_merge, i);
        }
 
       /* Initialize callback data for traversing.  */
       cbdata.sccs_to_merge = sccs_to_merge;
       cbdata.alias_ddrs = alias_ddrs;
       cbdata.vertices_component = XNEWVEC (int, pg->n_vertices);
+      cbdata.vertices_post = XNEWVEC (int, pg->n_vertices);
       /* Record the component information which will be corrupted by next
         graph scc finding call.  */
       for (i = 0; i < pg->n_vertices; ++i)
@@ -2088,8 +2479,13 @@ break_alias_scc_partitions (struct graph *rdg,
       /* Collect data dependences for runtime alias checks to break SCCs.  */
       if (bitmap_count_bits (sccs_to_merge) != (unsigned) num_sccs)
        {
+         /* Record the postorder information which will be corrupted by next
+            graph SCC finding call.  */
+         for (i = 0; i < pg->n_vertices; ++i)
+           cbdata.vertices_post[i] = pg->vertices[i].post;
+
          /* Run SCC finding algorithm again, with alias dependence edges
-            skipped.  This is to topologically sort paritions according to
+            skipped.  This is to topologically sort partitions according to
             compilation time known dependence.  Note the topological order
             is stored in the form of pg's post order number.  */
          num_sccs_no_alias = graphds_scc (pg, NULL, pg_skip_alias_edge);
@@ -2111,21 +2507,46 @@ break_alias_scc_partitions (struct graph *rdg,
          for (j = 0; partitions->iterate (j, &first); ++j)
            if (cbdata.vertices_component[j] == i)
              break;
-         for (++j; partitions->iterate (j, &partition); ++j)
+         for (k = j + 1; partitions->iterate (k, &partition); ++k)
            {
              struct pg_vdata *data;
 
-             if (cbdata.vertices_component[j] != i)
+             if (cbdata.vertices_component[k] != i)
                continue;
 
              partition_merge_into (NULL, first, partition, FUSE_SAME_SCC);
-             (*partitions)[j] = NULL;
+             (*partitions)[k] = NULL;
              partition_free (partition);
-             data = (struct pg_vdata *)pg->vertices[j].data;
-             gcc_assert (data->id == j);
+             data = (struct pg_vdata *)pg->vertices[k].data;
+             gcc_assert (data->id == k);
              data->partition = NULL;
+             /* The result partition of merged SCC must be sequential.  */
+             first->type = PTYPE_SEQUENTIAL;
+           }
+       }
+      /* Restore the postorder information if it's corrupted in finding SCC
+        with alias dependence edges skipped.  If reduction partition's SCC is
+        broken by runtime alias checks, we force a negative post order to it
+        making sure it will be scheduled in the last.  */
+      if (num_sccs_no_alias > 0)
+       {
+         j = -1;
+         for (i = 0; i < pg->n_vertices; ++i)
+           {
+             pg->vertices[i].post = cbdata.vertices_post[i];
+             struct pg_vdata *data = (struct pg_vdata *)pg->vertices[i].data;
+             if (data->partition && partition_reduction_p (data->partition))
+               {
+                 gcc_assert (j == -1);
+                 j = i;
+               }
            }
+         if (j >= 0)
+           pg->vertices[j].post = -1;
        }
+
+      free (cbdata.vertices_component);
+      free (cbdata.vertices_post);
     }
 
   sort_partitions_by_post_order (pg, partitions);
@@ -2146,23 +2567,19 @@ break_alias_scc_partitions (struct graph *rdg,
 static tree
 data_ref_segment_size (struct data_reference *dr, tree niters)
 {
-  tree segment_length;
-
-  if (integer_zerop (DR_STEP (dr)))
-    segment_length = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr)));
-  else
-    segment_length = size_binop (MULT_EXPR,
-                                fold_convert (sizetype, DR_STEP (dr)),
-                                fold_convert (sizetype, niters));
-
-  return segment_length;
+  niters = size_binop (MINUS_EXPR,
+                      fold_convert (sizetype, niters),
+                      size_one_node);
+  return size_binop (MULT_EXPR,
+                    fold_convert (sizetype, DR_STEP (dr)),
+                    fold_convert (sizetype, niters));
 }
 
 /* Return true if LOOP's latch is dominated by statement for data reference
    DR.  */
 
 static inline bool
-latch_dominated_by_data_ref (struct loop *loop, data_reference *dr)
+latch_dominated_by_data_ref (class loop *loop, data_reference *dr)
 {
   return dominated_by_p (CDI_DOMINATORS, single_exit (loop)->src,
                         gimple_bb (DR_STMT (dr)));
@@ -2172,7 +2589,7 @@ latch_dominated_by_data_ref (struct loop *loop, data_reference *dr)
    data dependence relations ALIAS_DDRS.  */
 
 static void
-compute_alias_check_pairs (struct loop *loop, vec<ddr_p> *alias_ddrs,
+compute_alias_check_pairs (class loop *loop, vec<ddr_p> *alias_ddrs,
                           vec<dr_with_seg_len_pair_t> *comp_alias_pairs)
 {
   unsigned int i;
@@ -2193,12 +2610,6 @@ compute_alias_check_pairs (struct loop *loop, vec<ddr_p> *alias_ddrs,
       struct data_reference *dr_a = DDR_A (ddr);
       struct data_reference *dr_b = DDR_B (ddr);
       tree seg_length_a, seg_length_b;
-      int comp_res = data_ref_compare_tree (DR_BASE_ADDRESS (dr_a),
-                                           DR_BASE_ADDRESS (dr_b));
-
-      if (comp_res == 0)
-       comp_res = data_ref_compare_tree (DR_OFFSET (dr_a), DR_OFFSET (dr_b));
-      gcc_assert (comp_res != 0);
 
       if (latch_dominated_by_data_ref (loop, dr_a))
        seg_length_a = data_ref_segment_size (dr_a, niters_plus_one);
@@ -2210,13 +2621,18 @@ compute_alias_check_pairs (struct loop *loop, vec<ddr_p> *alias_ddrs,
       else
        seg_length_b = data_ref_segment_size (dr_b, niters);
 
-      dr_with_seg_len_pair_t dr_with_seg_len_pair
-         (dr_with_seg_len (dr_a, seg_length_a),
-          dr_with_seg_len (dr_b, seg_length_b));
+      unsigned HOST_WIDE_INT access_size_a
+       = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_a))));
+      unsigned HOST_WIDE_INT access_size_b
+       = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_b))));
+      unsigned int align_a = TYPE_ALIGN_UNIT (TREE_TYPE (DR_REF (dr_a)));
+      unsigned int align_b = TYPE_ALIGN_UNIT (TREE_TYPE (DR_REF (dr_b)));
 
-      /* Canonicalize pairs by sorting the two DR members.  */
-      if (comp_res > 0)
-       std::swap (dr_with_seg_len_pair.first, dr_with_seg_len_pair.second);
+      dr_with_seg_len_pair_t dr_with_seg_len_pair
+       (dr_with_seg_len (dr_a, seg_length_a, access_size_a, align_a),
+        dr_with_seg_len (dr_b, seg_length_b, access_size_b, align_b),
+        /* ??? Would WELL_ORDERED be safe?  */
+        dr_with_seg_len_pair_t::REORDERED);
 
       comp_alias_pairs->safe_push (dr_with_seg_len_pair);
     }
@@ -2236,11 +2652,12 @@ compute_alias_check_pairs (struct loop *loop, vec<ddr_p> *alias_ddrs,
    checks and version LOOP under condition of these runtime alias checks.  */
 
 static void
-version_loop_by_alias_check (struct loop *loop, vec<ddr_p> *alias_ddrs)
+version_loop_by_alias_check (vec<struct partition *> *partitions,
+                            class loop *loop, vec<ddr_p> *alias_ddrs)
 {
   profile_probability prob;
   basic_block cond_bb;
-  struct loop *nloop;
+  class loop *nloop;
   tree lhs, arg0, cond_expr = NULL_TREE;
   gimple_seq cond_stmts = NULL;
   gimple *call_stmt = NULL;
@@ -2259,9 +2676,25 @@ version_loop_by_alias_check (struct loop *loop, vec<ddr_p> *alias_ddrs)
                                      is_gimple_val, NULL_TREE);
 
   /* Depend on vectorizer to fold IFN_LOOP_DIST_ALIAS.  */
-  if (flag_tree_loop_vectorize)
+  bool cancelable_p = flag_tree_loop_vectorize;
+  if (cancelable_p)
+    {
+      unsigned i = 0;
+      struct partition *partition;
+      for (; partitions->iterate (i, &partition); ++i)
+       if (!partition_builtin_p (partition))
+         break;
+
+     /* If all partitions are builtins, distributing it would be profitable and
+       we don't want to cancel the runtime alias checks.  */
+      if (i == partitions->length ())
+       cancelable_p = false;
+    }
+
+  /* Generate internal function call for loop distribution alias check if the
+     runtime alias check should be cancelable.  */
+  if (cancelable_p)
     {
-      /* Generate internal function call for loop distribution alias check.  */
       call_stmt = gimple_build_call_internal (IFN_LOOP_DIST_ALIAS,
                                              2, NULL_TREE, cond_expr);
       lhs = make_ssa_name (boolean_type_node);
@@ -2315,38 +2748,172 @@ version_for_distribution_p (vec<struct partition *> *partitions,
   return (alias_ddrs->length () > 0);
 }
 
-/* Fuse all partitions if necessary before finalizing distribution.  */
+/* Compare base offset of builtin mem* partitions P1 and P2.  */
+
+static int
+offset_cmp (const void *vp1, const void *vp2)
+{
+  struct partition *p1 = *(struct partition *const *) vp1;
+  struct partition *p2 = *(struct partition *const *) vp2;
+  unsigned HOST_WIDE_INT o1 = p1->builtin->dst_base_offset;
+  unsigned HOST_WIDE_INT o2 = p2->builtin->dst_base_offset;
+  return (o2 < o1) - (o1 < o2);
+}
+
+/* Fuse adjacent memset builtin PARTITIONS if possible.  This is a special
+   case optimization transforming below code:
+
+     __builtin_memset (&obj, 0, 100);
+     _1 = &obj + 100;
+     __builtin_memset (_1, 0, 200);
+     _2 = &obj + 300;
+     __builtin_memset (_2, 0, 100);
+
+   into:
+
+     __builtin_memset (&obj, 0, 400);
+
+   Note we don't have dependence information between different partitions
+   at this point, as a result, we can't handle nonadjacent memset builtin
+   partitions since dependence might be broken.  */
 
 static void
-finalize_partitions (vec<struct partition *> *partitions,
-                    vec<ddr_p> *alias_ddrs)
+fuse_memset_builtins (vec<struct partition *> *partitions)
+{
+  unsigned i, j;
+  struct partition *part1, *part2;
+  tree rhs1, rhs2;
+
+  for (i = 0; partitions->iterate (i, &part1);)
+    {
+      if (part1->kind != PKIND_MEMSET)
+       {
+         i++;
+         continue;
+       }
+
+      /* Find sub-array of memset builtins of the same base.  Index range
+        of the sub-array is [i, j) with "j > i".  */
+      for (j = i + 1; partitions->iterate (j, &part2); ++j)
+       {
+         if (part2->kind != PKIND_MEMSET
+             || !operand_equal_p (part1->builtin->dst_base_base,
+                                  part2->builtin->dst_base_base, 0))
+           break;
+
+         /* Memset calls setting different values can't be merged.  */
+         rhs1 = gimple_assign_rhs1 (DR_STMT (part1->builtin->dst_dr));
+         rhs2 = gimple_assign_rhs1 (DR_STMT (part2->builtin->dst_dr));
+         if (!operand_equal_p (rhs1, rhs2, 0))
+           break;
+       }
+
+      /* Stable sort is required in order to avoid breaking dependence.  */
+      gcc_stablesort (&(*partitions)[i], j - i, sizeof (*partitions)[i],
+                     offset_cmp);
+      /* Continue with next partition.  */
+      i = j;
+    }
+
+  /* Merge all consecutive memset builtin partitions.  */
+  for (i = 0; i < partitions->length () - 1;)
+    {
+      part1 = (*partitions)[i];
+      if (part1->kind != PKIND_MEMSET)
+       {
+         i++;
+         continue;
+       }
+
+      part2 = (*partitions)[i + 1];
+      /* Only merge memset partitions of the same base and with constant
+        access sizes.  */
+      if (part2->kind != PKIND_MEMSET
+         || TREE_CODE (part1->builtin->size) != INTEGER_CST
+         || TREE_CODE (part2->builtin->size) != INTEGER_CST
+         || !operand_equal_p (part1->builtin->dst_base_base,
+                              part2->builtin->dst_base_base, 0))
+       {
+         i++;
+         continue;
+       }
+      rhs1 = gimple_assign_rhs1 (DR_STMT (part1->builtin->dst_dr));
+      rhs2 = gimple_assign_rhs1 (DR_STMT (part2->builtin->dst_dr));
+      int bytev1 = const_with_all_bytes_same (rhs1);
+      int bytev2 = const_with_all_bytes_same (rhs2);
+      /* Only merge memset partitions of the same value.  */
+      if (bytev1 != bytev2 || bytev1 == -1)
+       {
+         i++;
+         continue;
+       }
+      wide_int end1 = wi::add (part1->builtin->dst_base_offset,
+                              wi::to_wide (part1->builtin->size));
+      /* Only merge adjacent memset partitions.  */
+      if (wi::ne_p (end1, part2->builtin->dst_base_offset))
+       {
+         i++;
+         continue;
+       }
+      /* Merge partitions[i] and partitions[i+1].  */
+      part1->builtin->size = fold_build2 (PLUS_EXPR, sizetype,
+                                         part1->builtin->size,
+                                         part2->builtin->size);
+      partition_free (part2);
+      partitions->ordered_remove (i + 1);
+    }
+}
+
+void
+loop_distribution::finalize_partitions (class loop *loop,
+                                       vec<struct partition *> *partitions,
+                                       vec<ddr_p> *alias_ddrs)
 {
   unsigned i;
-  struct partition *a, *partition;
+  struct partition *partition, *a;
 
   if (partitions->length () == 1
       || alias_ddrs->length () > 0)
     return;
 
-  a = (*partitions)[0];
-  if (a->kind != PKIND_NORMAL)
-    return;
-
-  for (i = 1; partitions->iterate (i, &partition); ++i)
+  unsigned num_builtin = 0, num_normal = 0, num_partial_memset = 0;
+  bool same_type_p = true;
+  enum partition_type type = ((*partitions)[0])->type;
+  for (i = 0; partitions->iterate (i, &partition); ++i)
     {
-      /* Don't fuse if partition has different type or it is a builtin.  */
-      if (partition->type != a->type
-         || partition->kind != PKIND_NORMAL)
-       return;
+      same_type_p &= (type == partition->type);
+      if (partition_builtin_p (partition))
+       {
+         num_builtin++;
+         continue;
+       }
+      num_normal++;
+      if (partition->kind == PKIND_PARTIAL_MEMSET)
+       num_partial_memset++;
+    }
+
+  /* Don't distribute current loop into too many loops given we don't have
+     memory stream cost model.  Be even more conservative in case of loop
+     nest distribution.  */
+  if ((same_type_p && num_builtin == 0
+       && (loop->inner == NULL || num_normal != 2 || num_partial_memset != 1))
+      || (loop->inner != NULL
+         && i >= NUM_PARTITION_THRESHOLD && num_normal > 1)
+      || (loop->inner == NULL
+         && i >= NUM_PARTITION_THRESHOLD && num_normal > num_builtin))
+    {
+      a = (*partitions)[0];
+      for (i = 1; partitions->iterate (i, &partition); ++i)
+       {
+         partition_merge_into (NULL, a, partition, FUSE_FINALIZE);
+         partition_free (partition);
+       }
+      partitions->truncate (1);
     }
 
-  /* Fuse all partitions.  */
-  for (i = 1; partitions->iterate (i, &partition); ++i)
-    {
-      partition_merge_into (NULL, a, partition, FUSE_FINALIZE);
-      partition_free (partition);
-    }
-  partitions->truncate (1);
+  /* Fuse memset builtins if possible.  */
+  if (partitions->length () > 1)
+    fuse_memset_builtins (partitions);
 }
 
 /* Distributes the code from LOOP in such a way that producer statements
@@ -2355,14 +2922,15 @@ finalize_partitions (vec<struct partition *> *partitions,
    distributed loops.  Set NB_CALLS to number of generated builtin calls.
    Set *DESTROY_P to whether LOOP needs to be destroyed.  */
 
-static int
-distribute_loop (struct loop *loop, vec<gimple *> stmts,
-                control_dependences *cd, int *nb_calls, bool *destroy_p)
+int
+loop_distribution::distribute_loop (class loop *loop,
+                const vec<gimple *> &stmts,
+                control_dependences *cd, int *nb_calls, bool *destroy_p,
+                bool only_patterns_p)
 {
   ddrs_table = new hash_table<ddr_hasher> (389);
   struct graph *rdg;
   partition *partition;
-  bool any_builtin;
   int i, nbp;
 
   *destroy_p = false;
@@ -2376,6 +2944,7 @@ distribute_loop (struct loop *loop, vec<gimple *> stmts,
     }
 
   datarefs_vec.create (20);
+  has_nonaddressable_dataref_p = false;
   rdg = build_rdg (loop, cd);
   if (!rdg)
     {
@@ -2421,16 +2990,18 @@ distribute_loop (struct loop *loop, vec<gimple *> stmts,
   for (i = 1; partitions.iterate (i, &partition); ++i)
     bitmap_and_into (stmt_in_all_partitions, partitions[i]->stmts);
 
-  any_builtin = false;
+  bool any_builtin = false;
+  bool reduction_in_all = false;
   FOR_EACH_VEC_ELT (partitions, i, partition)
     {
-      classify_partition (loop, rdg, partition, stmt_in_all_partitions);
+      reduction_in_all
+       |= classify_partition (loop, rdg, partition, stmt_in_all_partitions);
       any_builtin |= partition_builtin_p (partition);
     }
 
   /* If we are only distributing patterns but did not detect any,
      simply bail out.  */
-  if (!flag_tree_loop_distribution
+  if (only_patterns_p
       && !any_builtin)
     {
       nbp = 0;
@@ -2442,7 +3013,7 @@ distribute_loop (struct loop *loop, vec<gimple *> stmts,
      a loop into pieces, separated by builtin calls.  That is, we
      only want no or a single loop body remaining.  */
   struct partition *into;
-  if (!flag_tree_loop_distribution)
+  if (only_patterns_p)
     {
       for (i = 0; partitions.iterate (i, &into); ++i)
        if (!partition_builtin_p (into))
@@ -2477,7 +3048,7 @@ distribute_loop (struct loop *loop, vec<gimple *> stmts,
   for (i = 0; partitions.iterate (i, &into); ++i)
     {
       bool changed = false;
-      if (partition_builtin_p (into))
+      if (partition_builtin_p (into) || into->kind == PKIND_PARTIAL_MEMSET)
        continue;
       for (int j = i + 1;
           partitions.iterate (j, &partition); ++j)
@@ -2499,16 +3070,55 @@ distribute_loop (struct loop *loop, vec<gimple *> stmts,
        i--;
     }
 
-  /* Build the partition dependency graph.  */
+  /* Put a non-builtin partition last if we need to preserve a reduction.
+     ???  This is a workaround that makes sort_partitions_by_post_order do
+     the correct thing while in reality it should sort each component
+     separately and then put the component with a reduction or a non-builtin
+     last.  */
+  if (reduction_in_all
+      && partition_builtin_p (partitions.last()))
+    FOR_EACH_VEC_ELT (partitions, i, partition)
+      if (!partition_builtin_p (partition))
+       {
+         partitions.unordered_remove (i);
+         partitions.quick_push (partition);
+         break;
+       }
+
+  /* Build the partition dependency graph and fuse partitions in strong
+     connected component.  */
   if (partitions.length () > 1)
     {
-      merge_dep_scc_partitions (rdg, &partitions);
-      alias_ddrs.truncate (0);
-      if (partitions.length () > 1)
-       break_alias_scc_partitions (rdg, &partitions, &alias_ddrs);
+      /* Don't support loop nest distribution under runtime alias check
+        since it's not likely to enable many vectorization opportunities.
+        Also if loop has any data reference which may be not addressable
+        since alias check needs to take, compare address of the object.  */
+      if (loop->inner || has_nonaddressable_dataref_p)
+       merge_dep_scc_partitions (rdg, &partitions, false);
+      else
+       {
+         merge_dep_scc_partitions (rdg, &partitions, true);
+         if (partitions.length () > 1)
+           break_alias_scc_partitions (rdg, &partitions, &alias_ddrs);
+       }
     }
 
-  finalize_partitions (&partitions, &alias_ddrs);
+  finalize_partitions (loop, &partitions, &alias_ddrs);
+
+  /* If there is a reduction in all partitions make sure the last one
+     is not classified for builtin code generation.  */
+  if (reduction_in_all)
+    {
+      partition = partitions.last ();
+      if (only_patterns_p
+         && partition_builtin_p (partition)
+         && !partition_builtin_p (partitions[0]))
+       {
+         nbp = 0;
+         goto ldist_done;
+       }
+      partition->kind = PKIND_NORMAL;
+    }
 
   nbp = partitions.length ();
   if (nbp == 0
@@ -2520,7 +3130,7 @@ distribute_loop (struct loop *loop, vec<gimple *> stmts,
     }
 
   if (version_for_distribution_p (&partitions, &alias_ddrs))
-    version_loop_by_alias_check (loop, &alias_ddrs);
+    version_loop_by_alias_check (&partitions, loop, &alias_ddrs);
 
   if (dump_file && (dump_flags & TDF_DETAILS))
     {
@@ -2554,45 +3164,136 @@ distribute_loop (struct loop *loop, vec<gimple *> stmts,
   return nbp - *nb_calls;
 }
 
-/* Distribute all loops in the current function.  */
 
-namespace {
+void loop_distribution::bb_top_order_init (void)
+{
+  int rpo_num;
+  int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS);
+  edge entry = single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun));
+  bitmap exit_bbs = BITMAP_ALLOC (NULL);
 
-const pass_data pass_data_loop_distribution =
+  bb_top_order_index = XNEWVEC (int, last_basic_block_for_fn (cfun));
+  bb_top_order_index_size = last_basic_block_for_fn (cfun);
+
+  entry->flags &= ~EDGE_DFS_BACK;
+  bitmap_set_bit (exit_bbs, EXIT_BLOCK);
+  rpo_num = rev_post_order_and_mark_dfs_back_seme (cfun, entry, exit_bbs, true,
+                                                  rpo, NULL);
+  BITMAP_FREE (exit_bbs);
+
+  for (int i = 0; i < rpo_num; i++)
+    bb_top_order_index[rpo[i]] = i;
+
+  free (rpo);
+}
+
+void loop_distribution::bb_top_order_destroy ()
 {
-  GIMPLE_PASS, /* type */
-  "ldist", /* name */
-  OPTGROUP_LOOP, /* optinfo_flags */
-  TV_TREE_LOOP_DISTRIBUTION, /* tv_id */
-  ( PROP_cfg | PROP_ssa ), /* properties_required */
-  0, /* properties_provided */
-  0, /* properties_destroyed */
-  0, /* todo_flags_start */
-  0, /* todo_flags_finish */
-};
+  free (bb_top_order_index);
+  bb_top_order_index = NULL;
+  bb_top_order_index_size = 0;
+}
 
-class pass_loop_distribution : public gimple_opt_pass
+
+/* Given LOOP, this function records seed statements for distribution in
+   WORK_LIST.  Return false if there is nothing for distribution.  */
+
+static bool
+find_seed_stmts_for_distribution (class loop *loop, vec<gimple *> *work_list)
 {
-public:
-  pass_loop_distribution (gcc::context *ctxt)
-    : gimple_opt_pass (pass_data_loop_distribution, ctxt)
-  {}
+  basic_block *bbs = get_loop_body_in_dom_order (loop);
 
-  /* opt_pass methods: */
-  virtual bool gate (function *)
+  /* Initialize the worklist with stmts we seed the partitions with.  */
+  for (unsigned i = 0; i < loop->num_nodes; ++i)
     {
-      return flag_tree_loop_distribution
-       || flag_tree_loop_distribute_patterns;
+      /* In irreducible sub-regions we don't know how to redirect
+        conditions, so fail.  See PR100492.  */
+      if (bbs[i]->flags & BB_IRREDUCIBLE_LOOP)
+       {
+         if (dump_file && (dump_flags & TDF_DETAILS))
+           fprintf (dump_file, "loop %d contains an irreducible region.\n",
+                    loop->num);
+         work_list->truncate (0);
+         break;
+       }
+      for (gphi_iterator gsi = gsi_start_phis (bbs[i]);
+          !gsi_end_p (gsi); gsi_next (&gsi))
+       {
+         gphi *phi = gsi.phi ();
+         if (virtual_operand_p (gimple_phi_result (phi)))
+           continue;
+         /* Distribute stmts which have defs that are used outside of
+            the loop.  */
+         if (!stmt_has_scalar_dependences_outside_loop (loop, phi))
+           continue;
+         work_list->safe_push (phi);
+       }
+      for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
+          !gsi_end_p (gsi); gsi_next (&gsi))
+       {
+         gimple *stmt = gsi_stmt (gsi);
+
+         /* Ignore clobbers, they do not have true side effects.  */
+         if (gimple_clobber_p (stmt))
+           continue;
+
+         /* If there is a stmt with side-effects bail out - we
+            cannot and should not distribute this loop.  */
+         if (gimple_has_side_effects (stmt))
+           {
+             free (bbs);
+             return false;
+           }
+
+         /* Distribute stmts which have defs that are used outside of
+            the loop.  */
+         if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
+           ;
+         /* Otherwise only distribute stores for now.  */
+         else if (!gimple_vdef (stmt))
+           continue;
+
+         work_list->safe_push (stmt);
+       }
     }
+  free (bbs);
+  return work_list->length () > 0;
+}
 
-  virtual unsigned int execute (function *);
+/* Given innermost LOOP, return the outermost enclosing loop that forms a
+   perfect loop nest.  */
+
+static class loop *
+prepare_perfect_loop_nest (class loop *loop)
+{
+  class loop *outer = loop_outer (loop);
+  tree niters = number_of_latch_executions (loop);
+
+  /* TODO: We only support the innermost 3-level loop nest distribution
+     because of compilation time issue for now.  This should be relaxed
+     in the future.  Note we only allow 3-level loop nest distribution
+     when parallelizing loops.  */
+  while ((loop->inner == NULL
+         || (loop->inner->inner == NULL && flag_tree_parallelize_loops > 1))
+        && loop_outer (outer)
+        && outer->inner == loop && loop->next == NULL
+        && single_exit (outer)
+        && !chrec_contains_symbols_defined_in_loop (niters, outer->num)
+        && (niters = number_of_latch_executions (outer)) != NULL_TREE
+        && niters != chrec_dont_know)
+    {
+      loop = outer;
+      outer = loop_outer (loop);
+    }
+
+  return loop;
+}
 
-}; // class pass_loop_distribution
 
 unsigned int
-pass_loop_distribution::execute (function *fun)
+loop_distribution::execute (function *fun)
 {
-  struct loop *loop;
+  class loop *loop;
   bool changed = false;
   basic_block bb;
   control_dependences *cd = NULL;
@@ -2601,22 +3302,7 @@ pass_loop_distribution::execute (function *fun)
   if (number_of_loops (fun) <= 1)
     return 0;
 
-  /* Compute topological order for basic blocks.  Topological order is
-     needed because data dependence is computed for data references in
-     lexicographical order.  */
-  if (bb_top_order_index == NULL)
-    {
-      int rpo_num;
-      int *rpo = XNEWVEC (int, last_basic_block_for_fn (cfun));
-
-      bb_top_order_index = XNEWVEC (int, last_basic_block_for_fn (cfun));
-      bb_top_order_index_size = last_basic_block_for_fn (cfun);
-      rpo_num = pre_and_rev_post_order_compute_fn (cfun, NULL, rpo, true);
-      for (int i = 0; i < rpo_num; i++)
-       bb_top_order_index[rpo[i]] = i;
-
-      free (rpo);
-    }
+  bb_top_order_init ();
 
   FOR_ALL_BB_FN (bb, fun)
     {
@@ -2629,20 +3315,13 @@ pass_loop_distribution::execute (function *fun)
 
   /* We can at the moment only distribute non-nested loops, thus restrict
      walking to innermost loops.  */
-  FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
+  for (auto loop : loops_list (cfun, LI_ONLY_INNERMOST))
     {
-      auto_vec<gimple *> work_list;
-      basic_block *bbs;
-      int num = loop->num;
-      unsigned int i;
-
-      /* If the loop doesn't have a single exit we will fail anyway,
-        so do that early.  */
-      if (!single_exit (loop))
-       continue;
-
-      /* Only optimize hot loops.  */
-      if (!optimize_loop_for_speed_p (loop))
+      /* Don't distribute multiple exit edges loop, or cold loop when
+         not doing pattern detection.  */
+      if (!single_exit (loop)
+         || (!flag_tree_loop_distribute_patterns
+             && !optimize_loop_for_speed_p (loop)))
        continue;
 
       /* Don't distribute loop if niters is unknown.  */
@@ -2650,56 +3329,16 @@ pass_loop_distribution::execute (function *fun)
       if (niters == NULL_TREE || niters == chrec_dont_know)
        continue;
 
-      /* Initialize the worklist with stmts we seed the partitions with.  */
-      bbs = get_loop_body_in_dom_order (loop);
-      for (i = 0; i < loop->num_nodes; ++i)
+      /* Get the perfect loop nest for distribution.  */
+      loop = prepare_perfect_loop_nest (loop);
+      for (; loop; loop = loop->inner)
        {
-         for (gphi_iterator gsi = gsi_start_phis (bbs[i]);
-              !gsi_end_p (gsi);
-              gsi_next (&gsi))
-           {
-             gphi *phi = gsi.phi ();
-             if (virtual_operand_p (gimple_phi_result (phi)))
-               continue;
-             /* Distribute stmts which have defs that are used outside of
-                the loop.  */
-             if (!stmt_has_scalar_dependences_outside_loop (loop, phi))
-               continue;
-             work_list.safe_push (phi);
-           }
-         for (gimple_stmt_iterator gsi = gsi_start_bb (bbs[i]);
-              !gsi_end_p (gsi);
-              gsi_next (&gsi))
-           {
-             gimple *stmt = gsi_stmt (gsi);
-
-             /* If there is a stmt with side-effects bail out - we
-                cannot and should not distribute this loop.  */
-             if (gimple_has_side_effects (stmt))
-               {
-                 work_list.truncate (0);
-                 goto out;
-               }
-
-             /* Distribute stmts which have defs that are used outside of
-                the loop.  */
-             if (stmt_has_scalar_dependences_outside_loop (loop, stmt))
-               ;
-             /* Otherwise only distribute stores for now.  */
-             else if (!gimple_vdef (stmt))
-               continue;
+         auto_vec<gimple *> work_list;
+         if (!find_seed_stmts_for_distribution (loop, &work_list))
+           break;
 
-             work_list.safe_push (stmt);
-           }
-       }
-out:
-      free (bbs);
-
-      int nb_generated_loops = 0;
-      int nb_generated_calls = 0;
-      location_t loc = find_loop_location (loop);
-      if (work_list.length () > 0)
-       {
+         const char *str = loop->inner ? " nest" : "";
+         dump_user_location_t loc = find_loop_location (loop);
          if (!cd)
            {
              calculate_dominance_info (CDI_DOMINATORS);
@@ -2707,35 +3346,38 @@ out:
              cd = new control_dependences ();
              free_dominance_info (CDI_POST_DOMINATORS);
            }
+
          bool destroy_p;
-         nb_generated_loops = distribute_loop (loop, work_list, cd,
-                                               &nb_generated_calls,
-                                               &destroy_p);
+         int nb_generated_loops, nb_generated_calls;
+         nb_generated_loops
+           = distribute_loop (loop, work_list, cd, &nb_generated_calls,
+                              &destroy_p, (!optimize_loop_for_speed_p (loop)
+                                           || !flag_tree_loop_distribution));
          if (destroy_p)
            loops_to_be_destroyed.safe_push (loop);
-       }
 
-      if (nb_generated_loops + nb_generated_calls > 0)
-       {
-         changed = true;
-         dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
-                          loc, "Loop %d distributed: split to %d loops "
-                          "and %d library calls.\n",
-                          num, nb_generated_loops, nb_generated_calls);
+         if (nb_generated_loops + nb_generated_calls > 0)
+           {
+             changed = true;
+             if (dump_enabled_p ())
+               dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
+                                loc, "Loop%s %d distributed: split to %d loops "
+                                "and %d library calls.\n", str, loop->num,
+                                nb_generated_loops, nb_generated_calls);
+
+             break;
+           }
+
+         if (dump_file && (dump_flags & TDF_DETAILS))
+           fprintf (dump_file, "Loop%s %d not distributed.\n", str, loop->num);
        }
-      else if (dump_file && (dump_flags & TDF_DETAILS))
-       fprintf (dump_file, "Loop %d is the same.\n", num);
     }
 
   if (cd)
     delete cd;
 
   if (bb_top_order_index != NULL)
-    {
-      free (bb_top_order_index);
-      bb_top_order_index = NULL;
-      bb_top_order_index_size = 0;
-    }
+    bb_top_order_destroy ();
 
   if (changed)
     {
@@ -2754,7 +3396,49 @@ out:
 
   checking_verify_loop_structure ();
 
-  return 0;
+  return changed ? TODO_cleanup_cfg : 0;
+}
+
+
+/* Distribute all loops in the current function.  */
+
+namespace {
+
+const pass_data pass_data_loop_distribution =
+{
+  GIMPLE_PASS, /* type */
+  "ldist", /* name */
+  OPTGROUP_LOOP, /* optinfo_flags */
+  TV_TREE_LOOP_DISTRIBUTION, /* tv_id */
+  ( PROP_cfg | PROP_ssa ), /* properties_required */
+  0, /* properties_provided */
+  0, /* properties_destroyed */
+  0, /* todo_flags_start */
+  0, /* todo_flags_finish */
+};
+
+class pass_loop_distribution : public gimple_opt_pass
+{
+public:
+  pass_loop_distribution (gcc::context *ctxt)
+    : gimple_opt_pass (pass_data_loop_distribution, ctxt)
+  {}
+
+  /* opt_pass methods: */
+  virtual bool gate (function *)
+    {
+      return flag_tree_loop_distribution
+       || flag_tree_loop_distribute_patterns;
+    }
+
+  virtual unsigned int execute (function *);
+
+}; // class pass_loop_distribution
+
+unsigned int
+pass_loop_distribution::execute (function *fun)
+{
+  return loop_distribution ().execute (fun);
 }
 
 } // anon namespace