| 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. Each is |
| 4 | one instruction of the machine, so each is a code procedure, one |
| 5 | file per machine: this one for x86-64, Arith.arm64.raz for arm64. A |
| 6 | call of sqrt, a sqrtsd and ret, is made in place (Gen.oneRealOp). |
| 7 | Depends on Check, for its test. *) |
| 8 | module Arith; |
| 9 | import Check; |
| 10 | import SYSTEM; |
| 11 | |
| 12 | (* The square root of x, exact to the last bit; NaN for x below 0. *) |
| 13 | proc sqrt*(x: F64): F64; |
| 14 | code |
| 15 | sqrtsd xmm0, xmm0; |
| 16 | ret; |
| 17 | end sqrt; |
| 18 | |
| 19 | (* a times b: the low 64 bits of the product, and the high. *) |
| 20 | proc mul*(a, b: U64): (U64, U64); |
| 21 | code |
| 22 | mov rax, rdi; |
| 23 | mul rsi; |
| 24 | ret; |
| 25 | end mul; |
| 26 | |
| 27 | (* hi, lo divided by d: the quotient and the remainder, by the |
| 28 | machine's one instruction; it faults if hi >= d, which the caller |
| 29 | checks first. *) |
| 30 | proc div128*(hi, lo, d: U64): (U64, U64); |
| 31 | code |
| 32 | mov rcx, rdx; |
| 33 | mov rdx, rdi; |
| 34 | mov rax, rsi; |
| 35 | div rcx; |
| 36 | ret; |
| 37 | end div128; |
| 38 | |
| 39 | (* The module's test; Math's tests these more. *) |
| 40 | proc main*; |
| 41 | var lo, hi, q, r: U64; |
| 42 | begin |
| 43 | Check.ok(sqrt(2.0) = 1.4142135623730951, "Arith.sqrt"); |
| 44 | lo, hi := mul(0FFFFFFFFFFFFFFFFH, 0FFFFFFFFFFFFFFFFH); |
| 45 | Check.ok((lo = 1) and (hi = 0FFFFFFFFFFFFFFFEH), "Arith.mul"); |
| 46 | q, r := div128(5, 9, 6); |
| 47 | Check.ok((q = 0D555555555555556H) and (r = 5), "Arith.div128"); |
| 48 | end; |
| 49 | |
| 50 | end Arith. |