[libcxx-commits] [libcxx] [libc++] Optimize bitset shift operations (PR #106225)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu Sep 12 09:43:39 PDT 2024


================
@@ -290,6 +290,15 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI __bit_iterator<_Cp, false> _
 template <class _Cp, bool _IsConst>
 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 __bit_iterator<_Cp, false>
 copy(__bit_iterator<_Cp, _IsConst> __first, __bit_iterator<_Cp, _IsConst> __last, __bit_iterator<_Cp, false> __result) {
+  if (__builtin_constant_p(
+          __result.__ctz_ == 0 && __first.__seg_ == __last.__seg_ && __last.__seg_ == __result.__seg_) &&
+      __result.__ctz_ == 0 && __first.__seg_ == __last.__seg_ && __last.__seg_ == __result.__seg_) {
+    if (__first == __last)
+      return __result;
+    *__result.__seg_ >>= __first.__ctz_;
----------------
ldionne wrote:

Based on our discussion just now, I think what you want to do is something like:

```
Starting point
====================================
xxxxxxxxxyyyyyyyyyyyyyxxxxxxxxxx
         ^           ^         ^
                             result
       last        first

Desired result (where Y is y's that were not moved around)
====================================
xxxxxxxxxYYYYYYYYYYyyyyyyyyyyyyy
         ^           ^         ^
                             result
       last        first



xxxxxxxxxyyyyyyyyyy0000000000000   (A)
bitor
0000000000000000000yyyyyyyyyyyyy   (B)
=
xxxxxxxxxYYYYYYYYYYyyyyyyyyyyyyy
         ^           ^         ^
                             result
       last        first
```

Now, we have:

```
mask = (~0 << (last - first))

(A) = mask & originalthing
(B) = ~mask & (originalthing >> first.ctz)
```

I *think* this should work. Obviously we need some pretty good testing for that (which we don't seem to have right now). We should also consider all the degenerate cases that might exist.

It would also be nice to re-run the benchmark in light of these changes.

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


More information about the libcxx-commits mailing list