https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128744

            Bug ID: 128744
           Summary: wrong code at -O3: unroll-and-jam ignores a self
                    output dependence with distance (1,-1) since r8-5159
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jeffchen006 at gmail dot com
  Target Milestone: ---
            Target: x86_64-pc-linux-gnu

#include <cstdio>
int a[20], b[48];
int main() {
  for (int i = 0; i < 4; i++)
    for (int j = 0; j < 20; j++) {
      a[j]++;
      b[2 * i + 2 * j] = i;
    }
  printf("%d\n", b[2]);
}

$ g++ -O0 t.cpp && ./a.out
1
$ g++ -O3 t.cpp && ./a.out
0

-O3 fails; -O1/-O2 with -floop-unroll-and-jam also fail; -O3
-fno-loop-unroll-and-jam gives 1.

Expected 1: b[2] is written at (i,j) = (0,1) with 0 and later at (1,0) with 1.

-fopt-info: "applying unroll and jam with factor 2". The unrolljam dump has the
right distance vector for the self pair of b[_4] = i_20:

  dist_vector = (1 -1 )

After unrolling the outer loop by 2 and jamming, (1,0) runs in the same jammed
iteration as (0,0), before (0,1), so the older store wins.

Cause: tree_loop_unroll_and_jam (gimple-loop-jam.cc):

  if (dra == drb)
    {
      if (DR_IS_WRITE (dra)
          && !DR_ACCESS_FNS (dra).is_empty ()
          && DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
        { unroll_factor = 0; break; }
      else
        continue;
    }

A self write DDR with known distance vectors never reaches
adjust_unroll_factor, so the (1,-1) distance (which becomes (0,-1) after
jamming) is ignored. r13-3133-g3ec926d36fb only added the chrec_dont_know case.
a[j]++ (distance (1,0)) only makes the transformation happen.

The same test also fails with -O2 -floop-interchange (interchange has the same
gap for self dependences, PR128648). Outer-loop vectorization skips dra == drb
in the same way (PR128649).

-O0 -fsanitize=undefined,address is clean.

gcc -Wall -Wextra gives no warnings. -fno-strict-aliasing -fwrapv does not
change the output.

Possible fix: One possible fix is to send a self dependence of a write (dra ==
drb, DR_IS_WRITE) that has distance vectors to adjust_unroll_factor like the
other pairs, instead of skipping it with `continue`; the (1,-1) distance then
stops the transformation. A minimal guard would be to set unroll_factor = 0 for
a self write DDR with any non-zero distance vector.

gcc version 17.0.0 20261114 (experimental), r17-6275-gfceddda853f,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release
  • [Bug tree-optimization/128744] N... jeffchen006 at gmail dot com via Gcc-bugs

Reply via email to