<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/105539>105539</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
RISC-V missed optimisation: branch on equal to small constant
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Wren6991
</td>
</tr>
</table>
<pre>
In this code:
```c
void __attribute__((naked)) f() {asm ("ret");}
void __attribute__((naked)) g() {asm ("ret");}
void h(int a) {
if (a == 15) {
f();
} else {
g();
}
}
```
clang trunk on godbolt produces the following at `-Oz`:
```c
h(int):
li a1, 15
bne a0, a1, .LBB2_2
tail f()
.LBB2_2:
tail g()
```
(Godbolt link: [https://godbolt.org/z/srT6MhG5Y](https://godbolt.org/z/srT6MhG5Y))
However the following is two bytes smaller (because `bnez` compresses) and avoids a register clobber:
```c
h(int):
addi a0, a0, -15
bnez a0, .LBB2_2
tail f()
.LBB2_2:
tail g()
```
This transform applies when the branch is the final use of the value, and the comparison constant is not -2048 or -32 (due to the sign change). It is useful when the branch is in compressible range, or when avoiding the clobber is profitable.
The same pattern applies to some sparse switch statements, like [here](https://github.com/raspberrypi/armulet/blob/c620715d8ffbc332af012b6b25c7cf888a700419/varmulet/varmulet_armv6m_core.S#L850-L861) in the RP2350 bootrom. That source file has several instances where this pattern saved static code size in handwritten code.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJycVU2P2zYQ_TX0ZWBDoj4sH3SIYzgNkKJFErToyRhSI4tdilRJykb21xekvV5vsUm3FQxZ4nxw5r2nIXqvjoaoZdWWVbsFzmGwrv3dkak3m3whbPet_WggDMqDtB2x4h3Ldix7utfZ5Scv7yerOjgcMASnxBzocGC8Ybwx-EAd4xvGN9CnpQ2w9Rb9COmNOwqM8-hRbNl69_Zsxzdnu8s5MN4oEwCvkRcTAIDqYwoEVuxYsYO8eulxrT2mvYWw9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