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

            Bug ID: 129106
           Summary: [14/15/16/17 Regression] wrong code at -O3: vector
                    loop bound is 0 for 256 iterations of an unsigned char
                    counter
           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: hhhuang at smu dot edu.sg
  Target Milestone: ---

Compiler Explorer: https://godbolt.org/z/KjjGj5G3r

Note:
- works: 13.4
- fails: 14.1 to trunk (bc49f1e37014, 20261127) at -O3 -mgeneral-regs-only
- riscv64, i686, s390x and powerpc fail at plain -O3 (16.2 and trunk)
- x86_64: only when hi == 0 (256 iterations) and a is 8-byte aligned
- -fno-tree-loop-vectorize or --param vect-max-peeling-for-alignment=0 hides it
- not bisected

$ gcc-17 -v
Using built-in specs.
COLLECT_GCC=gcc-17
Target: x86_64-pc-linux-gnu
Configured with: ../gcc-17-20261127/configure --prefix=/w/out/gcc-trunk
--program-suffix=-17 --enable-languages=c --disable-bootstrap
--disable-multilib --disable-nls --disable-libsanitizer --enable-multiarch
Thread model: posix
Supported LTO compression algorithms: zlib
gcc version 17.0.0 20261127 (experimental) (GCC)
$ gcc-17 -O3 -mgeneral-regs-only t.c && ./a.out
Aborted (core dumped)
$ gcc-17 -O3 -mgeneral-regs-only -fno-tree-loop-vectorize t.c && ./a.out
$ gcc-17 -O2 -mgeneral-regs-only t.c && ./a.out
$ cat t.c
unsigned char b[4096];

__attribute__((noipa)) void
f (unsigned char *a, unsigned char hi)
{
  unsigned char i = 0;
  do
    *a++ ^= 1;
  while (++i != hi);
}

int
main (void)
{
  f (b, 0);                     /* 256 iterations: b[0] .. b[255] */
  for (int j = 0; j < 4096; j++)
    if (b[j] != (j < 256))
      __builtin_abort ();
  return 0;
}

f should change b[0] .. b[255].
With these flags trunk changes b[0] .. b[2047], 16.2 only b[0] .. b[7].
No warnings with -Wall -Wextra; -fsanitize=address,undefined is clean (16.2).
Same with -fno-strict-aliasing -fwrapv -fno-aggressive-loop-optimizations.

$ gcc-17 -O3 -mgeneral-regs-only -fdump-tree-vect-details -fdump-tree-vrp2 t.c
$ grep -h 'niters.9_30 = ' *.vect
Global Exported: niters.9_30 = [irange] unsigned char [8, +INF]
  niters.9_30 = hi_11(D) - prolog_loop_niters.8_12;
$ grep -hE 'bnd.10_48 = |_50 = |_167 = ' *.vrp2
  _167 = niters.9_30 >> 3;
  _50 = _167 + 255;
  bnd.10_48 = _50 + 1;

niters.9_30 is 0 here (256 in unsigned char).
That is outside the range [8, +INF] which vect_do_peeling sets on it.
With that range ((niters - 8) >> 3) + 1, which is 32, becomes niters >> 3 = 0.

Reply via email to