okami.mom/strata

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

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

main
50.6 KiB1358 linesraw
1//==---- util.hpp ---------------------------------*- 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_UTIL_HPP__
10#define __DPCT_UTIL_HPP__
11
12#include <sycl/sycl.hpp>
13#include <complex>
14#include <type_traits>
15#include <cassert>
16#include <cstdint>
17
18// TODO: Remove these function definitions once they exist in the DPC++ compiler
19#if defined(__SYCL_DEVICE_ONLY__) && defined(__INTEL_LLVM_COMPILER)
20template <typename T>
21__SYCL_CONVERGENT__ extern SYCL_EXTERNAL __SYCL_EXPORT __attribute__((noduplicate))
22T __spirv_GroupNonUniformShuffle(__spv::Scope::Flag, T, unsigned) noexcept;
23
24template <typename T>
25__SYCL_CONVERGENT__ extern SYCL_EXTERNAL __SYCL_EXPORT __attribute__((noduplicate))
26T __spirv_GroupNonUniformShuffleDown(__spv::Scope::Flag, T, unsigned) noexcept;
27
28template <typename T>
29__SYCL_CONVERGENT__ extern SYCL_EXTERNAL __SYCL_EXPORT __attribute__((noduplicate))
30T __spirv_GroupNonUniformShuffleUp(__spv::Scope::Flag, T, unsigned) noexcept;
31#endif
32
33namespace dpct {
34/// dim3 is used to store 3 component dimensions.
35class dim3 {
36public:
37  unsigned x, y, z;
38
39  constexpr dim3(unsigned x = 1, unsigned y = 1, unsigned z = 1)
40      : x(x), y(y), z(z) {}
41
42  dim3(const sycl::id<3> &r) : dim3(r[2], r[1], r[0]) {}
43
44  operator sycl::range<3>() const { return sycl::range<3>(z, y, x); }
45};
46
47inline dim3 operator*(const dim3 &a, const dim3 &b) {
48  return dim3{a.x * b.x, a.y * b.y, a.z * b.z};
49}
50
51namespace detail {
52
53template <typename tag, typename T> class generic_error_type {
54public:
55  generic_error_type() = default;
56  generic_error_type(T value) : value{value} {}
57  operator T() const { return value; }
58
59private:
60  T value;
61};
62
63} // namespace detail
64
65using err0 = detail::generic_error_type<struct err0_tag, int>;
66using err1 = detail::generic_error_type<struct err1_tag, int>;
67
68template <int... Ints> struct integer_sequence {};
69template <int Size, int... Ints>
70struct make_index_sequence
71    : public make_index_sequence<Size - 1, Size - 1, Ints...> {};
72template <int... Ints>
73struct make_index_sequence<0, Ints...> : public integer_sequence<Ints...> {};
74
75template <typename T> struct [[deprecated]] DataType { using T2 = T; };
76template <typename T> struct DataType<sycl::vec<T, 2>> {
77  using T2 = std::complex<T>;
78};
79
80[[deprecated("Please use dpct::blas::matrix_mem_copy() instead.")]] inline void
81matrix_mem_copy(void *to_ptr, const void *from_ptr, int to_ld, int from_ld,
82                int rows, int cols, int elem_size,
83                memcpy_direction direction = automatic,
84                sycl::queue &queue = dpct::get_default_queue(),
85                bool async = false) {
86  if (to_ptr == from_ptr && to_ld == from_ld) {
87    return;
88  }
89
90  if (to_ld == from_ld) {
91    size_t copy_size = elem_size * ((cols - 1) * (size_t)to_ld + rows);
92    if (async)
93      detail::dpct_memcpy(queue, (void *)to_ptr, (void *)from_ptr, copy_size,
94                          direction);
95    else
96      detail::dpct_memcpy(queue, (void *)to_ptr, (void *)from_ptr, copy_size,
97                          direction)
98          .wait();
99  } else {
100    if (async)
101      detail::dpct_memcpy(queue, to_ptr, from_ptr, elem_size * to_ld,
102                          elem_size * from_ld, elem_size * rows, cols,
103                          direction);
104    else
105      sycl::event::wait(detail::dpct_memcpy(
106          queue, to_ptr, from_ptr, elem_size * to_ld, elem_size * from_ld,
107          elem_size * rows, cols, direction));
108  }
109}
110
111/// Copy matrix data. The default leading dimension is column.
112/// \param [out] to_ptr A pointer points to the destination location.
113/// \param [in] from_ptr A pointer points to the source location.
114/// \param [in] to_ld The leading dimension the destination matrix.
115/// \param [in] from_ld The leading dimension the source matrix.
116/// \param [in] rows The number of rows of the source matrix.
117/// \param [in] cols The number of columns of the source matrix.
118/// \param [in] direction The direction of the data copy.
119/// \param [in] queue The queue where the routine should be executed.
120/// \param [in] async If this argument is true, the return of the function
121/// does NOT guarantee the copy is completed.
122template <typename T>
123[[deprecated("Please use dpct::blas::matrix_mem_copy() instead.")]] inline void
124matrix_mem_copy(T *to_ptr, const T *from_ptr, int to_ld, int from_ld, int rows,
125                int cols, memcpy_direction direction = automatic,
126                sycl::queue &queue = dpct::get_default_queue(),
127                bool async = false) {
128  using Ty = typename DataType<T>::T2;
129  matrix_mem_copy((void *)to_ptr, (void *)from_ptr, to_ld, from_ld, rows, cols,
130                  sizeof(Ty), direction, queue, async);
131}
132
133/// Cast the high or low 32 bits of a double to an integer.
134/// \param [in] d The double value.
135/// \param [in] use_high32 Cast the high 32 bits of the double if true;
136/// otherwise cast the low 32 bits.
137inline int cast_double_to_int(double d, bool use_high32 = true) {
138  sycl::vec<double, 1> v0{d};
139  auto v1 = v0.as<sycl::int2>();
140  if (use_high32)
141    return v1[1];
142  return v1[0];
143}
144
145/// Combine two integers, the first as the high 32 bits and the second
146/// as the low 32 bits, into a double.
147/// \param [in] high32 The integer as the high 32 bits
148/// \param [in] low32 The integer as the low 32 bits
149inline double cast_ints_to_double(int high32, int low32) {
150  sycl::int2 v0{low32, high32};
151  auto v1 = v0.as<sycl::vec<double, 1>>();
152  return v1;
153}
154
155/// Reverse the bit order of an unsigned integer
156/// \param [in] a Input unsigned integer value
157/// \returns Value of a with the bit order reversed
158template <typename T> inline T reverse_bits(T a) {
159  static_assert(std::is_unsigned<T>::value && std::is_integral<T>::value,
160                "unsigned integer required");
161  if (!a)
162    return 0;
163  T mask = 0;
164  size_t count = 4 * sizeof(T);
165  mask = ~mask >> count;
166  while (count) {
167    a = ((a & mask) << count) | ((a & ~mask) >> count);
168    count = count >> 1;
169    mask = mask ^ (mask << count);
170  }
171  return a;
172}
173
174/// \param [in] a The first value contains 4 bytes
175/// \param [in] b The second value contains 4 bytes
176/// \param [in] s The selector value, only lower 16bit used
177/// \returns the permutation result of 4 bytes selected in the way
178/// specified by \p s from \p a and \p b
179inline unsigned int byte_level_permute(unsigned int a, unsigned int b,
180                                       unsigned int s) {
181  unsigned int ret;
182  ret =
183      ((((std::uint64_t)b << 32 | a) >> (s & 0x7) * 8) & 0xff) |
184      (((((std::uint64_t)b << 32 | a) >> ((s >> 4) & 0x7) * 8) & 0xff) << 8) |
185      (((((std::uint64_t)b << 32 | a) >> ((s >> 8) & 0x7) * 8) & 0xff) << 16) |
186      (((((std::uint64_t)b << 32 | a) >> ((s >> 12) & 0x7) * 8) & 0xff) << 24);
187  return ret;
188}
189
190/// \param [in] low32 The 4 bytes to construct the 8 bytes value as low 32 bits.
191/// \param [in] high32 The 4 bytes to construct the 8 bytes value as high 32
192/// bits.
193/// \param [in] sel The selector value. It is used to generate selectors which are
194/// used to fetch byte value from \p low32 and \p high32 to construct result
195/// value.
196/// \param [in] mode The mode of permutation, together with \p sel, it
197/// further defines the behavior of data selection. \p mode and \p sel define 4
198/// selectors (s[i], i=0, 1, 2, 3), which are used as index to fetch 4 bytes from
199/// the 8 bytes value constructed by \p low32 and \p high32; the byte selected by s[i]
200/// is used to fill the i-th byte of the result.
201/// The available mode values are:
202/// mode value 0: s[i] = sel[i * 4 + 3 : i * 4]
203/// mode value 1: s[i] = sel[1 : 0] + i
204/// mode value 2: s[i] = (sel[1 : 0] + 7) % 8
205/// mode value 3: s[i] = sel[1 : 0]
206/// mode value 4: s[i] = max(sel[1 : 0], i)
207/// mode value 5: s[i] = min(sel[1 : 0], i)
208/// mode value 6: s[0] = sel[0 : 0] * 2
209///               s[1] = sel[0 : 0] * 2 + 1
210///               s[2] = s[0]
211///               s[3] = s[1]
212/// other value: illegal, undefined behavior, return 0.
213inline uint32_t byte_level_permute_custom(uint32_t low32, uint32_t high32,
214                                          uint32_t sel, int mode = 0) {
215  constexpr uint16_t lookup[6][4] = {
216      {0x3210, 0x4321, 0x5432, 0x6543}, // Forward 4-byte extract
217      {0x5670, 0x6701, 0x7012, 0x0123}, // Backward 4-byte extract
218      {0x0000, 0x1111, 0x2222, 0x3333}, // Replicate 8-bit values
219      {0x3210, 0x3211, 0x3222, 0x3333}, // Edge clamp left
220      {0x0000, 0x1110, 0x2210, 0x3210}, // Edge clamp right
221      {0x1010, 0x3232, 0x1010, 0x3232}  // Replicate 16-bit values
222  };
223
224  if (mode >= 1 && mode <= 6) {
225    return byte_level_permute(low32, high32, lookup[mode - 1][sel & 0x3]);
226  } else if (!mode) {
227    return byte_level_permute(low32, high32, sel);
228  }
229  return 0;
230}
231
232/// Find position of first least significant set bit in an integer.
233/// ffs(0) returns 0.
234///
235/// \param [in] a Input integer value
236/// \returns The position
237template <typename T> inline int ffs(T a) {
238  static_assert(std::is_integral<T>::value, "integer required");
239  return (sycl::ctz(a) + 1) % (sizeof(T) * 8 + 1);
240}
241
242/// select_from_sub_group allows work-items to obtain a copy of a value held by
243/// any other work-item in the sub_group. The input sub_group will be divided
244/// into several logical sub_groups with id range [0, \p logical_sub_group_size
245/// - 1]. Each work-item in logical sub_group gets value from another work-item
246/// whose id is \p remote_local_id. If \p remote_local_id is outside the
247/// logical sub_group id range, \p remote_local_id will modulo with \p
248/// logical_sub_group_size. The \p logical_sub_group_size must be a power of 2
249/// and not exceed input sub_group size.
250/// \tparam T Input value type
251/// \param [in] g Input sub_group
252/// \param [in] x Input value
253/// \param [in] remote_local_id Input source work item id
254/// \param [in] logical_sub_group_size Input logical sub_group size
255/// \returns The result
256template <typename T>
257T select_from_sub_group(sycl::sub_group g, T x, int remote_local_id,
258                        int logical_sub_group_size = 32) {
259  unsigned int start_index =
260      g.get_local_linear_id() / logical_sub_group_size * logical_sub_group_size;
261  return sycl::select_from_group(
262      g, x, start_index + remote_local_id % logical_sub_group_size);
263}
264
265/// shift_sub_group_left move values held by the work-items in a sub_group
266/// directly to another work-item in the sub_group, by shifting values a fixed
267/// number of work-items to the left. The input sub_group will be divided into
268/// several logical sub_groups with id range [0, \p logical_sub_group_size - 1].
269/// Each work-item in logical sub_group gets value from another work-item whose
270/// id is caller's id adds \p delta. If calculated id is outside the logical
271/// sub_group id range, the work-item will get value from itself. The \p
272/// logical_sub_group_size must be a power of 2 and not exceed input sub_group
273/// size.
274/// \tparam T Input value type
275/// \param [in] g Input sub_group
276/// \param [in] x Input value
277/// \param [in] delta Input delta
278/// \param [in] logical_sub_group_size Input logical sub_group size
279/// \returns The result
280template <typename T>
281T shift_sub_group_left(sycl::sub_group g, T x, unsigned int delta,
282                       int logical_sub_group_size = 32) {
283  unsigned int id = g.get_local_linear_id();
284  unsigned int end_index =
285      (id / logical_sub_group_size + 1) * logical_sub_group_size;
286  T result = sycl::shift_group_left(g, x, delta);
287  if ((id + delta) >= end_index) {
288    result = x;
289  }
290  return result;
291}
292
293/// shift_sub_group_right move values held by the work-items in a sub_group
294/// directly to another work-item in the sub_group, by shifting values a fixed
295/// number of work-items to the right. The input sub_group will be divided into
296/// several logical_sub_groups with id range [0, \p logical_sub_group_size - 1].
297/// Each work-item in logical_sub_group gets value from another work-item whose
298/// id is caller's id subtracts \p delta. If calculated id is outside the
299/// logical sub_group id range, the work-item will get value from itself. The \p
300/// logical_sub_group_size must be a power of 2 and not exceed input sub_group
301/// size.
302/// \tparam T Input value type
303/// \param [in] g Input sub_group
304/// \param [in] x Input value
305/// \param [in] delta Input delta
306/// \param [in] logical_sub_group_size Input logical sub_group size
307/// \returns The result
308template <typename T>
309T shift_sub_group_right(sycl::sub_group g, T x, unsigned int delta,
310                        int logical_sub_group_size = 32) {
311  unsigned int id = g.get_local_linear_id();
312  unsigned int start_index =
313      id / logical_sub_group_size * logical_sub_group_size;
314  T result = sycl::shift_group_right(g, x, delta);
315  if ((id - start_index) < delta) {
316    result = x;
317  }
318  return result;
319}
320
321/// permute_sub_group_by_xor permutes values by exchanging values held by pairs
322/// of work-items identified by computing the bitwise exclusive OR of the
323/// work-item id and some fixed mask. The input sub_group will be divided into
324/// several logical sub_groups with id range [0, \p logical_sub_group_size - 1].
325/// Each work-item in logical sub_group gets value from another work-item whose
326/// id is bitwise exclusive OR of the caller's id and \p mask. If calculated id
327/// is outside the logical sub_group id range, the work-item will get value from
328/// itself. The \p logical_sub_group_size must be a power of 2 and not exceed
329/// input sub_group size.
330/// \tparam T Input value type
331/// \param [in] g Input sub_group
332/// \param [in] x Input value
333/// \param [in] mask Input mask
334/// \param [in] logical_sub_group_size Input logical sub_group size
335/// \returns The result
336template <typename T>
337T permute_sub_group_by_xor(sycl::sub_group g, T x, unsigned int mask,
338                           int logical_sub_group_size = 32) {
339  unsigned int id = g.get_local_linear_id();
340  unsigned int start_index =
341      id / logical_sub_group_size * logical_sub_group_size;
342  unsigned int target_offset = (id % logical_sub_group_size) ^ mask;
343  return sycl::select_from_group(g, x,
344                                 target_offset < logical_sub_group_size
345                                     ? start_index + target_offset
346                                     : id);
347}
348
349/// The function match_any_over_sub_group conducts a comparison of values
350/// across work-items within a sub-group. match_any_over_sub_group return a mask
351/// in which some bits are set to 1, indicating that the \p value provided by
352/// the work-item represented by these bits are equal. The n-th bit of mask
353/// representing the work-item with id n. The parameter \p member_mask
354/// indicating the work-items participating the call.
355/// \tparam T Input value type
356/// \param [in] g Input sub_group
357/// \param [in] member_mask Input mask
358/// \param [in] value Input value
359/// \returns The result
360template <typename T>
361unsigned int match_any_over_sub_group(sycl::sub_group g, unsigned member_mask,
362                                      T value) {
363  static_assert(std::is_trivially_copyable_v<T>,
364                "Value type must be trivially copyable type.");
365  if (!member_mask) {
366    return 0;
367  }
368  unsigned int id = g.get_local_linear_id();
369  unsigned int flag = 0, result = 0, reduce_result = 0;
370  unsigned int bit_index = 0x1 << id;
371  bool is_participate = member_mask & bit_index;
372  T broadcast_value = 0;
373  bool matched = false;
374  while (flag != member_mask) {
375    broadcast_value =
376        sycl::select_from_group(g, value, sycl::ctz((~flag & member_mask)));
377    reduce_result = sycl::reduce_over_group(
378        g, is_participate ? (broadcast_value == value ? bit_index : 0) : 0,
379        sycl::plus<>());
380    flag |= reduce_result;
381    matched = reduce_result & bit_index;
382    result = matched * reduce_result + (1 - matched) * result;
383  }
384  return result;
385}
386
387/// The function match_all_over_sub_group conducts a comparison of values
388/// across work-items within a sub-group. match_all_over_sub_group return \p
389/// member_mask and predicate \p pred will be set to 1 if all \p value that
390/// provided by each work-item in \p member_mask are equal, otherwise return 0
391/// and the predicate \p pred will be set to 0. The n-th bit of \p member_mask
392/// representing the work-item with id n. The parameter \p member_mask
393/// indicating the work-items participating the call.
394/// \tparam T Input value type
395/// \param [in] g Input sub_group
396/// \param [in] member_mask Input mask
397/// \param [in] value Input value
398/// \param [out] pred Output predicate
399/// \returns The result
400template <typename T>
401unsigned int match_all_over_sub_group(sycl::sub_group g, unsigned member_mask,
402                                      T value, int *pred) {
403  static_assert(std::is_trivially_copyable_v<T>,
404                "Value type must be trivially copyable type.");
405  if (!member_mask) {
406    return 0;
407  }
408  unsigned int id = g.get_local_linear_id();
409  unsigned int bit_index = 0x1 << id;
410  bool is_participate = member_mask & bit_index;
411  T broadcast_value = sycl::select_from_group(g, value, sycl::ctz(member_mask));
412  unsigned int reduce_result = sycl::reduce_over_group(
413      g,
414      (member_mask & bit_index) ? (broadcast_value == value ? bit_index : 0)
415                                : 0,
416      sycl::plus<>());
417  bool all_equal = (reduce_result == member_mask);
418  *pred = is_participate & all_equal;
419  return all_equal * member_mask;
420}
421
422namespace experimental {
423#if defined(__NVPTX__) && defined(__SYCL_DEVICE_ONLY__)
424#define SHFL_SYNC(RES, MASK, VAL, SHFL_PARAM, C, SHUFFLE_INSTR)                \
425  if constexpr (std::is_same_v<T, double>) {                                   \
426    int x_a, x_b;                                                              \
427    asm("mov.b64 {%0,%1},%2;" : "=r"(x_a), "=r"(x_b) : "d"(VAL));              \
428    auto tmp_a = __nvvm_shfl_sync_##SHUFFLE_INSTR(MASK, x_a, SHFL_PARAM, C);   \
429    auto tmp_b = __nvvm_shfl_sync_##SHUFFLE_INSTR(MASK, x_b, SHFL_PARAM, C);   \
430    asm("mov.b64 %0,{%1,%2};" : "=d"(RES) : "r"(tmp_a), "r"(tmp_b));           \
431  } else if constexpr (std::is_same_v<T, long> ||                              \
432                       std::is_same_v<T, unsigned long>) {                     \
433    int x_a, x_b;                                                              \
434    asm("mov.b64 {%0,%1},%2;" : "=r"(x_a), "=r"(x_b) : "l"(VAL));              \
435    auto tmp_a = __nvvm_shfl_sync_##SHUFFLE_INSTR(MASK, x_a, SHFL_PARAM, C);   \
436    auto tmp_b = __nvvm_shfl_sync_##SHUFFLE_INSTR(MASK, x_b, SHFL_PARAM, C);   \
437    asm("mov.b64 %0,{%1,%2};" : "=l"(RES) : "r"(tmp_a), "r"(tmp_b));           \
438  } else if constexpr (std::is_same_v<T, sycl::half>) {                        \
439    short tmp_b16;                                                             \
440    asm("mov.b16 %0,%1;" : "=h"(tmp_b16) : "h"(VAL));                          \
441    auto tmp_b32 = __nvvm_shfl_sync_##SHUFFLE_INSTR(                           \
442        MASK, static_cast<int>(tmp_b16), SHFL_PARAM, C);                       \
443    asm("mov.b16 %0,%1;" : "=h"(RES) : "h"(static_cast<short>(tmp_b32)));      \
444  } else if constexpr (std::is_same_v<T, float>) {                             \
445    auto tmp_b32 = __nvvm_shfl_sync_##SHUFFLE_INSTR(                           \
446        MASK, __nvvm_bitcast_f2i(VAL), SHFL_PARAM, C);                         \
447    RES = __nvvm_bitcast_i2f(tmp_b32);                                         \
448  } else {                                                                     \
449    RES = __nvvm_shfl_sync_##SHUFFLE_INSTR(MASK, VAL, SHFL_PARAM, C);          \
450  }
451#endif
452/// Masked version of select_from_sub_group, which execute masked sub-group
453/// operation. The parameter member_mask indicating the work-items participating
454/// the call. Whether the n-th bit is set to 1 representing whether the
455/// work-item with id n is participating the call. All work-items named in
456/// member_mask must be executed with the same member_mask, or the result is
457/// undefined.
458/// \tparam T Input value type
459/// \param [in] member_mask Input mask
460/// \param [in] g Input sub_group
461/// \param [in] x Input value
462/// \param [in] remote_local_id Input source work item id
463/// \param [in] logical_sub_group_size Input logical sub_group size
464/// \returns The result
465template <typename T>
466T select_from_sub_group(unsigned int member_mask,
467                        sycl::sub_group g, T x, int remote_local_id,
468                        int logical_sub_group_size = 32) {
469#if defined(__SYCL_DEVICE_ONLY__)
470#if defined(__SPIR__)
471  unsigned int start_index =
472      g.get_local_linear_id() / logical_sub_group_size * logical_sub_group_size;
473  unsigned logical_remote_id =
474      start_index + remote_local_id % logical_sub_group_size;
475  return __spirv_GroupNonUniformShuffle(__spv::Scope::Subgroup, x, logical_remote_id);
476#elif defined(__NVPTX__)
477  T result;
478  int cVal = ((32 - logical_sub_group_size) << 8) | 31;
479  SHFL_SYNC(result, member_mask, x, remote_local_id, cVal, idx_i32)
480  return result;
481#endif
482#else
483  (void)g;
484  (void)x;
485  (void)remote_local_id;
486  (void)logical_sub_group_size;
487  (void)member_mask;
488  throw sycl::exception(sycl::errc::runtime, "Masked version of select_from_sub_group not "
489                        "supported on host device.");
490#endif // __SYCL_DEVICE_ONLY__
491}
492
493/// Masked version of shift_sub_group_left, which execute masked sub-group
494/// operation. The parameter member_mask indicating the work-items participating
495/// the call. Whether the n-th bit is set to 1 representing whether the
496/// work-item with id n is participating the call. All work-items named in
497/// member_mask must be executed with the same member_mask, or the result is
498/// undefined.
499/// \tparam T Input value type
500/// \param [in] member_mask Input mask
501/// \param [in] g Input sub_group
502/// \param [in] x Input value
503/// \param [in] delta Input delta
504/// \param [in] logical_sub_group_size Input logical sub_group size
505/// \returns The result
506template <typename T>
507T shift_sub_group_left(unsigned int member_mask,
508                       sycl::sub_group g, T x, unsigned int delta,
509                       int logical_sub_group_size = 32) {
510#if defined(__SYCL_DEVICE_ONLY__)
511#if defined(__SPIR__)
512  unsigned int id = g.get_local_linear_id();
513  unsigned int end_index =
514      (id / logical_sub_group_size + 1) * logical_sub_group_size;
515  T result = __spirv_GroupNonUniformShuffleDown(__spv::Scope::Subgroup, x, delta);
516  if ((id + delta) >= end_index) {
517    result = x;
518  }
519  return result;
520#elif defined(__NVPTX__)
521  T result;
522  int cVal = ((32 - logical_sub_group_size) << 8) | 31;
523  SHFL_SYNC(result, member_mask, x, delta, cVal, down_i32)
524  return result;
525#endif
526#else
527  (void)g;
528  (void)x;
529  (void)delta;
530  (void)logical_sub_group_size;
531  (void)member_mask;
532  throw sycl::exception(sycl::errc::runtime, "Masked version of shift_sub_group_left not "
533                        "supported on host device.");
534#endif // __SYCL_DEVICE_ONLY__
535}
536
537/// Masked version of shift_sub_group_right, which execute masked sub-group
538/// operation. The parameter member_mask indicating the work-items participating
539/// the call. Whether the n-th bit is set to 1 representing whether the
540/// work-item with id n is participating the call. All work-items named in
541/// member_mask must be executed with the same member_mask, or the result is
542/// undefined.
543/// \tparam T Input value type
544/// \param [in] member_mask Input mask
545/// \param [in] g Input sub_group
546/// \param [in] x Input value
547/// \param [in] delta Input delta
548/// \param [in] logical_sub_group_size Input logical sub_group size
549/// \returns The result
550template <typename T>
551T shift_sub_group_right(unsigned int member_mask,
552                        sycl::sub_group g, T x, unsigned int delta,
553                        int logical_sub_group_size = 32) {
554#if defined(__SYCL_DEVICE_ONLY__)
555#if defined(__SPIR__)
556  unsigned int id = g.get_local_linear_id();
557  unsigned int start_index =
558      id / logical_sub_group_size * logical_sub_group_size;
559  T result = __spirv_GroupNonUniformShuffleUp(__spv::Scope::Subgroup, x, delta);
560  if ((id - start_index) < delta) {
561    result = x;
562  }
563  return result;
564#elif defined(__NVPTX__)
565  T result;
566  int cVal = ((32 - logical_sub_group_size) << 8);
567  SHFL_SYNC(result, member_mask, x, delta, cVal, up_i32)
568  return result;
569#endif
570#else
571  (void)g;
572  (void)x;
573  (void)delta;
574  (void)logical_sub_group_size;
575  (void)member_mask;
576  throw sycl::exception(sycl::errc::runtime, "Masked version of shift_sub_group_right not "
577                        "supported on host device.");
578#endif // __SYCL_DEVICE_ONLY__
579}
580
581/// Masked version of shift_sub_group_left, which execute masked sub-group
582/// operation. The parameter member_mask indicating the work-items participating
583/// the call. Whether the n-th bit is set to 1 representing whether the
584/// work-item with id n is participating the call. All work-items named in
585/// member_mask must be executed with the same member_mask, or the result is
586/// undefined.
587/// \tparam LogicSubGroupSize Input logical sub_group size
588/// \tparam T Input value type
589/// \param [in] member_mask Input mask
590/// \param [in] g Input sub_group
591/// \param [in] x Input value
592/// \param [in] delta Input delta
593/// \param [in] last_item Index of last thread in logical subgroup
594/// \returns The result
595template <size_t LogicSubGroupSize, typename T>
596T shift_sub_group_left(sycl::sub_group sg, T input, int delta, int last_item,
597                       unsigned member_mask) {
598#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
599  T result;
600  constexpr int cVal = ((32 - LogicSubGroupSize) << 8);
601  SHFL_SYNC(result, member_mask, input, delta, cVal | last_item, down_i32)
602  return result;
603#else
604  if ((1U << sg.get_local_linear_id()) & member_mask) {
605    auto inner = sycl::ext::oneapi::experimental::entangle(sg);
606    sycl::group_barrier(inner);
607  }
608  auto partition =
609      sycl::ext::oneapi::experimental::chunked_partition<LogicSubGroupSize>(
610          sg);
611  int id = partition.get_local_linear_id();
612  T result = sycl::shift_group_left(partition, input, delta);
613  if ((id + delta) > last_item)
614    result = input;
615  return result;
616#endif
617}
618
619/// Masked version of shift_sub_group_right, which execute masked sub-group
620/// operation. The parameter member_mask indicating the work-items participating
621/// the call. Whether the n-th bit is set to 1 representing whether the
622/// work-item with id n is participating the call. All work-items named in
623/// member_mask must be executed with the same member_mask, or the result is
624/// undefined.
625/// \tparam LogicSubGroupSize Input logical sub_group size
626/// \tparam T Input value type
627/// \param [in] member_mask Input mask
628/// \param [in] g Input sub_group
629/// \param [in] x Input value
630/// \param [in] delta Input delta
631/// \param [in] first_item Index of first lane in logical subgroup
632/// \returns The result
633template <size_t LogicSubGroupSize, typename T>
634T shift_sub_group_right(sycl::sub_group sg, T input, int delta, int first_item,
635                        unsigned member_mask) {
636#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
637  T result;
638  constexpr int cVal = ((32 - LogicSubGroupSize) << 8);
639  SHFL_SYNC(result, member_mask, input, delta, cVal | first_item, up_i32)
640  return result;
641#else
642  if ((1U << sg.get_local_linear_id()) & member_mask) {
643    auto inner = sycl::ext::oneapi::experimental::entangle(sg);
644    sycl::group_barrier(inner);
645  }
646  auto partition =
647      sycl::ext::oneapi::experimental::chunked_partition<LogicSubGroupSize>(
648          sg);
649  int id = sg.get_local_linear_id();
650  T result = sycl::shift_group_right(partition, input, delta);
651  if ((id - first_item) < delta)
652    result = input;
653  return result;
654#endif
655}
656
657/// Masked version of permute_sub_group_by_xor, which execute masked sub-group
658/// operation. The parameter member_mask indicating the work-items participating
659/// the call. Whether the n-th bit is set to 1 representing whether the
660/// work-item with id n is participating the call. All work-items named in
661/// member_mask must be executed with the same member_mask, or the result is
662/// undefined.
663/// \tparam T Input value type
664/// \param [in] member_mask Input mask
665/// \param [in] g Input sub_group
666/// \param [in] x Input value
667/// \param [in] mask Input mask
668/// \param [in] logical_sub_group_size Input logical sub_group size
669/// \returns The result
670template <typename T>
671T permute_sub_group_by_xor(unsigned int member_mask,
672                           sycl::sub_group g, T x, unsigned int mask,
673                           int logical_sub_group_size = 32) {
674#if defined(__SYCL_DEVICE_ONLY__)
675#if defined(__SPIR__)
676  unsigned int id = g.get_local_linear_id();
677  unsigned int start_index =
678      id / logical_sub_group_size * logical_sub_group_size;
679  unsigned int target_offset = (id % logical_sub_group_size) ^ mask;
680  unsigned logical_remote_id = (target_offset < logical_sub_group_size) ? start_index + target_offset : id;
681  return __spirv_GroupNonUniformShuffle(__spv::Scope::Subgroup, x, logical_remote_id);
682#elif defined(__NVPTX__)
683  T result;
684  int cVal = ((32 - logical_sub_group_size) << 8) | 31;
685  SHFL_SYNC(result, member_mask, x, mask, cVal, bfly_i32)
686  return result;
687#endif
688#else
689  (void)g;
690  (void)x;
691  (void)mask;
692  (void)logical_sub_group_size;
693  (void)member_mask;
694  throw sycl::exception(sycl::errc::runtime, "Masked version of permute_sub_group_by_xor not "
695                        "supported on host device.");
696#endif // __SYCL_DEVICE_ONLY__
697}
698#if defined(__NVPTX__)
699#undef SHFL_SYNC
700#endif
701} // namespace experimental
702
703/// Computes the multiplication of two complex numbers.
704/// \tparam T Complex element type
705/// \param [in] x The first input complex number
706/// \param [in] y The second input complex number
707/// \returns The result
708template <typename T>
709sycl::vec<T, 2> cmul(sycl::vec<T, 2> x, sycl::vec<T, 2> y) {
710  std::complex<T> t1(x[0], x[1]), t2(y[0], y[1]);
711  t1 = t1 * t2;
712  return sycl::vec<T, 2>(t1.real(), t1.imag());
713}
714
715/// Computes the division of two complex numbers.
716/// \tparam T Complex element type
717/// \param [in] x The first input complex number
718/// \param [in] y The second input complex number
719/// \returns The result
720template <typename T>
721sycl::vec<T, 2> cdiv(sycl::vec<T, 2> x, sycl::vec<T, 2> y) {
722  std::complex<T> t1(x[0], x[1]), t2(y[0], y[1]);
723  t1 = t1 / t2;
724  return sycl::vec<T, 2>(t1.real(), t1.imag());
725}
726
727/// Computes the magnitude of a complex number.
728/// \tparam T Complex element type
729/// \param [in] x The input complex number
730/// \returns The result
731template <typename T>
732T cabs(sycl::vec<T, 2> x) {
733  std::complex<T> t(x[0], x[1]);
734  return std::abs(t);
735}
736
737/// Computes the complex conjugate of a complex number.
738/// \tparam T Complex element type
739/// \param [in] x The input complex number
740/// \returns The result
741template <typename T>
742sycl::vec<T, 2> conj(sycl::vec<T, 2> x) {
743  std::complex<T> t(x[0], x[1]);
744  t = std::conj(t);
745  return sycl::vec<T, 2>(t.real(), t.imag());
746}
747
748inline int get_sycl_language_version() {
749#ifdef SYCL_LANGUAGE_VERSION
750  return SYCL_LANGUAGE_VERSION;
751#else
752  return 202000;
753#endif
754}
755
756// Returns the SYCL event status for the SYCL command.
757/// \param [in] event_ptr A pointer points to the SYCL event
758/// \returns The execution result for the SYCL command
759inline int sycl_event_query(sycl::event *event_ptr) {
760  if (event_ptr->get_info<sycl::info::event::command_execution_status>() ==
761      sycl::info::event_command_status::complete) {
762    // The SYCL command has finished running on the SYCL device.
763    return 0;
764  } else {
765    // The SYCL command has not finished running on the SYCL device.
766    return 1;
767  }
768}
769
770namespace experimental {
771/// Synchronize work items from all work groups within a SYCL kernel.
772/// \param [in] item:  Represents a work group.
773/// \param [in] counter: An atomic object defined on a device memory which can
774/// be accessed by work items in all work groups. The initial value of the
775/// counter should be zero.
776/// Note: Please make sure that all the work items of all work groups within
777/// a SYCL kernel can be scheduled actively at the same time on a device.
778template <int dimensions = 3>
779[[deprecated(
780    "Please use "
781    "sycl::group_barrier(sycl::ext::oneapi::experimental::root_group G) "
782    "instead.")]] inline void
783nd_range_barrier(
784    const sycl::nd_item<dimensions> &item,
785    sycl::atomic_ref<unsigned int,
786#ifdef __AMDGPU__
787                     sycl::memory_order::acq_rel,
788#else
789                     sycl::memory_order::seq_cst,
790#endif
791                     sycl::memory_scope::device,
792                     sycl::access::address_space::global_space> &counter) {
793
794  static_assert(dimensions == 3, "dimensions must be 3.");
795
796  unsigned int num_groups = item.get_group_range(2) * item.get_group_range(1) *
797                            item.get_group_range(0);
798
799  item.barrier();
800
801  if (item.get_local_linear_id() == 0) {
802    unsigned int inc = 1;
803    unsigned int old_arrive = 0;
804    bool is_group0 =
805        (item.get_group(2) + item.get_group(1) + item.get_group(0) == 0);
806    if (is_group0) {
807      inc = 0x80000000 - (num_groups - 1);
808    }
809
810    old_arrive = counter.fetch_add(inc);
811    // Synchronize all the work groups
812    while (((old_arrive ^ counter.load()) & 0x80000000) == 0)
813      ;
814  }
815
816  item.barrier();
817}
818
819/// Synchronize work items from all work groups within a SYCL kernel.
820/// \param [in] item:  Represents a work group.
821/// \param [in] counter: An atomic object defined on a device memory which can
822/// be accessed by work items in all work groups. The initial value of the
823/// counter should be zero.
824/// Note: Please make sure that all the work items of all work groups within
825/// a SYCL kernel can be scheduled actively at the same time on a device.
826template <>
827[[deprecated(
828    "Please use "
829    "sycl::group_barrier(sycl::ext::oneapi::experimental::root_group G) "
830    "instead.")]] inline void
831nd_range_barrier(
832    const sycl::nd_item<1> &item,
833    sycl::atomic_ref<unsigned int,
834#ifdef __AMDGPU__
835                     sycl::memory_order::acq_rel,
836#else
837                     sycl::memory_order::seq_cst,
838#endif
839                     sycl::memory_scope::device,
840                     sycl::access::address_space::global_space> &counter) {
841  unsigned int num_groups = item.get_group_range(0);
842
843  item.barrier();
844
845  if (item.get_local_linear_id() == 0) {
846    unsigned int inc = 1;
847    unsigned int old_arrive = 0;
848    bool is_group0 = (item.get_group(0) == 0);
849    if (is_group0) {
850      inc = 0x80000000 - (num_groups - 1);
851    }
852
853    old_arrive = counter.fetch_add(inc);
854    // Synchronize all the work groups
855    while (((old_arrive ^ counter.load()) & 0x80000000) == 0)
856      ;
857  }
858
859  item.barrier();
860}
861
862/// The logical-group is a logical collection of some work-items within a
863/// work-group.
864/// Note: Please make sure that the logical-group size is a power of 2 in the
865/// range [1, current_sub_group_size].
866template <int dimensions = 3> class logical_group {
867  sycl::nd_item<dimensions> _item;
868  sycl::group<dimensions> _g;
869  uint32_t _logical_group_size;
870  uint32_t _group_linear_range_in_parent;
871
872public:
873  /// Dividing \p parent_group into several logical-groups.
874  /// \param [in] item Current work-item.
875  /// \param [in] parent_group The group to be divided.
876  /// \param [in] size The logical-group size.
877  logical_group(sycl::nd_item<dimensions> item,
878                sycl::group<dimensions> parent_group, uint32_t size)
879      : _item(item), _g(parent_group), _logical_group_size(size) {
880    _group_linear_range_in_parent =
881        (_g.get_local_linear_range() - 1) / _logical_group_size + 1;
882  }
883  logical_group(sycl::nd_item<dimensions> item)
884      : _item(item), _g(item.get_group()) {}
885  /// Returns the index of the work-item within the logical-group.
886  uint32_t get_local_linear_id() const {
887    return _item.get_local_linear_id() % _logical_group_size;
888  }
889  /// Returns the index of the logical-group in the parent group.
890  uint32_t get_group_linear_id() const {
891    return _item.get_local_linear_id() / _logical_group_size;
892  }
893  /// Returns the number of work-items in the logical-group.
894  uint32_t get_local_linear_range() const {
895    if (_g.get_local_linear_range() % _logical_group_size == 0) {
896      return _logical_group_size;
897    }
898    uint32_t last_item_group_id =
899        _g.get_local_linear_range() / _logical_group_size;
900    uint32_t first_of_last_group = last_item_group_id * _logical_group_size;
901    if (_item.get_local_linear_id() >= first_of_last_group) {
902      return _g.get_local_linear_range() - first_of_last_group;
903    } else {
904      return _logical_group_size;
905    }
906  }
907  /// Returns the number of logical-group in the parent group.
908  uint32_t get_group_linear_range() const {
909    return _group_linear_range_in_parent;
910  }
911};
912
913// The original source of the functions calculate_max_active_wg_per_xecore and
914// calculate_max_potential_wg were under the license below:
915//
916// Copyright (C) Intel Corporation
917//
918// Permission is hereby granted, free of charge, to any person obtaining a copy
919// of this software and associated documentation files (the "Software"), to deal
920// in the Software without restriction, including without limitation the rights
921// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
922// copies of the Software, and to permit persons to whom the Software is
923// furnished to do so, subject to the following conditions:
924//
925// The above copyright notice and this permission notice shall be included in
926// all copies or substantial portions of the Software.
927//
928// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
929// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
930// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
931// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
932// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
933// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
934// SOFTWARE.
935//
936/// This function is used for occupancy calculation, it computes the max active
937/// work-group number per Xe-Core. Ref to
938/// https://github.com/oneapi-src/oneAPI-samples/tree/master/Tools/GPU-Occupancy-Calculator
939/// \param [out] num_wg Active work-group number.
940/// \param [in] wg_size Work-group size.
941/// \param [in] slm_size Share local memory size.
942/// \param [in] sg_size Sub-group size.
943/// \param [in] used_barrier Whether barrier is used.
944/// \param [in] used_large_grf Whether large General Register File is used.
945/// \return If no error, returns 0.
946/// If \p wg_size exceeds the max work-group size, the max work-group size will
947/// be used instead of \p wg_size and returns -1.
948inline int calculate_max_active_wg_per_xecore(int *num_wg, int wg_size,
949                                              int slm_size = 0,
950                                              int sg_size = 32,
951                                              bool used_barrier = false,
952                                              bool used_large_grf = false) {
953  int ret = 0;
954  const int slm_size_per_xe_core = 64 * 1024;
955  const int max_barrier_registers = 32;
956  dpct::device_ext &dev = dpct::get_current_device();
957
958  size_t max_wg_size = dev.get_info<sycl::info::device::max_work_group_size>();
959  if (wg_size > max_wg_size) {
960    wg_size = max_wg_size;
961    ret = -1;
962  }
963
964  int num_threads_ss = 56;
965  int max_num_wg = 56;
966  if (dev.has(sycl::aspect::ext_intel_gpu_eu_count_per_subslice) &&
967      dev.has(sycl::aspect::ext_intel_gpu_hw_threads_per_eu)) {
968    auto eu_count =
969        dev.get_info<sycl::info::device::ext_intel_gpu_eu_count_per_subslice>();
970    auto threads_count =
971        dev.get_info<sycl::ext::intel::info::device::gpu_hw_threads_per_eu>();
972    num_threads_ss = eu_count * threads_count;
973    max_num_wg = eu_count * threads_count;
974  }
975
976  if (used_barrier) {
977    max_num_wg = max_barrier_registers;
978  }
979
980  // Calculate num_wg_slm
981  int num_wg_slm = 0;
982  if (slm_size == 0) {
983    num_wg_slm = max_num_wg;
984  } else {
985    num_wg_slm = std::floor((float)slm_size_per_xe_core / slm_size);
986  }
987
988  // Calculate num_wg_threads
989  if (used_large_grf)
990    num_threads_ss = num_threads_ss / 2;
991  int num_threads = std::ceil((float)wg_size / sg_size);
992  int num_wg_threads = std::floor((float)num_threads_ss / num_threads);
993
994  // Calculate num_wg
995  *num_wg = (std::min)(num_wg_slm, num_wg_threads);
996  *num_wg = (std::min)(*num_wg, max_num_wg);
997  return ret;
998}
999
1000/// This function is used for occupancy calculation, it computes the work-group
1001/// number and the work-group size which achieves the maximum occupancy of the
1002/// device potentially. Ref to
1003/// https://github.com/oneapi-src/oneAPI-samples/tree/master/Tools/GPU-Occupancy-Calculator
1004/// \param [out] num_wg Work-group number.
1005/// \param [out] wg_size Work-group size.
1006/// \param [in] max_ws_size_for_device_code The maximum working work-group size
1007/// for current device code logic. Zero means no limitation.
1008/// \param [in] slm_size Share local memory size.
1009/// \param [in] sg_size Sub-group size.
1010/// \param [in] used_barrier Whether barrier is used.
1011/// \param [in] used_large_grf Whether large General Register File is used.
1012/// \return Returns 0.
1013inline int calculate_max_potential_wg(int *num_wg, int *wg_size,
1014                                      int max_ws_size_for_device_code,
1015                                      int slm_size = 0, int sg_size = 32,
1016                                      bool used_barrier = false,
1017                                      bool used_large_grf = false) {
1018  sycl::device &dev = dpct::get_current_device();
1019  size_t max_wg_size = dev.get_info<sycl::info::device::max_work_group_size>();
1020  if (max_ws_size_for_device_code == 0 ||
1021      max_ws_size_for_device_code >= max_wg_size)
1022    *wg_size = (int)max_wg_size;
1023  else
1024    *wg_size = max_ws_size_for_device_code;
1025  calculate_max_active_wg_per_xecore(num_wg, *wg_size, slm_size, sg_size,
1026                                     used_barrier, used_large_grf);
1027  std::uint32_t num_ss = 1;
1028  if (dev.has(sycl::aspect::ext_intel_gpu_slices) &&
1029      dev.has(sycl::aspect::ext_intel_gpu_subslices_per_slice)) {
1030    num_ss =
1031        dev.get_info<sycl::ext::intel::info::device::gpu_slices>() *
1032        dev.get_info<sycl::ext::intel::info::device::gpu_subslices_per_slice>();
1033  }
1034  num_wg[0] = num_ss * num_wg[0];
1035  return 0;
1036}
1037
1038/// Supported group type during migration.
1039enum class group_type { work_group, sub_group, logical_group, root_group };
1040
1041/// The group_base will dispatch the function call to the specific interface
1042/// based on the group type.
1043template <int dimensions = 3> class group_base {
1044public:
1045  group_base(sycl::nd_item<dimensions> item)
1046      : nd_item(item), logical_group(item) {}
1047  ~group_base() {}
1048  /// Returns the number of work-items in the group.
1049  size_t get_local_linear_range() {
1050    switch (type) {
1051    case group_type::work_group:
1052      return nd_item.get_group().get_local_linear_range();
1053    case group_type::sub_group:
1054      return nd_item.get_sub_group().get_local_linear_range();
1055    case group_type::logical_group:
1056      return logical_group.get_local_linear_range();
1057    default:
1058      return -1; // Unkonwn group type
1059    }
1060  }
1061  /// Returns the index of the work-item within the group.
1062  size_t get_local_linear_id() {
1063    switch (type) {
1064    case group_type::work_group:
1065      return nd_item.get_group().get_local_linear_id();
1066    case group_type::sub_group:
1067      return nd_item.get_sub_group().get_local_linear_id();
1068    case group_type::logical_group:
1069      return logical_group.get_local_linear_id();
1070    default:
1071      return -1; // Unkonwn group type
1072    }
1073  }
1074  /// Wait for all the elements within the group to complete their execution
1075  /// before proceeding.
1076  void barrier() {
1077    switch (type) {
1078    case group_type::work_group:
1079      sycl::group_barrier(nd_item.get_group());
1080      break;
1081    case group_type::sub_group:
1082    case group_type::logical_group:
1083      sycl::group_barrier(nd_item.get_sub_group());
1084      break;
1085    default:
1086      break;
1087    }
1088  }
1089
1090protected:
1091  logical_group<dimensions> logical_group;
1092  sycl::nd_item<dimensions> nd_item;
1093  group_type type;
1094};
1095
1096/// The group class is a container type that can storage supported group_type.
1097template <typename T, int dimensions = 3>
1098class group : public group_base<dimensions> {
1099  using group_base<dimensions>::type;
1100  using group_base<dimensions>::logical_group;
1101
1102public:
1103  group(T g, sycl::nd_item<dimensions> item) : group_base<dimensions>(item) {
1104    if constexpr (std::is_same_v<T, sycl::sub_group>) {
1105      type = group_type::sub_group;
1106    } else if constexpr (std::is_same_v<T, sycl::group<dimensions>>) {
1107      type = group_type::work_group;
1108    } else if constexpr (std::is_same_v<T, dpct::experimental::logical_group<
1109                                               dimensions>>) {
1110      logical_group = g;
1111      type = group_type::logical_group;
1112    }
1113  }
1114};
1115} // namespace experimental
1116
1117/// If x <= 2, then return a pointer to the deafult queue;
1118/// otherwise, return x reinterpreted as a dpct::queue_ptr.
1119inline queue_ptr int_as_queue_ptr(uintptr_t x) {
1120  return x <= 2 ?
1121  &get_default_queue()
1122  : reinterpret_cast<queue_ptr>(x);
1123}
1124
1125template <int n_nondefault_params, int n_default_params, typename T>
1126class args_selector;
1127
1128/// args_selector is a helper class for extracting arguments from an
1129/// array of pointers to arguments or buffer of arguments to pass to a
1130/// kernel function.
1131///
1132/// \param R(Ts...) The type of the kernel
1133/// \param n_nondefault_params The number of nondefault parameters of the kernel
1134/// (excluding parameters that like sycl::nd_item, etc.)
1135/// \param n_default_params The number of default parameters of the kernel
1136///
1137/// Example usage:
1138/// With the following kernel:
1139///   void foo(sycl::float2 *x, int n, sycl::nd_item<3> item_ct1, float f=.1) {}
1140/// and with the declaration:
1141///   args_selector<2, 1, decltype(foo)> selector(kernelParams, extra);
1142/// we have:
1143///   selector.get<0>() returns a reference to sycl::float*,
1144///   selector.get<1>() returns a reference to int,
1145///   selector.get<2>() returns a reference to float
1146template <int n_nondefault_params, int n_default_params,
1147   typename R, typename... Ts>
1148class args_selector<n_nondefault_params, n_default_params, R(Ts...)> {
1149private:
1150  void **kernel_params;
1151  char *args_buffer;
1152
1153  template <int i>
1154  static constexpr int account_for_default_params() {
1155    constexpr int n_total_params = sizeof...(Ts);
1156    if constexpr (i >= n_nondefault_params) {
1157      return n_total_params - n_default_params + (i - n_nondefault_params);
1158    } else {
1159      return i;
1160    }
1161  }    
1162
1163public:
1164  /// Get the type of the ith argument of R(Ts...)
1165  /// \param [in] i Index of parameter to get
1166  /// \returns Type of ith parameter
1167  template <int i>
1168  using arg_type = std::tuple_element_t<account_for_default_params<i>(),
1169					  std::tuple<Ts...>>;
1170  static constexpr int params_num = sizeof...(Ts);
1171
1172private:
1173  template <int i>
1174  static constexpr int get_offset() {
1175    if constexpr (i == 0) {
1176      // we can assume args_buffer is properly aligned to the
1177      // first argument
1178      return 0;
1179    } else {
1180      constexpr int prev_off = get_offset<i-1>();
1181      constexpr int prev_past_end = prev_off + sizeof(arg_type<i-1>);
1182      using T = arg_type<i>;
1183      // is the past-the-end of the i-1st element properly aligned
1184      // with the ith element's alignment?
1185      if constexpr (prev_past_end % alignof(T) == 0) {
1186	return prev_past_end;
1187      }
1188      // otherwise bump prev_past_end to match alignment
1189      else {
1190	return prev_past_end + (alignof(T) - (prev_past_end % alignof(T)));
1191      }
1192    }
1193  }
1194
1195  static char *get_args_buffer(void **extra) {
1196    if (!extra)
1197      return nullptr;
1198    for (; (std::size_t) *extra != 0; ++extra) {
1199      if ((std::size_t) *extra == 1) {
1200	return static_cast<char*>(*(extra+1));
1201      }
1202    }
1203    return nullptr;
1204  }
1205    
1206public:
1207  /// If kernel_params is nonnull, then args_selector will
1208  /// extract arguments from kernel_params. Otherwise, it
1209  /// will extract them from extra.
1210  /// \param [in] kernel_params Array of pointers to arguments
1211  /// a or null pointer.
1212  /// \param [in] extra Array containing pointer to argument buffer.
1213  args_selector(void **kernel_params, void **extra)
1214    : kernel_params(kernel_params),
1215      args_buffer(get_args_buffer(extra))
1216  {}
1217
1218  /// Get a reference to the ith argument extracted from kernel_params
1219  /// or extra.
1220  /// \param [in] i Index of argument to get
1221  /// \returns Reference to the ith argument
1222  template <int i>    
1223  arg_type<i> &get() {
1224    if (kernel_params) {
1225      return *static_cast<arg_type<i>*>(kernel_params[i]);
1226    } else {
1227      return *reinterpret_cast<arg_type<i>*>(args_buffer + get_offset<i>());
1228    }
1229  }
1230};
1231
1232/// \brief This struct template used to get the type of the N-th argument of a
1233/// callable type `Func`. It supports both function types (e.g., `void(int,
1234/// double)`) and callable objects such as lambdas or functors.
1235///
1236/// \tparam Func The callable type from which to extract the argument type.
1237/// \tparam N The index of the argument to retrieve.
1238///
1239/// Example:
1240/// using Func = void(int, double, const char*);
1241/// static_assert(std::is_same<nth_argument_type<Func, 0>::type, int>::value,
1242/// "Unexpected type");
1243template <typename Func, std::size_t N> struct nth_argument_type {
1244  template <typename R, typename... Args>
1245  static auto
1246      helper(R(Args...)) -> std::tuple_element_t<N, std::tuple<Args...>>;
1247  using type = decltype(helper(std::declval<Func>()));
1248};
1249
1250/// \brief The function performs bitwise logical operations on three input
1251/// values of \p a, \p b and \p c based on the specified 8-bit truth table \p
1252/// lut and return the result
1253///
1254/// \param [in] a Input value
1255/// \param [in] b Input value
1256/// \param [in] c Input value
1257/// \param [in] lut truth table for looking up
1258/// \returns The result
1259inline uint32_t ternary_logic_op(uint32_t a, uint32_t b, uint32_t c,
1260                                 uint8_t lut) {
1261  uint32_t result = 0;
1262
1263  switch (lut) {
1264  case 0x0:
1265    result = 0;
1266    break;
1267  case 0x1:
1268    result = ~a & ~b & ~c;
1269    break;
1270  case 0x2:
1271    result = ~a & ~b & c;
1272  case 0x4:
1273    result = ~a & b & ~c;
1274    break;
1275  case 0x8:
1276    result = ~a & b & c;
1277    break;
1278  case 0x10:
1279    result = a & ~b & ~c;
1280    break;
1281  case 0x20:
1282    result = a & ~b & c;
1283    break;
1284  case 0x40:
1285    result = a & b & ~c;
1286    break;
1287  case 0x80:
1288    result = a & b & c;
1289    break;
1290  case 0x1a:
1291    result = (a & b | c) ^ a;
1292    break;
1293  case 0x1e:
1294    result = a ^ (b | c);
1295    break;
1296  case 0x2d:
1297    result = ~a ^ (~b & c);
1298    break;
1299  case 0x78:
1300    result = a ^ (b & c);
1301    break;
1302  case 0x96:
1303    result = a ^ b ^ c;
1304    break;
1305  case 0xb4:
1306    result = a ^ (b & ~c);
1307    break;
1308  case 0xb8:
1309    result = a ^ (b & (c ^ a));
1310    break;
1311  case 0xd2:
1312    result = a ^ (~b & c);
1313    break;
1314  case 0xe8:
1315    result = a & (b | c) | (b & c);
1316    break;
1317  case 0xea:
1318    result = a & b | c;
1319    break;
1320  case 0xfe:
1321    result = a | b | c;
1322    break;
1323  case 0xff:
1324    result = -1;
1325    break;
1326  default: {
1327    if (lut & 0x01)
1328      result |= ~a & ~b & ~c;
1329    if (lut & 0x02)
1330      result |= ~a & ~b & c;
1331    if (lut & 0x04)
1332      result |= ~a & b & ~c;
1333    if (lut & 0x08)
1334      result |= ~a & b & c;
1335    if (lut & 0x10)
1336      result |= a & ~b & ~c;
1337    if (lut & 0x20)
1338      result |= a & ~b & c;
1339    if (lut & 0x40)
1340      result |= a & b & ~c;
1341    if (lut & 0x80)
1342      result |= a & b & c;
1343    break;
1344  }
1345  }
1346
1347  return result;
1348}
1349
1350#ifdef _WIN32
1351#define DPCT_EXPORT __declspec(dllexport)
1352#else
1353#define DPCT_EXPORT
1354#endif
1355
1356} // namespace dpct
1357
1358#endif // __DPCT_UTIL_HPP__