Issue 115444
Summary [RISCV] Suboptimal switch code generation
Labels new issue
Assignees
Reporter WojciechMula
    Version `clang version 20.0.0git (https://github.com/llvm/llvm-project.git 5b697ef5dd6b3e29e257e6099014bf8d8e77ac9a)`

Arguments: `-O3`

The following switch is nicely compiled:

```c++
bool one_of(int num) {
    switch (num) {
        case 0:
        case 1:
        case 3:
        case 4:
        case 6:
        case 10:
 return true;
        default:
            return false;
 }
```

```asm
one_of(int):
        sltiu   a1, a0, 11
 li      a2, 1115
        srl     a0, a2, a0
        and     a0, a0, a1
        ret
```

However, changing the return type from `bool` to `int` changes the generated code dramatically.

```c++
int one_of_int(int num) {
    switch (num) {
        case 0:
 case 1:
        case 3:
        case 4:
        case 6:
 case 10:
            return 1;
        default:
            return 0;
    }
}
```

```asm
one_of_int(int):
        li a1, 10
        bltu    a1, a0, .LBB1_2
        slli    a0, a0, 2
.Lpcrel_hi0:
        auipc   a1, %pcrel_hi(.Lswitch.table.one_of_int(int))
        addi    a1, a1, %pcrel_lo(.Lpcrel_hi0)
        add     a0, a0, a1
        lw      a0, 0(a0)
        ret
.LBB1_2:
        li      a0, 0
 ret

.Lswitch.table.one_of_int(int):
        .word   1
 .word   1
        .word   0
        .word   1
        .word   1
 .word   0
        .word   1
        .word   0
        .word 0
        .word   0
        .word   1
```

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

Reply via email to