<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/74101>74101</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            misoptimizations around `__builtin_clz`
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          amotzop
      </td>
    </tr>
</table>

<pre>
    You can use `__builtin_clz` to calculate the integer part of `log2(integer)` as `ilog(num) = 31 - __builtin_clz(num)` which produces a single `bsr` instruction (on x86-64).
However, if you add 1 to the result it uses a `xor` and `add` instructions after the `bsr` instead of just using a single `add` or `inc` instruction ([godbolt](https://godbolt.org/z/xavKh5n9T) example, [quick-bench](https://quick-bench.com/q/NduZQs_oSySAldBvjlfhsmjZqII) comparison) .
(This is just one example, but it seems to be also true for other arithmetic operations)

I think this comes from the IR representing `__builtin_clz` as an "atomic" operation, but in reality it's expanded into two instructions.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJxsU81u4zYQfhrqMrAhUZIjHXRIGhgNChRody_dS0CRY4lZiqPlkImTpy-ouN11kAsFajjz_fCjYraTRxxEeyfa-0KlOFMY1ELxjdZiJPM6_EMJtPKQGEEcysfHMVkXrX_U7k0cSogEWjmdnIoIcUawPuKEAVYVItApNzmapJDdpSJknxsV55J1NAnZ-bQI2YOo76GuYAfXMP_Vc9vLbPUMayCTNDIoYOsnt3EbOeQT1nMMSUdLHoTsyMO5O-wOjZD9XpT3orz9nV7wORP5DewJXimBMgaqrCUrCMjJRbAxi84Q4lCeaZutvMk7ZcwHJAZ1ihi2_msqqEy24Slxnmf9dMX5MonCZobXnwgQ7d1EZiQXRXsvZDfHuLKob4U8Cnm8lPYUJiGPb0Iez-r5j7n1_dfsKJ7VsjrMUkV79yNZ_X03otfzZ7N-Ke81LfmPkMc_Tfr2Fz_Sl9cvt87cPT-508zL07cfDw8ZQdOyqmCZfN5dHBay-zpbBsvvwsnjr1TGtNnLiAtn10cE5ZgghoRwogAUZwyggo3zgtFqoBWD2ozOOXjH2NYHiLP13_PKmQsynAIt20U8_A0B14CMPmbjP8uvYlDZZqkiLVYLKX9i_U_VQ0DlbHwFG4W8YcDzqrxBk9NOEF_oKgv7wgy16eteFThUN2XVNJ3sq2Ieyr7qRyPLQ4d9JdG0repU25XqgKfqRvaFHWQp60qWVXWoq7rcnxojTT02emz6UqEUTYmLsm7v3POSb72wzAmHm6Yqq8KpER1v71lKjy-wFYWU-XmHIffsxjSxaEpnOfLPKdFGh8NimdZoF_umLqkOlN4z_9G5IgU3fMiijXMaL9HJky-f3RroCXUU8rjxYSGPG99_AwAA__-vnXjn">