[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 11:10:05 PDT 2026
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-libcxx
Author: serge-sans-paille
<details>
<summary>Changes</summary>
---
Full diff: https://github.com/llvm/llvm-project/pull/192804.diff
1 Files Affected:
- (modified) libcxx/include/__numeric/midpoint.h (+10-5)
``````````diff
diff --git a/libcxx/include/__numeric/midpoint.h b/libcxx/include/__numeric/midpoint.h
index d8e73ab8cad36..7c3f8cc8bd8f9 100644
--- a/libcxx/include/__numeric/midpoint.h
+++ b/libcxx/include/__numeric/midpoint.h
@@ -36,14 +36,19 @@ 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>
``````````
</details>
https://github.com/llvm/llvm-project/pull/192804
More information about the libcxx-commits
mailing list