https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98501
Bug ID: 98501
Summary: potential optimization for base<->derived pointer
casts
Product: gcc
Version: 10.2.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: vanyacpp at gmail dot com
Target Milestone: ---
Consider this code:
struct base1 { int a; };
struct base2 { int b; };
struct derived : base1, base2 {};
derived& to_derived_bad(base2* b)
{
return *static_cast<derived*>(b);
}
derived& to_derived_good(base2* b)
{
return static_cast<derived&>(*b);
}
I believe both of these functions are functionally equivalent and should
generate the same code. Both functions cast pointer from base to derived if it
is not nullptr and both cause undefined behavior if it is nullptr.
GCC optimizes to_derived_good() to a single subtraction, but it inserts
nullptr-check into to_derived_bad():
to_derived_good(base2*):
lea rax, [rdi-4]
ret
to_derived_bad(base2*):
lea rax, [rdi-4]
test rdi, rdi
mov edx, 0
cmove rax, rdx
ret
Could GCC omit the nullptr-check in to_derived_bad?