https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129124
Bug ID: 129124
Summary: [16/17 Regression] wrong code at -Os (and -O2/-O3 in
larger programs): ivopts folds (signed char)(p + 16) -
(signed char)p to 16, ignoring the wrap of the
conversion
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: haoxintu at gmail dot com
Target Milestone: ---
Created attachment 66319
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=66319&action=edit
repro-creduce.c that miscompiles at -O2/-O3/-Os in trunk version
Hi,
$cat repro.c
__attribute__((noinline)) short f(signed char p)
{
short a[24];
short c = 0;
for (int i = 0; i < 24; i++)
a[i] = 0;
for (int i = 0; i < 24; i++) {
c = (signed char)(p + 16) - (signed char)p;
c = a[i] != 254 ? i * c : 7;
}
return c;
}
int main(void)
{
/* (signed char)(127 + 16) - 127 == -113 - 127 == -240, and 23 * -240 ==
-5520 */
if (f(127) != -5520)
__builtin_abort();
return 0;
}
```
```
$ gcc -O0 repro.c && ./a.out # ok, also -O1, -O2, -O3
$ gcc -Os repro.c && ./a.out
Aborted
```
(p + 16 is computed in int; converting 143 to signed char is
implementation-defined and GCC gives -113.) For p = 112..127, where (signed
char)(p + 16) wraps, the -Os code returns 23 * 16 = 368 instead of 23 * (p -
256 + 16 - p) = -5520. The optimized dump of f is
```
_6 = (unsigned char) ivtmp.9_31;
_28 = _6 w* 16;
c_10 = (short int) _28;
return c_10;
```
The constant 16 appears in ivopts: it rewrites `c = i * d` with `d =
(short)(signed char)((unsigned char)p + 16) - (short)p` as `(unsigned short)
ivtmp * 16`, so the affine expansion of d treats the narrowing conversion to
signed char as if it could not wrap. Each of `-fno-ivopts`, `-fno-tree-pre`,
`-fno-tree-ch`, `-fno-tree-loop-im` and `-fno-tree-loop-optimize` restores the
right result.
Attached repro-creduce.c (the creduce output of the generated program) fails
the same way at -O2 and -O3, with the same set of fixing flags.
Reproduced in Godbolt (gcc trunk, -Os vs -O0): https://godbolt.org/z/aesjs8cqT
## Checked versions
- gcc trunk c3129ba5e3e (2026-11-27, --enable-checking=yes): -Os aborts;
-O0..-O3 ok (repro-creduce.c: -O2/-O3/-Os wrong)
- gcc 16.0.1 and gcc 16.2 (Godbolt): -Os aborts
- gcc 15.2, 12.2, 13.4, 14.4, 15.1, 15.3 (Godbolt): ok
- clang 21 -Os with -fsanitize=undefined,memory: ok; gcc -O0
-fsanitize=address,undefined clean
Thanks.