Skip to content

Commit

Permalink
[libc++] Fix the rotate direction used in countl_zero()
Browse files Browse the repository at this point in the history
This "bug" was probably not noticed because it doesn't affect any integer
type we currently support. It requires integers with more than 2x the
size of `unsigned long long`. However, with such types, the algorithm
used to break down the large integer into groups of size `unsigned long long`
didn't work because we rotated in the wrong direction.

For example, the 256 bit number (1 << 255) would yield the wrong answer
when used with the algorithm before this patch.

In particular, note that the current rotation happens to work for 128 bit
integers because it just swaps the halves in this case.

Differential Revision: https://reviews.llvm.org/D134625
Co-authored-by: Louis Dionne <[email protected]>
  • Loading branch information
Delta-dev-99 authored and ldionne committed Sep 12, 2023
1 parent da81b1b commit d78ca73
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
2 changes: 1 addition & 1 deletion libcxx/include/__bit/countl.h
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ int __countl_zero(_Tp __t) _NOEXCEPT
int __iter = 0;
const unsigned int __ulldigits = numeric_limits<unsigned long long>::digits;
while (true) {
__t = std::__rotr(__t, __ulldigits);
__t = std::__rotl(__t, __ulldigits);
if ((__iter = std::__countl_zero(static_cast<unsigned long long>(__t))) != __ulldigits)
break;
__ret += __iter;
Expand Down
7 changes: 6 additions & 1 deletion libcxx/include/__bit/rotate.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,16 @@ _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotr(_Tp __t, int __cn
return (__t >> (__cnt % __dig)) | (__t << (__dig - (__cnt % __dig)));
}

template <class _Tp>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotl(_Tp __t, int __cnt) _NOEXCEPT {
return std::__rotr(__t, -__cnt);
}

#if _LIBCPP_STD_VER >= 20

template <__libcpp_unsigned_integer _Tp>
[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotl(_Tp __t, int __cnt) noexcept {
return std::__rotr(__t, -__cnt);
return std::__rotl(__t, __cnt);
}

template <__libcpp_unsigned_integer _Tp>
Expand Down

0 comments on commit d78ca73

Please sign in to comment.