template <typename T>
typename std::enable_if<std::is_signed<T>::value, T>::type
AddOverflow(T X, T Y, T &Result) {
+#if __has_builtin(__builtin_add_overflow)
+ return __builtin_add_overflow(X, Y, &Result);
+#else
// Perform the unsigned addition.
using U = typename std::make_unsigned<T>::type;
const U UX = static_cast<U>(X);
if (X < 0 && Y < 0)
return Result >= 0;
return false;
+#endif
}
/// Subtract two signed integers, computing the two's complement truncated
template <typename T>
typename std::enable_if<std::is_signed<T>::value, T>::type
SubOverflow(T X, T Y, T &Result) {
+#if __has_builtin(__builtin_sub_overflow)
+ return __builtin_sub_overflow(X, Y, &Result);
+#else
// Perform the unsigned addition.
using U = typename std::make_unsigned<T>::type;
const U UX = static_cast<U>(X);
if (X >= 0 && Y < 0)
return Result <= 0;
return false;
+#endif
}
template <typename T>
typename std::enable_if<std::is_signed<T>::value, T>::type
MulOverflow(T X, T Y, T &Result) {
+#if __has_builtin(__builtin_mul_overflow)
+ return __builtin_mul_overflow(X, Y, &Result);
+#else
// Perform the unsigned multiplication on absolute values.
using U = typename std::make_unsigned<T>::type;
const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
else
return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
+#endif
}
} // End llvm namespace