From: Philipp Tomsich <[email protected]>

A memcpy of a small FP array, such as 4 floats, is folded to a wide
integer load/store pair (unsigned __int128 for 16 bytes), and FRE turns
the element reads into BIT_FIELD_REF extractions of that value. On
targets without a vector type for the wide integer, any loop containing
it then fails to vectorize with "no vectype for stmt".

Split such a load when its only uses are BIT_FIELD_REF extractions of
one type, each covering exactly one lane, and copy stores of the whole
value. Without a copy store, every lane must be read. The load becomes a
load of each lane, aligned as the wide access implies at its offset, and
each copy store a store of every lane, which the vectorizer can group.

Only loads of integers wider than a word are considered, to keep the
check off the hot path of ordinary integer loads. Lanes must be at least
32 bits wide, since narrower lanes cost more than the split gains. Loads
and copy stores that are volatile, in reverse storage order, or can
throw internally are left alone. If the mode of the extraction type
cannot transfer every bit pattern, as for floats under x87 math, the
lanes are loaded and stored as unsigned integers and the extractions
reinterpret them.

The wide load is not diagnosed as uninitialized if any of its bytes were
written, but a lane load of an unwritten lane can be. So only memory
that the caller provides is split, since the uninitialized-use analysis
takes it as written: the address must be computed from parameters by
pointer arithmetic and PHIs only, none of them declared not to be read
through, and no clobber may write the loaded memory. The split waits for
IPA inlining, which can turn a parameter into the address of a local of
the caller.

Motivating case: the LogOpCPU renderers of SPEC CPU 2026 736.ocio_r,
where at -Ofast the per-pixel memcpy (out, in, 16) blocked vectorization
of the exp2f kernels to _ZGVnN4v_exp2f AdvSIMD math clones.

Bootstrapped and regtested on AArch64 and x86-64.

gcc/ChangeLog:

        * tree-ssa-forwprop.cc (clobber_walker): New function.
        (ref_reads_caller_memory_p): New function.
        (optimize_scalar_wide_load): New function.
        (pass_forwprop::execute): Call optimize_scalar_wide_load.

gcc/testsuite/ChangeLog:

        * g++.dg/tree-ssa/forwprop-wide-load-uninit.C: New test.
        * gcc.dg/tree-ssa/forwprop-wide-load-align.c: New test.
        * gcc.dg/tree-ssa/forwprop-wide-load-uninit.c: New test.
        * gcc.dg/tree-ssa/forwprop-wide-load.c: New test.

Co-authored-by: Konstantinos Eleftheriou <[email protected]>
---
 .../tree-ssa/forwprop-wide-load-uninit.C      |  35 ++
 .../tree-ssa/forwprop-wide-load-align.c       |  32 ++
 .../tree-ssa/forwprop-wide-load-uninit.c      |  30 ++
 .../gcc.dg/tree-ssa/forwprop-wide-load.c      |  41 +++
 gcc/tree-ssa-forwprop.cc                      | 328 +++++++++++++++++-
 5 files changed, 465 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/g++.dg/tree-ssa/forwprop-wide-load-uninit.C
 create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load-align.c
 create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load-uninit.c
 create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load.c

diff --git a/gcc/testsuite/g++.dg/tree-ssa/forwprop-wide-load-uninit.C 
b/gcc/testsuite/g++.dg/tree-ssa/forwprop-wide-load-uninit.C
new file mode 100644
index 000000000000..716953790276
--- /dev/null
+++ b/gcc/testsuite/g++.dg/tree-ssa/forwprop-wide-load-uninit.C
@@ -0,0 +1,35 @@
+// { dg-do compile }
+// { dg-options "-O2 -Wall" }
+
+// Bytes that were never written may be copied, also out of an object
+// whose lifetime starts in a constructor.
+
+struct V
+{
+  float f[4];
+  V (float x) { f[0] = x; f[3] = x; }
+};
+
+float
+from_new (float *out, float x)
+{
+  V *p = new V (x);
+  __builtin_memcpy (out, p->f, 16); // { dg-bogus "uninitialized" }
+  float r = out[0] + out[3];
+  delete p;
+  return r;
+}
+
+struct W
+{
+  float f[4];
+  W (float *out, float x);
+};
+
+W::W (float *out, float x)
+{
+  f[0] = x;
+  f[3] = x;
+  __builtin_memcpy (out, f, 16); // { dg-bogus "uninitialized" }
+  out[0] += out[3];
+}
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load-align.c 
b/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load-align.c
new file mode 100644
index 000000000000..81d3533c023e
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load-align.c
@@ -0,0 +1,32 @@
+/* { dg-do compile { target int128 } } */
+/* { dg-options "-O2 -fdump-tree-forwprop2-gimple" } */
+
+/* A lane has the alignment that the wide access implies at its offset.  */
+
+typedef unsigned __int128 u128 __attribute__ ((aligned (16)));
+typedef unsigned __int128 u128u __attribute__ ((aligned (1)));
+
+/* Under-aligned load.  */
+float
+load_lanes (const u128u *p)
+{
+  u128u v = *p;
+  float f[4];
+  __builtin_memcpy (f, &v, 16);
+  return f[0] + f[1] + f[2] + f[3];
+}
+
+/* Aligned load, under-aligned store.  */
+float
+store_lanes (u128u *q, const u128 *p)
+{
+  union { u128 v; float f[4]; } u;
+  u.v = *p;
+  *q = u.v;
+  return u.f[0] + u.f[3];
+}
+
+/* { dg-final { scan-tree-dump-times "__MEM <float, 8>" 8 "forwprop2" } } */
+/* { dg-final { scan-tree-dump-times "__MEM <float> " 2 "forwprop2" } } */
+/* { dg-final { scan-tree-dump-times "__MEM <float, 64>" 1 "forwprop2" } } */
+/* { dg-final { scan-tree-dump-times "__MEM <float, 128>" 1 "forwprop2" } } */
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load-uninit.c 
b/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load-uninit.c
new file mode 100644
index 000000000000..9313e0d57d01
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load-uninit.c
@@ -0,0 +1,30 @@
+/* { dg-do compile } */
+/* { dg-options "-O2 -Wall" } */
+
+/* A copy may include bytes that were never written.  Splitting such a copy
+   into lanes must not turn a lane that is never written into a diagnosed
+   read.  */
+
+/* Lanes 1 and 2 are never written.  */
+float
+middle_unwritten (float *out, float x)
+{
+  float a[4];
+  a[0] = x;
+  a[3] = x;
+  __builtin_memcpy (out, a, 16); /* { dg-bogus "uninitialized" } */
+  return out[0] + out[3];
+}
+
+/* Memory the function allocates itself.  */
+float
+heap (float *out, float x)
+{
+  float *p = __builtin_malloc (16);
+  p[0] = x;
+  p[3] = x;
+  __builtin_memcpy (out, p, 16); /* { dg-bogus "uninitialized" } */
+  float r = out[0] + out[3];
+  __builtin_free (p);
+  return r;
+}
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load.c 
b/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load.c
new file mode 100644
index 000000000000..d2c4a0d10a56
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/forwprop-wide-load.c
@@ -0,0 +1,41 @@
+/* { dg-do run { target int128 } } */
+/* { dg-options "-O2 -fdump-tree-forwprop2" } */
+
+/* FRE reads the floats of the union as BIT_FIELD_REFs of the 128-bit
+   integer.  Forwprop splits the load of the integer and its copy into
+   float lanes, but leaves a value that is neither copied nor read in every
+   lane alone.  */
+
+typedef unsigned __int128 u128;
+
+float __attribute__ ((noipa))
+copy_lanes (u128 *out, const u128 *in)
+{
+  union { u128 v; float f[4]; } u;
+  u.v = *in;
+  *out = u.v;
+  return u.f[0] - u.f[3];
+}
+
+/* Lanes 1 and 2 are not read.  */
+float
+some_lanes (const u128 *in)
+{
+  union { u128 v; float f[4]; } u;
+  u.v = *in;
+  return u.f[0] - u.f[3];
+}
+
+int
+main (void)
+{
+  float lanes[4] = { 1.0f, 2.0f, 4.0f, 8.0f };
+  u128 src, dst;
+  __builtin_memcpy (&src, lanes, sizeof src);
+  if (copy_lanes (&dst, &src) != -7.0f || dst != src)
+    __builtin_abort ();
+  return 0;
+}
+
+/* { dg-final { scan-tree-dump-times "BIT_FIELD_REF" 2 "forwprop2" } } */
+/* { dg-final { scan-tree-dump-times "MEM <float>" 8 "forwprop2" } } */
diff --git a/gcc/tree-ssa-forwprop.cc b/gcc/tree-ssa-forwprop.cc
index 88f69e12ed19..fce798927e53 100644
--- a/gcc/tree-ssa-forwprop.cc
+++ b/gcc/tree-ssa-forwprop.cc
@@ -44,6 +44,7 @@ along with GCC; see the file COPYING3.  If not see
 #include "tree-ssa-dom.h"
 #include "tree-ssa-strlen.h"
 #include "builtins.h"
+#include "attribs.h"
 #include "tree-cfgcleanup.h"
 #include "cfganal.h"
 #include "optabs-tree.h"
@@ -5956,6 +5957,321 @@ optimize_vector_load (gimple_stmt_iterator *gsi)
   gsi_remove (gsi, true);
 }
 
+/* Callback for walk_aliased_vdefs.  Stop at a clobber and set *DATA.  */
+
+static bool
+clobber_walker (ao_ref *, tree vdef, void *data)
+{
+  if (!gimple_clobber_p (SSA_NAME_DEF_STMT (vdef)))
+    return false;
+
+  *(bool *) data = true;
+  return true;
+}
+
+/* Return true if REF, a MEM_REF read at STMT, reads memory that the caller
+   provides, which the uninitialized-use analysis in tree-ssa-uninit.cc never
+   diagnoses.  Once its walk reaches the function entry, that analysis takes
+   the memory a parameter points to as written by the caller, unless the
+   parameter is declared not to be read through.  So the address of REF must
+   be computed from such parameters by pointer arithmetic and PHIs only.
+   Also, no clobber may write REF, since a clobber can end that walk before
+   it reaches the function entry.  */
+
+static bool
+ref_reads_caller_memory_p (gimple *stmt, tree ref)
+{
+  auto_vec<tree, 8> worklist;
+  auto_bitmap visited;
+  unsigned limit = param_ssa_name_def_chain_limit;
+  worklist.safe_push (TREE_OPERAND (ref, 0));
+  while (!worklist.is_empty ())
+    {
+      tree ptr = worklist.pop ();
+      if (TREE_CODE (ptr) == ADDR_EXPR)
+       {
+         tree base = get_base_address (TREE_OPERAND (ptr, 0));
+         if (TREE_CODE (base) != MEM_REF)
+           return false;
+
+         ptr = TREE_OPERAND (base, 0);
+       }
+
+      if (TREE_CODE (ptr) != SSA_NAME)
+       return false;
+
+      if (!bitmap_set_bit (visited, SSA_NAME_VERSION (ptr)))
+       continue;
+
+      if (limit-- == 0)
+       return false;
+
+      tree var = SSA_NAME_VAR (ptr);
+      if (var && TREE_CODE (var) == PARM_DECL)
+       {
+         if (lookup_attribute ("clobber *this", DECL_ATTRIBUTES (var)))
+           return false;
+
+         rdwr_map rdwr_idx;
+         attr_access *access = get_parm_access (rdwr_idx, var);
+         if (access
+             && (access->mode == access_none
+                 || access->mode == access_write_only))
+           return false;
+
+         if (SSA_NAME_IS_DEFAULT_DEF (ptr))
+           continue;
+       }
+
+      gimple *def_stmt = SSA_NAME_DEF_STMT (ptr);
+      if (gphi *phi = dyn_cast <gphi *> (def_stmt))
+       {
+         for (unsigned i = 0; i < gimple_phi_num_args (phi); ++i)
+           worklist.safe_push (gimple_phi_arg_def (phi, i));
+         continue;
+       }
+
+      if (!is_gimple_assign (def_stmt))
+       return false;
+
+      tree_code code = gimple_assign_rhs_code (def_stmt);
+      tree rhs1 = gimple_assign_rhs1 (def_stmt);
+      if ((code != ADDR_EXPR
+          && code != POINTER_PLUS_EXPR
+          && code != SSA_NAME
+          && !CONVERT_EXPR_CODE_P (code))
+         || !POINTER_TYPE_P (TREE_TYPE (rhs1)))
+       return false;
+
+      worklist.safe_push (rhs1);
+    }
+
+  ao_ref aor;
+  ao_ref_init (&aor, ref);
+  bool clobbered = false;
+  return (walk_aliased_vdefs (&aor, gimple_vuse (stmt), clobber_walker,
+                             &clobbered, NULL, NULL,
+                             param_sccvn_max_alias_queries_per_access) >= 0
+         && !clobbered);
+}
+
+/* STMT at *GSI is a non-volatile load of an integer wider than a word, such
+   as the 128-bit load that a memcpy of four floats becomes, from a plain
+   MEM_REF that cannot throw internally and is not in reverse storage order.
+   If the value is only read through lane extractions of one type or copied
+   whole to memory, and is copied or read in every lane, split the load and
+   the copies into lanes: a wide integer without a vector type blocks loop
+   vectorization, while the lanes can be grouped.  */
+
+static void
+optimize_scalar_wide_load (gimple_stmt_iterator *gsi, function *fun)
+{
+  gimple *stmt = gsi_stmt (*gsi);
+  tree lhs = gimple_assign_lhs (stmt);
+  tree rhs = gimple_assign_rhs1 (stmt);
+  unsigned HOST_WIDE_INT load_bits = tree_to_uhwi (TYPE_SIZE (TREE_TYPE 
(lhs)));
+
+  /* Collect the BIT_FIELD_REF extractions with the lanes they read, and the
+     copy stores.  Give up on any other use, since the wide value is needed
+     then anyway.  All extractions must read the same type, whose size evenly
+     divides the load.  */
+  use_operand_p use_p;
+  imm_use_iterator iter;
+  auto_vec<gimple *, 8> bf_stmts;
+  auto_vec<gimple *, 4> store_stmts;
+  auto_bitmap read_lanes;
+  tree etype = NULL_TREE;
+  unsigned HOST_WIDE_INT esize = 0;
+  FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
+    {
+      gimple *use_stmt = USE_STMT (use_p);
+      if (is_gimple_debug (use_stmt))
+       continue;
+
+      if (is_gimple_assign (use_stmt)
+         && gimple_assign_rhs_code (use_stmt) == BIT_FIELD_REF)
+       {
+         tree bfr = gimple_assign_rhs1 (use_stmt);
+         tree bf_type = TREE_TYPE (bfr);
+         unsigned HOST_WIDE_INT size, pos;
+         if (TREE_OPERAND (bfr, 0) == lhs
+             && !VECTOR_TYPE_P (bf_type)
+             && TYPE_MODE (bf_type) != BLKmode
+             && bit_field_size (bfr).is_constant (&size)
+             && size % BITS_PER_UNIT == 0
+             /* Each lane is a separate access, and narrower lanes cost
+                more than the split gains.  */
+             && size >= 32
+             && size < load_bits
+             && load_bits % size == 0
+             && bit_field_offset (bfr).is_constant (&pos)
+             /* The extraction must cover exactly one lane.  */
+             && pos % size == 0
+             && (!etype || types_compatible_p (etype, bf_type)))
+           {
+             if (!etype)
+               {
+                 esize = size;
+                 etype = bf_type;
+               }
+
+             bitmap_set_bit (read_lanes, pos / size);
+             bf_stmts.safe_push (use_stmt);
+             continue;
+           }
+       }
+      /* A copy store of the whole value.  The lane stores of a store that
+        can throw internally would each need their own block and exception
+        edge.  */
+      else if (gimple_store_p (use_stmt)
+              && is_gimple_assign (use_stmt)
+              && gimple_assign_rhs1 (use_stmt) == lhs
+              && TREE_CODE (gimple_assign_lhs (use_stmt)) == MEM_REF
+              && !REF_REVERSE_STORAGE_ORDER (gimple_assign_lhs (use_stmt))
+              && !gimple_has_volatile_ops (use_stmt)
+              && !stmt_can_throw_internal (fun, use_stmt))
+       {
+         store_stmts.safe_push (use_stmt);
+         continue;
+       }
+
+      gsi_next (gsi);
+      return;
+    }
+
+  if (bf_stmts.is_empty ())
+    {
+      gsi_next (gsi);
+      return;
+    }
+
+  unsigned nlanes = load_bits / esize;
+  unsigned HOST_WIDE_INT ebytes = esize / BITS_PER_UNIT;
+
+  /* Without a copy store, which needs every lane, split only a value that is
+     read in every lane.  Basic-block vectorization can treat the wide value
+     as a vector, but cannot load an incomplete set of lanes as one.  */
+  if (store_stmts.is_empty () && bitmap_count_bits (read_lanes) != nlanes)
+    {
+      gsi_next (gsi);
+      return;
+    }
+
+  machine_mode emode = TYPE_MODE (etype);
+  /* Load and store the lanes in ETYPE, so that the vectorizer can group the
+     lane stores with other stores of that type, unless a value of ETYPE may
+     not keep its bits through a register.  Then load and store them as
+     unsigned integers of the same size.  */
+  tree ltype = etype;
+  if (!mode_can_transfer_bits (emode))
+    {
+      ltype = bitwise_type_for_mode (emode);
+      if (!ltype)
+       {
+         gsi_next (gsi);
+         return;
+       }
+    }
+
+  /* A load of the whole value from partly written memory is not diagnosed
+     as uninitialized, while a lane load of the unwritten part can be, unless
+     the caller provides the memory.  */
+  if (!ref_reads_caller_memory_p (stmt, rhs))
+    {
+      gsi_next (gsi);
+      return;
+    }
+
+  /* Return a reference of type LTYPE to lane LANE of the wide access MEM,
+     in the address space of MEM, with the alignment that MEM implies at the
+     offset of the lane and with its restrict dependence information and
+     location.  */
+  auto lane_ref = [&] (tree mem, unsigned lane)
+    {
+      tree ref_type = ltype;
+      addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (mem));
+      if (!ADDR_SPACE_GENERIC_P (as))
+       ref_type = build_qualified_type (ref_type,
+                                        (TYPE_QUALS (ref_type)
+                                         | ENCODE_QUAL_ADDR_SPACE (as)));
+      unsigned int align;
+      unsigned HOST_WIDE_INT misalign;
+      get_object_alignment_1 (mem, &align, &misalign);
+      align = least_bit_hwi (align | (misalign + lane * esize));
+      if (align != TYPE_ALIGN (ref_type))
+       ref_type = build_aligned_type (ref_type, align);
+      tree off = TREE_OPERAND (mem, 1);
+      tree ref = build2_loc (EXPR_LOCATION (mem), MEM_REF, ref_type,
+                            TREE_OPERAND (mem, 0),
+                            wide_int_to_tree (TREE_TYPE (off),
+                                              wi::to_wide (off)
+                                              + lane * ebytes));
+      MR_DEPENDENCE_CLIQUE (ref) = MR_DEPENDENCE_CLIQUE (mem);
+      MR_DEPENDENCE_BASE (ref) = MR_DEPENDENCE_BASE (mem);
+      return ref;
+    };
+
+  /* Load every lane, at the original load's position and with its VUSE, so
+     all lanes observe the same memory state.  The lane loads and stores stay
+     in the exception region of the access they replace, which needs no new
+     edges: neither the load nor a copy store can throw internally.  */
+  auto_vec<tree, 4> lane_defs (nlanes);
+  for (unsigned lane = 0; lane < nlanes; ++lane)
+    {
+      tree def = make_ssa_name (ltype);
+      gimple *ld = gimple_build_assign (def, lane_ref (rhs, lane));
+      gimple_set_location (ld, gimple_location (stmt));
+      gimple_set_vuse (ld, gimple_vuse (stmt));
+      maybe_duplicate_eh_stmt (ld, stmt);
+      gsi_insert_before (gsi, ld, GSI_SAME_STMT);
+      lane_defs.quick_push (def);
+    }
+
+  /* Rewrite each extraction into the matching lane, reinterpreted as ETYPE.
+     On either endianness, the position of a byte-aligned BIT_FIELD_REF is
+     the offset of the field within the value as laid out in memory.  */
+  for (gimple *use_stmt : bf_stmts)
+    {
+      tree bfr = gimple_assign_rhs1 (use_stmt);
+      unsigned lane = bit_field_offset (bfr).to_constant () / esize;
+      tree val = lane_defs[lane];
+      if (!useless_type_conversion_p (etype, ltype))
+       val = build1 (VIEW_CONVERT_EXPR, etype, val);
+      gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
+      gimple_assign_set_rhs_from_tree (&gsi2, val);
+      update_stmt (gsi_stmt (gsi2));
+    }
+
+  /* Split each copy store: store every lane but the last before it, chaining
+     the virtual operands, and turn it into the store of the last lane.  */
+  for (gimple *use_stmt : store_stmts)
+    {
+      tree dst = gimple_assign_lhs (use_stmt);
+      gimple_stmt_iterator sgsi = gsi_for_stmt (use_stmt);
+      for (unsigned lane = 0; lane < nlanes - 1; ++lane)
+       {
+         gimple *st = gimple_build_assign (lane_ref (dst, lane),
+                                           lane_defs[lane]);
+         gimple_set_location (st, gimple_location (use_stmt));
+         maybe_duplicate_eh_stmt (st, use_stmt);
+         gimple_set_vuse (st, gimple_vuse (use_stmt));
+         gimple_set_vdef (st, make_ssa_name (gimple_vop (fun), st));
+         gimple_set_vuse (use_stmt, gimple_vdef (st));
+         gsi_insert_before (&sgsi, st, GSI_SAME_STMT);
+       }
+
+      gimple_assign_set_lhs (use_stmt, lane_ref (dst, nlanes - 1));
+      gimple_assign_set_rhs1 (use_stmt, lane_defs[nlanes - 1]);
+      update_stmt (use_stmt);
+    }
+
+  /* Only debug binds still use the wide value.  Reset them and remove the
+     now dead load.  */
+  reset_debug_uses (stmt);
+  release_defs (stmt);
+  gsi_remove (gsi, true);
+}
+
 
 /* Primitive "lattice" function for gimple_simplify.  */
 
@@ -6953,7 +7269,17 @@ pass_forwprop::execute (function *fun)
                   && !stmt_can_throw_internal (fun, stmt)
                   && (!VAR_P (rhs) || !DECL_HARD_REGISTER (rhs)))
            optimize_vector_load (&gsi);
-
+         else if (code == MEM_REF
+                  && INTEGRAL_TYPE_P (TREE_TYPE (lhs))
+                  && (TYPE_PRECISION (TREE_TYPE (lhs))
+                      > (unsigned) BITS_PER_WORD)
+                  && !gimple_has_volatile_ops (stmt)
+                  && !REF_REVERSE_STORAGE_ORDER (rhs)
+                  && !stmt_can_throw_internal (fun, stmt)
+                  /* IPA inlining can turn a parameter into the address
+                     of a local of the caller.  */
+                  && fun->after_inlining)
+           optimize_scalar_wide_load (&gsi, fun);
          else if (code == COMPLEX_EXPR)
            {
              /* Rewrite stores of a single-use complex build expression
-- 
2.55.0

Reply via email to