raz / commit 969b2572

commit
969b257253bf60c394f0cfb09f15254a5b118aed
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
338ec357
A blank among results from memory; plainer code where review asked

v0.7.0 step 7, first part, from a fresh reader's review. MultiAssign
discarded an item it hadn't made when a blank stood first among results
that come back in memory (three, or with a real): made the same way on
both paths now, and conform/run/TwoWords drops some of three.

FirstLocal names the walk to a procedure's locals that four routines
repeated; ChooseRegs's Find, which hid sym's, is Candidate; ForStatement
uses ForCmp; LocalsFromScratch is ResetLocals, Log2 ExactLog2; Call's
empty branch and EndProc's dangling else are spelt out.

compiler.md gains "Better code, in one procedure": Str.decode's first
lines before v0.7.0 and after, and what each step took away. PLAN.md
records where the milestone stands.

patch · log

7 files changed, +200 -36

PLAN.md (history) modified +19 -0

@@ -20,6 +20,25 @@
2020 listings show the steps below. ulam's `doc/codegen.md` measured the
2121 same rewrites in a compiler of the same kind; its gains are quoted.
2222
23+**Where it stands.** Steps 1 to 6 are done and pushed. rat takes 504
24+to 512 ms against 614 to 625 for the same workload built by the
25+milestone's first compiler, on a machine that drifts by 3%; pt built
26+with `-O2 -Cr` takes 424 ms on the same day, so rat is at 1.19 times,
27+inside the goal. Text is 1.5% smaller. Each step, with its commit:
28+
29+| Step | rat | Its kernel |
30+|---|---|---|
31+| 1. Prologue | -12% | |
32+| 2. Two words in rax, rdx | noise | calls returning two results, -9% |
33+| 3. Two results on the stack | -8% | |
34+| 4. Conditions as jumps | noise | a search leaving by break, -28% |
35+| 5. Shifts, constants right | noise | heap sort and list walk, -11% |
36+| 6. for loops | noise | matrix product -14%, sum -21% |
37+
38+Steps that left rat's time alone stayed for their kernels, which the
39+2% rule allows. Moves between registers bought size, not time: this
40+machine renames them away, as ulam found.
41+
2342 1. **A prologue that does only what it must.** A register variable
2443 keeps a frame slot that is zeroed for nothing, and so do the slots
2544 the registers are saved in: `Str.decode`, whose four variables are

conform/run/TwoWords.expect (history) modified +2 -0

@@ -8,3 +8,5 @@
88 14 111
99 18
1010 5 22
11+2 3
12+7

conform/run/TwoWords.raz (history) modified +5 -0

@@ -45,6 +45,8 @@
4545 if n > 0 then return 1, 2; end;
4646 end;
4747
48+proc three(n: INT): (INT, INT, INT); begin return n, n + 1, n + 2; end;
49+
4850 proc main*;
4951 var x, y: I32; b: BOOL; v, p, q: INT; w: I64; h: proc(n: INT): (INT, INT); pv: ^INT;
5052 begin
@@ -59,6 +61,9 @@
5961 (* in order: the second result is the one left *)
6062 v, v := nested(4); Out.int(v); Out.ln;
6163 pv := ADR(q); pv^, p := nested(5); Out.int(q); Out.str(" "); Out.int(p); Out.ln;
64+ (* three results, which come back in memory, some dropped *)
65+ _, p, q := three(1); Out.int(p); Out.str(" "); Out.int(q); Out.ln;
66+ p, _, _ := three(7); Out.int(p); Out.ln;
6267 end;
6368
6469 end TwoWords.

doc/compiler.md (history) modified +139 -4

@@ -8,14 +8,14 @@
88
99 | File | Lines | Code | What |
1010 |---|---|---|---|
11-| `src/diag.pas` | 310 | 229 | Messages: positions, source excerpts, colour, counts |
11+| `src/diag.pas` | 316 | 233 | Messages: positions, source excerpts, colour, counts |
1212 | `src/scan.pas` | 886 | 747 | Symbols, literals, comments, positions |
1313 | `src/sym.pas` | 643 | 527 | Types, objects, scopes, layout |
1414 | `src/chunk.pas` | 318 | 246 | The compiled program: chunks, fixups, line notes |
1515 | `src/x64.pas` | 1,125 | 936 | The instruction encoder, jumps within a procedure, the assembler |
16-| `src/gen.pas` | 1,665 | 1,291 | The stack machine, for x86-64: values, operations, checks, calls, frames |
17-| `src/item.pas` | 1,535 | 1,277 | Items: types, constants, variables, operators, conversions, calls |
18-| `src/parse.pas` | 2,966 | 2,615 | Declarations, statements, expressions, built-ins, recovery, warnings |
16+| `src/gen.pas` | 1,666 | 1,291 | The stack machine, for x86-64: values, operations, checks, calls, frames |
17+| `src/item.pas` | 1,536 | 1,278 | Items: types, constants, variables, operators, conversions, calls |
18+| `src/parse.pas` | 2,967 | 2,612 | Declarations, statements, expressions, built-ins, recovery, warnings |
1919 | `src/link.pas` | 247 | 190 | Tree shaking, layout, patching, the places |
2020 | `src/elf.pas` | 435 | 352 | Static and dynamic ELF, symbol table, line numbers |
2121 | `src/raz.pas` | 197 | 147 | The command line |
@@ -119,6 +119,141 @@
119119 `ReturnJump`'s, and the frame is `EnterBody`'s and `EndProc`'s. It is
120120 not fast code. It is code whose every instruction you can account
121121 for, which is the point.
122+
123+## Better code, in one procedure
124+
125+`Str.decode` reads one UTF-8 character from a slice of bytes, and for
126+plain ASCII it is done by its third line. It is called once for each
127+character a program prints, so its first lines are worth looking at.
128+Here is what `raz -S lib/Str.raz` says of them, before the work of
129+v0.7.0:
130+
131+```
132+ 102 proc decode*(s: []U8): (I32, INT);
133+ 0 push rbp
134+ 1 mov rbp, rsp
135+ 4 sub rsp, 96
136+ 11 xor eax, eax
137+ 13 mov r10, -7
138+ 20 mov [rbp + r10 * 8 - 24], rax
139+ 25 add r10, 1
140+ 29 jne 20
141+ 35 mov [rbp - 80], rbx
142+ 39 xor ebx, ebx
143+ 41 mov [rbp - 72], r12
144+ 45 xor r12d, r12d
145+ 48 mov [rbp - 64], r13
146+ 52 xor r13d, r13d
147+ 55 mov [rbp - 56], r14
148+ 59 xor r14d, r14d
149+ 62 mov [rbp - 8], rdi
150+ 66 mov [rbp - 24], rsi
151+ 70 mov [rbp - 16], rdx
152+ 105 if LEN(s) = 0 then return 0, 0; end;
153+ 74 mov r8, [rbp - 16]
154+ 78 cmp r8, 0
155+ 82 jne 118
156+ 88 xor r8d, r8d
157+ 91 mov rcx, [rbp - 8]
158+ 95 mov [rcx], r8d
159+ 98 xor r8d, r8d
160+ 101 mov rcx, [rbp - 8]
161+ 105 mov [rcx + 8], r8
162+ 109 mov rax, [rbp - 8]
163+ 113 jmp 807
164+ 106 c := I32(s[0]);
165+ 118 xor r8d, r8d
166+ 121 mov rax, r8
167+ 124 cmp rax, [rbp - 16]
168+ 128 jae 825
169+ 134 add rax, [rbp - 24]
170+ 138 mov r8, rax
171+ 141 movzx r8d, byte [r8]
172+ 145 movsxd r8, r8d
173+ 148 mov rbx, r8
174+ 107 if c < 80H then return c, 1;
175+ 151 cmp rbx, 128
176+ 158 jge 202
177+ 164 mov r8, rbx
178+ 167 mov rcx, [rbp - 8]
179+ 171 mov [rcx], r8d
180+ 174 mov r8, 1
181+ 180 mov rcx, [rbp - 8]
182+ 184 mov [rcx + 8], r8
183+ 188 mov rax, [rbp - 8]
184+ 192 jmp 807
185+ 197 jmp 421
186+ 202 cmp rbx, 192
187+ 209 jge 256
188+```
189+
190+and after:
191+
192+```
193+ 102 proc decode*(s: []U8): (I32, INT);
194+ 0 push rbp
195+ 1 mov rbp, rsp
196+ 4 sub rsp, 64
197+ 11 mov [rbp - 48], rbx
198+ 15 xor ebx, ebx
199+ 17 mov [rbp - 40], r12
200+ 21 xor r12d, r12d
201+ 24 mov [rbp - 32], r13
202+ 28 xor r13d, r13d
203+ 31 mov [rbp - 24], r14
204+ 35 xor r14d, r14d
205+ 38 mov [rbp - 16], rdi
206+ 42 mov [rbp - 8], rsi
207+ 105 if LEN(s) = 0 then return 0, 0; end;
208+ 46 mov r8, [rbp - 8]
209+ 50 test r8, r8
210+ 53 jne 68
211+ 59 xor edx, edx
212+ 61 xor eax, eax
213+ 63 jmp 595
214+ 106 c := I32(s[0]);
215+ 68 xor r8d, r8d
216+ 71 cmp r8, [rbp - 8]
217+ 75 jae 613
218+ 81 add r8, [rbp - 16]
219+ 85 movzx r8d, byte [r8]
220+ 89 movsxd r8, r8d
221+ 92 mov rbx, r8
222+ 107 if c < 80H then return c, 1;
223+ 95 cmp rbx, 128
224+ 102 jge 121
225+ 108 mov rdx, 1
226+ 113 mov rax, rbx
227+ 116 jmp 595
228+ 121 cmp rbx, 192
229+ 128 jge 149
230+```
231+
232+What went, and the routine that took it away:
233+
234+1. **The loop at 11 to 29**, which zeroed seven quadwords: the frame
235+ slots of the four variables, all of them in registers, and the slots
236+ the registers are saved in, which are written before they are read.
237+ Now a variable in a register has no slot, and only the locals in
238+ memory are zeroed (`PlaceLocals`, `UseRegs`, `EnterBody`).
239+2. **The hidden pointer**: the two results went through `rcx` to the
240+ caller's memory. Two words come back in `rax` and `rdx` now
241+ (`InTwoRegs`), so `return 0, 0` is two instructions; and the caller
242+ pops them straight into its variables (`mWords`, `MultiAssign`).
243+3. **`cmp r8, 0`** is `test r8, r8`, the same flags in fewer bytes
244+ (`CmpI`).
245+4. **Copies through `rax`**: `s[0]`'s address is worked out in the
246+ register it is used from (`IndexSlice`), and a result is put in `rax`
247+ from where it is (`PopTo`).
248+5. **The `jmp 421` after `return`**, which nothing could reach: a branch
249+ of an `if` that ends gets no jump past the others (`IfStatement`).
250+
251+What is left is worth knowing too. The slice's two words still go to
252+the frame, since only single values live in registers; `movzx` then
253+`movsxd` reads a byte and makes an `I32` of it in two steps where one
254+would do; and the four registers are saved and restored on every call,
255+though this path uses one of them. Each could go, at the cost of lines
256+a reader would have to follow.
122257
123258 ## diag.pas: messages
124259

src/gen.pas modified +10 -9

@@ -153,7 +153,7 @@
153153 procedure KeepTemps;
154154
155155 procedure BeginProc(sig: PType; params: PObj);
156-procedure LocalsFromScratch;
156+procedure ResetLocals;
157157 procedure UseRegs(mask: longint);
158158 procedure MarkCode(var m: TCodeMark);
159159 procedure Redo(const m: TCodeMark);
@@ -539,20 +539,20 @@
539539
540540 { Operations }
541541
542-function Log2(v: int64): longint;
542+function ExactLog2(v: int64): longint;
543543 var n: longint;
544544 begin
545545 n := 0;
546546 while (v > 1) and (v and 1 = 0) do begin v := v shr 1; inc(n) end;
547547 if v <> 1 then n := -1;
548- Log2 := n;
548+ ExactLog2 := n;
549549 end;
550550
551551 { r times v, a size: by a shift where v is a power of two, as it
552552 mostly is, since a shift takes one cycle and imul three }
553553 procedure MulI(r: longint; v: int64);
554554 begin
555- if Log2(v) > 0 then ShiftI(shShl, r, Log2(v))
555+ if ExactLog2(v) > 0 then ShiftI(shShl, r, ExactLog2(v))
556556 else if v <> 1 then ImulI(r, v);
557557 end;
558558
@@ -651,7 +651,7 @@
651651 and (stack[depth - 1].loc <> lConst) then Swap;
652652 c := TopConst(v);
653653 sh := -1;
654- if c and (op in [sTimes, sDiv, sMod]) then sh := Log2(v);
654+ if c and (op in [sTimes, sDiv, sMod]) then sh := ExactLog2(v);
655655 if c and (sh >= 1) then begin
656656 Drop;
657657 r := Top;
@@ -1272,6 +1272,7 @@
12721272 two results on the stack, the first under the second, and a single
12731273 value on top }
12741274 if res = nil then
1275+ { nothing comes back }
12751276 else if res^.form = fSlice then begin
12761277 Store(Mem(RBP, c.ret), RAX, 8);
12771278 Store(Mem(RBP, c.ret + 8), RDX, 8);
@@ -1383,7 +1384,7 @@
13831384
13841385 { The frame as BeginProc left it, with the parameters' slots only: the
13851386 locals are given theirs again once their registers are chosen. }
1386-procedure LocalsFromScratch;
1387+procedure ResetLocals;
13871388 begin
13881389 frameTop := paramTop; frameMax := paramTop; permTop := paramTop;
13891390 end;
@@ -1520,7 +1521,7 @@
15201521 begin
15211522 codeChunk := -1;
15221523 if (depth <> 0) or (pushed <> 0) then Fatal('internal error: stack depth');
1523- if open then
1524+ if open then begin
15241525 if BehindPointer(resType) then begin
15251526 Load(RDI, Mem(RBP, retSlot), 8, false);
15261527 MovRI(RCX, resType^.size);
@@ -1531,8 +1532,8 @@
15311532 MovRI(RAX, 0);
15321533 if InTwoRegs(resType) then MovRI(RDX, 0);
15331534 MovqXR(0, RAX);
1534- end
1535- else DropJumpTo(exitL);
1535+ end;
1536+ end else DropJumpTo(exitL);
15361537 FixLink(exitL);
15371538 n := 0;
15381539 for i := 0 to 4 do

src/item.pas modified +2 -1

@@ -106,6 +106,7 @@
106106 procedure TempItem(var x: TItem; t: PType; off: int64);
107107 function ScalarSize(t: PType): longint;
108108 procedure ForStep(o: PObj; step: int64);
109+procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint);
109110 procedure ForNext(o: PObj; const lim: TItem; step: int64; var exitL: longint; top, body: longint);
110111
111112 procedure BeginProc(sig: PType; params: PObj);
@@ -1329,7 +1330,7 @@
13291330 Assign(v, w);
13301331 end;
13311332
1332-{ For ForNext: pushes the variable o and the limit lim, a constant or
1333+{ For a for loop: pushes the variable o and the limit lim, a constant or
13331334 the slot it was put in, and jumps to L if the one is op the other, as
13341335 the type of o compares }
13351336 procedure ForCmp(o: PObj; const lim: TItem; op: TSym; var L: longint);

src/parse.pas modified +23 -22

@@ -1332,7 +1332,7 @@
13321332 so that a round of a loop by 1 takes one compare and one jump. }
13331333 procedure ForStatement(const start: TPos; ind: longint);
13341334 var
1335- o: PObj; v, a, b, s, lim: TItem; step: int64; top, body, bodyL, exitL: longint;
1335+ o: PObj; v, a, b, s: TItem; step: int64; top, body, bodyL, exitL: longint;
13361336 lp: TLoop; old: PLoop;
13371337 begin
13381338 Next;
@@ -1364,12 +1364,7 @@
13641364 end;
13651365 Expect(sDo);
13661366 exitL := NoLabel;
1367- MakeItem(v, o);
1368- Value(v);
1369- lim := b;
1370- Value(lim);
1371- if step > 0 then JumpCmp(sGtr, o^.typ^.signed, exitL)
1372- else JumpCmp(sLss, o^.typ^.signed, exitL);
1367+ if step > 0 then ForCmp(o, b, sGtr, exitL) else ForCmp(o, b, sLss, exitL);
13731368 bodyL := NoLabel;
13741369 Jump(bodyL);
13751370 top := pc;
@@ -1592,13 +1587,11 @@
15921587 if y.mode = mWords then Swap;
15931588 f := y.typ^.fields;
15941589 for i := 0 to n - 1 do begin
1595- if y.mode = mWords then begin
1596- z := y;
1597- z.mode := mStack; z.typ := f^.typ;
1598- end;
1590+ z := y;
1591+ if y.mode = mWords then begin z.mode := mStack; z.typ := f^.typ end
1592+ else Field(z, f);
15991593 if blanks[i] then Discard(z)
16001594 else begin
1601- if y.mode <> mWords then begin z := y; Field(z, f) end;
16021595 CoerceExact(z, d[i].typ, 'several results go to variables of just their types');
16031596 Assign(d[i], z);
16041597 end;
@@ -1830,6 +1823,14 @@
18301823 or (o^.typ^.form = fSet) and (o^.typ^.size <= 8));
18311824 end;
18321825
1826+{ The first local of the procedure being compiled. Locals are chained
1827+ by link in the order declared, the module's own first; before is the
1828+ last one declared before the procedure's, or nil if there was none. }
1829+function FirstLocal(before: PObj): PObj;
1830+begin
1831+ if before = nil then FirstLocal := curModule^.locals else FirstLocal := before^.link;
1832+end;
1833+
18331834 { Puts the busiest variables of the procedure, whose parameters are
18341835 params and whose locals follow before, in registers: read ahead from
18351836 its "begin" to its end, a use counts 1, in a loop 4, in two 16, and
@@ -1842,11 +1843,11 @@
18421843 isLoop: array[0..255] of boolean;
18431844 n, i, k, d, loops, best: longint; o: PObj; st: TScanState; afterDot, wasSkipping: boolean;
18441845
1845- function Find(name: longint): longint;
1846+ function Candidate(name: longint): longint;
18461847 var j: longint;
18471848 begin
18481849 for j := 0 to n - 1 do if cand[j]^.name = name then exit(j);
1849- Find := -1;
1850+ Candidate := -1;
18501851 end;
18511852
18521853 procedure Add(o: PObj);
@@ -1858,7 +1859,7 @@
18581859 n := 0;
18591860 o := params;
18601861 while o <> nil do begin Add(o); o := o^.next end;
1861- if before = nil then o := curModule^.locals else o := before^.link;
1862+ o := FirstLocal(before);
18621863 while o <> nil do begin Add(o); o := o^.link end;
18631864 if n > 0 then begin
18641865 SaveScan(st);
@@ -1881,9 +1882,9 @@
18811882 if id = nameAdr then begin
18821883 Next;
18831884 if tok = sLparen then Next;
1884- if (tok = sIdent) and (Find(id) >= 0) then weight[Find(id)] := low(longint) div 2;
1885- end else if not afterDot and (Find(id) >= 0) then begin
1886- k := Find(id);
1885+ if (tok = sIdent) and (Candidate(id) >= 0) then weight[Candidate(id)] := low(longint) div 2;
1886+ end else if not afterDot and (Candidate(id) >= 0) then begin
1887+ k := Candidate(id);
18871888 if loops > 2 then inc(weight[k], 64) else inc(weight[k], 1 shl (2 * loops));
18881889 end;
18891890 end;
@@ -1913,7 +1914,7 @@
19131914 for k := 0 to 4 do if o^.reg = VarRegs[k] then m := m or (1 shl k);
19141915 o := o^.next;
19151916 end;
1916- if before = nil then o := curModule^.locals else o := before^.link;
1917+ o := FirstLocal(before);
19171918 while o <> nil do begin
19181919 if o^.cls = oVar then
19191920 for k := 0 to 4 do if o^.reg = VarRegs[k] then m := m or (1 shl k);
@@ -1929,8 +1930,8 @@
19291930 procedure PlaceLocals(params, before: PObj);
19301931 var o: PObj;
19311932 begin
1932- LocalsFromScratch;
1933- if before = nil then o := curModule^.locals else o := before^.link;
1933+ ResetLocals;
1934+ o := FirstLocal(before);
19341935 while o <> nil do begin
19351936 if (o^.cls = oVar) and (o^.reg = 0) then o^.val := AllocPerm(o^.typ^.size, o^.typ^.align);
19361937 o := o^.link;
@@ -1991,7 +1992,7 @@
19911992 until false;
19921993 EndProc(p^.chunk, p^.openEnd);
19931994 { its parameters and variables, for the trap report }
1994- if before = nil then o := curModule^.locals else o := before^.link;
1995+ o := FirstLocal(before);
19951996 q := params;
19961997 while q <> nil do begin
19971998 if VarKind(q) <> 0 then NoteVar(p^.chunk, q^.name, q^.val, VarKind(q));