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

    <tr>
        <th>Summary</th>
        <td>
            Missed optimization for flooring division of signed by power of two
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
      </td>
    </tr>

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

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

<pre>
    If a signed integer is divided by a power of two it is not a simple shift like for unsigned because division rounds to zero while the shift would round down. If flooring division is implemented, then flooring division by a power of two is equivalent to an arithmetic shift.

Here, `floor_div4_a` and `floor_div4_b` are equivalent, but the code generated for `_a` is not as good as `_c`.

```c
inline int floor_div(int n, int d)
{
    int q = n / d;
    int r = n % d;
    if ((r < 0 && d > 0) || (r > 0 && d < 0))
        q -= 1;
    return q;
}

int floor_div4_a(int i)
{
    return floor_div(i, 4);
}

int floor_div4_b(int i)
{
    return i >> 2;
}
```

\[[Compiler explorer](https://godbolt.org/z/vebf4Waxv)\]

(This is similar to rustc issue https://github.com/rust-lang/rust/issues/71096.)
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyNVEtv2zAM_jX2hWjgt5ODD23SYTvsNmDHQrZoW5siOZKctP31o-wkq7NgqKHYEh8fP5Jias3fqm8tMLCiU8hBKIcdGhAWuDgKTqL6jdSDPpFUt-BOGoTzeqXd5LcfJILtRetAit8IrTYwqjNejQ0bLU5gVmgFRo-KW3Aa3tFoOPWCvF1_QTjpUfLZCLg-qRUQu1ZqbYTq_qJQ-CnuHokvD5Kth1B3DO-Qt4CHURyZJF_PgylgRrh-j040M41VEO2C6HF-f0WDPkJQRBP-C4FnL4yO5MpvxPUkNvghhvetRzcl2WiO0KFCw4j3VCpymMEuJbXQac3916saei3o0HlezXwWSgqFvnFw5REka39WPrTfUIU2Z-_yad4APV51gCDdgYIg-UJm6Y3WXLX5rbYl4ZqWN9lCRKeCFlBB0meIKCAE5ZYWnG2elzbbyebKC87PAR58xHgRy6AbjYLDVRiUu48lWeTuWzOnL-5nfUZbFMsXKvPmn4tQfyqC8Fn7xJM7sJcuLlqbb4P8idZW7weaCwP4Okht0AT5jkL2zg02SB-pV7Q6zWst3Uqbjk7v9Dti3WY_2evR0_JYixwI4EfvB8f6oRWSGX_7zWhdQzI7Itzg00yM9arRezp4swfJVHfe02fysbQp42hTrChmiFVcFGlcpkVShrxK-SbdsNAJJ7H6TvZ05fXgKPg7c346_f3_d2ZpUC__Hm-L2Q1HI6v_kJTyePk8DEb_wmbBMy_LLA77isUswySLsjzDNsmzTdvEaR7ncVxkTVOnoWQ1SltNvdiFokqiJIk2cUb6KMlXeZrxiJfFmucsW2dZkEW4Z0KufGDfjtBUE4d67CwppbDO_lUyO2WHF3w2ul6bytlBODQinPhWE9k_y0az1A">