raz / lib / Arith.x86_64.raz

50 lines · 1.4 KiB · raw · history · last change 89524972

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. *)
8module Arith;
9import Check;
10import SYSTEM;
11
12(* The square root of x, exact to the last bit; NaN for x below 0. *)
13proc sqrt*(x: F64): F64;
14code
15 sqrtsd xmm0, xmm0;
16 ret;
17end sqrt;
18
19(* a times b: the low 64 bits of the product, and the high. *)
20proc mul*(a, b: U64): (U64, U64);
21code
22 mov rax, rdi;
23 mul rsi;
24 ret;
25end 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. *)
30proc div128*(hi, lo, d: U64): (U64, U64);
31code
32 mov rcx, rdx;
33 mov rdx, rdi;
34 mov rax, rsi;
35 div rcx;
36 ret;
37end div128;
38
39(* The module's test; Math's tests these more. *)
40proc main*;
41var lo, hi, q, r: U64;
42begin
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");
48end;
49
50end Arith.