| 1 | (* Arith: the machine's arithmetic that raz has no operator for, which |
| 2 | Math gives as sqrt, mul and divMod: an F64's square root, the 128-bit |
| 3 | product of two U64s, and a 128-bit number divided by a U64. This file |
| 4 | is arm64's, Arith.x86_64.raz x86-64's. The root is fsqrt, and a call |
| 5 | of sqrt, an fsqrt and ret, is made in place (Gen.oneRealOp); the |
| 6 | product is mul for its low half and umulh for its high. arm64 has no |
| 7 | division of 128 bits by 64, only udiv of 64 by 64, so div128 is |
| 8 | long division in raz, a bit of the quotient at each of 64 steps. |
| 9 | Depends on Check, for its test. *) |
| 10 | module Arith; |
| 11 | import Check; |
| 12 | import SYSTEM; |
| 13 | |
| 14 | (* The square root of x, exact to the last bit; NaN for x below 0. *) |
| 15 | proc sqrt*(x: F64): F64; |
| 16 | code |
| 17 | fsqrt d0, d0; |
| 18 | ret; |
| 19 | end sqrt; |
| 20 | |
| 21 | (* a times b: the low 64 bits of the product, and the high, which come |
| 22 | back in x0 and x1. *) |
| 23 | proc mul*(a, b: U64): (U64, U64); |
| 24 | code |
| 25 | mul x2, x0, x1; |
| 26 | umulh x1, x0, x1; |
| 27 | mov x0, x2; |
| 28 | ret; |
| 29 | end mul; |
| 30 | |
| 31 | (* hi, lo divided by d, with hi < d, which the caller checks first: the |
| 32 | quotient and the remainder. As by hand, in base 2: the remainder so |
| 33 | far, hi, takes the next bit of lo at each step, and where it then |
| 34 | holds d, d is taken from it and that bit of the quotient is 1. The |
| 35 | remainder is below d before a step, so below 2d after the shift: it |
| 36 | holds d once at most, and its bit shifted out, top, says it is more |
| 37 | than 64 bits can hold, and so holds d too. *) |
| 38 | proc div128*(hi, lo, d: U64): (U64, U64); |
| 39 | var q: U64; i: INT; top: BOOL; |
| 40 | begin |
| 41 | q := 0; |
| 42 | for i := 1 to 64 do |
| 43 | top := hi shr 63 = 1; |
| 44 | hi := hi shl 1 | lo shr 63; |
| 45 | lo := lo shl 1; |
| 46 | q := q shl 1; |
| 47 | if top or (hi >= d) then |
| 48 | hi := hi - d; |
| 49 | q := q | 1; |
| 50 | end; |
| 51 | end; |
| 52 | return q, hi; |
| 53 | end; |
| 54 | |
| 55 | (* The module's test; Math's tests these more. *) |
| 56 | proc main*; |
| 57 | var lo, hi, q, r: U64; |
| 58 | begin |
| 59 | Check.ok(sqrt(2.0) = 1.4142135623730951, "Arith.sqrt"); |
| 60 | lo, hi := mul(0FFFFFFFFFFFFFFFFH, 0FFFFFFFFFFFFFFFFH); |
| 61 | Check.ok((lo = 1) and (hi = 0FFFFFFFFFFFFFFFEH), "Arith.mul"); |
| 62 | q, r := div128(5, 9, 6); |
| 63 | Check.ok((q = 0D555555555555556H) and (r = 5), "Arith.div128"); |
| 64 | end; |
| 65 | |
| 66 | end Arith. |