RAJA
RAJA provides a collection of platform portability abstractions for C++ HPC applications.
math.hpp
Go to the documentation of this file.
1 
11 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
12 // Copyright (c) Lawrence Livermore National Security, LLC and other
13 // RAJA Project Developers. See top-level LICENSE and COPYRIGHT
14 // files for dates and other details. No copyright assignment is required
15 // to contribute to RAJA.
16 //
17 // SPDX-License-Identifier: (BSD-3-Clause)
18 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
19 
20 #ifndef RAJA_util_math_HPP
21 #define RAJA_util_math_HPP
22 
23 #include "RAJA/config.hpp"
24 
25 #include <type_traits>
26 #include <climits>
27 
28 namespace RAJA
29 {
30 
39 template<typename T, std::enable_if_t<std::is_integral<T>::value>* = nullptr>
40 RAJA_HOST_DEVICE RAJA_INLINE constexpr T log2(T n) noexcept
41 {
42  T result = 0;
43  if (n > 0)
44  {
45  while (n >>= 1)
46  {
47  ++result;
48  }
49  }
50  return result;
51 }
52 
62 template<typename T, std::enable_if_t<std::is_integral<T>::value>* = nullptr>
63 RAJA_HOST_DEVICE RAJA_INLINE constexpr T next_pow2(T n) noexcept
64 {
65  --n;
66  for (size_t s = 1; s < CHAR_BIT * sizeof(T); s *= 2)
67  {
68  n |= n >> s;
69  }
70  ++n;
71  return n;
72 }
73 
84 template<typename T, std::enable_if_t<std::is_integral<T>::value>* = nullptr>
85 RAJA_HOST_DEVICE RAJA_INLINE constexpr T prev_pow2(T n) noexcept
86 {
87  if (n < 0) return 0;
88  for (size_t s = 1; s < CHAR_BIT * sizeof(T); s *= 2)
89  {
90  n |= n >> s;
91  }
92  return n - (n >> 1);
93 }
94 
98 template<typename L,
99  typename R,
100  std::enable_if_t<std::is_integral<L>::value &&
101  std::is_integral<R>::value>* = nullptr>
102 RAJA_HOST_DEVICE RAJA_INLINE constexpr auto power_of_2_mod(L lhs,
103  R rhs) noexcept
104 {
105  return lhs & (rhs - R(1));
106 }
107 
108 } // namespace RAJA
109 
110 #endif
#define RAJA_HOST_DEVICE
Definition: macros.hpp:65
Definition: AlignedRangeIndexSetBuilders.cpp:35
RAJA_HOST_DEVICE constexpr RAJA_INLINE T next_pow2(T n) noexcept
"round up" to the next greatest power of 2
Definition: math.hpp:63
RAJA_HOST_DEVICE constexpr RAJA_INLINE auto power_of_2_mod(L lhs, R rhs) noexcept
compute lhs mod rhs where lhs is non-negative and rhs is a power of 2
Definition: math.hpp:102
RAJA_HOST_DEVICE constexpr RAJA_INLINE T log2(T n) noexcept
evaluate log base 2 of n
Definition: math.hpp:40
RAJA_HOST_DEVICE constexpr RAJA_INLINE T prev_pow2(T n) noexcept
"round down" to the largest power of 2 that is less than or equal to n
Definition: math.hpp:85