https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128689
Bug ID: 128689
Summary: [vect] wrong code at -O3 -march=x86-64-v2: early-break
vectorization of an uncounted loop drops the DR
no-wrap bound, vectorizing a wrapping unsigned char
index as linear
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 -march=x86-64-v2 (also -march=x86-64-v3,
-msse4.1).
* Early-break vectorization of an uncounted loop over a ring buffer indexed by
a
* wrapping unsigned char: the index is vectorized as if it never wrapped (the
* no-wrap bound from DR analysis is dropped because the iteration count is
unknown).
* Godbolt: x86-64 gcc (trunk), flags: -O3 -march=x86-64-v2
* EXPECTED: prints 66, exit 0. BUGGY: prints 322, exit 1 (or segfaults).
*/
#include <stdio.h>
struct { unsigned char ring[256]; unsigned char after[4096]; } g;
__attribute__((noipa)) int find(unsigned char i, unsigned char key) {
int n = 0;
while (g.ring[i] != key) { /* i wraps 255 -> 0 */
i++;
n++;
}
return n;
}
int main(void) {
g.ring[10] = 1;
g.after[100] = 1;
int n = find(200, 1); /* 200..255, 0..10 -> 66 */
printf("%d\n", n);
return n != 66;
}
```
Resulted in this output:
```
$ gcc -O3 -march=x86-64-v2 repro.c && ./a.out (also -march=x86-64-v3,
-msse4.1)
322
(exit 1; with ring[] as a plain global the binary segfaults. gcc -O0, -O3
(SSE2, no early-break vectorization),
-O3 -fno-tree-vectorize, GCC 11.4 -O3 -march=x86-64-v3 and clang -O3
-march=x86-64-v3 print 66)
```
Trunk: https://godbolt.org/z/MqbqebTx4 (x86-64 gcc trunk, -O3 -march=x86-64-v2,
executed; reproduces as of 2026-11-12)
Root cause: `vect_find_stmt_data_reference` (gcc/tree-vect-data-refs.cc)
requests no-wrap analysis for every data reference since df0ac78ff ("vect:
Request no-wrap bounds from DR analysis", PR121908). For `g.ring[i]` with an
`unsigned char` IV, `scev_probably_wraps_p` answers "does not wrap" while
recording the condition as a bound (`DR_NOWRAP_BOUND`, here 254 - i) that the
caller is expected to check. `vect_build_assumptions` (gcc/tree-vect-loop.cc)
only materializes that bound as a runtime check under `if (niter_known &&
bound_min)`. For an uncounted early-break loop (iteration count unknown) the
bound is silently dropped, so the access is vectorized as a linear walk over
`g.ring[200..]` and beyond instead of wrapping to `g.ring[0]`. AGT-GCC's
loop-bound claim flags the scalar epilogue (`latch=32 bound=31`).
Suggested fix: fail vectorization (or do not request no-wrap analysis) when a
data reference carries a no-wrap bound but the loop's iteration count is
unknown, or emit the bound check against the IV value range instead of niter.