Skip to content

Commit

Permalink
Use checked arithmetic builtins for overflow detection (kokkos#6313)
Browse files Browse the repository at this point in the history
* Use checked arithmetic builtins for clang and gcc

* Use `__has_builtin` instead of checking the compilers explicitly

* Fix unreachable code warning
  • Loading branch information
cz4rs committed Aug 4, 2023
1 parent 00dca3a commit fcd6132
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions core/src/impl/Kokkos_CheckedIntegerOps.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,33 @@
namespace Kokkos {
namespace Impl {

#if defined(__has_builtin)
#if __has_builtin(__builtin_mul_overflow)
#define KOKKOS_IMPL_USE_MUL_OVERFLOW_BUILTIN
#endif
#endif

template <typename T>
std::enable_if_t<std::is_integral_v<T>, bool> constexpr multiply_overflow(
T a, T b, T& res) {
static_assert(std::is_unsigned_v<T>,
"Operation not implemented for signed integers.");

#if defined(KOKKOS_IMPL_USE_MUL_OVERFLOW_BUILTIN)
return __builtin_mul_overflow(a, b, &res);
#else
auto product = a * b;
if ((a == 0) || (b == 0) || (a == product / b)) {
res = product;
return false;
} else {
return true;
}
#endif
}

#undef KOKKOS_IMPL_USE_MUL_OVERFLOW_BUILTIN

template <typename T>
T multiply_overflow_abort(T a, T b) {
T result;
Expand Down

0 comments on commit fcd6132

Please sign in to comment.