Hi all, This patch implements the bit_reverse function from P3104R6 for C++29, using the __builtin_bitreverseg. Since the paper's implementation is incomplete, I just use the __cplusplus macro guard without bumping the FTM.
Built and tested on x86_64 linux, ok for trunk? Thanks, Yuao
From ffe865861d50a8f5011c1ab5f463e134f1c91bdb Mon Sep 17 00:00:00 2001 From: Yuao Ma <[email protected]> Date: Sun, 30 Aug 2026 21:03:09 +0800 Subject: [PATCH] libstdc++: implement bit_reverse from P3104R6 for C++29 libstdc++-v3/ChangeLog: * include/std/bit (bit_reverse): New. * testsuite/26_numerics/bit/bit.permutation/bit_reverse.cc: New test. --- libstdc++-v3/include/std/bit | 8 ++++ .../bit/bit.permutation/bit_reverse.cc | 41 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 libstdc++-v3/testsuite/26_numerics/bit/bit.permutation/bit_reverse.cc diff --git a/libstdc++-v3/include/std/bit b/libstdc++-v3/include/std/bit index b735044ca18..a492ca74660 100644 --- a/libstdc++-v3/include/std/bit +++ b/libstdc++-v3/include/std/bit @@ -503,6 +503,14 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION }; #endif // __cpp_lib_endian +#if __cplusplus > 202603L + + template<__unsigned_integer _Tp> + constexpr _Tp + bit_reverse(_Tp __x) noexcept + { return __builtin_bitreverseg(__x); } +#endif + /// @} _GLIBCXX_END_NAMESPACE_VERSION diff --git a/libstdc++-v3/testsuite/26_numerics/bit/bit.permutation/bit_reverse.cc b/libstdc++-v3/testsuite/26_numerics/bit/bit.permutation/bit_reverse.cc new file mode 100644 index 00000000000..e0db76ed127 --- /dev/null +++ b/libstdc++-v3/testsuite/26_numerics/bit/bit.permutation/bit_reverse.cc @@ -0,0 +1,41 @@ +// { dg-do run { target c++29 } } + +#include <testsuite_hooks.h> + +#include <bit> + +constexpr void test01() { +#if __CHAR_BIT__ == 8 +#if __SIZEOF_INT__ == 4 + static_assert(std::bit_reverse(0x2fa889a7U) == 0xe59115f4U, ""); +#endif +#if __SIZEOF_LONG_LONG__ == 8 + static_assert( + std::bit_reverse(0xd7632f428bdccb94ULL) == 0x29d33bd142f4c6ebULL, ""); +#endif + static_assert(std::bit_reverse((unsigned char)0xac) == (unsigned char)0x35, + ""); +#if __SIZEOF_SHORT__ == 2 + static_assert( + std::bit_reverse((unsigned short)0xc4f0) == (unsigned short)0x0f23, ""); +#endif +#if __SIZEOF_INT128__ == 16 + static_assert( + std::bit_reverse((((unsigned __int128)0x398773ddb9250c54ULL) << 64) | + 0x26933639cdf63ea6ULL) == + ((((unsigned __int128)0x657c6fb39c6cc964ULL) << 64) | + 0x2a30a49dbbcee19cULL), + ""); +#endif +#endif +} + +constexpr bool test() { + test01(); + return true; +} + +int main() { + static_assert(test()); + test(); +} -- 2.54.0
