raz / test / run / KeptCopy.raz

102 lines · 2.6 KiB · raw · history · last change 16eaf7cb

1(* A procedure that calls nothing keeps its first parameters in rdi and
2 rsi; when it copies an array, which needs them, it is compiled again
3 with those parameters in callee-saved registers where some are free
4 and they are used enough, or in memory. The copy and the uses after
5 it must agree either way, and a failed check still says their
6 values. *)
7module KeptCopy;
8import Out;
9
10const N = 8;
11
12type Row = [N]I64;
13
14var r1, r2: Row; total: I64;
15
16(* out a copy of st, then each element worked on through both pointers *)
17proc mix(const st: Row; var out: Row; k: INT);
18var i: INT;
19begin
20 out := st;
21 for i := 0 to N - 1 do out[i] := out[i] * 3 + st[N - 1 - i] + k; end;
22 for i := 1 to N - 1 do out[i] := out[i] + out[i - 1]; end;
23end;
24
25(* a slice, kept in both registers, then a copy, then the slice read:
26 one callee-saved register is left, too few for it, so it goes to
27 memory *)
28proc sumAfter(s: []I64; var a: Row; const b: Row): I64;
29var i: INT; t: I64;
30begin
31 a := b;
32 t := 0;
33 for i := 0 to LEN(s) - 1 do t := t + s[i] * a[i mod N]; end;
34 return t;
35end;
36
37(* the same, with registers enough left for the slice's two *)
38proc sumThen(s: []I64; var a: Row): I64;
39var i: INT; t: I64;
40begin
41 a := r1;
42 t := 0;
43 for i := 0 to LEN(s) - 1 do t := t + s[i] * s[LEN(s) - 1 - i]; end;
44 return t + a[0];
45end;
46
47(* five busy locals take every callee-saved register: the pointers go
48 to memory *)
49proc busy(var out: Row; const st: Row): I64;
50var a, b, c, d, e, i: INT;
51begin
52 out := st;
53 a := 1; b := 2; c := 3; d := 4; e := 5;
54 for i := 0 to N - 1 do
55 a := a + b; b := b + c; c := c + d; d := d + e; e := e + a;
56 out[i] := out[i] + a + b + c + d + e + st[i];
57 end;
58 return out[N - 1];
59end;
60
61(* a pointer used once only goes to memory *)
62proc once(var out: Row; const st: Row);
63begin
64 out := st;
65 out[0] := 99;
66end;
67
68(* the element at k of a copy, which may be out of range *)
69proc pick(const st: Row; var out: Row; k: INT): I64;
70var i: INT;
71begin
72 out := st;
73 for i := 0 to N - 1 do out[i] := out[i] + st[i]; end;
74 return out[k] + st[0];
75end;
76
77proc say(const r: Row);
78var i: INT;
79begin
80 for i := 0 to N - 1 do Out.int(r[i]); Out.char(' '); end;
81 Out.ln;
82end;
83
84proc main*;
85var i: INT;
86begin
87 for i := 0 to N - 1 do r1[i] := I64(i * i - 10); end;
88 mix(r1, r2, 7);
89 say(r2);
90 total := sumAfter(r1[1..N], r2, r1);
91 Out.int(total); Out.ln;
92 say(r2);
93 Out.int(sumThen(r1[2..N], r2)); Out.ln;
94 Out.int(busy(r2, r1)); Out.ln;
95 say(r2);
96 once(r2, r1);
97 say(r2);
98 Out.int(pick(r1, r2, 3)); Out.ln;
99 Out.int(pick(r1, r2, N + 1)); Out.ln;
100end;
101
102end KeptCopy.