llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[libc++][PSTL] Dispatching to default algorithms is broken in some cases (at least std::any_of)

Open ldionne opened this issue 3 years ago • 2 comments

The default implementation of std::none_of in the PSTL is (here):

      [&](_ForwardIterator __g_first, _ForwardIterator __g_last, _Pred __g_pred) -> optional<bool> {
        auto __res = std::__any_of(__policy, __g_first, __g_last, __g_pred);
        if (!__res)
          return nullopt;
        return !*__res;
      },

Notice how this calls std::__any_of with lvalues __g_first, __g_last, __g_pred. Now, __any_of is implemented like (here):

template <class _ExecutionPolicy, class _ForwardIterator, class _Predicate, ...>
optional<bool>
__any_of(_ExecutionPolicy&& __policy, _ForwardIterator&& __first, _ForwardIterator&& __last, _Predicate&& __pred) {
  return std::__pstl_frontend_dispatch(
      _LIBCPP_PSTL_CUSTOMIZATION_POINT(__pstl_any_of, _RawPolicy),
      [&](_ForwardIterator __g_first, _ForwardIterator __g_last, _Predicate __g_pred) -> optional<bool> {
        auto __res = std::__find_if(__policy, __g_first, __g_last, __g_pred);
        if (!__res)
          return nullopt;
        return *__res != __g_last;
      },
      std::move(__first),
      std::move(__last),
      std::move(__pred));
}

Since __any_of is called with lvalues and we're taking universal references, when none_of calls __any_of we get the following deduction: _ForwardIterator&& == _Iter& && for some ref-unqualified type _Iter. As a result, the lambda declaration inside __any_of basically has signature [&](_Iter&, _Iter&, _Predicate) and that doesn't work since we're trying to pass it a rvalue (std::move(__first) & al).

This issue happens whenever the default implementation of std::any_of is used. It can be seen by removing:

libcxx/include/__algorithm/pstl_backends/cpu_backends/any_of.h

Normally, things should work even in that case because any_of is not a mandatory algorithm for general backends.

ldionne avatar Oct 30 '23 20:10 ldionne

Was the solution that we talked about just to change std::move to std::forward for each implementation that uses _LIBCPP_PSTL_CUSTOMIZATION_POINT , or do you think more changes are needed?

AntonRydahl avatar Oct 30 '23 21:10 AntonRydahl

I am not sure forward is what we want -- I wanted to talk to @philnik777 about it in our next 1:1.

ldionne avatar Oct 31 '23 04:10 ldionne