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

            Bug ID: 129044
           Summary: [niter] wrong code at -O3: number_of_iterations_cltz
                    ignores that the exit is not tested on every
                    iteration, so cunroll forces a bit-test exit that is
                    never taken
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: 0599jiangyc at gmail dot com
  Target Milestone: ---

The following code:

```c
/* GCC trunk: wrong code at -O3 (also -O2 -fpeel-loops, -O2 -funroll-loops);
correct at -O0, -O1, -O2,
 * GCC 11.4 -O3, clang -O3.
 * number_of_iterations_cltz derives "exit after at most 7 iterations" for the
(x & 1) exit although
 * that exit is not executed on every iteration (skipped at i == 7) and a bit
test is not monotone;
 * cunroll then forces the exit in the last unrolled copy.
 * Godbolt: x86-64 gcc (trunk), flags: -O3
 * EXPECTED: prints 1, exit 0.   BUGGY: prints -1, exit 1.
 */
#include <stdio.h>

__attribute__((noinline)) int f(unsigned char x) {
  x |= 0x80;
  for (int i = 0; i < 10; i++) {
    if (i != 7 && (x & 1))   /* bit 0 of x >> i is set only at i == 7, where
the test is skipped */
      return -1;
    x >>= 1;
  }
  return 1;
}

int main(void) {
  volatile unsigned char v = 0;
  int r = f(v);
  printf("%d\n", r);
  return r != 1;
}
```

Resulted in this output:
```
$ gcc -O3 repro.c && ./a.out        (also -O2 -fpeel-loops, -O2 -funroll-loops)
-1
(exit 1; gcc -O0/-O1/-O2, GCC 11.4 -O3 and clang -O3 print 1)
```

Trunk: https://godbolt.org/z/1dd8vhEoe (x86-64 gcc trunk, -O3, executed;
reproduces as of 2026-11-12)

Reply via email to