raz / lib / Arith.arm64.raz

66 lines · 2.1 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. 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. *)
10module Arith;
11import Check;
12import SYSTEM;
13
14(* The square root of x, exact to the last bit; NaN for x below 0. *)
15proc sqrt*(x: F64): F64;
16code
17 fsqrt d0, d0;
18 ret;
19end sqrt;
20
21(* a times b: the low 64 bits of the product, and the high, which come
22 back in x0 and x1. *)
23proc mul*(a, b: U64): (U64, U64);
24code
25 mul x2, x0, x1;
26 umulh x1, x0, x1;
27 mov x0, x2;
28 ret;
29end 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. *)
38proc div128*(hi, lo, d: U64): (U64, U64);
39var q: U64; i: INT; top: BOOL;
40begin
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;
53end;
54
55(* The module's test; Math's tests these more. *)
56proc main*;
57var lo, hi, q, r: U64;
58begin
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");
64end;
65
66end Arith.