Issue 180870
Summary [IndVarSimplify][SCEV] IndVarSimplify incorrectly hoists loop exit condition due to signed wrap
Labels llvm:SCEV, llvm:analysis
Assignees
Reporter KirillVNaumov
    ### Bug
Here is a link to the test, demonstrating the issue: https://godbolt.org/z/8rqoE6s9E
This is one of the tests that demonstrates the issue:
```
define void @test_indvar_limits_samesign(i32 %unknown_limit, ptr addrspace(1) %length_ptr) {
entry:
  br label %header

header: ; preds = %latch, %entry
  %iv = phi i32 [ 1, %entry ], [ %iv.next, %latch ]
  %iv.next = add i32 %iv, 1
 %range_check1 = icmp samesign ult i32 %iv.next, %unknown_limit
 %is_positive = icmp sgt i32 %unknown_limit, 0
  %or.cond = and i1 %range_check1, %is_positive
  br i1 %or.cond, label %latch, label %ret

latch:                                            ; preds = %header
 %iv.prev = add i32 %iv, -1
  %length = load i32, ptr addrspace(1) %length_ptr, align 4, !range !0
  %range_check2 = icmp ult i32 %iv.prev, %length
  br i1 %range_check2, label %header, label %ret

ret: ; preds = %latch, %header
  ret void
}

!0 = !{i32 0, i32 2147483647}
```
Running `indvars` pass for this test results in hoisting of `%range_check1 = icmp samesign ult i32 %iv.next, %unknown_limit` instruction to the preheader with the replacement of the inductive variable by its value during the first iteration: `%range_check1.first_iter = icmp ult i32 2, %unknown_limit`. As is obvious from this test, this is a misoptimization since the information in the test is not sufficient to make this substitution.

### Analysis
The cause of the bug is likely located not in IndVarSimplify analysis, but in SCEV, since it's used to prove the replacement invariants. Another observation is related to signed wrap, since the range metadata plays a crucial role in the test to identify the maximum number of iterations and the value of the inductive variable on the last iteration - reducing the upper bound on the range metadata or removing it altogether masks the bug. `samesign` attribute also affects the bug's reproducibility, so I added two tests - with and without this attribute.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to