[libcxx-commits] [libcxx] [libc++] Improve performance of std::midpoint for small types (PR #192804)
via libcxx-commits
libcxx-commits at lists.llvm.org
Sat Apr 18 13:11:37 PDT 2026
https://github.com/serge-sans-paille updated https://github.com/llvm/llvm-project/pull/192804
>From a604431a4c78776b2db85fa0429e0573a76bd67e Mon Sep 17 00:00:00 2001
From: serge-sans-paille <sguelton at mozilla.com>
Date: Sat, 18 Apr 2026 20:08:10 +0200
Subject: [PATCH 1/2] [libc++] Improve performance of std::midpoint for small
types
---
libcxx/include/__numeric/midpoint.h | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/libcxx/include/__numeric/midpoint.h b/libcxx/include/__numeric/midpoint.h
index d8e73ab8cad36..736e2b152cd38 100644
--- a/libcxx/include/__numeric/midpoint.h
+++ b/libcxx/include/__numeric/midpoint.h
@@ -36,14 +36,18 @@ template <class _Tp>
[[nodiscard]]
_LIBCPP_HIDE_FROM_ABI constexpr _Tp midpoint(_Tp __a, _Tp __b) noexcept _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK {
using _Up = make_unsigned_t<_Tp>;
- constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
+ if constexpr (sizeof(_Tp) < sizeof(unsigned)) {
+ return (static_cast<unsigned>(__a) + static_cast<unsigned>(__b)) / 2;
+ } else {
+ constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
- _Up __diff = _Up(__b) - _Up(__a);
- _Up __sign_bit = __b < __a;
+ _Up __diff = _Up(__b) - _Up(__a);
+ _Up __sign_bit = __b < __a;
- _Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);
+ _Up __half_diff = (__diff / 2) + (__sign_bit << __bitshift) + (__sign_bit & __diff);
- return __a + __half_diff;
+ return __a + __half_diff;
+ }
}
template <class _Tp>
>From 24123590a0d64d80bacb9740c5b262763681eeb3 Mon Sep 17 00:00:00 2001
From: serge-sans-paille <sguelton at mozilla.com>
Date: Sat, 18 Apr 2026 22:11:10 +0200
Subject: [PATCH 2/2] fixup! [libc++] Improve performance of std::midpoint for
small types
---
libcxx/include/__numeric/midpoint.h | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/libcxx/include/__numeric/midpoint.h b/libcxx/include/__numeric/midpoint.h
index 736e2b152cd38..aa6d7096878f0 100644
--- a/libcxx/include/__numeric/midpoint.h
+++ b/libcxx/include/__numeric/midpoint.h
@@ -37,7 +37,8 @@ template <class _Tp>
_LIBCPP_HIDE_FROM_ABI constexpr _Tp midpoint(_Tp __a, _Tp __b) noexcept _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK {
using _Up = make_unsigned_t<_Tp>;
if constexpr (sizeof(_Tp) < sizeof(unsigned)) {
- return (static_cast<unsigned>(__a) + static_cast<unsigned>(__b)) / 2;
+ using _Ip = conditional_t<is_signed_v<_Tp>, signed, unsigned>;
+ return (static_cast<_Ip>(__a) + static_cast<_Ip>(__b)) / 2;
} else {
constexpr _Up __bitshift = numeric_limits<_Up>::digits - 1;
More information about the libcxx-commits
mailing list