Skip to content

Commit 9691bc0

Browse files
authored
Merge pull request #842 from steffenlarsen/steffen/abs_diff_ub
Do not check for undefined behavior in abs_diff
2 parents d3d479a + 860adde commit 9691bc0

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

util/math_reference.h

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -305,21 +305,30 @@ sycl_cts::resultRef<sycl::marray<T, N>> abs(sycl::marray<T, N> a) {
305305

306306
/* absolute difference */
307307
template <typename T>
308-
T abs_diff(T a, T b) {
308+
sycl_cts::resultRef<T> abs_diff(T a, T b) {
309+
using U = std::make_unsigned_t<T>;
309310
T h = (a > b) ? a : b;
310311
T l = (a <= b) ? a : b;
311-
return h - l;
312+
// Using two's-complement and that unsigned integer underflow is defined as
313+
// modulo 2^n we get the result by computing the distance based on signed
314+
// comparison.
315+
U result = static_cast<U>(h) - static_cast<U>(l);
316+
return result > std::numeric_limits<T>::max()
317+
? sycl_cts::resultRef<T>(0, true)
318+
: T(result);
312319
}
313320
template <typename T, int N>
314-
sycl::vec<T, N> abs_diff(sycl::vec<T, N> a, sycl::vec<T, N> b) {
315-
return sycl_cts::math::run_func_on_vector<T, T, N>(
321+
sycl_cts::resultRef<sycl::vec<T, N>> abs_diff(sycl::vec<T, N> a,
322+
sycl::vec<T, N> b) {
323+
return sycl_cts::math::run_func_on_vector_result_ref<T, N>(
316324
[](T x, T y) { return abs_diff(x, y); }, a, b);
317325
}
318326
// FIXME: hipSYCL does not support marray
319327
#ifndef SYCL_CTS_COMPILING_WITH_HIPSYCL
320328
template <typename T, size_t N>
321-
sycl::marray<T, N> abs_diff(sycl::marray<T, N> a, sycl::marray<T, N> b) {
322-
return sycl_cts::math::run_func_on_marray<T, T, N>(
329+
sycl_cts::resultRef<sycl::marray<T, N>> abs_diff(sycl::marray<T, N> a,
330+
sycl::marray<T, N> b) {
331+
return sycl_cts::math::run_func_on_marray_result_ref<T, N>(
323332
[](T x, T y) { return abs_diff(x, y); }, a, b);
324333
}
325334
#endif

0 commit comments

Comments
 (0)