Skip to content

Commit 5307a57

Browse files
Update MathExtras.h
1 parent 9a0d4ad commit 5307a57

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

llvm/include/llvm/Support/MathExtras.h

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -760,7 +760,7 @@ std::enable_if_t<std::is_signed_v<T>, T> SubOverflow(T X, T Y, T &Result) {
760760
/// Multiply two signed integers, computing the two's complement truncated
761761
/// result, returning true if an overflow occurred.
762762
template <typename T>
763-
std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) {
763+
std::enable_if_t<std::is_signed_v<T>, bool> MulOverflow(T X, T Y, T &Result) {
764764
#if __has_builtin(__builtin_mul_overflow)
765765
return __builtin_mul_overflow(X, Y, &Result);
766766
#else
@@ -775,23 +775,26 @@ std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) {
775775
bool IsNegative = (X < 0) ^ (Y < 0);
776776

777777
// Safely compute absolute values
778-
const U AbsX = X < 0 ? (0 - static_cast<U>(X+1))+1 : static_cast<U>(X);
779-
const U AbsY = Y < 0 ? (0 - static_cast<U>(Y+1))+1 : static_cast<U>(Y);
778+
const U AbsX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
779+
const U AbsY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
780780

781781
// Overflow check before actual multiplication
782782
constexpr U MaxPositive = static_cast<U>(std::numeric_limits<T>::max());
783783
constexpr U MaxNegative = static_cast<U>(std::numeric_limits<T>::max()) + 1;
784-
784+
785785
// Safe to multiply
786786
U AbsResult = AbsX * AbsY;
787787
Result = IsNegative ? static_cast<T>(0-AbsResult) : static_cast<T>(AbsResult);
788788

789+
790+
789791
// Handle INT_MIN * -1 overflow case explicitly
790792
if ((X == std::numeric_limits<T>::min() && Y == -1) ||
791793
(Y == std::numeric_limits<T>::min() && X == -1)) {
792794
return true; // overflow
793795
}
794796

797+
795798
U Limit = IsNegative ? MaxNegative : MaxPositive;
796799

797800
if (AbsX > Limit / AbsY)

0 commit comments

Comments
 (0)