Path: blob/main/contrib/llvm-project/libcxx/include/__bit/popcount.h
35260 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78// TODO: __builtin_popcountg is available since Clang 19 and GCC 14. When support for older versions is dropped, we can9// refactor this code to exclusively use __builtin_popcountg.1011#ifndef _LIBCPP___BIT_POPCOUNT_H12#define _LIBCPP___BIT_POPCOUNT_H1314#include <__bit/rotate.h>15#include <__concepts/arithmetic.h>16#include <__config>17#include <limits>1819#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)20# pragma GCC system_header21#endif2223_LIBCPP_PUSH_MACROS24#include <__undef_macros>2526_LIBCPP_BEGIN_NAMESPACE_STD2728inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_popcount(unsigned __x) _NOEXCEPT {29return __builtin_popcount(__x);30}3132inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_popcount(unsigned long __x) _NOEXCEPT {33return __builtin_popcountl(__x);34}3536inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR int __libcpp_popcount(unsigned long long __x) _NOEXCEPT {37return __builtin_popcountll(__x);38}3940#if _LIBCPP_STD_VER >= 204142template <__libcpp_unsigned_integer _Tp>43[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr int popcount(_Tp __t) noexcept {44# if __has_builtin(__builtin_popcountg)45return __builtin_popcountg(__t);46# else // __has_builtin(__builtin_popcountg)47if (sizeof(_Tp) <= sizeof(unsigned int))48return std::__libcpp_popcount(static_cast<unsigned int>(__t));49else if (sizeof(_Tp) <= sizeof(unsigned long))50return std::__libcpp_popcount(static_cast<unsigned long>(__t));51else if (sizeof(_Tp) <= sizeof(unsigned long long))52return std::__libcpp_popcount(static_cast<unsigned long long>(__t));53else {54int __ret = 0;55while (__t != 0) {56__ret += std::__libcpp_popcount(static_cast<unsigned long long>(__t));57__t >>= numeric_limits<unsigned long long>::digits;58}59return __ret;60}61# endif // __has_builtin(__builtin_popcountg)62}6364#endif // _LIBCPP_STD_VER >= 206566_LIBCPP_END_NAMESPACE_STD6768_LIBCPP_POP_MACROS6970#endif // _LIBCPP___BIT_POPCOUNT_H717273