<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/74844>74844</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Missed optimization: inefficient bitfield increment with saturation
</td>
</tr>
<tr>
<th>Labels</th>
<td>
llvm:optimizations,
missed-optimization
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
dvyukov
</td>
</tr>
</table>
<pre>
The code is:
```
struct X {
unsigned a : 10;
unsigned b : 4;
unsigned c : 10;
};
void foo(X* x) {
if (x->b < 10) {
x->b++;
}
}
```
Clang generates:
```
foo(X*): # @foo(X*)
movl (%rdi), %eax
movl %eax, %ecx
andl $14336, %ecx # imm = 0x3800
cmpl $10239, %ecx # imm = 0x27FF
ja .LBB0_2
leal 1024(%rax), %ecx
andl $15360, %ecx # imm = 0x3C00
andl $-15361, %eax # imm = 0xC3FF
orl %ecx, %eax
movl %eax, (%rdi)
.LBB0_2:
retq
```
https://godbolt.org/z/8KEqvx8Mh
Since we already checked that `x->b++` won't overflow, the code can be faster/smaller:
```
foo(X*): # @foo(X*)
movl (%rdi), %eax
movl %eax, %ecx
andl $14336, %ecx # imm = 0x3800
cmpl $10239, %ecx # imm = 0x27FF
ja .LBB0_2
addl $1024, %eax
movl %eax, (%rdi)
.LBB0_2:
retq
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy0VUuT2jgQ_jXtSxeU3BJ-HHzgEV92c9o95LYlSwIrka2JJTNMfv2WDTPAzCS7qUpcLhv0dX_dXz9AhmAPvTEVrDaw2iVyjK0fKn18Gr_4Y9J4_VT93RpUXhu0Afga2A7YGjJ2ueevIQ6jivgJId-cTxDHfqbWKBH4GlMG_C3WzJi4Qi-Ieu0F-e76eX4evdW49x6o-AS0xhNQeZsBot0jUHFaAP8wRdpOfFTijdEZA9pMN79xncK9xH1P8_m5dbI_4MH0ZpDRfLdA1yyBykkYEEcQ7P78Jfh0df7o5kSoAFoN2k4WtEWglZGni-3VaD68wOp0TyV7fbESqeA8u9rhO9eUmu06BL5DduIFY_dsqnt4YWPEy59ho7yu79k-y_N7-edmw_6he9AZOYdKGYlLHSaV5RuhtwpXPGM_pXD7WuHMBiQWE1d6Lfp_Um35a3l-cPjcIHV60783vb628abrs-1zgZ4nDAcTv747bG2MD_MkUg1UH7xuvItLPxyA6m9AdfHHh6_HU_GxvR3kv2yvDD4alG4wUj-hao36YjTGVkaEjN1tSsbw0fdAeUR_NMPe-ccp6_j8U6Fkj43BvQzRDEB16KRzZvjf6_HD6xftzg9q_53J-kW78zsXR2p9s5zidw9coiuuS17KxFRpzoiJLFsVSVuJVLHU8KxRSmRkVqksykbnTSPznKkmT2xFjHhKrEiFEGmxLJRacdqzrCiJkypBMNNJ65bOHbtpehMbwmiqXBRCJE42xoX5b4tosgC-9g_RdvabjNb3AYiAtkDU2RCMXtyCE7baJUM1OS6a8RBAMGdDDNdg0UZnqo-zM9458zXa3uz3VlnTR2xs3FvjNNpeDaabjh5tbDHIOA6zRzIOrnq1lDa2Y7NUvgOq5_TPr8XD4D8bFYHqWW0AqmfB_wYAAP__XoPz-w">