| Issue |
235778
|
| Summary |
[SCEV] Conditions on switch edges are not used as loop guards
|
| Labels |
llvm:SCEV,
missed-optimization
|
| Assignees |
|
| Reporter |
chfast
|
```c
void a(void);
void b(void);
void f(unsigned long *r, unsigned x)
{
unsigned long n = x & 3;
if (n == 0)
return a();
if (n == 1)
return b();
for (unsigned long i = 0; i < n - 1; ++i)
r[i] += 1;
}
```
https://godbolt.org/z/TEozcd8dY
The loop runs once or twice (`n` is 2 or 3), but `clang -O2` vectorizes it, with a scalar remainder loop. With `if (n < 2) return n ? b() : a();` instead of the two checks it is fully unrolled.
The two checks become a switch, and CorrelatedValuePropagation removes the loop entry check using the switch edge. SCEV then has no max trip count for the loop, because `LoopGuards::collectFromBlock()` takes conditions only from conditional branches. `opt -passes='print<scalar-evolution>'` on the IR below gives a constant max backedge-taken count of -1 for `@sw` and 1 for `@br`.
<details><summary>IR</summary>
```llvm
declare void @a()
declare void @b()
declare void @use(i64)
; n is 2 or 3 in the loop: constant max backedge-taken count should be 1.
define void @sw(i32 %x) {
entry:
%n32 = and i32 %x, 3
%n = zext i32 %n32 to i64
switch i64 %n, label %loop.ph [
i64 0, label %ra
i64 1, label %rb
]
ra:
call void @a()
ret void
rb:
call void @b()
ret void
loop.ph:
%m = add nsw i64 %n, -1
br label %loop
loop:
%i = phi i64 [ 0, %loop.ph ], [ %i.next, %loop ]
call void @use(i64 %i)
%i.next = add nuw i64 %i, 1
%done = icmp eq i64 %i.next, %m
br i1 %done, label %exit, label %loop
exit:
ret void
}
; The same with a br.
define void @br(i32 %x) {
entry:
%n32 = and i32 %x, 3
%n = zext i32 %n32 to i64
%small = icmp ult i64 %n, 2
br i1 %small, label %ret, label %loop.ph
ret:
ret void
loop.ph:
%m = add nsw i64 %n, -1
br label %loop
loop:
%i = phi i64 [ 0, %loop.ph ], [ %i.next, %loop ]
call void @use(i64 %i)
%i.next = add nuw i64 %i, 1
%done = icmp eq i64 %i.next, %m
br i1 %done, label %exit, label %loop
exit:
ret void
}
```
</details>
Found in intx (multi-precision integers), where the dispatch on the divisor word count (1 word, 2 words, otherwise Knuth division) is such a switch: the remainder loop after the Knuth division is not unrolled (`udivrem<192,192>` +31 instructions at -O2).
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs