Issue 58137
Summary Missing optimization for reducing common factors in integer division.
Labels new issue
Assignees
Reporter tstanisl
    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;
```


_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to