| Issue |
241954
|
| Summary |
[IndVarSimplify] Congruent IV elimination replaces an IV with one whose start value may be poison
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
arie2026
|
`SCEVExpander::replaceCongruentIVs` merges header phis that have the same SCEV and keeps the first one.
Two phis can have the same SCEV even when only one of them can be poison, for example when only one start
value carries a poison-generating flag. If the dropped phi was the one that controls the exit branch, the
loop now branches on a possibly-poison value.
Reproducer (`opt -passes=indvars -S test.ll`, tested on 8b3872a98; `-O2` gives the same loop):
```llvm
declare void @use(i16)
define void @f(i16 %a, i16 %b) {
entry:
%s1 = or disjoint i16 %a, %b
%s2 = add i16 %a, %b
br label %loop
loop:
%k = phi i16 [ %s1, %entry ], [ %k.next, %loop ]
%l = phi i16 [ %s2, %entry ], [ %l.next, %loop ]
call void @use(i16 %k)
%k.next = add i16 %k, 1
%l.next = add i16 %l, 1
%c = icmp eq i16 %l.next, 2
br i1 %c, label %exit, label %loop
exit:
ret void
}
```
```
$ opt -passes=indvars -S test.ll
define void @f(i16 %a, i16 %b) {
entry:
%s1 = or disjoint i16 %a, %b
br label %loop
loop:
%k = phi i16 [ %s1, %entry ], [ %k.next, %loop ]
call void @use(i16 %k)
%k.next = add i16 %k, 1
%c = icmp eq i16 %k.next, 2
br i1 %c, label %exit, label %loop
exit:
ret void
}
```
(`-debug-_only_=indvars`: `Eliminated congruent iv: %l = phi ...`, `Original iv: %k = phi ...`)
Why this is wrong: for `%a = %b = -32768`, `or disjoint` is poison but `add` is 0. The source loops twice
on `%l`, calls `@use(poison)` twice (not UB) and returns. The target branches on `%k.next` = poison, which
is immediate UB. alive2 (`alive-tv --src-unroll=4 --tgt-unroll=4 test.ll tgt.ll`):
```
ERROR: Source is more defined than target
i16 %a = #x0002 (2)
i16 %b = #x0002 (2)
Source: ... %s1 = poison, %s2 = 4 ... (no UB)
Target: %k.next = poison, %c = poison, UB triggered on br
```
The same happens with `%s1 = shl nuw i16 %x, 1` / `%s2 = shl i16 %x, 1` (`%x = 0x8000`). With the two phis in
the other order, `%k` is replaced by `%l` and the result is correct.
Expected: do not replace a phi with a congruent phi that may be more poisonous. For example, check the
start values with `canCreatePoison`/`isGuaranteedNotToBePoison`, drop the poison-generating flags on the
surviving IV's start value, or prefer the less poisonous phi as the representative.
Notes: #237702 also involves `replaceCongruentIVs` (nsw kept on the increment after a truncation match). This
case has no truncation and no increment flags, so I think it is a separate problem. LLVM 18 behaves the same.
Found with a mutation-based IR fuzzer. Triage, test-case minimization and parts of this write-up were
assisted by an LLM; verified the reproducer on 8b3872a98.
Assisted-by: Claude (Anthropic)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs