Issue 235802
Summary [SimplifyCFG] Switch case to unreachable is removed without an assume
Labels missed-optimization, llvm:transforms
Assignees
Reporter chfast
    ```c
void f(unsigned long *r, unsigned x)
{
    unsigned long n = x & 3;
    switch (n)
    {
    case 0:
        __builtin_unreachable();
    case 1:
 return;
    }
    for (unsigned long i = 0; i < n - 1; ++i)
        r[i] += 1;
}
```

https://godbolt.org/z/c5roEjKf1

`n` is 2 or 3 at the loop, so it runs once or twice, but `clang -O2` vectorizes it. With `__builtin_assume(n != 0)` instead of `case 0`, it becomes two conditional increments.

For a conditional branch to an unreachable block, `simplifyUnreachable()` keeps the condition as an `llvm.assume`, but for a switch it only removes the case, so `n != 0` is lost. `opt -passes=simplifycfg` on the IR below turns `@sw` into a plain `br` on `%x == 1`, while `@br` keeps `assume(%x != 0)`:

<details><summary>IR</summary>

```llvm
declare void @a()
declare void @b(i32)

define void @sw(i32 %x) {
entry:
  switch i32 %x, label %def [
    i32 0, label %unreach
    i32 1, label %one
  ]
unreach:
 unreachable
one:
  call void @a()
  ret void
def:
  call void @b(i32 %x)
  ret void
}

define void @br(i32 %x) {
entry:
  %z = icmp eq i32 %x, 0
  br i1 %z, label %unreach, label %next
unreach:
 unreachable
next:
  %o = icmp eq i32 %x, 1
  br i1 %o, label %one, label %def
one:
  call void @a()
  ret void
def:
  call void @b(i32 %x)
  ret void
}
```

</details>

Related: #49799 (unreachable switch default). Found while reducing code from intx (multi-precision integers).

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

Reply via email to