-
Notifications
You must be signed in to change notification settings - Fork 14.4k
[libc++] Optimize {std,ranges}::distance for segmented iterators #133612
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,41 +10,82 @@ | |
#ifndef _LIBCPP___ITERATOR_DISTANCE_H | ||
#define _LIBCPP___ITERATOR_DISTANCE_H | ||
|
||
#include <__algorithm/for_each_segment.h> | ||
#include <__config> | ||
#include <__iterator/concepts.h> | ||
#include <__iterator/incrementable_traits.h> | ||
#include <__iterator/iterator_traits.h> | ||
#include <__iterator/segmented_iterator.h> | ||
#include <__ranges/access.h> | ||
#include <__ranges/concepts.h> | ||
#include <__ranges/size.h> | ||
#include <__type_traits/decay.h> | ||
#include <__type_traits/enable_if.h> | ||
#include <__type_traits/remove_cvref.h> | ||
#include <__utility/move.h> | ||
|
||
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) | ||
# pragma GCC system_header | ||
#endif | ||
|
||
_LIBCPP_PUSH_MACROS | ||
#include <__undef_macros> | ||
|
||
_LIBCPP_BEGIN_NAMESPACE_STD | ||
|
||
template <class _InputIter> | ||
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 typename iterator_traits<_InputIter>::difference_type | ||
__distance(_InputIter __first, _InputIter __last, input_iterator_tag) { | ||
typename iterator_traits<_InputIter>::difference_type __r(0); | ||
#if _LIBCPP_STD_VER >= 20 | ||
template <class _Iter> | ||
using __iter_distance_t _LIBCPP_NODEBUG = std::iter_difference_t<_Iter>; | ||
#else | ||
template <class _Iter> | ||
using __iter_distance_t _LIBCPP_NODEBUG = typename iterator_traits<_Iter>::difference_type; | ||
#endif | ||
|
||
template <class _InputIter, class _Sent> | ||
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 __iter_distance_t<_InputIter> | ||
__distance(_InputIter __first, _Sent __last) { | ||
__iter_distance_t<_InputIter> __r(0); | ||
for (; __first != __last; ++__first) | ||
++__r; | ||
return __r; | ||
} | ||
|
||
template <class _RandIter> | ||
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 typename iterator_traits<_RandIter>::difference_type | ||
__distance(_RandIter __first, _RandIter __last, random_access_iterator_tag) { | ||
template <class _RandIter, __enable_if_t<__has_random_access_iterator_category<_RandIter>::value, int> = 0> | ||
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 __iter_distance_t<_RandIter> | ||
__distance(_RandIter __first, _RandIter __last) { | ||
return __last - __first; | ||
} | ||
|
||
template <class _SegmentedIter, class _Difference> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there a reason to apply this optimization before C++20? AFAICT this only applies to There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks! I've now made this optimization only for |
||
struct __segment_distance { | ||
using _Traits _LIBCPP_NODEBUG = __segmented_iterator_traits<_SegmentedIter>; | ||
|
||
_Difference& __r_; | ||
|
||
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 explicit __segment_distance(_Difference& __r) : __r_(__r) {} | ||
|
||
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 void | ||
operator()(typename _Traits::__local_iterator __lfirst, typename _Traits::__local_iterator __llast) { | ||
__r_ += std::__distance(__lfirst, __llast); | ||
} | ||
}; | ||
|
||
template <class _SegmentedIter, | ||
__enable_if_t<!__has_random_access_iterator_category<_SegmentedIter>::value && | ||
__is_segmented_iterator<_SegmentedIter>::value, | ||
int> = 0> | ||
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 __iter_distance_t<_SegmentedIter> | ||
__distance(_SegmentedIter __first, _SegmentedIter __last) { | ||
using __difference_type = __iter_distance_t<_SegmentedIter>; | ||
__difference_type __r(0); | ||
std::__for_each_segment(__first, __last, std::__segment_distance<_SegmentedIter, __difference_type>(__r)); | ||
return __r; | ||
} | ||
|
||
template <class _InputIter> | ||
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX17 typename iterator_traits<_InputIter>::difference_type | ||
distance(_InputIter __first, _InputIter __last) { | ||
return std::__distance(__first, __last, typename iterator_traits<_InputIter>::iterator_category()); | ||
return std::__distance(__first, __last); | ||
} | ||
|
||
#if _LIBCPP_STD_VER >= 20 | ||
|
@@ -56,12 +97,7 @@ struct __distance { | |
template <class _Ip, sentinel_for<_Ip> _Sp> | ||
requires(!sized_sentinel_for<_Sp, _Ip>) | ||
_LIBCPP_HIDE_FROM_ABI constexpr iter_difference_t<_Ip> operator()(_Ip __first, _Sp __last) const { | ||
iter_difference_t<_Ip> __n = 0; | ||
while (__first != __last) { | ||
++__first; | ||
++__n; | ||
} | ||
return __n; | ||
return std::__distance(std::move(__first), std::move(__last)); | ||
} | ||
|
||
template <class _Ip, sized_sentinel_for<decay_t<_Ip>> _Sp> | ||
|
@@ -92,4 +128,6 @@ inline constexpr auto distance = __distance{}; | |
|
||
_LIBCPP_END_NAMESPACE_STD | ||
|
||
_LIBCPP_POP_MACROS | ||
|
||
#endif // _LIBCPP___ITERATOR_DISTANCE_H |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||
// See https://llvm.org/LICENSE.txt for license information. | ||
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
// UNSUPPORTED: c++03, c++11, c++14, c++17 | ||
|
||
#include <cstddef> | ||
#include <deque> | ||
#include <iterator> | ||
#include <ranges> | ||
#include <vector> | ||
|
||
#include <benchmark/benchmark.h> | ||
|
||
int main(int argc, char** argv) { | ||
auto std_distance = [](auto first, auto last) { return std::distance(first, last); }; | ||
|
||
// {std,ranges}::distance | ||
{ | ||
auto bm = []<class Container>(std::string name, auto distance, std::size_t seg_size) { | ||
benchmark::RegisterBenchmark( | ||
name, | ||
[distance, seg_size](auto& st) { | ||
std::size_t const size = st.range(0); | ||
std::size_t const segments = (size + seg_size - 1) / seg_size; | ||
Container c(segments); | ||
for (std::size_t i = 0, n = size; i < segments; ++i, n -= seg_size) { | ||
c[i].resize(std::min(seg_size, n)); | ||
} | ||
|
||
auto view = c | std::views::join; | ||
auto first = view.begin(); | ||
auto last = view.end(); | ||
|
||
for ([[maybe_unused]] auto _ : st) { | ||
benchmark::DoNotOptimize(c); | ||
auto result = distance(first, last); | ||
benchmark::DoNotOptimize(result); | ||
} | ||
}) | ||
->Arg(50) // non power-of-two | ||
->Arg(1024) | ||
->Arg(4096) | ||
->Arg(8192); | ||
// ->Arg(1 << 14) | ||
// ->Arg(1 << 16) | ||
// ->Arg(1 << 18) | ||
// ->Arg(1 << 20); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Did you mean to leave those commented? Let's either keep them uncommented or drop them. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've dropped these large benchmark sizes, which were only used when running the benchmarks for this patch. |
||
}; | ||
bm.operator()<std::vector<std::vector<int>>>("std::distance(join_view(vector<vector<int>>))", std_distance, 256); | ||
bm.operator()<std::deque<std::deque<int>>>("std::distance(join_view(deque<deque<int>>))", std_distance, 256); | ||
bm.operator()<std::vector<std::vector<int>>>( | ||
"rng::distance(join_view(vector<vector<int>>)", std::ranges::distance, 256); | ||
bm.operator()<std::deque<std::deque<int>>>( | ||
"rng::distance(join_view(deque<deque<int>>)", std::ranges::distance, 256); | ||
|
||
bm.operator()<std::vector<std::vector<int>>>("std::distance(join_view(vector<vector<int>>))", std_distance, 1024); | ||
bm.operator()<std::deque<std::deque<int>>>("std::distance(join_view(deque<deque<int>>))", std_distance, 1024); | ||
bm.operator()<std::vector<std::vector<int>>>( | ||
"rng::distance(join_view(vector<vector<int>>)", std::ranges::distance, 1024); | ||
bm.operator()<std::deque<std::deque<int>>>( | ||
"rng::distance(join_view(deque<deque<int>>)", std::ranges::distance, 1024); | ||
} | ||
|
||
benchmark::Initialize(&argc, argv); | ||
benchmark::RunSpecifiedBenchmarks(); | ||
benchmark::Shutdown(); | ||
return 0; | ||
} |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not attached to this file: let's add a release note! There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We already have
__iter_diff_t
initerator_traits.h
. It doesn't do exactly what you want, but I think we should make it do what you need instead of introducing a new thing that's essentially identical.Basically, we should try re-defining
__iter_diff_t
initerator_traits.h
as:And if that's not possible for some reason, it would be interesting to understand why.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems that the standard hasn't requires
iterator_traits<I>::difference_type
to be same asiter_difference_t<I>
yet whenI
is a non-random-access iterator type. One is allowed to make them different by specializingincrementable_traits
. This is perhaps a defect, for which I've submitted LWG4080.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given the potential mismatch between
iterator_traits<I>::difference_type
anditer_difference_t<I>
(as pointed out by @frederick-vs-ja), I am now consistently usingiterator_traits<I>::difference_type
as the return type for the non-rangestd::__distance
algorithm, anditer_difference_t<I>
for the range algorithm.To enable the range algorithm to reuse the same optimization introduced for the non-range
std::__distance
, I am now adding astatic_cast
to explicitly cast the result ofstd::__distance
to the desired typeiter_difference_t<I>
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
However, this approach fails when the range algorithm
std::ranges::distance
forwards tostd::__distance
withI = cpp20_input_iterator
, resulting in a hard substitution error:no type named 'difference_type' in 'std::iterator_traits<cpp20_input_iterator<int *>>'
, as captured by the testsrange.pass.cpp
anditerator_sentinel.pass.cpp
(see the full log: stage1 (generic-modules, clang-21, clang++-21)).The root cause for this error is that
cpp20_input_iterator
does not have the member typeiterator_category
(although it provides theiterator_concept
member type), leading to a hard substitution failure instd::iterator_traits<cpp20_input_iterator<Iter>>::difference_type
(See A reproducer).To resolve this, I still need the above internal definition of
__iter_distance_t
, which is used as the return type of the internal functionstd::__distance
. This allows both the non-rangestd::distance
and range versionstd::ranges::distance
to share the same implementation and optimization. However, to handle the potential mismatch betweeniterator_traits<I>::difference_type
anditer_difference_t<I>
, I explicitly specifiediterator_traits<I>::difference_type
as the return type ofstd::distance
anditer_difference_t<I>
as the return type ofstd::ranges::distance
. This way the underlying implicit conversion would automatically take place when there is a type mismatch.I am a bit hesitant to make this change because
__iter_diff_t
is currently unconditionally defined asiterator_traits<_Iter>::difference_type
, and it is used by many algorithms. Making this change would introduce the potential type mismatch to many algorithms. My current approach with the introduction of__iter_distance_t
ensures that the potential type mismatch is confined and handled withindistance.h
.