alpaka
Abstraction Library for Parallel Kernel Acceleration
Utility.hpp
Go to the documentation of this file.
1 /* Copyright 2024 Benjamin Worpitz, RenĂ© Widera, Bernhard Manfred Gruber, Jan Stephan, Andrea Bocci
2  * SPDX-License-Identifier: MPL-2.0
3  */
4 #pragma once
5 
6 #include "alpaka/core/Common.hpp"
7 
8 #include <type_traits>
9 #include <utility>
10 
11 namespace alpaka::core
12 {
13  //! convert any type to a reference type
14  //
15  // This function is equivalent to std::declval() but can be used
16  // within an alpaka accelerator kernel too.
17  // This function can be used only within std::decltype().
18 #if BOOST_LANG_CUDA && BOOST_COMP_CLANG_CUDA || BOOST_COMP_HIP
19  template<class T>
20  ALPAKA_FN_HOST_ACC std::add_rvalue_reference_t<T> declval();
21 #else
22  using std::declval;
23 #endif
24 
25  /// Returns the ceiling of a / b, as integer.
26  template<typename Integral, typename = std::enable_if_t<std::is_integral_v<Integral>>>
27  [[nodiscard]] ALPAKA_FN_HOST_ACC constexpr auto divCeil(Integral a, Integral b) -> Integral
28  {
29  return (a + b - 1) / b;
30  }
31 
32  /// Computes the nth power of base, in integers.
33  template<typename Integral, typename = std::enable_if_t<std::is_integral_v<Integral>>>
34  [[nodiscard]] ALPAKA_FN_HOST_ACC constexpr auto intPow(Integral base, Integral n) -> Integral
35  {
36  if(n == 0)
37  return 1;
38  auto r = base;
39  for(Integral i = 1; i < n; i++)
40  r *= base;
41  return r;
42  }
43 
44  /// Computes the floor of the nth root of value, in integers.
45  template<typename Integral, typename = std::enable_if_t<std::is_integral_v<Integral>>>
46  [[nodiscard]] ALPAKA_FN_HOST_ACC constexpr auto nthRootFloor(Integral value, Integral n) -> Integral
47  {
48  // adapted from: https://en.wikipedia.org/wiki/Integer_square_root
49  Integral L = 0;
50  Integral R = value + 1;
51  while(L != R - 1)
52  {
53  Integral const M = (L + R) / 2;
54  if(intPow(M, n) <= value)
55  L = M;
56  else
57  R = M;
58  }
59  return L;
60  }
61 
62 } // namespace alpaka::core
#define ALPAKA_FN_HOST_ACC
Definition: Common.hpp:39
constexpr ALPAKA_FN_HOST_ACC auto divCeil(Integral a, Integral b) -> Integral
Returns the ceiling of a / b, as integer.
Definition: Utility.hpp:27
constexpr ALPAKA_FN_HOST_ACC auto intPow(Integral base, Integral n) -> Integral
Computes the nth power of base, in integers.
Definition: Utility.hpp:34
constexpr ALPAKA_FN_HOST_ACC auto nthRootFloor(Integral value, Integral n) -> Integral
Computes the floor of the nth root of value, in integers.
Definition: Utility.hpp:46