<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/58137>58137</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Missing optimization for reducing common factors in integer division.
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
tstanisl
</td>
</tr>
</table>
<pre>
The optimizer fails to reduce a common factor in nominator and denominator producing efficient code.
```
int foo(int a, int b) {
return (2 * a * b) / (2 * a);
}
int bar(int a, int b) {
return (2 * b * a) / (2 * a);
}
```
Compiled with CLANG 15.0 and options "-O3" produces assembly:
```
foo(int, int):
mov eax,esi
ret
bar(int, int):
mov eax,esi
add edi,edi
imul eax,edi
cdq
idiv edi
ret
```
The `idiv` instruction is about 10+ times slower than `imul`. Using `int` guarantees no overflow due to invoking UB so the order of operand of `*` can be safely reordered allowing reduction of common factors in nominator and denominator. This issue appears when working with VLA when the number of elements is computed with `sizeof` operator. For example:
```
int A[n][m];
int rows = sizeof A / sizeof *A;
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyVVMlu2zAQ_RrpQkTQ4k0HHewY7iVtL2nvlDiy2VKkS1J20q_vI63ECZoGjWFwGc7y5s2MWiMem_sDMXP0cpC_ybKeS-WYN8ySGDtinHVmGIzGQ-eNZVIzbQapebhwLZig6_1oDYyk3jPqe9lJ0h7mgrIk3yb5eloX-fSPVwmd3pikXIUTT8pbFg5tUtYsWW4uSgw_S360mkGxxLIGsrBe9MrdCzkkSTUZJsvty9jRM7cfD9Y-u_6vYK9TvKy3ZjhKRYKdpT-w27v1l0-smGd5ZDEUwGgHn-XN1wrrxCU5xp2joVWPSfU2gc_kTdlERJMqG8wppEP8Aa_k5CRGekH8Et4zLR9ww4WIYiGDWDyJ5TCqq_azuBO_rkGZFPI02V4xvUNfaFOIghk2IHTejl1gjUmQ1JrRsyJPyg1DK4M2p8wZ_ewPXEc7YMKWsW8u9GeQIEc42o_ccu0JJtowcyLbw5KJkcIUSH0yP4PBtw1zBt4wK1bAr-lRM7Kxdn1wh24I7jqEa4k53pN6RE5RG0XnCl6DozhXETbsXs2We3e4MnZ_QKLSOSDjxyNxGJwPpNnZ2Agx9tX3u_VFGqDqcWgvWEnRgGkM9iHocfRPjQjQDpNv-oA-phSD7YCAHvhwVHRtvH_N7zqZb3Qy32IbwvY0EOHNmjPautqySxS2jgM0XUDa-jo-b5U9paZYLGarZVHVVSqaStRVzVMvvaLmM9gImU-fLx5p7YE8khxe_iYYmGgPUtBH0kE_S0ermoP3RxcSLXf470HM2GYwxkWp09N2g6H8QR1mYxfr4HCYr4pqmR4aXnezei7aKhf5rOjyuahrKuqyKIp8XhSrVPGWlGvAEcZb0_lSSpzBWCqbMi_LIs9n-apYVFW2nC8WSz6rS9GKtp1VySynAd_mLODIjN2ntomQ2nHv8Kik8-76iI-G3GuiGA7--egPxjbeea6lU2mM3UTsfwDiSM_5">