https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112608
Bug ID: 112608
Summary: Missed-optimization: Multiple Division Constants
Product: gcc
Version: 13.2.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: goon.pri.low at gmail dot com
Target Milestone: ---
The following C code on all optimization levels uses a division instruction:
int inst_division(int a, int b) {
if (b < 10)
b = 7;
else
b = 13;
return a / b;
}
inst_division:
cmp esi, 9
mov edx, 7
mov ecx, 13
mov eax, edi
cmovle ecx, edx
cdq
idiv ecx
ret
This could be avoided since we know all the possible divisors and instead could
do multiplications as shown in the following code:
int constant_division(int a, int b) {
if (b < 10)
return a / 7;
else
return a / 13;
}
constant_division:
movsx rax, edi
cmp esi, 9
jg .L6
imul rax, rax, -1840700269
shr rax, 32
add eax, edi
sar edi, 31
sar eax, 2
sub eax, edi
ret
.L6:
imul rax, rax, 1321528399
sar edi, 31
sar rax, 34
sub eax, edi
ret