| Issue |
239659
|
| Summary |
nuw on loop-index arithmetic lost when the loop condition is behind an always_inline operator
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
Nemi26
|
A loop written as a range-for over a small always-inline range type loses no-wrap flags that the equivalent hand-written counted loop gets.
```cpp
struct Range {
struct Sentinel { unsigned long long end; };
struct Iterator {
unsigned long long i;
[[gnu::always_inline]] unsigned long long operator*() const { return i; }
[[gnu::always_inline]] void operator++() { i++; }
[[gnu::always_inline]] bool operator!=(Sentinel s) const { return i < s.end; }
};
unsigned long long n;
[[gnu::always_inline]] Iterator begin() const { return {0}; }
[[gnu::always_inline]] Sentinel end() const { return {n}; }
};
void hand(unsigned long long *out, unsigned n, unsigned long long m) {
for (unsigned long long j = 0; j < n; j++) out[j] = j * j % m;
}
void ranged(unsigned long long *out, unsigned n, unsigned long long m) {
for (unsigned long long j : Range{n}) out[j] = j * j % m;
}
```
With clang 23.1.4, `clang++ --target=x86_64-linux-gnu -O2 -std=c++20 -S -emit-llvm`: `hand` gets `mul nuw i64 %j, %j`, `ranged` a plain `mul i64`. The two functions are otherwise the same after inlining.
`hand`'s flag comes from IPSCCP (it is there in `-print-after=ipsccp`, not in `-print-before`), which runs before the always-inliner in the default pipeline: from `j < zext(n)` it knows `j < 2^32`, so `j * j` cannot wrap. In `ranged`, IPSCCP sees the comparison only as a call to `Iterator::operator!=` and learns nothing, and no pass after inlining derives the flag from the loop guard that inlining exposes. `__builtin_assume(i < end)` inside `operator*` does not bring it back either, since it too appears only after inlining; `__builtin_assume(j < n)` written in `ranged`'s loop body does.
Perhaps CVP could derive `nuw`/`nsw` on arithmetic of an induction variable from the loop guard's range, once inlining has exposed it.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs