[libcxx-commits] [libcxx] [libc++] Implement `<bit>` parts of P3793R2 Better shifting (PR #219389)

Jan Schultke via libcxx-commits libcxx-commits at lists.llvm.org
Fri Aug 28 06:35:04 PDT 2026


================
@@ -0,0 +1,59 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___BIT_SHIFT_H
+#define _LIBCPP___BIT_SHIFT_H
+
+#include <__config>
+#include <__type_traits/integer_traits.h>
+#include <__type_traits/make_unsigned.h>
+#include <limits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 29
+
+template <__signed_or_unsigned_integer _Tp, __signed_or_unsigned_integer _Shift>
+[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp shl(_Tp __t, _Shift __cnt) noexcept {
+  constexpr auto __n = static_cast<_Shift>(numeric_limits<make_unsigned_t<_Tp>>::digits);
+  if constexpr (is_signed_v<_Shift>) {
+    if (__cnt < 0) {
+      if (__cnt <= -__n)
+        return static_cast<_Tp>(__t < 0 ? -1 : 0);
+      return __t >> -__cnt;
+    }
+  }
----------------
eisenwave wrote:

Hmm wait, I think I messed up and confused the signedness of the shift amount with the signedness of the left operand. All four combinations of those need to be considered if one wants to minimize the emitted runtime code.

https://github.com/llvm/llvm-project/pull/219389


More information about the libcxx-commits mailing list