okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
15.1 KiB486 linesraw
1//==---- functional.h -----------------------------*- C++ -*----------------==//
2//
3// Copyright (C) Intel Corporation
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5// See https://llvm.org/LICENSE.txt for license information.
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef __DPCT_FUNCTIONAL_H__
10#define __DPCT_FUNCTIONAL_H__
11
12#include <functional>
13#include <oneapi/dpl/functional>
14#include <oneapi/dpl/iterator>
15
16#if ONEDPL_USE_DPCPP_BACKEND
17#include <oneapi/dpl/pstl/hetero/dpcpp/parallel_backend_sycl_utils.h>
18#endif
19
20#include <tuple>
21#include <utility>
22
23#define _DPCT_GCC_VERSION                                                      \
24  (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
25
26// Portability "#pragma" definition
27#ifdef _MSC_VER
28#define _DPCT_PRAGMA(x) __pragma(x)
29#else
30#define _DPCT_PRAGMA(x) _Pragma(#x)
31#endif
32
33// Enable loop unrolling pragmas where supported
34#if (__INTEL_COMPILER ||                                                       \
35     (!defined(__INTEL_COMPILER) && _DPCT_GCC_VERSION >= 80000))
36#define _DPCT_PRAGMA_UNROLL _DPCT_PRAGMA(unroll)
37#else // no pragma unroll
38#define _DPCT_PRAGMA_UNROLL
39#endif
40
41namespace dpct {
42
43struct null_type {};
44
45// Function object to wrap user defined functors to provide compile time "const"
46// workaround for user function objects.
47// The SYCL spec (4.12) states that writing to a function object during a SYCL
48// kernel is undefined behavior.  This wrapper is provided as a compile-time
49// work around, but functors used in SYCL kernels must be `const` in practice.
50template <typename _Op> struct mark_functor_const {
51  mutable _Op op;
52  mark_functor_const() : op() {}
53  mark_functor_const(const _Op &__op) : op(__op) {}
54  mark_functor_const(_Op &&__op) : op(::std::move(__op)) {}
55  template <typename... _T> auto operator()(_T &&...x) const {
56    return op(std::forward<_T>(x)...);
57  }
58};
59
60// Forward declare key_value_pair to avoid creating cyclic dependency between
61// iterators.h and functional.h.
62template <typename _KeyTp, typename _ValueTp> class key_value_pair;
63
64// Returns the smaller of two key_value_pair objects based on their value
65// member. If value elements compare equal, then the pair with the lower key is
66// returned.
67struct argmin {
68  template <typename _ValueTp, typename _KeyTp>
69  key_value_pair<_KeyTp, _ValueTp>
70  operator()(const key_value_pair<_KeyTp, _ValueTp> &lhs,
71             const key_value_pair<_KeyTp, _ValueTp> &rhs) const {
72    return (lhs.value < rhs.value) ||
73                   (lhs.value == rhs.value && lhs.key < rhs.key)
74               ? lhs
75               : rhs;
76  }
77};
78
79// Returns the larger of two key_value_pair objects based on their value member.
80// If value elements compare equal, then the pair with the lower key is
81// returned.
82struct argmax {
83  template <typename _ValueTp, typename _KeyTp>
84  key_value_pair<_KeyTp, _ValueTp>
85  operator()(const key_value_pair<_KeyTp, _ValueTp> &lhs,
86             const key_value_pair<_KeyTp, _ValueTp> &rhs) const {
87    return (lhs.value > rhs.value) ||
88                   (lhs.value == rhs.value && lhs.key < rhs.key)
89               ? lhs
90               : rhs;
91  }
92};
93
94namespace internal {
95
96template <class _ExecPolicy, class _T>
97using enable_if_execution_policy =
98    typename std::enable_if<oneapi::dpl::execution::is_execution_policy<
99                                typename std::decay<_ExecPolicy>::type>::value,
100                            _T>::type;
101
102template <typename _T> struct is_hetero_execution_policy : ::std::false_type {};
103
104template <typename... PolicyParams>
105struct is_hetero_execution_policy<
106    oneapi::dpl::execution::device_policy<PolicyParams...>> : ::std::true_type {
107};
108
109template <typename _T> struct is_fpga_execution_policy : ::std::false_type {};
110
111#if _ONEDPL_FPGA_DEVICE
112template <unsigned int unroll_factor, typename... PolicyParams>
113struct is_hetero_execution_policy<
114    execution::fpga_policy<unroll_factor, PolicyParams...>> : ::std::true_type {
115};
116#endif
117
118template <class _ExecPolicy, class _T>
119using enable_if_hetero_execution_policy = typename std::enable_if<
120    is_hetero_execution_policy<typename std::decay<_ExecPolicy>::type>::value,
121    _T>::type;
122
123#if _ONEDPL_CPP14_INTEGER_SEQUENCE_PRESENT
124
125template <std::size_t... _Sp>
126using index_sequence = std::index_sequence<_Sp...>;
127template <std::size_t _Np>
128using make_index_sequence = std::make_index_sequence<_Np>;
129
130#else
131
132template <std::size_t... _Sp> class index_sequence {};
133
134template <std::size_t _Np, std::size_t... _Sp>
135struct make_index_sequence_impl
136    : make_index_sequence_impl<_Np - 1, _Np - 1, _Sp...> {};
137
138template <std::size_t... _Sp> struct make_index_sequence_impl<0, _Sp...> {
139  using type = index_sequence<_Sp...>;
140};
141
142template <std::size_t _Np>
143using make_index_sequence = typename make_index_sequence_impl<_Np>::type;
144#endif
145
146// Minimal buffer implementations for temporary storage in mapping rules
147// Some of our algorithms need to start with raw memory buffer,
148// not an initialized array, because initialization/destruction
149// would make the span be at least O(N).
150#if ONEDPL_USE_DPCPP_BACKEND
151template <typename _Tp> class __buffer {
152  sycl::buffer<_Tp, 1> __buf;
153
154  __buffer(const __buffer &) = delete;
155
156  void operator=(const __buffer &) = delete;
157
158public:
159  // Try to obtain buffer of given size to store objects of _Tp type
160  __buffer(std::size_t __n) : __buf(sycl::range<1>(__n)) {}
161
162  // Return pointer to buffer, or  NULL if buffer could not be obtained.
163  auto get() -> decltype(oneapi::dpl::begin(__buf)) const {
164    return oneapi::dpl::begin(__buf);
165  }
166};
167#else
168template <typename _Tp> class __buffer {
169  std::unique_ptr<_Tp> _M_ptr;
170
171  __buffer(const __buffer &) = delete;
172
173  void operator=(const __buffer &) = delete;
174
175public:
176  // Try to obtain buffer of given size to store objects of _Tp type
177  __buffer(const std::size_t __n) : _M_ptr(new _Tp[__n]) {}
178
179  // Return pointer to buffer, or  NULL if buffer could not be obtained.
180  _Tp *get() const { return _M_ptr.get(); }
181};
182#endif
183
184// Implements C++14 std::less<void> specialization to allow parameter type
185// deduction.
186class __less {
187public:
188  template <typename _Xp, typename _Yp>
189  bool operator()(_Xp &&__x, _Yp &&__y) const {
190    return std::forward<_Xp>(__x) < std::forward<_Yp>(__y);
191  }
192};
193
194template <typename Policy, typename NewName> struct rebind_policy {
195  using type = Policy;
196};
197
198template <typename KernelName, typename NewName>
199struct rebind_policy<oneapi::dpl::execution::device_policy<KernelName>,
200                     NewName> {
201  using type = oneapi::dpl::execution::device_policy<NewName>;
202};
203
204#if _ONEDPL_FPGA_DEVICE
205template <unsigned int factor, typename KernelName, typename NewName>
206struct rebind_policy<oneapi::dpl::execution::fpga_policy<factor, KernelName>,
207                     NewName> {
208  using type = oneapi::dpl::execution::fpga_policy<factor, NewName>;
209};
210#endif
211
212template <typename T1, typename T2,
213          typename R1 = typename std::iterator_traits<T1>::reference,
214          typename R2 = typename std::iterator_traits<T2>::reference>
215struct perm_fun {
216  typedef R2 result_of;
217  perm_fun(T1 input) : source(input) {}
218
219  R2 operator()(R1 x) const { return *(source + x); }
220
221private:
222  T1 source;
223};
224
225// Functor compares first element (key) from tied sequence.
226template <typename Compare = class internal::__less> struct compare_key_fun {
227  typedef bool result_of;
228  compare_key_fun(Compare _comp = internal::__less()) : comp(_comp) {}
229
230  template <typename _T1, typename _T2>
231  result_of operator()(_T1 &&a, _T2 &&b) const {
232    using std::get;
233    return comp(get<0>(a), get<0>(b));
234  }
235
236private:
237  mutable Compare comp;
238};
239
240// Functor evaluates second element of tied sequence with predicate.
241// Used by: copy_if, remove_copy_if, stable_partition_copy
242// Lambda:
243template <typename Predicate> struct predicate_key_fun {
244  typedef bool result_of;
245  predicate_key_fun(Predicate _pred) : pred(_pred) {}
246
247  template <typename _T1> result_of operator()(_T1 &&a) const {
248    using std::get;
249    return pred(get<1>(a));
250  }
251
252private:
253  mutable Predicate pred;
254};
255
256// Used by: remove_if
257template <typename Predicate> struct negate_predicate_key_fun {
258  typedef bool result_of;
259  negate_predicate_key_fun(Predicate _pred) : pred(_pred) {}
260
261  template <typename _T1> result_of operator()(_T1 &&a) const {
262    using std::get;
263    return !pred(get<1>(a));
264  }
265
266private:
267  mutable Predicate pred;
268};
269
270template <typename T> struct sequence_fun {
271  using result_type = T;
272  sequence_fun(T _init, T _step) : init(_init), step(_step) {}
273
274  template <typename _T> result_type operator()(_T &&i) const {
275    return static_cast<T>(init + step * i);
276  }
277
278private:
279  const T init;
280  const T step;
281};
282
283//[binary_pred](Ref a, Ref b){ return(binary_pred(get<0>(a),get<0>(b)));
284template <typename Predicate> struct unique_fun {
285  typedef bool result_of;
286  unique_fun(Predicate _pred) : pred(_pred) {}
287  template <typename _T> result_of operator()(_T &&a, _T &&b) const {
288    using std::get;
289    return pred(get<0>(a), get<0>(b));
290  }
291
292private:
293  mutable Predicate pred;
294};
295
296// Lambda: [pred, &new_value](Ref1 a, Ref2 s) {return pred(s) ? new_value : a;
297// });
298template <typename T, typename Predicate> struct replace_if_fun {
299public:
300  typedef T result_of;
301  replace_if_fun(Predicate _pred, T _new_value)
302      : pred(_pred), new_value(_new_value) {}
303
304  template <typename _T1, typename _T2> T operator()(_T1 &&a, _T2 &&s) const {
305    return pred(s) ? new_value : a;
306  }
307
308private:
309  mutable Predicate pred;
310  const T new_value;
311};
312
313//[pred,op](Ref a){return pred(a) ? op(a) : a; }
314template <typename T, typename Predicate, typename Operator>
315struct transform_if_fun {
316  transform_if_fun(Predicate _pred, Operator _op) : pred(_pred), op(_op) {}
317  template <typename _T>
318  void operator()(_T&& t) const {
319    using std::get;
320    if (pred(get<0>(t)))
321      get<1>(t) = op(get<0>(t));
322  }
323
324private:
325  mutable Predicate pred;
326  mutable Operator op;
327};
328
329//[pred, op](Ref1 a, Ref2 s) { return pred(s) ? op(a) : a; });
330template <typename T, typename Predicate, typename Operator>
331struct transform_if_unary_zip_mask_fun {
332  transform_if_unary_zip_mask_fun(Predicate _pred, Operator _op) : pred(_pred), op(_op) {}
333  template <typename _T>
334  void operator()(_T&& t) const {
335    using std::get;
336    if (pred(get<1>(t)))
337      get<2>(t) = op(get<0>(t));
338  }
339
340private:
341  mutable Predicate pred;
342  mutable Operator op;
343};
344
345template <typename T, typename Predicate, typename BinaryOperation>
346class transform_if_zip_mask_fun {
347public:
348  transform_if_zip_mask_fun(Predicate _pred = oneapi::dpl::identity(),
349                            BinaryOperation _op = oneapi::dpl::identity())
350      : pred(_pred), op(_op) {}
351  template <typename _T> void operator()(_T &&t) const {
352    using std::get;
353    if (pred(get<2>(t)))
354      get<3>(t) = op(get<0>(t), get<1>(t));
355  }
356
357private:
358  mutable Predicate pred;
359  mutable BinaryOperation op;
360};
361
362// This following code is similar to a section of code in
363// oneDPL/include/oneapi/dpl/pstl/hetero/dpcpp/parallel_backend_sycl_radix_sort.h
364// It has a similar approach, and could be consolidated.
365// Outside of some differences in approach, there are two significant
366// differences in function.
367//
368// 1) This code allows the output type of the bit range translation to be fit
369// into to the minimal type required to provide that many bits. The code in
370// oneDPL to calculate the bucket for the radix is similar but its output is
371// always std::uint32_t.  The assumption that the bit range desired will fit in
372// 32 bits is not true for this code.
373//
374// 2) This code ensures that for floating point type, -0.0f and 0.0f map to the
375// same value.  This allows the output of this translation to be used to provide
376// a sort which ensures the stability of these values for floating point types.
377
378template <int N> struct uint_byte_map {};
379template <> struct uint_byte_map<1> { using type = uint8_t; };
380template <> struct uint_byte_map<2> { using type = uint16_t; };
381template <> struct uint_byte_map<4> { using type = uint32_t; };
382template <> struct uint_byte_map<8> { using type = uint64_t; };
383
384template <typename T> struct uint_map {
385  using type = typename uint_byte_map<sizeof(T)>::type;
386};
387
388template <typename T, typename OutKeyT> class translate_key {
389  using uint_type_t = typename uint_map<T>::type;
390
391public:
392  translate_key(int begin_bit, int end_bit) {
393    shift = begin_bit;
394    mask = ~OutKeyT(0); // all ones
395    mask = mask >> (sizeof(OutKeyT) * 8 -
396                    (end_bit - begin_bit));           // setup appropriate mask
397    flip_sign = uint_type_t(1) << (sizeof(uint_type_t) * 8 - 1); // sign bit
398    flip_key = ~uint_type_t(0);                       // 0xF...F
399  }
400
401  inline OutKeyT operator()(const T &key) const {
402    uint_type_t intermediate;
403    if constexpr (std::is_floating_point<T>::value) {
404        // normal case (both -0.0f and 0.0f equal -0.0f)
405        if (key != T(-0.0f)) {
406        uint_type_t is_negative = reinterpret_cast<const uint_type_t &>(key) >>
407              (sizeof(uint_type_t) * 8 - 1);
408          intermediate = reinterpret_cast<const uint_type_t &>(key) ^
409                         ((is_negative * flip_key) | flip_sign);
410        } else // special case for -0.0f to keep stability with 0.0f
411        {
412          T negzero = T(-0.0f);
413          intermediate = reinterpret_cast<const uint_type_t &>(negzero);
414        }
415    } else if constexpr (std::is_signed<T>::value) {
416        intermediate = reinterpret_cast<const uint_type_t &>(key) ^ flip_sign;
417    } else {
418      intermediate = key;
419    }
420
421    return static_cast<OutKeyT>(intermediate >> shift) &
422           mask; // shift, cast, and mask
423  }
424
425private:
426  uint8_t shift;
427  OutKeyT mask;
428  uint_type_t flip_sign;
429  uint_type_t flip_key;
430};
431
432// Unary operator that returns reference to its argument. Ported from
433// oneDPL: oneapi/dpl/pstl/utils.h
434struct no_op_fun {
435  template <typename Tp> Tp &&operator()(Tp &&a) const {
436    return ::std::forward<Tp>(a);
437  }
438};
439
440// Unary functor which composes a pair of functors by calling them in succession
441// on an input
442template <typename FunctorInner, typename FunctorOuter>
443struct __composition_functor {
444  __composition_functor(FunctorInner in, FunctorOuter out)
445      : _in(in), _out(out) {}
446  template <typename T> T operator()(const T &i) const {
447    return _out(_in(i));
448  }
449  FunctorInner _in;
450  FunctorOuter _out;
451};
452
453// Unary functor which maps an index of a ROI into a 2D flattened array
454template <typename OffsetT> struct __roi_2d_index_functor {
455  __roi_2d_index_functor(const OffsetT &num_cols,
456                         const ::std::size_t &row_stride)
457      : _num_cols(num_cols), _row_stride(row_stride) {}
458
459  template <typename Index> Index operator()(const Index &i) const {
460    return _row_stride * (i / _num_cols) + (i % _num_cols);
461  }
462
463  OffsetT _num_cols;
464  ::std::size_t _row_stride;
465};
466
467// Unary functor which maps and index into an interleaved array by its active
468// channel
469template <typename OffsetT> struct __interleaved_index_functor {
470  __interleaved_index_functor(const OffsetT &total_channels,
471                              const OffsetT &active_channel)
472      : _total_channels(total_channels), _active_channel(active_channel) {}
473
474  template <typename Index> Index operator()(const Index &i) const {
475    return i * _total_channels + _active_channel;
476  }
477
478  OffsetT _total_channels;
479  OffsetT _active_channel;
480};
481
482} // end namespace internal
483
484} // end namespace dpct
485
486#endif