xref: /freebsd/contrib/llvm-project/libcxx/include/__bit/countr.h (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef _LIBCPP___BIT_COUNTR_H
10 #define _LIBCPP___BIT_COUNTR_H
11 
12 #include <__bit/rotate.h>
13 #include <__concepts/arithmetic.h>
14 #include <__config>
15 #include <limits>
16 
17 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
18 #  pragma GCC system_header
19 #endif
20 
21 _LIBCPP_PUSH_MACROS
22 #include <__undef_macros>
23 
24 _LIBCPP_BEGIN_NAMESPACE_STD
25 
26 _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_ctz(unsigned __x) _NOEXCEPT {
27   return __builtin_ctz(__x);
28 }
29 
30 _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_ctz(unsigned long __x) _NOEXCEPT {
31   return __builtin_ctzl(__x);
32 }
33 
34 _LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_ctz(unsigned long long __x) _NOEXCEPT {
35   return __builtin_ctzll(__x);
36 }
37 
38 #if _LIBCPP_STD_VER >= 20
39 
40 template <__libcpp_unsigned_integer _Tp>
41 _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int countr_zero(_Tp __t) noexcept {
42   if (__t == 0)
43     return numeric_limits<_Tp>::digits;
44 
45   if (sizeof(_Tp) <= sizeof(unsigned int))
46     return std::__libcpp_ctz(static_cast<unsigned int>(__t));
47   else if (sizeof(_Tp) <= sizeof(unsigned long))
48     return std::__libcpp_ctz(static_cast<unsigned long>(__t));
49   else if (sizeof(_Tp) <= sizeof(unsigned long long))
50     return std::__libcpp_ctz(static_cast<unsigned long long>(__t));
51   else {
52     int __ret                      = 0;
53     const unsigned int __ulldigits = numeric_limits<unsigned long long>::digits;
54     while (static_cast<unsigned long long>(__t) == 0uLL) {
55       __ret += __ulldigits;
56       __t >>= __ulldigits;
57     }
58     return __ret + std::__libcpp_ctz(static_cast<unsigned long long>(__t));
59   }
60 }
61 
62 template <__libcpp_unsigned_integer _Tp>
63 _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int countr_one(_Tp __t) noexcept {
64   return __t != numeric_limits<_Tp>::max() ? std::countr_zero(static_cast<_Tp>(~__t)) : numeric_limits<_Tp>::digits;
65 }
66 
67 #endif // _LIBCPP_STD_VER >= 20
68 
69 _LIBCPP_END_NAMESPACE_STD
70 
71 _LIBCPP_POP_MACROS
72 
73 #endif // _LIBCPP___BIT_COUNTR_H
74