raz / site / content / advanced / 11-asm.txt

246 lines · 6.8 KiB · raw · history · last change a5145f64

1title: Procedures in assembly
2part: The machine
3summary: code procedures: the convention, registers, labels, db for what the assembler doesn't know.
4---
5Sometimes a program needs an instruction the language has no word for: reading the cycle counter, asking the CPU what it is, counting bits in one instruction, a square root in the hardware. A procedure whose body is `code` is machine code, written by hand in the target's assembly language, one instruction to each `;`, up to `end`.
6
7The compiler doesn't look past what the instructions say. It trusts you, and you owe it a few rules.
8
9## A first one
10
11This reads the processor's time stamp counter. The result of a procedure goes in `rax`; `rdtsc` leaves the counter in `edx:eax`, so the two halves are joined first.
12
13```raz Cycles run
14module Cycles;
15import Out;
16import SYSTEM;
17
18proc rdtsc*: U64;
19code
20 rdtsc;
21 shl rdx, 32;
22 or rax, rdx;
23 ret;
24end rdtsc;
25
26proc main*;
27var a, b: U64;
28begin
29 a := rdtsc();
30 b := rdtsc();
31 if b > a then Out.str("the counter moves forward\n"); end;
32end;
33
34end Cycles.
35```
36
37A code procedure is called like any procedure. Everything in it is yours, `ret` included.
38
39## The convention
40
41A code procedure follows the System V convention, as every raz procedure does:
42
43- Integer and pointer arguments arrive in `rdi`, `rsi`, `rdx`, `rcx`, `r8` and `r9`; `F32` and `F64` ones in `xmm0` to `xmm7`.
44- The result goes in `rax` (and `rdx` for a second) or `xmm0`.
45- It must keep `rbx`, `rbp`, `rsp` and `r12` to `r15` as it found them. `rax`, `rcx`, `rdx`, `rsi`, `rdi` and `r8` to `r11` are free to change.
46- A slice is two integers, its address and its length, as System V passes a struct of two. As a parameter it takes two registers in a row; as the result its address goes in `rax` and its length in `rdx`.
47- Its parameters and results are therefore of the types C can take, or slices: at most six integer and eight real parameters, and two results, a slice being the only one.
48
49That is why the next one is so short: the argument is already in `rdi`.
50
51```raz Bits run
52module Bits;
53import Out;
54import SYSTEM;
55
56(* the bytes of x in the opposite order: bswap rax, which the assembler
57 doesn't know, written as its bytes *)
58proc swap64(x: U64): U64;
59code
60 mov rax, rdi;
61 db 48H, 0FH, 0C8H;
62 ret;
63end swap64;
64
65(* the number of bits set in x *)
66proc ones(x: U64): INT;
67code
68 popcnt rax, rdi;
69 ret;
70end ones;
71
72proc main*;
73begin
74 Out.str("0x"); Out.hex(swap64(0102030405060708H), 16); Out.ln;
75 Out.int(ones(0FFH)); Out.char(' ');
76 Out.int(ones(0)); Out.char(' ');
77 Out.int(ones(0FFFFFFFFFFFFFFFFH)); Out.ln;
78end;
79
80end Bits.
81```
82
83`db` writes any bytes, for an instruction the assembler doesn't know. Which instructions it knows is the implementation's business: this one knows `popcnt` but not `bswap`, and `db` keeps you from waiting for it to learn one. (`bswap r64` is `REX.W 0F C8+r` in the processor manuals.)
84
85## Labels and loops
86
87A label, `name:`, names the place of the instruction after it, within the procedure. Jumps go to labels, and a constant of the module may stand wherever a number does. This sums a slice of `INT`s, whose address arrives in `rdi` and its length in `rsi`:
88
89```raz Sum run
90module Sum;
91import Out;
92import SYSTEM;
93
94(* the sum of the INTs of a *)
95proc sum(a: []INT): INT;
96code
97 xor eax, eax;
98 test rsi, rsi;
99 jle done;
100again:
101 add rax, [rdi];
102 add rdi, 8;
103 dec rsi;
104 jnz again;
105done:
106 ret;
107end sum;
108
109(* the same in raz, to check it against *)
110proc sumRaz(a: []INT): INT;
111var i, t: INT;
112begin
113 for i := 0 to LEN(a) - 1 do t := t + a[i]; end;
114 return t;
115end;
116
117proc main*;
118var a: [6]INT; i: INT;
119begin
120 for i := 0 to 5 do a[i] := (i + 1) * 100; end;
121 Out.int(sum(a)); Out.char(' ');
122 Out.int(sumRaz(a)); Out.char(' ');
123 Out.int(sum(a[2..4])); Out.char(' ');
124 Out.int(sum(a[0..0])); Out.ln;
125end;
126
127end Sum.
128```
129
130The procedure trusts the length it is given, as it must: the checks of the language end where its code begins.
131
132A slice comes back the same way, its address in `rax` and its length in `rdx`. This one returns what is left of a string past its leading blanks:
133
134```raz Trim run
135module Trim;
136import Out;
137import SYSTEM;
138
139(* s past its leading blanks *)
140proc trim(s: []const U8): []const U8;
141code
142 mov rax, rdi;
143 mov rdx, rsi;
144again:
145 test rdx, rdx;
146 jz done;
147 cmp byte [rax], 32;
148 jne done;
149 inc rax;
150 dec rdx;
151 jmp again;
152done:
153 ret;
154end trim;
155
156proc main*;
157begin
158 Out.char('['); Out.str(trim(" raz")); Out.str("]\n");
159 Out.char('['); Out.str(trim("raz")); Out.str("]\n");
160 Out.char('['); Out.str(trim(" ")); Out.str("]\n");
161end;
162
163end Trim.
164```
165
166A procedure may have up to 64 labels. The check against the raz version is the habit worth keeping: write the procedure in raz first, then in assembly, and compare their results on awkward inputs.
167
168## Two results, and reals
169
170A second result goes in `rdx`. That is exactly where `idiv` leaves the remainder, so `divmod` is four instructions. Reals travel in the `xmm` registers.
171
172```raz Divmod run
173module Divmod;
174import Out, Fmt;
175import SYSTEM;
176
177(* quotient and remainder, as idiv gives them: rax and rdx *)
178proc divmod(a, b: INT): (INT, INT);
179code
180 mov rax, rdi;
181 cqo;
182 idiv rsi;
183 ret;
184end divmod;
185
186(* a * x + b, on F64s in xmm0 to xmm2 *)
187proc fma(a, x, b: F64): F64;
188code
189 mulsd xmm0, xmm1;
190 addsd xmm0, xmm2;
191 ret;
192end fma;
193
194proc main*;
195var q, r: INT;
196begin
197 q, r := divmod(-17, 5);
198 Out.int(q); Out.char(' '); Out.int(r); Out.ln;
199 Fmt.print("{}\n", [Fmt.real(fma(2.0, 3.5, 0.25), 2)]);
200end;
201
202end Divmod.
203```
204
205`idiv` by zero stops the program with the machine's own division fault. It isn't a check the compiler added, since the compiler doesn't look inside a code procedure.
206
207## Keeping what isn't yours
208
209A procedure that uses `rbx` must put it back. `cpuid` clobbers `rbx`, so the vendor-string example saves it with `push` and restores it with `pop`, and keeps the buffer's address in `r8` while it works:
210
211```raz Vendor run
212module Vendor;
213import Out;
214import SYSTEM;
215
216(* the 12 bytes of the processor vendor, in buf (rdi) *)
217proc vendor(buf: ^U8);
218code
219 push rbx;
220 mov r8, rdi;
221 xor eax, eax;
222 cpuid;
223 mov [r8], ebx;
224 mov [r8 + 4], edx;
225 mov [r8 + 8], ecx;
226 pop rbx;
227 ret;
228end vendor;
229
230proc main*;
231var buf: [12]U8; i: INT; ok: BOOL;
232begin
233 vendor(SYSTEM.ADR(buf[0]));
234 ok := true;
235 for i := 0 to 11 do
236 if (buf[i] < ' ') or (buf[i] > '~') then ok := false; end;
237 end;
238 if ok then Out.str("the vendor is 12 printable bytes\n"); end;
239end;
240
241end Vendor.
242```
243
244## What goes wrong
245
246A code procedure that breaks its rules breaks the program, and what follows isn't defined. Writing through a wrong pointer, a changed `rbx`, a missing `ret`, a stack left unbalanced: the language can't help, because it doesn't see inside. Keep them short, give each a comment that says what it expects in which register, test each against a raz twin, and use them for what only the machine can do.