muldiv.h 1.0 KiB raw
1
#ifndef MULDIV_H
2
#define MULDIV_H
3
4
#include "types.h"
5
6
__extension__ typedef unsigned __int128 u128;
7
8
/* High 64 bits of the unsigned 128-bit product. */
9
static inline u64 mulhu64(u64 a, u64 b) {
10
    return (u64)(((u128)a * b) >> 64);
11
}
12
13
/* High 64 bits of the signed x signed product. */
14
static inline u64 mulh64(u64 a, u64 b) {
15
    return mulhu64(a, b) - ((i64)a < 0 ? b : 0) - ((i64)b < 0 ? a : 0);
16
}
17
18
/* High 64 bits of the signed x unsigned product. */
19
static inline u64 mulhsu64(u64 a, u64 b) {
20
    return mulhu64(a, b) - ((i64)a < 0 ? b : 0);
21
}
22
23
/* Signed division with the RISC-V results for a zero divisor (quotient -1,
24
 * remainder a) and for overflow (INT_MIN / -1: quotient INT_MIN, remainder 0).
25
 * Operands are sign-extended, so the same helper serves the W forms. */
26
static inline u64 divs64(u64 a, u64 b, bool remainder) {
27
    if (b == 0)
28
        return remainder ? a : (u64)-1;
29
    if (b == (u64)-1)
30
        return remainder ? 0 : -a;
31
    return remainder ? (u64)((i64)a % (i64)b) : (u64)((i64)a / (i64)b);
32
}
33
34
#endif /* MULDIV_H */