1 // -*- C++ -*-
2 //===----------------------------------------------------------------------===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef _PSTL_PARALLEL_BACKEND_TBB_H
11 #define _PSTL_PARALLEL_BACKEND_TBB_H
12 
13 #include <algorithm>
14 #include <type_traits>
15 
16 #include "pstl_config.h"
17 #include "parallel_backend_utils.h"
18 
19 // Bring in minimal required subset of Intel TBB
20 #include <tbb/blocked_range.h>
21 #include <tbb/parallel_for.h>
22 #include <tbb/parallel_reduce.h>
23 #include <tbb/parallel_scan.h>
24 #include <tbb/parallel_invoke.h>
25 #include <tbb/task_arena.h>
26 #include <tbb/tbb_allocator.h>
27 #include <tbb/task.h>
28 
29 #if TBB_INTERFACE_VERSION < 10000
30 #    error Intel(R) Threading Building Blocks 2018 is required; older versions are not supported.
31 #endif
32 
33 _PSTL_HIDE_FROM_ABI_PUSH
34 
35 namespace __pstl
36 {
37 namespace __tbb_backend
38 {
39 
40 //! Raw memory buffer with automatic freeing and no exceptions.
41 /** Some of our algorithms need to start with raw memory buffer,
42 not an initialize array, because initialization/destruction
43 would make the span be at least O(N). */
44 // tbb::allocator can improve performance in some cases.
45 template <typename _Tp>
46 class __buffer
47 {
48     tbb::tbb_allocator<_Tp> _M_allocator;
49     _Tp* _M_ptr;
50     const std::size_t _M_buf_size;
51     __buffer(const __buffer&) = delete;
52     void
53     operator=(const __buffer&) = delete;
54 
55   public:
56     //! Try to obtain buffer of given size to store objects of _Tp type
__buffer(std::size_t n)57     __buffer(std::size_t n) : _M_allocator(), _M_ptr(_M_allocator.allocate(n)), _M_buf_size(n) {}
58     //! True if buffer was successfully obtained, zero otherwise.
59     operator bool() const { return _M_ptr != NULL; }
60     //! Return pointer to buffer, or  NULL if buffer could not be obtained.
61     _Tp*
get()62     get() const
63     {
64         return _M_ptr;
65     }
66     //! Destroy buffer
~__buffer()67     ~__buffer() { _M_allocator.deallocate(_M_ptr, _M_buf_size); }
68 };
69 
70 // Wrapper for tbb::task
71 inline void
__cancel_execution()72 __cancel_execution()
73 {
74 #if TBB_INTERFACE_VERSION <= 12000
75     tbb::task::self().group()->cancel_group_execution();
76 #else
77     tbb::task::current_context()->cancel_group_execution();
78 #endif
79 }
80 
81 //------------------------------------------------------------------------
82 // parallel_for
83 //------------------------------------------------------------------------
84 
85 template <class _Index, class _RealBody>
86 class __parallel_for_body
87 {
88   public:
__parallel_for_body(const _RealBody & __body)89     __parallel_for_body(const _RealBody& __body) : _M_body(__body) {}
__parallel_for_body(const __parallel_for_body & __body)90     __parallel_for_body(const __parallel_for_body& __body) : _M_body(__body._M_body) {}
91     void
operator()92     operator()(const tbb::blocked_range<_Index>& __range) const
93     {
94         _M_body(__range.begin(), __range.end());
95     }
96 
97   private:
98     _RealBody _M_body;
99 };
100 
101 //! Evaluation of brick f[i,j) for each subrange [i,j) of [first,last)
102 // wrapper over tbb::parallel_for
103 template <class _ExecutionPolicy, class _Index, class _Fp>
104 void
__parallel_for(_ExecutionPolicy &&,_Index __first,_Index __last,_Fp __f)105 __parallel_for(_ExecutionPolicy&&, _Index __first, _Index __last, _Fp __f)
106 {
107     tbb::this_task_arena::isolate([=]() {
108         tbb::parallel_for(tbb::blocked_range<_Index>(__first, __last), __parallel_for_body<_Index, _Fp>(__f));
109     });
110 }
111 
112 //! Evaluation of brick f[i,j) for each subrange [i,j) of [first,last)
113 // wrapper over tbb::parallel_reduce
114 template <class _ExecutionPolicy, class _Value, class _Index, typename _RealBody, typename _Reduction>
115 _Value
__parallel_reduce(_ExecutionPolicy &&,_Index __first,_Index __last,const _Value & __identity,const _RealBody & __real_body,const _Reduction & __reduction)116 __parallel_reduce(_ExecutionPolicy&&, _Index __first, _Index __last, const _Value& __identity,
117                   const _RealBody& __real_body, const _Reduction& __reduction)
118 {
119     return tbb::this_task_arena::isolate([__first, __last, &__identity, &__real_body, &__reduction]() -> _Value {
120         return tbb::parallel_reduce(
121             tbb::blocked_range<_Index>(__first, __last), __identity,
122             [__real_body](const tbb::blocked_range<_Index>& __r, const _Value& __value) -> _Value {
123                 return __real_body(__r.begin(), __r.end(), __value);
124             },
125             __reduction);
126     });
127 }
128 
129 //------------------------------------------------------------------------
130 // parallel_transform_reduce
131 //
132 // Notation:
133 //      r(i,j,init) returns reduction of init with reduction over [i,j)
134 //      u(i) returns f(i,i+1,identity) for a hypothetical left identity element of r
135 //      c(x,y) combines values x and y that were the result of r or u
136 //------------------------------------------------------------------------
137 
138 template <class _Index, class _Up, class _Tp, class _Cp, class _Rp>
139 struct __par_trans_red_body
140 {
141     alignas(_Tp) char _M_sum_storage[sizeof(_Tp)]; // Holds generalized non-commutative sum when has_sum==true
142     _Rp _M_brick_reduce;                           // Most likely to have non-empty layout
143     _Up _M_u;
144     _Cp _M_combine;
145     bool _M_has_sum; // Put last to minimize size of class
146     _Tp&
sum__par_trans_red_body147     sum()
148     {
149         __TBB_ASSERT(_M_has_sum, "sum expected");
150         return *(_Tp*)_M_sum_storage;
151     }
__par_trans_red_body__par_trans_red_body152     __par_trans_red_body(_Up __u, _Tp __init, _Cp __c, _Rp __r)
153         : _M_brick_reduce(__r), _M_u(__u), _M_combine(__c), _M_has_sum(true)
154     {
155         new (_M_sum_storage) _Tp(__init);
156     }
157 
__par_trans_red_body__par_trans_red_body158     __par_trans_red_body(__par_trans_red_body& __left, tbb::split)
159         : _M_brick_reduce(__left._M_brick_reduce), _M_u(__left._M_u), _M_combine(__left._M_combine), _M_has_sum(false)
160     {
161     }
162 
~__par_trans_red_body__par_trans_red_body163     ~__par_trans_red_body()
164     {
165         // 17.6.5.12 tells us to not worry about catching exceptions from destructors.
166         if (_M_has_sum)
167             sum().~_Tp();
168     }
169 
170     void
join__par_trans_red_body171     join(__par_trans_red_body& __rhs)
172     {
173         sum() = _M_combine(sum(), __rhs.sum());
174     }
175 
176     void
operator__par_trans_red_body177     operator()(const tbb::blocked_range<_Index>& __range)
178     {
179         _Index __i = __range.begin();
180         _Index __j = __range.end();
181         if (!_M_has_sum)
182         {
183             __TBB_ASSERT(__range.size() > 1, "there should be at least 2 elements");
184             new (&_M_sum_storage)
185                 _Tp(_M_combine(_M_u(__i), _M_u(__i + 1))); // The condition i+1 < j is provided by the grain size of 3
186             _M_has_sum = true;
187             std::advance(__i, 2);
188             if (__i == __j)
189                 return;
190         }
191         sum() = _M_brick_reduce(__i, __j, sum());
192     }
193 };
194 
195 template <class _ExecutionPolicy, class _Index, class _Up, class _Tp, class _Cp, class _Rp>
196 _Tp
__parallel_transform_reduce(_ExecutionPolicy &&,_Index __first,_Index __last,_Up __u,_Tp __init,_Cp __combine,_Rp __brick_reduce)197 __parallel_transform_reduce(_ExecutionPolicy&&, _Index __first, _Index __last, _Up __u, _Tp __init, _Cp __combine,
198                             _Rp __brick_reduce)
199 {
200     __tbb_backend::__par_trans_red_body<_Index, _Up, _Tp, _Cp, _Rp> __body(__u, __init, __combine, __brick_reduce);
201     // The grain size of 3 is used in order to provide mininum 2 elements for each body
202     tbb::this_task_arena::isolate(
203         [__first, __last, &__body]() { tbb::parallel_reduce(tbb::blocked_range<_Index>(__first, __last, 3), __body); });
204     return __body.sum();
205 }
206 
207 //------------------------------------------------------------------------
208 // parallel_scan
209 //------------------------------------------------------------------------
210 
211 template <class _Index, class _Up, class _Tp, class _Cp, class _Rp, class _Sp>
212 class __trans_scan_body
213 {
214     alignas(_Tp) char _M_sum_storage[sizeof(_Tp)]; // Holds generalized non-commutative sum when has_sum==true
215     _Rp _M_brick_reduce;                           // Most likely to have non-empty layout
216     _Up _M_u;
217     _Cp _M_combine;
218     _Sp _M_scan;
219     bool _M_has_sum; // Put last to minimize size of class
220   public:
__trans_scan_body(_Up __u,_Tp __init,_Cp __combine,_Rp __reduce,_Sp __scan)221     __trans_scan_body(_Up __u, _Tp __init, _Cp __combine, _Rp __reduce, _Sp __scan)
222         : _M_brick_reduce(__reduce), _M_u(__u), _M_combine(__combine), _M_scan(__scan), _M_has_sum(true)
223     {
224         new (_M_sum_storage) _Tp(__init);
225     }
226 
__trans_scan_body(__trans_scan_body & __b,tbb::split)227     __trans_scan_body(__trans_scan_body& __b, tbb::split)
228         : _M_brick_reduce(__b._M_brick_reduce), _M_u(__b._M_u), _M_combine(__b._M_combine), _M_scan(__b._M_scan),
229           _M_has_sum(false)
230     {
231     }
232 
~__trans_scan_body()233     ~__trans_scan_body()
234     {
235         // 17.6.5.12 tells us to not worry about catching exceptions from destructors.
236         if (_M_has_sum)
237             sum().~_Tp();
238     }
239 
240     _Tp&
sum()241     sum() const
242     {
243         __TBB_ASSERT(_M_has_sum, "sum expected");
244         return *const_cast<_Tp*>(reinterpret_cast<_Tp const*>(_M_sum_storage));
245     }
246 
247     void
operator()248     operator()(const tbb::blocked_range<_Index>& __range, tbb::pre_scan_tag)
249     {
250         _Index __i = __range.begin();
251         _Index __j = __range.end();
252         if (!_M_has_sum)
253         {
254             new (&_M_sum_storage) _Tp(_M_u(__i));
255             _M_has_sum = true;
256             ++__i;
257             if (__i == __j)
258                 return;
259         }
260         sum() = _M_brick_reduce(__i, __j, sum());
261     }
262 
263     void
operator()264     operator()(const tbb::blocked_range<_Index>& __range, tbb::final_scan_tag)
265     {
266         sum() = _M_scan(__range.begin(), __range.end(), sum());
267     }
268 
269     void
reverse_join(__trans_scan_body & __a)270     reverse_join(__trans_scan_body& __a)
271     {
272         if (_M_has_sum)
273         {
274             sum() = _M_combine(__a.sum(), sum());
275         }
276         else
277         {
278             new (&_M_sum_storage) _Tp(__a.sum());
279             _M_has_sum = true;
280         }
281     }
282 
283     void
assign(__trans_scan_body & __b)284     assign(__trans_scan_body& __b)
285     {
286         sum() = __b.sum();
287     }
288 };
289 
290 template <typename _Index>
291 _Index
__split(_Index __m)292 __split(_Index __m)
293 {
294     _Index __k = 1;
295     while (2 * __k < __m)
296         __k *= 2;
297     return __k;
298 }
299 
300 //------------------------------------------------------------------------
301 // __parallel_strict_scan
302 //------------------------------------------------------------------------
303 
304 template <typename _Index, typename _Tp, typename _Rp, typename _Cp>
305 void
__upsweep(_Index __i,_Index __m,_Index __tilesize,_Tp * __r,_Index __lastsize,_Rp __reduce,_Cp __combine)306 __upsweep(_Index __i, _Index __m, _Index __tilesize, _Tp* __r, _Index __lastsize, _Rp __reduce, _Cp __combine)
307 {
308     if (__m == 1)
309         __r[0] = __reduce(__i * __tilesize, __lastsize);
310     else
311     {
312         _Index __k = __split(__m);
313         tbb::parallel_invoke(
314             [=] { __tbb_backend::__upsweep(__i, __k, __tilesize, __r, __tilesize, __reduce, __combine); },
315             [=] {
316                 __tbb_backend::__upsweep(__i + __k, __m - __k, __tilesize, __r + __k, __lastsize, __reduce, __combine);
317             });
318         if (__m == 2 * __k)
319             __r[__m - 1] = __combine(__r[__k - 1], __r[__m - 1]);
320     }
321 }
322 
323 template <typename _Index, typename _Tp, typename _Cp, typename _Sp>
324 void
__downsweep(_Index __i,_Index __m,_Index __tilesize,_Tp * __r,_Index __lastsize,_Tp __initial,_Cp __combine,_Sp __scan)325 __downsweep(_Index __i, _Index __m, _Index __tilesize, _Tp* __r, _Index __lastsize, _Tp __initial, _Cp __combine,
326             _Sp __scan)
327 {
328     if (__m == 1)
329         __scan(__i * __tilesize, __lastsize, __initial);
330     else
331     {
332         const _Index __k = __split(__m);
333         tbb::parallel_invoke(
334             [=] { __tbb_backend::__downsweep(__i, __k, __tilesize, __r, __tilesize, __initial, __combine, __scan); },
335             // Assumes that __combine never throws.
336             //TODO: Consider adding a requirement for user functors to be constant.
337             [=, &__combine] {
338                 __tbb_backend::__downsweep(__i + __k, __m - __k, __tilesize, __r + __k, __lastsize,
339                                            __combine(__initial, __r[__k - 1]), __combine, __scan);
340             });
341     }
342 }
343 
344 // Adapted from Intel(R) Cilk(TM) version from cilkpub.
345 // Let i:len denote a counted interval of length n starting at i.  s denotes a generalized-sum value.
346 // Expected actions of the functors are:
347 //     reduce(i,len) -> s  -- return reduction value of i:len.
348 //     combine(s1,s2) -> s -- return merged sum
349 //     apex(s) -- do any processing necessary between reduce and scan.
350 //     scan(i,len,initial) -- perform scan over i:len starting with initial.
351 // The initial range 0:n is partitioned into consecutive subranges.
352 // reduce and scan are each called exactly once per subrange.
353 // Thus callers can rely upon side effects in reduce.
354 // combine must not throw an exception.
355 // apex is called exactly once, after all calls to reduce and before all calls to scan.
356 // For example, it's useful for allocating a __buffer used by scan but whose size is the sum of all reduction values.
357 // T must have a trivial constructor and destructor.
358 template <class _ExecutionPolicy, typename _Index, typename _Tp, typename _Rp, typename _Cp, typename _Sp, typename _Ap>
359 void
__parallel_strict_scan(_ExecutionPolicy &&,_Index __n,_Tp __initial,_Rp __reduce,_Cp __combine,_Sp __scan,_Ap __apex)360 __parallel_strict_scan(_ExecutionPolicy&&, _Index __n, _Tp __initial, _Rp __reduce, _Cp __combine, _Sp __scan,
361                        _Ap __apex)
362 {
363     tbb::this_task_arena::isolate([=, &__combine]() {
364         if (__n > 1)
365         {
366             _Index __p = tbb::this_task_arena::max_concurrency();
367             const _Index __slack = 4;
368             _Index __tilesize = (__n - 1) / (__slack * __p) + 1;
369             _Index __m = (__n - 1) / __tilesize;
370             __buffer<_Tp> __buf(__m + 1);
371             _Tp* __r = __buf.get();
372             __tbb_backend::__upsweep(_Index(0), _Index(__m + 1), __tilesize, __r, __n - __m * __tilesize, __reduce,
373                                      __combine);
374 
375             // When __apex is a no-op and __combine has no side effects, a good optimizer
376             // should be able to eliminate all code between here and __apex.
377             // Alternatively, provide a default value for __apex that can be
378             // recognized by metaprogramming that conditionlly executes the following.
379             size_t __k = __m + 1;
380             _Tp __t = __r[__k - 1];
381             while ((__k &= __k - 1))
382                 __t = __combine(__r[__k - 1], __t);
383             __apex(__combine(__initial, __t));
384             __tbb_backend::__downsweep(_Index(0), _Index(__m + 1), __tilesize, __r, __n - __m * __tilesize, __initial,
385                                        __combine, __scan);
386             return;
387         }
388         // Fewer than 2 elements in sequence, or out of memory.  Handle has single block.
389         _Tp __sum = __initial;
390         if (__n)
391             __sum = __combine(__sum, __reduce(_Index(0), __n));
392         __apex(__sum);
393         if (__n)
394             __scan(_Index(0), __n, __initial);
395     });
396 }
397 
398 template <class _ExecutionPolicy, class _Index, class _Up, class _Tp, class _Cp, class _Rp, class _Sp>
399 _Tp
__parallel_transform_scan(_ExecutionPolicy &&,_Index __n,_Up __u,_Tp __init,_Cp __combine,_Rp __brick_reduce,_Sp __scan)400 __parallel_transform_scan(_ExecutionPolicy&&, _Index __n, _Up __u, _Tp __init, _Cp __combine, _Rp __brick_reduce,
401                           _Sp __scan)
402 {
403     __trans_scan_body<_Index, _Up, _Tp, _Cp, _Rp, _Sp> __body(__u, __init, __combine, __brick_reduce, __scan);
404     auto __range = tbb::blocked_range<_Index>(0, __n);
405     tbb::this_task_arena::isolate([__range, &__body]() { tbb::parallel_scan(__range, __body); });
406     return __body.sum();
407 }
408 
409 //------------------------------------------------------------------------
410 // parallel_stable_sort
411 //------------------------------------------------------------------------
412 
413 //------------------------------------------------------------------------
414 // stable_sort utilities
415 //
416 // These are used by parallel implementations but do not depend on them.
417 //------------------------------------------------------------------------
418 #define _PSTL_MERGE_CUT_OFF 2000
419 
420 template <typename _Func>
421 class __func_task;
422 template <typename _Func>
423 class __root_task;
424 
425 #if TBB_INTERFACE_VERSION <= 12000
426 class __task : public tbb::task
427 {
428   public:
429     template <typename _Fn>
430     __task*
make_continuation(_Fn && __f)431     make_continuation(_Fn&& __f)
432     {
433         return new (allocate_continuation()) __func_task<typename std::decay<_Fn>::type>(std::forward<_Fn>(__f));
434     }
435 
436     template <typename _Fn>
437     __task*
make_child_of(__task * parent,_Fn && __f)438     make_child_of(__task* parent, _Fn&& __f)
439     {
440         return new (parent->allocate_child()) __func_task<typename std::decay<_Fn>::type>(std::forward<_Fn>(__f));
441     }
442 
443     template <typename _Fn>
444     __task*
make_additional_child_of(tbb::task * parent,_Fn && __f)445     make_additional_child_of(tbb::task* parent, _Fn&& __f)
446     {
447         return new (tbb::task::allocate_additional_child_of(*parent))
448             __func_task<typename std::decay<_Fn>::type>(std::forward<_Fn>(__f));
449     }
450 
451     inline void
recycle_as_continuation()452     recycle_as_continuation()
453     {
454         tbb::task::recycle_as_continuation();
455     }
456 
457     inline void
recycle_as_child_of(__task * parent)458     recycle_as_child_of(__task* parent)
459     {
460         tbb::task::recycle_as_child_of(*parent);
461     }
462 
463     inline void
spawn(__task * __t)464     spawn(__task* __t)
465     {
466         tbb::task::spawn(*__t);
467     }
468 
469     template <typename _Fn>
470     static inline void
spawn_root_and_wait(__root_task<_Fn> & __root)471     spawn_root_and_wait(__root_task<_Fn>& __root)
472     {
473         tbb::task::spawn_root_and_wait(*__root._M_task);
474     }
475 };
476 
477 template <typename _Func>
478 class __func_task : public __task
479 {
480     _Func _M_func;
481 
482     tbb::task*
execute()483     execute()
484     {
485         return _M_func(this);
486     };
487 
488   public:
489     template <typename _Fn>
__func_task(_Fn && __f)490     __func_task(_Fn&& __f) : _M_func{std::forward<_Fn>(__f)}
491     {
492     }
493 
494     _Func&
body()495     body()
496     {
497         return _M_func;
498     }
499 };
500 
501 template <typename _Func>
502 class __root_task
503 {
504     tbb::task* _M_task;
505 
506   public:
507     template <typename... Args>
__root_task(Args &&...args)508     __root_task(Args&&... args)
509         : _M_task{new (tbb::task::allocate_root()) __func_task<_Func>{_Func(std::forward<Args>(args)...)}}
510     {
511     }
512 
513     friend class __task;
514     friend class __func_task<_Func>;
515 };
516 
517 #else  // TBB_INTERFACE_VERSION <= 12000
518 class __task : public tbb::detail::d1::task
519 {
520   protected:
521     tbb::detail::d1::small_object_allocator _M_allocator{};
522     tbb::detail::d1::execution_data* _M_execute_data{};
523     __task* _M_parent{};
524     std::atomic<int> _M_refcount{};
525     bool _M_recycle{};
526 
527     template <typename _Fn>
528     __task*
allocate_func_task(_Fn && __f)529     allocate_func_task(_Fn&& __f)
530     {
531         _PSTL_ASSERT(_M_execute_data != nullptr);
532         tbb::detail::d1::small_object_allocator __alloc{};
533         auto __t =
534             __alloc.new_object<__func_task<typename std::decay<_Fn>::type>>(*_M_execute_data, std::forward<_Fn>(__f));
535         __t->_M_allocator = __alloc;
536         return __t;
537     }
538 
539   public:
540     __task*
parent()541     parent()
542     {
543         return _M_parent;
544     }
545 
546     void
set_ref_count(int __n)547     set_ref_count(int __n)
548     {
549         _M_refcount.store(__n, std::memory_order_release);
550     }
551 
552     template <typename _Fn>
553     __task*
make_continuation(_Fn && __f)554     make_continuation(_Fn&& __f)
555     {
556         auto __t = allocate_func_task(std::forward<_Fn&&>(__f));
557         __t->_M_parent = _M_parent;
558         _M_parent = nullptr;
559         return __t;
560     }
561 
562     template <typename _Fn>
563     __task*
make_child_of(__task * __parent,_Fn && __f)564     make_child_of(__task* __parent, _Fn&& __f)
565     {
566         auto __t = allocate_func_task(std::forward<_Fn&&>(__f));
567         __t->_M_parent = __parent;
568         return __t;
569     }
570 
571     template <typename _Fn>
572     __task*
make_additional_child_of(__task * __parent,_Fn && __f)573     make_additional_child_of(__task* __parent, _Fn&& __f)
574     {
575         auto __t = make_child_of(__parent, std::forward<_Fn>(__f));
576         _PSTL_ASSERT(__parent->_M_refcount.load(std::memory_order_relaxed) > 0);
577         ++__parent->_M_refcount;
578         return __t;
579     }
580 
581     inline void
recycle_as_continuation()582     recycle_as_continuation()
583     {
584         _M_recycle = true;
585     }
586 
587     inline void
recycle_as_child_of(__task * parent)588     recycle_as_child_of(__task* parent)
589     {
590         _M_recycle = true;
591         _M_parent = parent;
592     }
593 
594     inline void
spawn(__task * __t)595     spawn(__task* __t)
596     {
597         _PSTL_ASSERT(_M_execute_data != nullptr);
598         tbb::detail::d1::spawn(*__t, *_M_execute_data->context);
599     }
600 
601     template <typename _Fn>
602     static inline void
spawn_root_and_wait(__root_task<_Fn> & __root)603     spawn_root_and_wait(__root_task<_Fn>& __root)
604     {
605         tbb::detail::d1::execute_and_wait(*__root._M_func_task, __root._M_context, __root._M_wait_object,
606                                           __root._M_context);
607     }
608 
609     template <typename _Func>
610     friend class __func_task;
611 };
612 
613 template <typename _Func>
614 class __func_task : public __task
615 {
616     _Func _M_func;
617 
618     __task*
execute(tbb::detail::d1::execution_data & __ed)619     execute(tbb::detail::d1::execution_data& __ed) override
620     {
621         _M_execute_data = &__ed;
622         _M_recycle = false;
623         __task* __next = _M_func(this);
624         return finalize(__next);
625     };
626 
627     __task*
cancel(tbb::detail::d1::execution_data & __ed)628     cancel(tbb::detail::d1::execution_data& __ed) override
629     {
630         return finalize(nullptr);
631     }
632 
633     __task*
finalize(__task * __next)634     finalize(__task* __next)
635     {
636         bool __recycle = _M_recycle;
637         _M_recycle = false;
638 
639         if (__recycle)
640         {
641             return __next;
642         }
643 
644         auto __parent = _M_parent;
645         auto __alloc = _M_allocator;
646         auto __ed = _M_execute_data;
647 
648         this->~__func_task();
649 
650         _PSTL_ASSERT(__parent != nullptr);
651         _PSTL_ASSERT(__parent->_M_refcount.load(std::memory_order_relaxed) > 0);
652         if (--__parent->_M_refcount == 0)
653         {
654             _PSTL_ASSERT(__next == nullptr);
655             __alloc.deallocate(this, *__ed);
656             return __parent;
657         }
658 
659         return __next;
660     }
661 
662     friend class __root_task<_Func>;
663 
664   public:
665     template <typename _Fn>
__func_task(_Fn && __f)666     __func_task(_Fn&& __f) : _M_func(std::forward<_Fn>(__f))
667     {
668     }
669 
670     _Func&
body()671     body()
672     {
673         return _M_func;
674     }
675 };
676 
677 template <typename _Func>
678 class __root_task : public __task
679 {
680     __task*
execute(tbb::detail::d1::execution_data & __ed)681     execute(tbb::detail::d1::execution_data& __ed) override
682     {
683         _M_wait_object.release();
684         return nullptr;
685     };
686 
687     __task*
cancel(tbb::detail::d1::execution_data & __ed)688     cancel(tbb::detail::d1::execution_data& __ed) override
689     {
690         _M_wait_object.release();
691         return nullptr;
692     }
693 
694     __func_task<_Func>* _M_func_task{};
695     tbb::detail::d1::wait_context _M_wait_object{0};
696     tbb::task_group_context _M_context{};
697 
698   public:
699     template <typename... Args>
__root_task(Args &&...args)700     __root_task(Args&&... args) : _M_wait_object{1}
701     {
702         tbb::detail::d1::small_object_allocator __alloc{};
703         _M_func_task = __alloc.new_object<__func_task<_Func>>(_Func(std::forward<Args>(args)...));
704         _M_func_task->_M_allocator = __alloc;
705         _M_func_task->_M_parent = this;
706         _M_refcount.store(1, std::memory_order_relaxed);
707     }
708 
709     friend class __task;
710 };
711 #endif // TBB_INTERFACE_VERSION <= 12000
712 
713 template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _Compare, typename _Cleanup,
714           typename _LeafMerge>
715 class __merge_func
716 {
717     typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type _DifferenceType1;
718     typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type _DifferenceType2;
719     typedef typename std::common_type<_DifferenceType1, _DifferenceType2>::type _SizeType;
720     typedef typename std::iterator_traits<_RandomAccessIterator1>::value_type _ValueType;
721 
722     _RandomAccessIterator1 _M_x_beg;
723     _RandomAccessIterator2 _M_z_beg;
724 
725     _SizeType _M_xs, _M_xe;
726     _SizeType _M_ys, _M_ye;
727     _SizeType _M_zs;
728     _Compare _M_comp;
729     _LeafMerge _M_leaf_merge;
730     _SizeType _M_nsort; //number of elements to be sorted for partial_sort alforithm
731 
732     static const _SizeType __merge_cut_off = _PSTL_MERGE_CUT_OFF;
733 
734     bool _root;   //means a task is merging root task
735     bool _x_orig; //"true" means X(or left ) subrange is in the original container; false - in the buffer
736     bool _y_orig; //"true" means Y(or right) subrange is in the original container; false - in the buffer
737     bool _split; //"true" means a merge task is a split task for parallel merging, the execution logic differs
738 
739     bool
is_partial()740     is_partial() const
741     {
742         return _M_nsort > 0;
743     }
744 
745     struct __move_value
746     {
747         template <typename Iterator1, typename Iterator2>
748         void
operator__move_value749         operator()(Iterator1 __x, Iterator2 __z)
750         {
751             *__z = std::move(*__x);
752         }
753     };
754 
755     struct __move_value_construct
756     {
757         template <typename Iterator1, typename Iterator2>
758         void
operator__move_value_construct759         operator()(Iterator1 __x, Iterator2 __z)
760         {
761             ::new (std::addressof(*__z)) _ValueType(std::move(*__x));
762         }
763     };
764 
765     struct __move_range
766     {
767         template <typename Iterator1, typename Iterator2>
768         Iterator2
operator__move_range769         operator()(Iterator1 __first1, Iterator1 __last1, Iterator2 __first2)
770         {
771             if (__last1 - __first1 < __merge_cut_off)
772                 return std::move(__first1, __last1, __first2);
773 
774             auto __n = __last1 - __first1;
775             tbb::parallel_for(tbb::blocked_range<_SizeType>(0, __n, __merge_cut_off),
776                               [__first1, __first2](const tbb::blocked_range<_SizeType>& __range) {
777                                   std::move(__first1 + __range.begin(), __first1 + __range.end(),
778                                             __first2 + __range.begin());
779                               });
780             return __first2 + __n;
781         }
782     };
783 
784     struct __move_range_construct
785     {
786         template <typename Iterator1, typename Iterator2>
787         Iterator2
operator__move_range_construct788         operator()(Iterator1 __first1, Iterator1 __last1, Iterator2 __first2)
789         {
790             if (__last1 - __first1 < __merge_cut_off)
791             {
792                 for (; __first1 != __last1; ++__first1, ++__first2)
793                     __move_value_construct()(__first1, __first2);
794                 return __first2;
795             }
796 
797             auto __n = __last1 - __first1;
798             tbb::parallel_for(tbb::blocked_range<_SizeType>(0, __n, __merge_cut_off),
799                               [__first1, __first2](const tbb::blocked_range<_SizeType>& __range) {
800                                   for (auto i = __range.begin(); i != __range.end(); ++i)
801                                       __move_value_construct()(__first1 + i, __first2 + i);
802                               });
803             return __first2 + __n;
804         }
805     };
806 
807     struct __cleanup_range
808     {
809         template <typename Iterator>
810         void
operator__cleanup_range811         operator()(Iterator __first, Iterator __last)
812         {
813             if (__last - __first < __merge_cut_off)
814                 _Cleanup()(__first, __last);
815             else
816             {
817                 auto __n = __last - __first;
818                 tbb::parallel_for(tbb::blocked_range<_SizeType>(0, __n, __merge_cut_off),
819                                   [__first](const tbb::blocked_range<_SizeType>& __range) {
820                                       _Cleanup()(__first + __range.begin(), __first + __range.end());
821                                   });
822             }
823         }
824     };
825 
826   public:
__merge_func(_SizeType __xs,_SizeType __xe,_SizeType __ys,_SizeType __ye,_SizeType __zs,_Compare __comp,_Cleanup,_LeafMerge __leaf_merge,_SizeType __nsort,_RandomAccessIterator1 __x_beg,_RandomAccessIterator2 __z_beg,bool __x_orig,bool __y_orig,bool __root)827     __merge_func(_SizeType __xs, _SizeType __xe, _SizeType __ys, _SizeType __ye, _SizeType __zs, _Compare __comp,
828                  _Cleanup, _LeafMerge __leaf_merge, _SizeType __nsort, _RandomAccessIterator1 __x_beg,
829                  _RandomAccessIterator2 __z_beg, bool __x_orig, bool __y_orig, bool __root)
830         : _M_xs(__xs), _M_xe(__xe), _M_ys(__ys), _M_ye(__ye), _M_zs(__zs), _M_x_beg(__x_beg), _M_z_beg(__z_beg),
831           _M_comp(__comp), _M_leaf_merge(__leaf_merge), _M_nsort(__nsort), _root(__root),
832           _x_orig(__x_orig), _y_orig(__y_orig), _split(false)
833     {
834     }
835 
836     bool
is_left(_SizeType __idx)837     is_left(_SizeType __idx) const
838     {
839         return _M_xs == __idx;
840     }
841 
842     template <typename IndexType>
843     void
set_odd(IndexType __idx,bool __on_off)844     set_odd(IndexType __idx, bool __on_off)
845     {
846         if (is_left(__idx))
847             _x_orig = __on_off;
848         else
849             _y_orig = __on_off;
850     }
851 
852     __task*
853     operator()(__task* __self);
854 
855   private:
856     __merge_func*
parent_merge(__task * __self)857     parent_merge(__task* __self) const
858     {
859         return _root ? nullptr : &static_cast<__func_task<__merge_func>*>(__self->parent())->body();
860     }
861     bool
x_less_y()862     x_less_y()
863     {
864         const auto __nx = (_M_xe - _M_xs);
865         const auto __ny = (_M_ye - _M_ys);
866         _PSTL_ASSERT(__nx > 0 && __ny > 0);
867 
868         _PSTL_ASSERT(_x_orig == _y_orig);
869         _PSTL_ASSERT(!is_partial());
870 
871         if (_x_orig)
872         {
873             _PSTL_ASSERT(std::is_sorted(_M_x_beg + _M_xs, _M_x_beg + _M_xe, _M_comp));
874             _PSTL_ASSERT(std::is_sorted(_M_x_beg + _M_ys, _M_x_beg + _M_ye, _M_comp));
875             return !_M_comp(*(_M_x_beg + _M_ys), *(_M_x_beg + _M_xe - 1));
876         }
877 
878         _PSTL_ASSERT(std::is_sorted(_M_z_beg + _M_xs, _M_z_beg + _M_xe, _M_comp));
879         _PSTL_ASSERT(std::is_sorted(_M_z_beg + _M_ys, _M_z_beg + _M_ye, _M_comp));
880         return !_M_comp(*(_M_z_beg + _M_zs + __nx), *(_M_z_beg + _M_zs + __nx - 1));
881     }
882     void
move_x_range()883     move_x_range()
884     {
885         const auto __nx = (_M_xe - _M_xs);
886         const auto __ny = (_M_ye - _M_ys);
887         _PSTL_ASSERT(__nx > 0 && __ny > 0);
888 
889         if (_x_orig)
890             __move_range_construct()(_M_x_beg + _M_xs, _M_x_beg + _M_xe, _M_z_beg + _M_zs);
891         else
892         {
893             __move_range()(_M_z_beg + _M_zs, _M_z_beg + _M_zs + __nx, _M_x_beg + _M_xs);
894             __cleanup_range()(_M_z_beg + _M_zs, _M_z_beg + _M_zs + __nx);
895         }
896 
897         _x_orig = !_x_orig;
898     }
899     void
move_y_range()900     move_y_range()
901     {
902         const auto __nx = (_M_xe - _M_xs);
903         const auto __ny = (_M_ye - _M_ys);
904 
905         if (_y_orig)
906             __move_range_construct()(_M_x_beg + _M_ys, _M_x_beg + _M_ye, _M_z_beg + _M_zs + __nx);
907         else
908         {
909             __move_range()(_M_z_beg + _M_zs + __nx, _M_z_beg + _M_zs + __nx + __ny, _M_x_beg + _M_ys);
910             __cleanup_range()(_M_z_beg + _M_zs + __nx, _M_z_beg + _M_zs + __nx + __ny);
911         }
912 
913         _y_orig = !_y_orig;
914     }
915     __task*
merge_ranges(__task * __self)916     merge_ranges(__task* __self)
917     {
918         _PSTL_ASSERT(_x_orig == _y_orig); //two merged subrange must be lie into the same buffer
919 
920         const auto __nx = (_M_xe - _M_xs);
921         const auto __ny = (_M_ye - _M_ys);
922         const auto __n = __nx + __ny;
923 
924         // need to merge {x} and {y}
925         if (__n > __merge_cut_off)
926             return split_merging(__self);
927 
928         //merge to buffer
929         if (_x_orig)
930         {
931             _M_leaf_merge(_M_x_beg + _M_xs, _M_x_beg + _M_xe, _M_x_beg + _M_ys, _M_x_beg + _M_ye, _M_z_beg + _M_zs,
932                           _M_comp, __move_value_construct(), __move_value_construct(), __move_range_construct(),
933                           __move_range_construct());
934             _PSTL_ASSERT(parent_merge(__self)); //not root merging task
935         }
936         //merge to "origin"
937         else
938         {
939             _PSTL_ASSERT(_x_orig == _y_orig);
940 
941             _PSTL_ASSERT(is_partial() || std::is_sorted(_M_z_beg + _M_xs, _M_z_beg + _M_xe, _M_comp));
942             _PSTL_ASSERT(is_partial() || std::is_sorted(_M_z_beg + _M_ys, _M_z_beg + _M_ye, _M_comp));
943 
944             const auto __nx = (_M_xe - _M_xs);
945             const auto __ny = (_M_ye - _M_ys);
946 
947             _M_leaf_merge(_M_z_beg + _M_xs, _M_z_beg + _M_xe, _M_z_beg + _M_ys, _M_z_beg + _M_ye, _M_x_beg + _M_zs,
948                           _M_comp, __move_value(), __move_value(), __move_range(), __move_range());
949 
950             __cleanup_range()(_M_z_beg + _M_xs, _M_z_beg + _M_xe);
951             __cleanup_range()(_M_z_beg + _M_ys, _M_z_beg + _M_ye);
952         }
953         return nullptr;
954     }
955 
956     __task*
process_ranges(__task * __self)957     process_ranges(__task* __self)
958     {
959         _PSTL_ASSERT(_x_orig == _y_orig);
960         _PSTL_ASSERT(!_split);
961 
962         auto p = parent_merge(__self);
963 
964         if (!p)
965         { //root merging task
966 
967             //optimization, just for sort algorithm, //{x} <= {y}
968             if (!is_partial() && x_less_y()) //we have a solution
969             {
970                 if (!_x_orig)
971                 {                   //we have to move the solution to the origin
972                     move_x_range(); //parallel moving
973                     move_y_range(); //parallel moving
974                 }
975                 return nullptr;
976             }
977             //else: if we have data in the origin,
978             //we have to move data to the buffer for final merging into the origin.
979             if (_x_orig)
980             {
981                 move_x_range(); //parallel moving
982                 move_y_range(); //parallel moving
983             }
984             // need to merge {x} and {y}.
985             return merge_ranges(__self);
986         }
987         //else: not root merging task (parent_merge() == NULL)
988         //optimization, just for sort algorithm, //{x} <= {y}
989         if (!is_partial() && x_less_y())
990         {
991             const auto id_range = _M_zs;
992             p->set_odd(id_range, _x_orig);
993             return nullptr;
994         }
995         //else: we have to revert "_x(y)_orig" flag of the parent merging task
996         const auto id_range = _M_zs;
997         p->set_odd(id_range, !_x_orig);
998 
999         return merge_ranges(__self);
1000     }
1001 
1002     //splitting as merge task into 2 of the same level
1003     __task*
split_merging(__task * __self)1004     split_merging(__task* __self)
1005     {
1006         _PSTL_ASSERT(_x_orig == _y_orig);
1007         const auto __nx = (_M_xe - _M_xs);
1008         const auto __ny = (_M_ye - _M_ys);
1009 
1010         _SizeType __xm{};
1011         _SizeType __ym{};
1012         if (__nx < __ny)
1013         {
1014             __ym = _M_ys + __ny / 2;
1015 
1016             if (_x_orig)
1017                 __xm = std::upper_bound(_M_x_beg + _M_xs, _M_x_beg + _M_xe, *(_M_x_beg + __ym), _M_comp) - _M_x_beg;
1018             else
1019                 __xm = std::upper_bound(_M_z_beg + _M_xs, _M_z_beg + _M_xe, *(_M_z_beg + __ym), _M_comp) - _M_z_beg;
1020         }
1021         else
1022         {
1023             __xm = _M_xs + __nx / 2;
1024 
1025             if (_y_orig)
1026                 __ym = std::lower_bound(_M_x_beg + _M_ys, _M_x_beg + _M_ye, *(_M_x_beg + __xm), _M_comp) - _M_x_beg;
1027             else
1028                 __ym = std::lower_bound(_M_z_beg + _M_ys, _M_z_beg + _M_ye, *(_M_z_beg + __xm), _M_comp) - _M_z_beg;
1029         }
1030 
1031         auto __zm = _M_zs + ((__xm - _M_xs) + (__ym - _M_ys));
1032         __merge_func __right_func(__xm, _M_xe, __ym, _M_ye, __zm, _M_comp, _Cleanup(), _M_leaf_merge, _M_nsort,
1033                                   _M_x_beg, _M_z_beg, _x_orig, _y_orig, _root);
1034         __right_func._split = true;
1035         auto __merge_task = __self->make_additional_child_of(__self->parent(), std::move(__right_func));
1036         __self->spawn(__merge_task);
1037         __self->recycle_as_continuation();
1038 
1039         _M_xe = __xm;
1040         _M_ye = __ym;
1041         _split = true;
1042 
1043         return __self;
1044     }
1045 };
1046 
1047 template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename __M_Compare, typename _Cleanup,
1048           typename _LeafMerge>
1049 __task*
1050 __merge_func<_RandomAccessIterator1, _RandomAccessIterator2, __M_Compare, _Cleanup, _LeafMerge>::
operator()1051 operator()(__task* __self)
1052 {
1053     //a. split merge task into 2 of the same level; the special logic,
1054     //without processing(process_ranges) adjacent sub-ranges x and y
1055     if (_split)
1056         return merge_ranges(__self);
1057 
1058     //b. General merging of adjacent sub-ranges x and y (with optimization in case of {x} <= {y} )
1059 
1060     //1. x and y are in the even buffer
1061     //2. x and y are in the odd buffer
1062     if (_x_orig == _y_orig)
1063         return process_ranges(__self);
1064 
1065     //3. x is in even buffer, y is in the odd buffer
1066     //4. x is in odd buffer, y is in the even buffer
1067     if (!parent_merge(__self))
1068     { //root merge task
1069         if (_x_orig)
1070             move_x_range();
1071         else
1072             move_y_range();
1073     }
1074     else
1075     {
1076         const _SizeType __nx = (_M_xe - _M_xs);
1077         const _SizeType __ny = (_M_ye - _M_ys);
1078         _PSTL_ASSERT(__nx > 0);
1079         _PSTL_ASSERT(__nx > 0);
1080 
1081         if (__nx < __ny)
1082             move_x_range();
1083         else
1084             move_y_range();
1085     }
1086 
1087     return process_ranges(__self);
1088 }
1089 
1090 template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _Compare, typename _LeafSort>
1091 class __stable_sort_func
1092 {
1093   public:
1094     typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type _DifferenceType1;
1095     typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type _DifferenceType2;
1096     typedef typename std::common_type<_DifferenceType1, _DifferenceType2>::type _SizeType;
1097 
1098   private:
1099     _RandomAccessIterator1 _M_xs, _M_xe, _M_x_beg;
1100     _RandomAccessIterator2 _M_zs, _M_z_beg;
1101     _Compare _M_comp;
1102     _LeafSort _M_leaf_sort;
1103     bool _M_root;
1104     _SizeType _M_nsort; //zero or number of elements to be sorted for partial_sort alforithm
1105 
1106   public:
__stable_sort_func(_RandomAccessIterator1 __xs,_RandomAccessIterator1 __xe,_RandomAccessIterator2 __zs,bool __root,_Compare __comp,_LeafSort __leaf_sort,_SizeType __nsort,_RandomAccessIterator1 __x_beg,_RandomAccessIterator2 __z_beg)1107     __stable_sort_func(_RandomAccessIterator1 __xs, _RandomAccessIterator1 __xe, _RandomAccessIterator2 __zs,
1108                        bool __root, _Compare __comp, _LeafSort __leaf_sort, _SizeType __nsort,
1109                        _RandomAccessIterator1 __x_beg, _RandomAccessIterator2 __z_beg)
1110         : _M_xs(__xs), _M_xe(__xe), _M_x_beg(__x_beg), _M_zs(__zs), _M_z_beg(__z_beg), _M_comp(__comp),
1111           _M_leaf_sort(__leaf_sort), _M_root(__root), _M_nsort(__nsort)
1112     {
1113     }
1114 
1115     __task*
1116     operator()(__task* __self);
1117 };
1118 
1119 #define _PSTL_STABLE_SORT_CUT_OFF 500
1120 
1121 template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _Compare, typename _LeafSort>
1122 __task*
operator()1123 __stable_sort_func<_RandomAccessIterator1, _RandomAccessIterator2, _Compare, _LeafSort>::operator()(__task* __self)
1124 {
1125     typedef __merge_func<_RandomAccessIterator1, _RandomAccessIterator2, _Compare, __utils::__serial_destroy,
1126                          __utils::__serial_move_merge>
1127         _MergeTaskType;
1128 
1129     const _SizeType __n = _M_xe - _M_xs;
1130     const _SizeType __nmerge = _M_nsort > 0 ? _M_nsort : __n;
1131     const _SizeType __sort_cut_off = _PSTL_STABLE_SORT_CUT_OFF;
1132     if (__n <= __sort_cut_off)
1133     {
1134         _M_leaf_sort(_M_xs, _M_xe, _M_comp);
1135         _PSTL_ASSERT(!_M_root);
1136         return nullptr;
1137     }
1138 
1139     const _RandomAccessIterator1 __xm = _M_xs + __n / 2;
1140     const _RandomAccessIterator2 __zm = _M_zs + (__xm - _M_xs);
1141     const _RandomAccessIterator2 __ze = _M_zs + __n;
1142     _MergeTaskType __m(_MergeTaskType(_M_xs - _M_x_beg, __xm - _M_x_beg, __xm - _M_x_beg, _M_xe - _M_x_beg,
1143                                       _M_zs - _M_z_beg, _M_comp, __utils::__serial_destroy(),
1144                                       __utils::__serial_move_merge(__nmerge), _M_nsort, _M_x_beg, _M_z_beg,
1145                                       /*x_orig*/ true, /*y_orig*/ true, /*root*/ _M_root));
1146     auto __parent = __self->make_continuation(std::move(__m));
1147     __parent->set_ref_count(2);
1148     auto __right = __self->make_child_of(
1149         __parent, __stable_sort_func(__xm, _M_xe, __zm, false, _M_comp, _M_leaf_sort, _M_nsort, _M_x_beg, _M_z_beg));
1150     __self->spawn(__right);
1151     __self->recycle_as_child_of(__parent);
1152     _M_root = false;
1153     _M_xe = __xm;
1154 
1155     return __self;
1156 }
1157 
1158 template <class _ExecutionPolicy, typename _RandomAccessIterator, typename _Compare, typename _LeafSort>
1159 void
1160 __parallel_stable_sort(_ExecutionPolicy&&, _RandomAccessIterator __xs, _RandomAccessIterator __xe, _Compare __comp,
1161                        _LeafSort __leaf_sort, std::size_t __nsort = 0)
1162 {
1163     tbb::this_task_arena::isolate([=, &__nsort]() {
1164         //sorting based on task tree and parallel merge
1165         typedef typename std::iterator_traits<_RandomAccessIterator>::value_type _ValueType;
1166         typedef typename std::iterator_traits<_RandomAccessIterator>::difference_type _DifferenceType;
1167         const _DifferenceType __n = __xe - __xs;
1168         if (__nsort == __n)
1169             __nsort = 0; // 'partial_sort' becames 'sort'
1170 
1171         const _DifferenceType __sort_cut_off = _PSTL_STABLE_SORT_CUT_OFF;
1172         if (__n > __sort_cut_off)
1173         {
1174             __buffer<_ValueType> __buf(__n);
1175             __root_task<__stable_sort_func<_RandomAccessIterator, _ValueType*, _Compare, _LeafSort>> __root{
1176                 __xs, __xe, __buf.get(), true, __comp, __leaf_sort, __nsort, __xs, __buf.get()};
1177             __task::spawn_root_and_wait(__root);
1178             return;
1179         }
1180         //serial sort
1181         __leaf_sort(__xs, __xe, __comp);
1182     });
1183 }
1184 
1185 //------------------------------------------------------------------------
1186 // parallel_merge
1187 //------------------------------------------------------------------------
1188 template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _RandomAccessIterator3,
1189           typename _Compare, typename _LeafMerge>
1190 class __merge_func_static
1191 {
1192     _RandomAccessIterator1 _M_xs, _M_xe;
1193     _RandomAccessIterator2 _M_ys, _M_ye;
1194     _RandomAccessIterator3 _M_zs;
1195     _Compare _M_comp;
1196     _LeafMerge _M_leaf_merge;
1197 
1198   public:
__merge_func_static(_RandomAccessIterator1 __xs,_RandomAccessIterator1 __xe,_RandomAccessIterator2 __ys,_RandomAccessIterator2 __ye,_RandomAccessIterator3 __zs,_Compare __comp,_LeafMerge __leaf_merge)1199     __merge_func_static(_RandomAccessIterator1 __xs, _RandomAccessIterator1 __xe, _RandomAccessIterator2 __ys,
1200                         _RandomAccessIterator2 __ye, _RandomAccessIterator3 __zs, _Compare __comp,
1201                         _LeafMerge __leaf_merge)
1202         : _M_xs(__xs), _M_xe(__xe), _M_ys(__ys), _M_ye(__ye), _M_zs(__zs), _M_comp(__comp), _M_leaf_merge(__leaf_merge)
1203     {
1204     }
1205 
1206     __task*
1207     operator()(__task* __self);
1208 };
1209 
1210 //TODO: consider usage of parallel_for with a custom blocked_range
1211 template <typename _RandomAccessIterator1, typename _RandomAccessIterator2, typename _RandomAccessIterator3,
1212           typename __M_Compare, typename _LeafMerge>
1213 __task*
1214 __merge_func_static<_RandomAccessIterator1, _RandomAccessIterator2, _RandomAccessIterator3, __M_Compare, _LeafMerge>::
operator()1215 operator()(__task* __self)
1216 {
1217     typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type _DifferenceType1;
1218     typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type _DifferenceType2;
1219     typedef typename std::common_type<_DifferenceType1, _DifferenceType2>::type _SizeType;
1220     const _SizeType __n = (_M_xe - _M_xs) + (_M_ye - _M_ys);
1221     const _SizeType __merge_cut_off = _PSTL_MERGE_CUT_OFF;
1222     if (__n <= __merge_cut_off)
1223     {
1224         _M_leaf_merge(_M_xs, _M_xe, _M_ys, _M_ye, _M_zs, _M_comp);
1225         return nullptr;
1226     }
1227 
1228     _RandomAccessIterator1 __xm;
1229     _RandomAccessIterator2 __ym;
1230     if (_M_xe - _M_xs < _M_ye - _M_ys)
1231     {
1232         __ym = _M_ys + (_M_ye - _M_ys) / 2;
1233         __xm = std::upper_bound(_M_xs, _M_xe, *__ym, _M_comp);
1234     }
1235     else
1236     {
1237         __xm = _M_xs + (_M_xe - _M_xs) / 2;
1238         __ym = std::lower_bound(_M_ys, _M_ye, *__xm, _M_comp);
1239     }
1240     const _RandomAccessIterator3 __zm = _M_zs + ((__xm - _M_xs) + (__ym - _M_ys));
1241     auto __right = __self->make_additional_child_of(
1242         __self->parent(), __merge_func_static(__xm, _M_xe, __ym, _M_ye, __zm, _M_comp, _M_leaf_merge));
1243     __self->spawn(__right);
1244     __self->recycle_as_continuation();
1245     _M_xe = __xm;
1246     _M_ye = __ym;
1247 
1248     return __self;
1249 }
1250 
1251 template <class _ExecutionPolicy, typename _RandomAccessIterator1, typename _RandomAccessIterator2,
1252           typename _RandomAccessIterator3, typename _Compare, typename _LeafMerge>
1253 void
__parallel_merge(_ExecutionPolicy &&,_RandomAccessIterator1 __xs,_RandomAccessIterator1 __xe,_RandomAccessIterator2 __ys,_RandomAccessIterator2 __ye,_RandomAccessIterator3 __zs,_Compare __comp,_LeafMerge __leaf_merge)1254 __parallel_merge(_ExecutionPolicy&&, _RandomAccessIterator1 __xs, _RandomAccessIterator1 __xe,
1255                  _RandomAccessIterator2 __ys, _RandomAccessIterator2 __ye, _RandomAccessIterator3 __zs, _Compare __comp,
1256                  _LeafMerge __leaf_merge)
1257 {
1258     typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type _DifferenceType1;
1259     typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type _DifferenceType2;
1260     typedef typename std::common_type<_DifferenceType1, _DifferenceType2>::type _SizeType;
1261     const _SizeType __n = (__xe - __xs) + (__ye - __ys);
1262     const _SizeType __merge_cut_off = _PSTL_MERGE_CUT_OFF;
1263     if (__n <= __merge_cut_off)
1264     {
1265         // Fall back on serial merge
1266         __leaf_merge(__xs, __xe, __ys, __ye, __zs, __comp);
1267     }
1268     else
1269     {
1270         tbb::this_task_arena::isolate([=]() {
1271             typedef __merge_func_static<_RandomAccessIterator1, _RandomAccessIterator2, _RandomAccessIterator3,
1272                                         _Compare, _LeafMerge>
1273                 _TaskType;
1274             __root_task<_TaskType> __root{__xs, __xe, __ys, __ye, __zs, __comp, __leaf_merge};
1275             __task::spawn_root_and_wait(__root);
1276         });
1277     }
1278 }
1279 
1280 //------------------------------------------------------------------------
1281 // parallel_invoke
1282 //------------------------------------------------------------------------
1283 template <class _ExecutionPolicy, typename _F1, typename _F2>
1284 void
__parallel_invoke(_ExecutionPolicy &&,_F1 && __f1,_F2 && __f2)1285 __parallel_invoke(_ExecutionPolicy&&, _F1&& __f1, _F2&& __f2)
1286 {
1287     //TODO: a version of tbb::this_task_arena::isolate with variadic arguments pack should be added in the future
1288     tbb::this_task_arena::isolate([&]() { tbb::parallel_invoke(std::forward<_F1>(__f1), std::forward<_F2>(__f2)); });
1289 }
1290 
1291 } // namespace __tbb_backend
1292 } // namespace __pstl
1293 
1294 _PSTL_HIDE_FROM_ABI_POP
1295 
1296 #endif /* _PSTL_PARALLEL_BACKEND_TBB_H */
1297