A loop that reads and writes through two pointers that may alias is
versioned on a runtime alias check. The IFN and WAR/WAW checks accept
equal pointers, but many pairs get the address-based overlap test
instead: a pair with a reordered member, a merged pair whose members
access the two pointers in opposite orders, or a RAW pair that the
target's IFN pattern cannot handle. The overlap test fails when the
pointers are equal, so a loop called with its output equal to its input
runs the scalar version. This affects SPEC2026's 736.ocio_r benchmark,
whose renderers process a single buffer in place.

This patch makes the overlap test accept equal pointers for the pairs
where that is safe. A pair qualifies when its two accesses have the same
size and lie on a common grid of that size, meaning that their common
stride and the distance between them are multiples of the size. They
must also either never coincide, or coincide only in the same iteration
and stay in scalar order when vectorized. Other pairs, such as a read
one element ahead of a store or accesses of different sizes, can overlap
across iterations or partially, so they keep the original test. So do
pairs with a load realigned from the previous iteration's vector
(dr_explicit_realign_optimized), which reads part of its data before the
stores of the current iteration.

The check is done per member pair in vect_prune_runtime_alias_test_list,
before the group leaders are substituted and the pairs are merged. The
pair constructor sets a new DR_ALIAS_INPLACE_UNSAFE flag, which the
vectorizer clears for a pair that qualifies, so a merged pair stays
unsafe unless all its members qualify. For a pair without the flag,
create_intersect_range_checks ORs a base-address equality into the
overlap test.

This speeds up 736.ocio_r by 4.3% on AArch64.

Tested on aarch64-linux-gnu, x86_64-linux-gnu and powerpc64-linux-gnu.

gcc/ChangeLog:

        * tree-data-ref.cc (dump_alias_pair): Print whether the pair is
        safe for in-place aliasing.
        (create_ifn_alias_checks): Ignore DR_ALIAS_INPLACE_UNSAFE.
        (relax_cond_for_inplace_aliasing): New function.
        (create_intersect_range_checks_index): Ignore
        DR_ALIAS_INPLACE_UNSAFE.
        (create_waw_or_war_checks): Likewise.
        (create_intersect_range_checks): Use relax_cond_for_inplace_aliasing
        on the address-based overlap path only.
        * tree-data-ref.h (dr_with_seg_len_pair_t::dr_with_seg_len_pair_t):
        Set the new DR_ALIAS_INPLACE_UNSAFE flag.
        * tree-vect-data-refs.cc (vect_inplace_alias_result): New function.
        (vect_realigned_load_p): Likewise.
        (vect_inplace_alias_safe_p): Likewise.
        (vect_prune_runtime_alias_test_list): Call it on each member
        pair before substituting the group leaders, and clear
        DR_ALIAS_INPLACE_UNSAFE on safe pairs.

gcc/testsuite/ChangeLog:

        * gcc.dg/vect/vect-alias-check-inplace-run.c: New test.
        * gcc.target/aarch64/vect-alias-check-inplace.c: New test.
        * gcc.target/powerpc/vect-alias-check-inplace-realign.c: New test.

Co-authored-by: Philipp Tomsich <[email protected]>
Signed-off-by: Konstantinos Eleftheriou <[email protected]>
---

Changes in v2:
- Refuse pairs with a load vectorized with
  `dr_explicit_realign_optimized`, which reads part of its data in the
  previous iteration, as Sashiko reported.
- Replace the `inplace_safe` field with a `DR_ALIAS_INPLACE_UNSAFE` flag.
- Add gcc.target/powerpc/vect-alias-check-inplace-realign.c.
- Skip the run test's relaxed-count and dependence scans on PowerPC
  without misaligned vector accesses, where every pair is refused as
  realigned.

 .../vect/vect-alias-check-inplace-run.c       | 311 ++++++++++++++++++
 .../aarch64/vect-alias-check-inplace.c        |  30 ++
 .../vect-alias-check-inplace-realign.c        |  39 +++
 gcc/tree-data-ref.cc                          |  38 ++-
 gcc/tree-data-ref.h                           |   8 +-
 gcc/tree-vect-data-refs.cc                    | 116 +++++++
 6 files changed, 538 insertions(+), 4 deletions(-)
 create mode 100644 gcc/testsuite/gcc.dg/vect/vect-alias-check-inplace-run.c
 create mode 100644 gcc/testsuite/gcc.target/aarch64/vect-alias-check-inplace.c
 create mode 100644 
gcc/testsuite/gcc.target/powerpc/vect-alias-check-inplace-realign.c

diff --git a/gcc/testsuite/gcc.dg/vect/vect-alias-check-inplace-run.c 
b/gcc/testsuite/gcc.dg/vect/vect-alias-check-inplace-run.c
new file mode 100644
index 000000000000..81092719b305
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-alias-check-inplace-run.c
@@ -0,0 +1,311 @@
+/* Each kernel is called with the output aliasing the input and compared
+   against a scalar reference.  */
+
+#include "tree-vect.h"
+
+#define N 64
+
+__attribute__ ((noipa)) float
+read_ahead (float *x, float *y, int n)
+{
+  float s = 0.0f;
+  for (int i = 0; i < n; i++)
+    {
+      x[i] = (float) i;
+      s += y[i] + y[i + 1];
+    }
+  return s;
+}
+
+__attribute__ ((noipa)) float
+store_after_load (float *x, float *y, int n)
+{
+  float s = 0.0f;
+  for (int i = 0; i < n; i++)
+    {
+      x[2 * i] = (float) i;
+      s += y[2 * i] + y[2 * i + 1];
+      x[2 * i + 1] = 2.0f;
+    }
+  return s;
+}
+
+__attribute__ ((noipa)) float
+read_ahead_ref (float *x, float *y, int n)
+{
+  float s = 0.0f;
+#pragma GCC novector
+  for (int i = 0; i < n; i++)
+    {
+      x[i] = (float) i;
+      s += y[i] + y[i + 1];
+    }
+  return s;
+}
+
+__attribute__ ((noipa)) float
+store_after_load_ref (float *x, float *y, int n)
+{
+  float s = 0.0f;
+#pragma GCC novector
+  for (int i = 0; i < n; i++)
+    {
+      x[2 * i] = (float) i;
+      s += y[2 * i] + y[2 * i + 1];
+      x[2 * i + 1] = 2.0f;
+    }
+  return s;
+}
+
+/* Offsets two bytes apart are off the four-byte grid, so each load
+   partially overlaps the store of its own iteration and of the next one.  */
+
+__attribute__ ((noipa)) unsigned
+off_grid_cross (unsigned char *x, unsigned char *y, int n)
+{
+  unsigned s = 0;
+  for (int i = 0; i < n; i++)
+    {
+      unsigned v = i * 0x01010101u;
+      __builtin_memcpy (x + 4 * i + 2, &v, 4);
+      unsigned t;
+      __builtin_memcpy (&t, y + 4 * i + 4, 4);
+      s += t;
+    }
+  return s;
+}
+
+/* Accesses of different sizes, the smaller first, so that only the size
+   check refuses the pair.  The next iteration's short store overlaps this
+   iteration's int load.  */
+
+__attribute__ ((noipa)) unsigned
+mixed_size_cross (unsigned char *x, unsigned char *y, int n)
+{
+  unsigned s = 0;
+  for (int i = 0; i < n; i++)
+    {
+      unsigned short v = i * 3u;
+      __builtin_memcpy (x + 8 * i + 6, &v, 2);
+      unsigned t;
+      __builtin_memcpy (&t, y + 8 * i + 12, 4);
+      s += t;
+    }
+  return s;
+}
+
+__attribute__ ((noipa)) unsigned
+off_grid_cross_ref (unsigned char *x, unsigned char *y, int n)
+{
+  unsigned s = 0;
+#pragma GCC novector
+  for (int i = 0; i < n; i++)
+    {
+      unsigned v = i * 0x01010101u;
+      __builtin_memcpy (x + 4 * i + 2, &v, 4);
+      unsigned t;
+      __builtin_memcpy (&t, y + 4 * i + 4, 4);
+      s += t;
+    }
+  return s;
+}
+
+__attribute__ ((noipa)) unsigned
+mixed_size_cross_ref (unsigned char *x, unsigned char *y, int n)
+{
+  unsigned s = 0;
+#pragma GCC novector
+  for (int i = 0; i < n; i++)
+    {
+      unsigned short v = i * 3u;
+      __builtin_memcpy (x + 8 * i + 6, &v, 2);
+      unsigned t;
+      __builtin_memcpy (&t, y + 8 * i + 12, 4);
+      s += t;
+    }
+  return s;
+}
+
+/* Relaxed for an exact in-place call.  A partial overlap must still take
+   the scalar version.  */
+
+__attribute__ ((noipa)) void
+scale4 (float *out, const float *in, int n)
+{
+  for (int i = 0; i < n; i++, out += 4, in += 4)
+    {
+      out[0] = in[0] * 2.0f;
+      out[1] = in[1] * 3.0f;
+      out[2] = in[2] * 4.0f;
+      out[3] = in[3] * 5.0f;
+    }
+}
+
+__attribute__ ((noipa)) void
+scale4_ref (float *out, const float *in, int n)
+{
+#pragma GCC novector
+  for (int i = 0; i < n; i++, out += 4, in += 4)
+    {
+      out[0] = in[0] * 2.0f;
+      out[1] = in[1] * 3.0f;
+      out[2] = in[2] * 4.0f;
+      out[3] = in[3] * 5.0f;
+    }
+}
+
+/* The same kernel walked backwards, for a negative step.  */
+
+__attribute__ ((noipa)) void
+scale4_down (float *out, const float *in, int n)
+{
+  out += 4 * (n - 1);
+  in += 4 * (n - 1);
+  for (int i = 0; i < n; i++, out -= 4, in -= 4)
+    {
+      out[0] = in[0] * 2.0f;
+      out[1] = in[1] * 3.0f;
+      out[2] = in[2] * 4.0f;
+      out[3] = in[3] * 5.0f;
+    }
+}
+
+__attribute__ ((noipa)) void
+scale4_down_ref (float *out, const float *in, int n)
+{
+  out += 4 * (n - 1);
+  in += 4 * (n - 1);
+#pragma GCC novector
+  for (int i = 0; i < n; i++, out -= 4, in -= 4)
+    {
+      out[0] = in[0] * 2.0f;
+      out[1] = in[1] * 3.0f;
+      out[2] = in[2] * 4.0f;
+      out[3] = in[3] * 5.0f;
+    }
+}
+
+/* Byte channels fit several iterations into one vector, which the float
+   kernels above do not on most targets.  */
+
+__attribute__ ((noipa)) void
+add4 (unsigned char *out, const unsigned char *in, int n)
+{
+  for (int i = 0; i < n; i++, out += 4, in += 4)
+    {
+      out[0] = in[0] + 1;
+      out[1] = in[1] + 2;
+      out[2] = in[2] + 3;
+      out[3] = in[3] + 4;
+    }
+}
+
+__attribute__ ((noipa)) void
+add4_ref (unsigned char *out, const unsigned char *in, int n)
+{
+#pragma GCC novector
+  for (int i = 0; i < n; i++, out += 4, in += 4)
+    {
+      out[0] = in[0] + 1;
+      out[1] = in[1] + 2;
+      out[2] = in[2] + 3;
+      out[3] = in[3] + 4;
+    }
+}
+
+static float f[4 * N + 2], fref[4 * N + 2];
+static unsigned char c[8 * N + 16], cref[8 * N + 16];
+
+/* Give each buffer and its reference copy the same contents.  */
+
+static void
+reset (void)
+{
+  for (int i = 0; i < 4 * N + 2; i++)
+    f[i] = fref[i] = 1.0f + i;
+  for (int i = 0; i < 8 * N + 16; i++)
+    c[i] = cref[i] = i;
+}
+
+/* Abort unless each buffer matches its reference copy.  */
+
+static void
+check (void)
+{
+  if (__builtin_memcmp (f, fref, sizeof f) != 0
+      || __builtin_memcmp (c, cref, sizeof c) != 0)
+    __builtin_abort ();
+}
+
+int
+main (void)
+{
+  check_vect ();
+
+  reset ();
+  if (read_ahead (f, f, N) != read_ahead_ref (fref, fref, N))
+    __builtin_abort ();
+  check ();
+
+  reset ();
+  if (store_after_load (f, f, N) != store_after_load_ref (fref, fref, N))
+    __builtin_abort ();
+  check ();
+
+  /* Exactly in place.  The relaxation applies, and the result must match
+     the reference.  */
+  reset ();
+  scale4 (f, f, N);
+  scale4_ref (fref, fref, N);
+  check ();
+
+  /* Partial overlap off the grid, across iterations.  */
+  reset ();
+  if (off_grid_cross (c, c, N) != off_grid_cross_ref (cref, cref, N))
+    __builtin_abort ();
+  check ();
+
+  /* The same with mismatched access sizes.  */
+  reset ();
+  if (mixed_size_cross (c, c, N) != mixed_size_cross_ref (cref, cref, N))
+    __builtin_abort ();
+  check ();
+
+  /* Negative step, exactly in place.  */
+  reset ();
+  scale4_down (f, f, N);
+  scale4_down_ref (fref, fref, N);
+  check ();
+
+  /* Output one element ahead of the input.  The equality term is false,
+     so the scalar version must run.  */
+  reset ();
+  scale4 (f + 1, f, N - 1);
+  scale4_ref (fref + 1, fref, N - 1);
+  check ();
+
+  /* The byte kernel, exactly in place.  */
+  reset ();
+  add4 (c, c, N);
+  add4_ref (cref, cref, N);
+  check ();
+
+  /* The byte kernel with the output one byte ahead of the input.  */
+  reset ();
+  add4 (c + 1, c, N);
+  add4_ref (cref + 1, cref, N);
+  check ();
+
+  return 0;
+}
+
+/* scale4, scale4_down and add4 are relaxed, and every other kernel is
+   refused.  The memcpy kernels reach the check only where the memcpy folds
+   to a MEM_REF, hence non_strict_align.  PowerPC without misaligned vector
+   accesses realigns the loads across iterations, so it refuses every pair
+   for that reason alone.  */
+/* { dg-final { scan-tree-dump-times "relaxed to permit exact in-place 
aliasing" 3 "vect" { target { { vect_float && vect_int } && { ! { powerpc*-*-* 
&& { ! vect_hw_misalign } } } } } } } */
+/* { dg-final { scan-tree-dump "dependence across iterations" "vect" { target 
{ vect_float && { ! { powerpc*-*-* && { ! vect_hw_misalign } } } } } } } */
+/* { dg-final { scan-tree-dump "dependence distance 0, reordered" "vect" { 
target { vect_float && { ! { powerpc*-*-* && { ! vect_hw_misalign } } } } } } } 
*/
+/* { dg-final { scan-tree-dump "unsigned int> \[^\n\]* and MEM <unsigned int> 
\[^\n\]*may overlap partially" "vect" { target { vect_int && non_strict_align } 
} } } */
+/* { dg-final { scan-tree-dump "unsigned short> \[^\n\]*may overlap partially" 
"vect" { target { vect_int && non_strict_align } } } } */
diff --git a/gcc/testsuite/gcc.target/aarch64/vect-alias-check-inplace.c 
b/gcc/testsuite/gcc.target/aarch64/vect-alias-check-inplace.c
new file mode 100644
index 000000000000..1bd1e8d44663
--- /dev/null
+++ b/gcc/testsuite/gcc.target/aarch64/vect-alias-check-inplace.c
@@ -0,0 +1,30 @@
+/* { dg-do compile } */
+/* { dg-options "-O2 -ftree-vectorize -march=armv8-a -fdump-tree-vect-details" 
} */
+
+/* A RAW pair on plain Advanced SIMD reaches the address-based overlap
+   test, which is false for x == y and so needs the relaxation.  */
+
+float
+fn (float *x, float *y, int n)
+{
+  float s = 0.0f;
+  for (int i = 0; i < n; i++)
+    {
+      x[i] = (float) i;
+      s += y[i];
+    }
+  return s;
+}
+
+/* A WAR pair gets an ordering test, which admits distance zero already.
+   The count below asserts it does not pick up the equality term.  */
+
+void
+fn_war (float *x, const float *y, int n)
+{
+  for (int i = 0; i < n; i++)
+    x[i] = y[i] * 2.0f;
+}
+
+/* { dg-final { scan-tree-dump "using an address-based WAR/WAW test" "vect" } 
} */
+/* { dg-final { scan-tree-dump-times "relaxed to permit exact in-place 
aliasing" 1 "vect" } } */
diff --git 
a/gcc/testsuite/gcc.target/powerpc/vect-alias-check-inplace-realign.c 
b/gcc/testsuite/gcc.target/powerpc/vect-alias-check-inplace-realign.c
new file mode 100644
index 000000000000..cafcfd92f8a4
--- /dev/null
+++ b/gcc/testsuite/gcc.target/powerpc/vect-alias-check-inplace-realign.c
@@ -0,0 +1,39 @@
+/* { dg-do compile } */
+/* { dg-options "-O2 -fno-vect-cost-model -mdejagnu-cpu=power7 
-fdump-tree-vect-details" } */
+/* { dg-require-effective-target powerpc_vsx } */
+
+/* The vectorizer realigns the loads of y, so each vector includes data
+   fetched an iteration earlier, before the store to x.  The pair must
+   not be relaxed for x == y.  */
+
+int
+f (int *x, int *y, int n)
+{
+  int s = 0;
+  for (int i = 0; i < n; i++)
+    {
+      x[i] = i;
+      s += y[i];
+    }
+  return s;
+}
+
+/* With aligned pointers nothing is realigned, and the pair is relaxed.  */
+
+int
+f_aligned (int *x, int *y, int n)
+{
+  x = __builtin_assume_aligned (x, 16);
+  y = __builtin_assume_aligned (y, 16);
+  int s = 0;
+  for (int i = 0; i < n; i++)
+    {
+      x[i] = i;
+      s += y[i];
+    }
+  return s;
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 2 "vect" } } */
+/* { dg-final { scan-tree-dump "load realigned across iterations" "vect" } } */
+/* { dg-final { scan-tree-dump-times "relaxed to permit exact in-place 
aliasing" 1 "vect" } } */
diff --git a/gcc/tree-data-ref.cc b/gcc/tree-data-ref.cc
index edcc146c07de..edd505103f8f 100644
--- a/gcc/tree-data-ref.cc
+++ b/gcc/tree-data-ref.cc
@@ -1831,6 +1831,8 @@ dump_alias_pair (dr_with_seg_len_pair_t *alias_pair, 
const char *indent)
   if (alias_pair->flags == 0)
     dump_printf (MSG_NOTE, " <none>");
   dump_printf (MSG_NOTE, "\n");
+  if (!(alias_pair->flags & DR_ALIAS_INPLACE_UNSAFE))
+    dump_printf (MSG_NOTE, "%sin-place:       safe\n", indent);
 }
 
 /* Merge alias checks recorded in ALIAS_PAIRS and remove redundant ones.
@@ -2079,7 +2081,8 @@ create_ifn_alias_checks (tree *cond_expr,
      (b) the accesses are well-ordered in both the original and new code
         (see the comment above the DR_ALIAS_* flags for details); and
      (c) the DR_STEPs describe all access pairs covered by ALIAS_PAIR.  */
-  if (alias_pair.flags & ~(DR_ALIAS_RAW | DR_ALIAS_WAR | DR_ALIAS_WAW))
+  if (alias_pair.flags & ~(DR_ALIAS_RAW | DR_ALIAS_WAR | DR_ALIAS_WAW
+                          | DR_ALIAS_INPLACE_UNSAFE))
     return false;
 
   /* Make sure that both DRs access the same pattern of bytes,
@@ -2135,6 +2138,32 @@ create_ifn_alias_checks (tree *cond_expr,
   return true;
 }
 
+/* Extend *COND_EXPR, the overlap test for ALIAS_PAIR, to also accept equal
+   base addresses, so that an in-place call takes the vector version.  The
+   IFN and WAR/WAW checks already accept equal addresses, and on SVE2 an
+   equality term would stop the whilerw result from feeding the branch
+   directly.  */
+
+static void
+relax_cond_for_inplace_aliasing (tree *cond_expr,
+                                const dr_with_seg_len_pair_t &alias_pair)
+{
+  if (*cond_expr == boolean_true_node
+      || (alias_pair.flags & DR_ALIAS_INPLACE_UNSAFE))
+    return;
+
+  tree ba = DR_BASE_ADDRESS (alias_pair.first.dr);
+  tree bb = DR_BASE_ADDRESS (alias_pair.second.dr);
+  /* Compare as pointers, like the overlap test itself, which builds its
+     bounds from these same two bases.  */
+  tree base_eq = fold_build2 (EQ_EXPR, boolean_type_node, ba,
+                             fold_convert (TREE_TYPE (ba), bb));
+  *cond_expr = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
+                           base_eq, *cond_expr);
+  if (dump_enabled_p ())
+    dump_printf (MSG_NOTE, "relaxed to permit exact in-place aliasing\n");
+}
+
 /* Try to generate a runtime condition that is true if ALIAS_PAIR is
    free of aliases, using a condition based on index values instead
    of a condition based on addresses.  Return true on success,
@@ -2221,7 +2250,8 @@ create_intersect_range_checks_index (class loop *loop, 
tree *cond_expr,
                           abs_step, &niter_access2))
     return false;
 
-  bool waw_or_war_p = (alias_pair.flags & ~(DR_ALIAS_WAR | DR_ALIAS_WAW)) == 0;
+  bool waw_or_war_p = (alias_pair.flags & ~(DR_ALIAS_WAR | DR_ALIAS_WAW
+                                           | DR_ALIAS_INPLACE_UNSAFE)) == 0;
 
   int found = -1;
   for (unsigned int i = 0; i < DR_NUM_DIMENSIONS (dr_a.dr); i++)
@@ -2427,7 +2457,8 @@ create_waw_or_war_checks (tree *cond_expr,
      (b) the accesses are well-ordered in both the original and new code
         (see the comment above the DR_ALIAS_* flags for details); and
      (c) the DR_STEPs describe all access pairs covered by ALIAS_PAIR.  */
-  if (alias_pair.flags & ~(DR_ALIAS_WAR | DR_ALIAS_WAW))
+  if (alias_pair.flags & ~(DR_ALIAS_WAR | DR_ALIAS_WAW
+                          | DR_ALIAS_INPLACE_UNSAFE))
     return false;
 
   /* Check for equal (but possibly variable) steps.  */
@@ -2720,6 +2751,7 @@ create_intersect_range_checks (class loop *loop, tree 
*cond_expr,
        fold_build2 (cmp_code, boolean_type_node, seg_b_max, seg_a_min));
   if (dump_enabled_p ())
     dump_printf (MSG_NOTE, "using an address-based overlap test\n");
+  relax_cond_for_inplace_aliasing (cond_expr, alias_pair);
 }
 
 /* Create a conditional expression that represents the run-time checks for
diff --git a/gcc/tree-data-ref.h b/gcc/tree-data-ref.h
index af9ad3cdc557..3d13376fffd5 100644
--- a/gcc/tree-data-ref.h
+++ b/gcc/tree-data-ref.h
@@ -266,6 +266,11 @@ public:
        that the flag does not say anything about whether the DR_STEPs
        of the two references in the pair are the same.)
 
+   DR_ALIAS_INPLACE_UNSAFE:
+       There is a pair in P whose new code has not been proved correct
+       for equal DR_BASE_ADDRESSes.  The constructor sets this flag, and
+       a caller clears it after proving every pair in P.
+
    The ordering assumption mentioned above is that for every pair
    (DR_A, DR_B) in P:
 
@@ -304,6 +309,7 @@ const unsigned int DR_ALIAS_ARBITRARY = 1U << 3;
 const unsigned int DR_ALIAS_SWAPPED = 1U << 4;
 const unsigned int DR_ALIAS_UNSWAPPED = 1U << 5;
 const unsigned int DR_ALIAS_MIXED_STEPS = 1U << 6;
+const unsigned int DR_ALIAS_INPLACE_UNSAFE = 1U << 7;
 
 /* This struct contains two dr_with_seg_len objects with aliasing data
    refs.  Two comparisons are generated from them.  */
@@ -326,7 +332,7 @@ public:
 inline dr_with_seg_len_pair_t::
 dr_with_seg_len_pair_t (const dr_with_seg_len &d1, const dr_with_seg_len &d2,
                        sequencing seq)
-  : first (d1), second (d2), flags (0)
+  : first (d1), second (d2), flags (DR_ALIAS_INPLACE_UNSAFE)
 {
   if (DR_IS_READ (d1.dr) && DR_IS_WRITE (d2.dr))
     flags |= DR_ALIAS_WAR;
diff --git a/gcc/tree-vect-data-refs.cc b/gcc/tree-vect-data-refs.cc
index e65059081e71..fc426601e731 100644
--- a/gcc/tree-vect-data-refs.cc
+++ b/gcc/tree-vect-data-refs.cc
@@ -4076,6 +4076,114 @@ vectorizable_with_step_bound_p (dr_vec_info *dr_info_a, 
dr_vec_info *dr_info_b,
   return true;
 }
 
+/* Dump whether the in-place check found DR_INFO_A and DR_INFO_B safe, and
+   REASON, then return SAFE.  */
+
+static bool
+vect_inplace_alias_result (dr_vec_info *dr_info_a, dr_vec_info *dr_info_b,
+                          bool safe, const char *reason)
+{
+  if (dump_enabled_p ())
+    dump_printf_loc (MSG_NOTE, vect_location,
+                    "in-place aliasing %s for %T and %T (%s)\n",
+                    safe ? "safe" : "unsafe", DR_REF (dr_info_a->dr),
+                    DR_REF (dr_info_b->dr), reason);
+
+  return safe;
+}
+
+/* Return true if DR_INFO is a load vectorized with
+   dr_explicit_realign_optimized, which builds each vector partly from a
+   load done in the previous iteration.  The scheme is chosen for the whole
+   group, so ask its first element.  */
+
+static bool
+vect_realigned_load_p (loop_vec_info loop_vinfo, dr_vec_info *dr_info)
+{
+  stmt_vec_info first_stmt_info = DR_GROUP_FIRST_ELEMENT (dr_info->stmt);
+  if (first_stmt_info)
+    dr_info = STMT_VINFO_DR_INFO (first_stmt_info);
+
+  tree vectype = STMT_VINFO_VECTYPE (dr_info->stmt);
+  int misalignment = dr_misalignment (dr_info, vectype);
+  return (vect_supportable_dr_alignment (loop_vinfo, dr_info, vectype,
+                                        misalignment)
+         == dr_explicit_realign_optimized);
+}
+
+/* Return true if accesses DR_INFO_A and DR_INFO_B, which need a runtime
+   alias check, stay correct when their base addresses are equal.
+   PRESERVES_SCALAR_ORDER_P says whether vectorization keeps the two in
+   scalar order.
+
+   The two must have the same size and lie on a common grid of that size.
+   That is, the step and the distance between them are multiples of the
+   size, so that any two of their accesses cover the same bytes or none.
+   Other pairs could overlap partially and are refused.  Pairs on a common
+   grid are safe if they never access the same element, or access it in
+   the same iteration and stay in scalar order.  A load realigned from the
+   previous iteration's vector reads part of its data before the stores of
+   the current iteration, so pairs that include one are refused too.  */
+
+static bool
+vect_inplace_alias_safe_p (loop_vec_info loop_vinfo, dr_vec_info *dr_info_a,
+                          dr_vec_info *dr_info_b,
+                          bool preserves_scalar_order_p)
+{
+  data_reference *dr_a = dr_info_a->dr;
+  data_reference *dr_b = dr_info_b->dr;
+  if (!tree_fits_shwi_p (DR_STEP (dr_a))
+      || !tree_fits_shwi_p (DR_STEP (dr_b))
+      || !tree_fits_shwi_p (DR_INIT (dr_a))
+      || !tree_fits_shwi_p (DR_INIT (dr_b)))
+    return vect_inplace_alias_result (dr_info_a, dr_info_b, false,
+                                     "non-constant step or init");
+
+  HOST_WIDE_INT step = tree_to_shwi (DR_STEP (dr_a));
+  if (step != tree_to_shwi (DR_STEP (dr_b)) || step == 0)
+    return vect_inplace_alias_result (dr_info_a, dr_info_b, false,
+                                     "different or zero steps");
+
+  if (!operand_equal_p (DR_OFFSET (dr_a), DR_OFFSET (dr_b), 0))
+    return vect_inplace_alias_result (dr_info_a, dr_info_b, false,
+                                     "different offsets");
+
+  tree size_a = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_a)));
+  tree size_b = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr_b)));
+  /* The difference of the two inits can overflow a HOST_WIDE_INT.  */
+  offset_int init_distance
+    = wi::to_offset (DR_INIT (dr_a)) - wi::to_offset (DR_INIT (dr_b));
+  if (!tree_fits_shwi_p (size_a)
+      || !tree_int_cst_equal (size_a, size_b)
+      || tree_to_shwi (size_a) == 0
+      || step % tree_to_shwi (size_a) != 0
+      || init_distance % tree_to_shwi (size_a) != 0)
+    return vect_inplace_alias_result (dr_info_a, dr_info_b, false,
+                                     "accesses may overlap partially");
+
+  if (vect_realigned_load_p (loop_vinfo, dr_info_a)
+      || vect_realigned_load_p (loop_vinfo, dr_info_b))
+    return vect_inplace_alias_result (dr_info_a, dr_info_b, false,
+                                     "load realigned across iterations");
+
+  if (init_distance == 0)
+    {
+      if (!preserves_scalar_order_p)
+       return vect_inplace_alias_result (dr_info_a, dr_info_b, false,
+                                         "dependence distance 0, reordered");
+
+      return vect_inplace_alias_result (dr_info_a, dr_info_b, true,
+                                       "dependence distance 0, order kept");
+    }
+
+  if (init_distance % step == 0)
+    return vect_inplace_alias_result (dr_info_a, dr_info_b, false,
+                                     "dependence across iterations");
+
+  return vect_inplace_alias_result (dr_info_a, dr_info_b, true,
+                                   "no dependence");
+}
+
 /* Function vect_prune_runtime_alias_test_list.
 
    Prune a list of ddrs to be tested at run-time by versioning for alias.
@@ -4217,6 +4325,12 @@ vect_prune_runtime_alias_test_list (loop_vec_info 
loop_vinfo)
          continue;
        }
 
+      /* The in-place check needs the individual accesses, so do it before
+        DR_INFO_A and DR_INFO_B are replaced by their group leaders.  */
+      bool inplace_safe
+       = vect_inplace_alias_safe_p (loop_vinfo, dr_info_a, dr_info_b,
+                                    preserves_scalar_order_p);
+
       stmt_vec_info dr_group_first_a = DR_GROUP_FIRST_ELEMENT (stmt_info_a);
       if (dr_group_first_a)
        {
@@ -4316,6 +4430,8 @@ vect_prune_runtime_alias_test_list (loop_vec_info 
loop_vinfo)
        (dr_a, dr_b, (preserves_scalar_order_p
                      ? dr_with_seg_len_pair_t::WELL_ORDERED
                      : dr_with_seg_len_pair_t::REORDERED));
+      if (inplace_safe)
+       dr_with_seg_len_pair.flags &= ~DR_ALIAS_INPLACE_UNSAFE;
 
       comp_alias_ddrs.safe_push (dr_with_seg_len_pair);
     }
-- 
2.55.0

Reply via email to