#ifndef MULDIV_H #define MULDIV_H #include "types.h" __extension__ typedef unsigned __int128 u128; /* High 64 bits of the unsigned 128-bit product. */ static inline u64 mulhu64(u64 a, u64 b) { return (u64)(((u128)a * b) >> 64); } /* High 64 bits of the signed x signed product. */ static inline u64 mulh64(u64 a, u64 b) { return mulhu64(a, b) - ((i64)a < 0 ? b : 0) - ((i64)b < 0 ? a : 0); } /* High 64 bits of the signed x unsigned product. */ static inline u64 mulhsu64(u64 a, u64 b) { return mulhu64(a, b) - ((i64)a < 0 ? b : 0); } /* Signed division with the RISC-V results for a zero divisor (quotient -1, * remainder a) and for overflow (INT_MIN / -1: quotient INT_MIN, remainder 0). * Operands are sign-extended, so the same helper serves the W forms. */ static inline u64 divs64(u64 a, u64 b, bool remainder) { if (b == 0) return remainder ? a : (u64)-1; if (b == (u64)-1) return remainder ? 0 : -a; return remainder ? (u64)((i64)a % (i64)b) : (u64)((i64)a / (i64)b); } #endif /* MULDIV_H */