popcount.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #ifndef _LIBCPP___BIT_POPCOUNT_H
  9. #define _LIBCPP___BIT_POPCOUNT_H
  10. #include <__bit/rotate.h>
  11. #include <__concepts/arithmetic.h>
  12. #include <__config>
  13. #include <limits>
  14. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_PUSH_MACROS
  18. #include <__undef_macros>
  19. _LIBCPP_BEGIN_NAMESPACE_STD
  20. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_popcount(unsigned __x) _NOEXCEPT {
  21. return __builtin_popcount(__x);
  22. }
  23. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_popcount(unsigned long __x) _NOEXCEPT {
  24. return __builtin_popcountl(__x);
  25. }
  26. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_popcount(unsigned long long __x) _NOEXCEPT {
  27. return __builtin_popcountll(__x);
  28. }
  29. #if _LIBCPP_STD_VER >= 20
  30. template <__libcpp_unsigned_integer _Tp>
  31. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int popcount(_Tp __t) noexcept {
  32. if (sizeof(_Tp) <= sizeof(unsigned int))
  33. return std::__libcpp_popcount(static_cast<unsigned int>(__t));
  34. else if (sizeof(_Tp) <= sizeof(unsigned long))
  35. return std::__libcpp_popcount(static_cast<unsigned long>(__t));
  36. else if (sizeof(_Tp) <= sizeof(unsigned long long))
  37. return std::__libcpp_popcount(static_cast<unsigned long long>(__t));
  38. else {
  39. int __ret = 0;
  40. while (__t != 0) {
  41. __ret += std::__libcpp_popcount(static_cast<unsigned long long>(__t));
  42. __t >>= numeric_limits<unsigned long long>::digits;
  43. }
  44. return __ret;
  45. }
  46. }
  47. #endif // _LIBCPP_STD_VER >= 20
  48. _LIBCPP_END_NAMESPACE_STD
  49. _LIBCPP_POP_MACROS
  50. #endif // _LIBCPP___BIT_POPCOUNT_H