Issue 234352
Summary [IndVarSimplify] Bounds check `i - 1 u< smax(n, 0)` not eliminated when the loop guard is `n s< 1`
Labels new issue
Assignees
Reporter giordano
    IndVarSimplify doesn't fold the always-true bounds check in this loop over `i = 1 .. smax(n, 0)`, so the loop isn't vectorized at `-O2`/`-O3`.

```llvm
declare void @throw_boundserror(i64) noreturn
declare i64 @llvm.smax.i64(i64, i64)

define void @fill(ptr %p, i64 %n) {
entry:
  %len = call i64 @llvm.smax.i64(i64 %n, i64 0)
  %empty = icmp slt i64 %n, 1
  br i1 %empty, label %exit, label %loop

loop:
  %i = phi i64 [ 1, %entry ], [ %i.next, %latch ]
  %i0 = add i64 %i, -1
 %inbounds = icmp ult i64 %i0, %len
  br i1 %inbounds, label %latch, label %oob

oob:
  call void @throw_boundserror(i64 %i)
 unreachable

latch:
  %gep = getelementptr inbounds double, ptr %p, i64 %i0
  store double 0.0, ptr %gep, align 8
  %done = icmp eq i64 %i, %len
 %i.next = add i64 %i, 1
  br i1 %done, label %exit, label %loop

exit:
 ret void
}
```

**Expected:** with `opt -passes='loop(indvars)'` (and in `-O2`), `%inbounds` folds to `true`: on the non-empty path `n s>= 1`, so `%len = n` and `i - 1 u< %len` in every iteration.

**Actual:** the check is kept, in both `-passes='loop(indvars)'` and `-O2`/`-O3`.  [Reproducer on Compiler Explorer](https://godbolt.org/z/1hnsxrc8h).  [Alive2 verification of the correctness of the transformation](https://alive2.llvm.org/ce/z/GxN_BZ).

- If the guard tests `%len` instead (`icmp slt i64 %len, 1`), `loop(indvars)` does fold the check. But InstCombine canonicalizes that guard to `icmp slt i64 %n, 1`, so in `-O2` the check is kept either way.
- Without the store, `-O2` removes the check, since IndVarSimplify can then move the exit out of the loop.

CC @vchuravy.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to