https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109896
Bug ID: 109896
Summary: Missed optimisation: overflow detection in
multiplication instructions for operator new
Product: gcc
Version: 13.1.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: target
Assignee: unassigned at gcc dot gnu.org
Reporter: thiago at kde dot org
Target Milestone: ---
In the following code:
struct S
{
char buf[47]; // weird size
};
void *f(unsigned long paramCount)
{
return new S[paramCount];
}
GCC generates (see https://gcc.godbolt.org/z/o5eocj5n9):
movabsq $196241958230952676, %rax
cmpq %rdi, %rax
jb .L2
imulq $47, %rdi, %rdi
jmp operator new[](unsigned long)
f(unsigned long) [clone .cold]:
.L2:
pushq %rax
call __cxa_throw_bad_array_new_length
That's a slight pessimisation of the typical, non-exceptional case because of
the presence of the compare instructions. On modern x86, that's 3 retire slots
and 2 uops, in addition to the multiplication's 3 cycles (which may be
speculated and start early). But the presence of a 10-byte instruction and the
fact that the jump is further than 8-bit displacement range mean those three
instructions occupy 18 bytes, meaning the front-end is sub-utilised, requiring
2 cycles to decode the 5 instructions (pre-GLC [I think] CPUs decode 4
instructions in 16 bytes per cycle).
Instead, GCC should emit the multiplication and check if the overflow flag was
set. I believe the optimal code for GCC would be:
imulq $47, %rdi, %rdi
jo .L2
jmp operator new[](unsigned long)
That's 15 bytes, so 1 cycle for the decoder to decode all 3 instructions.
That's 3+1 cycles and 2 retire slots before the JMP.
In the Godbolt link above, Clang and MSVC emitted a CMOV:
mulq %rcx
movq $-1, %rdi
cmovnoq %rax, %rdi
jmp operator new[](unsigned long)@PLT
This is slightly worse (19 bytes, 4 instructions, though also 3+1 cycles). For
GCC's -fno-exceptions case, I recommend keeping the IMUL+JO case and only load
-1 in the .text.unlikely section. But see
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109895