https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121158
Bug ID: 121158
Summary: Missed optimization for condition before access to
union elements of the same layout
Product: gcc
Version: 16.0
Status: UNCONFIRMED
Keywords: missed-optimization
Severity: normal
Priority: P3
Component: middle-end
Assignee: unassigned at gcc dot gnu.org
Reporter: antoshkka at gmail dot com
Target Milestone: ---
Consider the following code:
struct string_view_like{
const char* data;
unsigned size;
};
struct string_like {
const char* data;
unsigned size;
unsigned other_payload;
};
struct unioned {
string_view_like GetView() const noexcept;
union {
string_view_like static_string;
string_like dynamic_string;
};
bool is_dynamic;
};
string_view_like unioned::GetView() const noexcept {
return is_dynamic
? string_view_like{dynamic_string.data, dynamic_string.size}
: static_string;
}
GCC-16 with -O2 produces the following assembly:
"unioned::GetView() const":
cmp BYTE PTR [rdi+16], 0
je .L2
xor edx, edx
mov esi, DWORD PTR [rdi+8]
mov rax, QWORD PTR [rdi]
movabs rdi, -4294967296
mov rcx, rdx
and rcx, rdi
or rcx, rsi
mov rdx, rcx
ret
.L2:
mov rax, QWORD PTR [rdi]
mov rdx, QWORD PTR [rdi+8]
ret
However a more optimal assembly would be:
"unioned::GetView() const":
mov rax, QWORD PTR [rdi]
mov rdx, QWORD PTR [rdi+8]
ret
Godbolt playground: https://godbolt.org/z/a3EThf8Yb