Skip to content

Commit

Permalink
UB in negate in mulh/mulhsu
Browse files Browse the repository at this point in the history
Ensuring No negation on -2^63(int64_t) is performed during mulh/mulhsu

Signed-off-by: Nicolas Brunie <[email protected]>

Update riscv/arith.h

Signed-off-by: Nicolas Brunie <[email protected]>
  • Loading branch information
nibrunieAtSi5 authored and nibrunie committed Aug 11, 2024
1 parent 6f28e4b commit fefc853
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions riscv/arith.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ inline uint64_t mulhu(uint64_t a, uint64_t b)
inline int64_t mulh(int64_t a, int64_t b)
{
int negate = (a < 0) != (b < 0);
uint64_t res = mulhu(a < 0 ? -a : a, b < 0 ? -b : b);
uint64_t res = mulhu(a < 0 ? -(uint64_t)a : a, b < 0 ? -(uint64_t)b : b);
return negate ? ~res + ((uint64_t)a * (uint64_t)b == 0) : res;
}

inline int64_t mulhsu(int64_t a, uint64_t b)
{
int negate = a < 0;
uint64_t res = mulhu(a < 0 ? -a : a, b);
return negate ? ~res + (a * b == 0) : res;
uint64_t res = mulhu(a < 0 ? -(uint64_t)a : a, b);
return negate ? ~res + ((uint64_t)a * b == 0) : res;
}

//ref: https://locklessinc.com/articles/sat_arithmetic/
Expand Down

0 comments on commit fefc853

Please sign in to comment.