llvm / llvm/llvm-project

[LoopVectorize] miscompiles counted loop at -O2 (off-by-one)

Open
#205,799 0 comments 0 reactions 0 assignees View on GitHub
confirmed miscompilation vectorizers
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

The following code is miscompiled in current trunk and all released versions since clang 19

``` c++
int32_t sumB = 0;
bool finished = false;
uint8_t counter = 0;
while (!finished) {
if (counter < a ) {
sumB += b;
counter++;
} else {
finished = true;
}
}
```
The bug is only there if a is 7, 15, 31, 63 or 127 and flag -O2 or -O3 is given.
It is not there with -mllvm -vectorize-loops=false

If Address or Undefined behavior sanitizer are enabled the bug does not show up

https://godbolt.org/z/rfjnPE8zd

Full reproducer code:
[clang-bug.cpp.txt](https://github.com/user-attachments/files/29336290/clang-bug.cpp.txt)

Contributor guide

Open the contributing guide

Research direction

Start with the attached clang-bug.cpp.txt reproducer and the linked Compiler Explorer example. Reproduce the off-by-one result at -O2 and -O3 for a values 7, 15, 31, 63, and 127, then compare with -mllvm -vectorize-loops=false and sanitizer-enabled builds. Done means the counted loop produces the correct result without disabling loop vectorization.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.