<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/116119>116119</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Failure to unroll loop with unknown but small count
</td>
</tr>
<tr>
<th>Labels</th>
<td>
missed-optimization
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Kmeakin
</td>
</tr>
</table>
<pre>
Consider this function that calculates the number of digits in `n`'s base-10 representation (eg as part of a formatting library):
```c
u8 src(u8 n) {
u8 num_digits = 0;
do {
num_digits++;
n /= 10;
} while (n != 0);
return num_digits;
}
```
Since `n` is in the range `0-255`, the loop will run exactly 1, 2 or 3 times, and the function can be optimized by unrolling the loop manually:
```c
u8 intermediate(u8 n) {
u8 num_digits = 0;
// iteration 1
num_digits++;
n /= 10;
if (n == 0) return num_digits;
// iteration 2
num_digits++;
n /= 10;
if (n == 0) return num_digits;
// iteration 3
num_digits++;
n /= 10;
return num_digits;
}
```
which then simplifies to:
```c
u8 tgt(u8 n) {
if (n < 10) return 1;
if (n < 100) return 2;
return 3;
}
```
LLVM is smart enough to do this optimization if the base is 16, but not for any other base
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy8VcuO4zYQ_Brq0vCApB4eH3TIjOFLNqcAuQaU1JI6S5EG2dyJ8_UBZXvszcZJkAHWEGxI_VB3VbFsYqTJIbaifhH1vjCJZx_aHxc0n8kVnR9O7at3kQYMwDNFGJPrmbwDng1Db2yfrGGMwDOCS0uHAfwIA03EEciBaKQTjRR6G6EzETdKQsBjwIiOzdpK6GecwEQ4msC52sDow2KYyU1gqQsmnITeifIHIfdCXr8beb768316hhh6oZ_TMzihdyC2L-cIAEB-mJZfL4OJcg9SlHfxwX-dnz-3AqFf8vVekIc-5Cbq6y5iu4e3mSzmpXKSOr8pD3-XFpBTcPf9r1Gx3f9lu_uVfybX4xVSoBXgDHwwblqfy42u6xXu1zVgvT_CG1kLITnA303P9gQqhzX4ACUwLRjzvXHDWvLOcG8cdAj-yLTQHzhAd4Lkgrc20_LefTEuGWtP_84OOcaw4ECG8f_QdAezPgh9AGIMZwmpW-wxaTn4gDcaL4SV-yth_0TS40H0VSDfbYpvRig_gMXHJfo2Uz9ndTiItBwtjZTdwd_k8a0weOJHerhB8prnvAGiHiCX0-7z9N8dvPI_LvPp0y8_5WMWl-xM6HyaZmCfzWJ1w8vZOONO43oossnlGtXkU9UlBuc5GxoYdwLPM4Y1pxjactiVO1Ngq7alqiu5q6tibvXWyKocmqZRzVDprupw6HVTj30nBznKglotdaWUKnVZ1nX1pKvKNFhWphvVbuhQVBIXQ_bJ2i_Lkw9TQTEmbJVqlNoV1nRo4-r5Wi8UIw6b-02E1vnPILS5fNOlKYpKWoocbw2Z2GJ7MGRTwAzJ2RmuhsMzJPfZ-Te3IhAXYy30PjkuUrDtzHyMWRGrdifiOXVPvV-EPuQ3XH42x-B_w56FPqzzR6EPlxW-tPrPAAAA__90fO2P">