I was looking at the code generated when I use std::bit_cast
to convert from arrays of a user-defined strong type to the underlying type and noticed that GCC seems to emit some code even at high optimization levels. For
<code>#include <array>
#include <bit>
struct StrongType {
float value;
};
std::array<float, 2> bitCast(std::array<StrongType, 2> const a) {
return std::bit_cast<std::array<float, 2>>(a);
}
std::array<float, 3> bitCast(std::array<StrongType, 3> const a) {
return std::bit_cast<std::array<float, 3>>(a);
}
</code>
<code>#include <array>
#include <bit>
struct StrongType {
float value;
};
std::array<float, 2> bitCast(std::array<StrongType, 2> const a) {
return std::bit_cast<std::array<float, 2>>(a);
}
std::array<float, 3> bitCast(std::array<StrongType, 3> const a) {
return std::bit_cast<std::array<float, 3>>(a);
}
</code>
#include <array>
#include <bit>
struct StrongType {
float value;
};
std::array<float, 2> bitCast(std::array<StrongType, 2> const a) {
return std::bit_cast<std::array<float, 2>>(a);
}
std::array<float, 3> bitCast(std::array<StrongType, 3> const a) {
return std::bit_cast<std::array<float, 3>>(a);
}
with -std=c++20 -O3
Clang 18.1.0 produces just ret
in both cases, but GCC 14.1 produces
<code>bitCast(std::array<StrongType, 3ul>):
movd DWORD PTR [rsp-16], xmm1
movss xmm1, DWORD PTR [rsp-16]
movss DWORD PTR [rsp-32], xmm1
movd xmm1, DWORD PTR [rsp-32]
ret
</code>
<code>bitCast(std::array<StrongType, 3ul>):
movd DWORD PTR [rsp-16], xmm1
movss xmm1, DWORD PTR [rsp-16]
movss DWORD PTR [rsp-32], xmm1
movd xmm1, DWORD PTR [rsp-32]
ret
</code>
bitCast(std::array<StrongType, 3ul>):
movd DWORD PTR [rsp-16], xmm1
movss xmm1, DWORD PTR [rsp-16]
movss DWORD PTR [rsp-32], xmm1
movd xmm1, DWORD PTR [rsp-32]
ret
for the overload that casts an array of three elements.
Compiler Explorer link: https://godbolt.org/z/e4ePPzMhY.
- Why is GCC generating this?
- Is
std::bit_cast
the shortest way of performing this kind of conversion with no undefined behavior? - Is it reasonable to assume that
std::bit_cast
in cases like these will be zero-cost in the future?
2